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 "ARMBaseInstrInfo.h"
10 #include "ARMFeatures.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMInstPrinter.h"
14 #include "MCTargetDesc/ARMMCExpr.h"
15 #include "MCTargetDesc/ARMMCTargetDesc.h"
16 #include "TargetInfo/ARMTargetInfo.h"
17 #include "Utils/ARMBaseInfo.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/StringRef.h"
26 #include "llvm/ADT/StringSet.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/MCParser/MCAsmLexer.h"
36 #include "llvm/MC/MCParser/MCAsmParser.h"
37 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
38 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
39 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
40 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/MC/MCSection.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSubtargetInfo.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/MC/SubtargetFeature.h"
47 #include "llvm/MC/TargetRegistry.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/raw_ostream.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <cstddef>
61 #include <cstdint>
62 #include <iterator>
63 #include <limits>
64 #include <memory>
65 #include <string>
66 #include <utility>
67 #include <vector>
68 
69 #define DEBUG_TYPE "asm-parser"
70 
71 using namespace llvm;
72 
73 namespace llvm {
74 extern const MCInstrDesc ARMInsts[];
75 } // end namespace llvm
76 
77 namespace {
78 
79 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
80 
81 static cl::opt<ImplicitItModeTy> ImplicitItMode(
82     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
83     cl::desc("Allow conditional instructions outdside of an IT block"),
84     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
85                           "Accept in both ISAs, emit implicit ITs in Thumb"),
86                clEnumValN(ImplicitItModeTy::Never, "never",
87                           "Warn in ARM, reject in Thumb"),
88                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
89                           "Accept in ARM, reject in Thumb"),
90                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
91                           "Warn in ARM, emit implicit ITs in Thumb")));
92 
93 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
94                                         cl::init(false));
95 
96 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
97 
98 static inline unsigned extractITMaskBit(unsigned Mask, unsigned Position) {
99   // Position==0 means we're not in an IT block at all. Position==1
100   // means we want the first state bit, which is always 0 (Then).
101   // Position==2 means we want the second state bit, stored at bit 3
102   // of Mask, and so on downwards. So (5 - Position) will shift the
103   // right bit down to bit 0, including the always-0 bit at bit 4 for
104   // the mandatory initial Then.
105   return (Mask >> (5 - Position) & 1);
106 }
107 
108 class UnwindContext {
109   using Locs = SmallVector<SMLoc, 4>;
110 
111   MCAsmParser &Parser;
112   Locs FnStartLocs;
113   Locs CantUnwindLocs;
114   Locs PersonalityLocs;
115   Locs PersonalityIndexLocs;
116   Locs HandlerDataLocs;
117   int FPReg;
118 
119 public:
120   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
121 
122   bool hasFnStart() const { return !FnStartLocs.empty(); }
123   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
124   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
125 
126   bool hasPersonality() const {
127     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
128   }
129 
130   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
131   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
132   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
133   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
134   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
135 
136   void saveFPReg(int Reg) { FPReg = Reg; }
137   int getFPReg() const { return FPReg; }
138 
139   void emitFnStartLocNotes() const {
140     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
141          FI != FE; ++FI)
142       Parser.Note(*FI, ".fnstart was specified here");
143   }
144 
145   void emitCantUnwindLocNotes() const {
146     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
147                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
148       Parser.Note(*UI, ".cantunwind was specified here");
149   }
150 
151   void emitHandlerDataLocNotes() const {
152     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
153                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
154       Parser.Note(*HI, ".handlerdata was specified here");
155   }
156 
157   void emitPersonalityLocNotes() const {
158     for (Locs::const_iterator PI = PersonalityLocs.begin(),
159                               PE = PersonalityLocs.end(),
160                               PII = PersonalityIndexLocs.begin(),
161                               PIE = PersonalityIndexLocs.end();
162          PI != PE || PII != PIE;) {
163       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
164         Parser.Note(*PI++, ".personality was specified here");
165       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
166         Parser.Note(*PII++, ".personalityindex was specified here");
167       else
168         llvm_unreachable(".personality and .personalityindex cannot be "
169                          "at the same location");
170     }
171   }
172 
173   void reset() {
174     FnStartLocs = Locs();
175     CantUnwindLocs = Locs();
176     PersonalityLocs = Locs();
177     HandlerDataLocs = Locs();
178     PersonalityIndexLocs = Locs();
179     FPReg = ARM::SP;
180   }
181 };
182 
183 // Various sets of ARM instruction mnemonics which are used by the asm parser
184 class ARMMnemonicSets {
185   StringSet<> CDE;
186   StringSet<> CDEWithVPTSuffix;
187 public:
188   ARMMnemonicSets(const MCSubtargetInfo &STI);
189 
190   /// Returns true iff a given mnemonic is a CDE instruction
191   bool isCDEInstr(StringRef Mnemonic) {
192     // Quick check before searching the set
193     if (!Mnemonic.startswith("cx") && !Mnemonic.startswith("vcx"))
194       return false;
195     return CDE.count(Mnemonic);
196   }
197 
198   /// Returns true iff a given mnemonic is a VPT-predicable CDE instruction
199   /// (possibly with a predication suffix "e" or "t")
200   bool isVPTPredicableCDEInstr(StringRef Mnemonic) {
201     if (!Mnemonic.startswith("vcx"))
202       return false;
203     return CDEWithVPTSuffix.count(Mnemonic);
204   }
205 
206   /// Returns true iff a given mnemonic is an IT-predicable CDE instruction
207   /// (possibly with a condition suffix)
208   bool isITPredicableCDEInstr(StringRef Mnemonic) {
209     if (!Mnemonic.startswith("cx"))
210       return false;
211     return Mnemonic.startswith("cx1a") || Mnemonic.startswith("cx1da") ||
212            Mnemonic.startswith("cx2a") || Mnemonic.startswith("cx2da") ||
213            Mnemonic.startswith("cx3a") || Mnemonic.startswith("cx3da");
214   }
215 
216   /// Return true iff a given mnemonic is an integer CDE instruction with
217   /// dual-register destination
218   bool isCDEDualRegInstr(StringRef Mnemonic) {
219     if (!Mnemonic.startswith("cx"))
220       return false;
221     return Mnemonic == "cx1d" || Mnemonic == "cx1da" ||
222            Mnemonic == "cx2d" || Mnemonic == "cx2da" ||
223            Mnemonic == "cx3d" || Mnemonic == "cx3da";
224   }
225 };
226 
227 ARMMnemonicSets::ARMMnemonicSets(const MCSubtargetInfo &STI) {
228   for (StringRef Mnemonic: { "cx1", "cx1a", "cx1d", "cx1da",
229                              "cx2", "cx2a", "cx2d", "cx2da",
230                              "cx3", "cx3a", "cx3d", "cx3da", })
231     CDE.insert(Mnemonic);
232   for (StringRef Mnemonic :
233        {"vcx1", "vcx1a", "vcx2", "vcx2a", "vcx3", "vcx3a"}) {
234     CDE.insert(Mnemonic);
235     CDEWithVPTSuffix.insert(Mnemonic);
236     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "t");
237     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "e");
238   }
239 }
240 
241 class ARMAsmParser : public MCTargetAsmParser {
242   const MCRegisterInfo *MRI;
243   UnwindContext UC;
244   ARMMnemonicSets MS;
245 
246   ARMTargetStreamer &getTargetStreamer() {
247     assert(getParser().getStreamer().getTargetStreamer() &&
248            "do not have a target streamer");
249     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
250     return static_cast<ARMTargetStreamer &>(TS);
251   }
252 
253   // Map of register aliases registers via the .req directive.
254   StringMap<unsigned> RegisterReqs;
255 
256   bool NextSymbolIsThumb;
257 
258   bool useImplicitITThumb() const {
259     return ImplicitItMode == ImplicitItModeTy::Always ||
260            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
261   }
262 
263   bool useImplicitITARM() const {
264     return ImplicitItMode == ImplicitItModeTy::Always ||
265            ImplicitItMode == ImplicitItModeTy::ARMOnly;
266   }
267 
268   struct {
269     ARMCC::CondCodes Cond;    // Condition for IT block.
270     unsigned Mask:4;          // Condition mask for instructions.
271                               // Starting at first 1 (from lsb).
272                               //   '1'  condition as indicated in IT.
273                               //   '0'  inverse of condition (else).
274                               // Count of instructions in IT block is
275                               // 4 - trailingzeroes(mask)
276                               // Note that this does not have the same encoding
277                               // as in the IT instruction, which also depends
278                               // on the low bit of the condition code.
279 
280     unsigned CurPosition;     // Current position in parsing of IT
281                               // block. In range [0,4], with 0 being the IT
282                               // instruction itself. Initialized according to
283                               // count of instructions in block.  ~0U if no
284                               // active IT block.
285 
286     bool IsExplicit;          // true  - The IT instruction was present in the
287                               //         input, we should not modify it.
288                               // false - The IT instruction was added
289                               //         implicitly, we can extend it if that
290                               //         would be legal.
291   } ITState;
292 
293   SmallVector<MCInst, 4> PendingConditionalInsts;
294 
295   void flushPendingInstructions(MCStreamer &Out) override {
296     if (!inImplicitITBlock()) {
297       assert(PendingConditionalInsts.size() == 0);
298       return;
299     }
300 
301     // Emit the IT instruction
302     MCInst ITInst;
303     ITInst.setOpcode(ARM::t2IT);
304     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
305     ITInst.addOperand(MCOperand::createImm(ITState.Mask));
306     Out.emitInstruction(ITInst, getSTI());
307 
308     // Emit the conditonal instructions
309     assert(PendingConditionalInsts.size() <= 4);
310     for (const MCInst &Inst : PendingConditionalInsts) {
311       Out.emitInstruction(Inst, getSTI());
312     }
313     PendingConditionalInsts.clear();
314 
315     // Clear the IT state
316     ITState.Mask = 0;
317     ITState.CurPosition = ~0U;
318   }
319 
320   bool inITBlock() { return ITState.CurPosition != ~0U; }
321   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
322   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
323 
324   bool lastInITBlock() {
325     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
326   }
327 
328   void forwardITPosition() {
329     if (!inITBlock()) return;
330     // Move to the next instruction in the IT block, if there is one. If not,
331     // mark the block as done, except for implicit IT blocks, which we leave
332     // open until we find an instruction that can't be added to it.
333     unsigned TZ = countTrailingZeros(ITState.Mask);
334     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
335       ITState.CurPosition = ~0U; // Done with the IT block after this.
336   }
337 
338   // Rewind the state of the current IT block, removing the last slot from it.
339   void rewindImplicitITPosition() {
340     assert(inImplicitITBlock());
341     assert(ITState.CurPosition > 1);
342     ITState.CurPosition--;
343     unsigned TZ = countTrailingZeros(ITState.Mask);
344     unsigned NewMask = 0;
345     NewMask |= ITState.Mask & (0xC << TZ);
346     NewMask |= 0x2 << TZ;
347     ITState.Mask = NewMask;
348   }
349 
350   // Rewind the state of the current IT block, removing the last slot from it.
351   // If we were at the first slot, this closes the IT block.
352   void discardImplicitITBlock() {
353     assert(inImplicitITBlock());
354     assert(ITState.CurPosition == 1);
355     ITState.CurPosition = ~0U;
356   }
357 
358   // Return the low-subreg of a given Q register.
359   unsigned getDRegFromQReg(unsigned QReg) const {
360     return MRI->getSubReg(QReg, ARM::dsub_0);
361   }
362 
363   // Get the condition code corresponding to the current IT block slot.
364   ARMCC::CondCodes currentITCond() {
365     unsigned MaskBit = extractITMaskBit(ITState.Mask, ITState.CurPosition);
366     return MaskBit ? ARMCC::getOppositeCondition(ITState.Cond) : ITState.Cond;
367   }
368 
369   // Invert the condition of the current IT block slot without changing any
370   // other slots in the same block.
371   void invertCurrentITCondition() {
372     if (ITState.CurPosition == 1) {
373       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
374     } else {
375       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
376     }
377   }
378 
379   // Returns true if the current IT block is full (all 4 slots used).
380   bool isITBlockFull() {
381     return inITBlock() && (ITState.Mask & 1);
382   }
383 
384   // Extend the current implicit IT block to have one more slot with the given
385   // condition code.
386   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
387     assert(inImplicitITBlock());
388     assert(!isITBlockFull());
389     assert(Cond == ITState.Cond ||
390            Cond == ARMCC::getOppositeCondition(ITState.Cond));
391     unsigned TZ = countTrailingZeros(ITState.Mask);
392     unsigned NewMask = 0;
393     // Keep any existing condition bits.
394     NewMask |= ITState.Mask & (0xE << TZ);
395     // Insert the new condition bit.
396     NewMask |= (Cond != ITState.Cond) << TZ;
397     // Move the trailing 1 down one bit.
398     NewMask |= 1 << (TZ - 1);
399     ITState.Mask = NewMask;
400   }
401 
402   // Create a new implicit IT block with a dummy condition code.
403   void startImplicitITBlock() {
404     assert(!inITBlock());
405     ITState.Cond = ARMCC::AL;
406     ITState.Mask = 8;
407     ITState.CurPosition = 1;
408     ITState.IsExplicit = false;
409   }
410 
411   // Create a new explicit IT block with the given condition and mask.
412   // The mask should be in the format used in ARMOperand and
413   // MCOperand, with a 1 implying 'e', regardless of the low bit of
414   // the condition.
415   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
416     assert(!inITBlock());
417     ITState.Cond = Cond;
418     ITState.Mask = Mask;
419     ITState.CurPosition = 0;
420     ITState.IsExplicit = true;
421   }
422 
423   struct {
424     unsigned Mask : 4;
425     unsigned CurPosition;
426   } VPTState;
427   bool inVPTBlock() { return VPTState.CurPosition != ~0U; }
428   void forwardVPTPosition() {
429     if (!inVPTBlock()) return;
430     unsigned TZ = countTrailingZeros(VPTState.Mask);
431     if (++VPTState.CurPosition == 5 - TZ)
432       VPTState.CurPosition = ~0U;
433   }
434 
435   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
436     return getParser().Note(L, Msg, Range);
437   }
438 
439   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
440     return getParser().Warning(L, Msg, Range);
441   }
442 
443   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
444     return getParser().Error(L, Msg, Range);
445   }
446 
447   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
448                            unsigned ListNo, bool IsARPop = false);
449   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
450                            unsigned ListNo);
451 
452   int tryParseRegister();
453   bool tryParseRegisterWithWriteBack(OperandVector &);
454   int tryParseShiftRegister(OperandVector &);
455   bool parseRegisterList(OperandVector &, bool EnforceOrder = true);
456   bool parseMemory(OperandVector &);
457   bool parseOperand(OperandVector &, StringRef Mnemonic);
458   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
459   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
460                               unsigned &ShiftAmount);
461   bool parseLiteralValues(unsigned Size, SMLoc L);
462   bool parseDirectiveThumb(SMLoc L);
463   bool parseDirectiveARM(SMLoc L);
464   bool parseDirectiveThumbFunc(SMLoc L);
465   bool parseDirectiveCode(SMLoc L);
466   bool parseDirectiveSyntax(SMLoc L);
467   bool parseDirectiveReq(StringRef Name, SMLoc L);
468   bool parseDirectiveUnreq(SMLoc L);
469   bool parseDirectiveArch(SMLoc L);
470   bool parseDirectiveEabiAttr(SMLoc L);
471   bool parseDirectiveCPU(SMLoc L);
472   bool parseDirectiveFPU(SMLoc L);
473   bool parseDirectiveFnStart(SMLoc L);
474   bool parseDirectiveFnEnd(SMLoc L);
475   bool parseDirectiveCantUnwind(SMLoc L);
476   bool parseDirectivePersonality(SMLoc L);
477   bool parseDirectiveHandlerData(SMLoc L);
478   bool parseDirectiveSetFP(SMLoc L);
479   bool parseDirectivePad(SMLoc L);
480   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
481   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
482   bool parseDirectiveLtorg(SMLoc L);
483   bool parseDirectiveEven(SMLoc L);
484   bool parseDirectivePersonalityIndex(SMLoc L);
485   bool parseDirectiveUnwindRaw(SMLoc L);
486   bool parseDirectiveTLSDescSeq(SMLoc L);
487   bool parseDirectiveMovSP(SMLoc L);
488   bool parseDirectiveObjectArch(SMLoc L);
489   bool parseDirectiveArchExtension(SMLoc L);
490   bool parseDirectiveAlign(SMLoc L);
491   bool parseDirectiveThumbSet(SMLoc L);
492 
493   bool isMnemonicVPTPredicable(StringRef Mnemonic, StringRef ExtraToken);
494   StringRef splitMnemonic(StringRef Mnemonic, StringRef ExtraToken,
495                           unsigned &PredicationCode,
496                           unsigned &VPTPredicationCode, bool &CarrySetting,
497                           unsigned &ProcessorIMod, StringRef &ITMask);
498   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef ExtraToken,
499                              StringRef FullInst, bool &CanAcceptCarrySet,
500                              bool &CanAcceptPredicationCode,
501                              bool &CanAcceptVPTPredicationCode);
502   bool enableArchExtFeature(StringRef Name, SMLoc &ExtLoc);
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 MCExpr *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       if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
1111         Val = CE->getValue();
1112       else
1113         return false;
1114     }
1115     else return false;
1116     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
1117   }
1118 
1119   bool isFPImm() const {
1120     if (!isImm()) return false;
1121     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1122     if (!CE) return false;
1123     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1124     return Val != -1;
1125   }
1126 
1127   template<int64_t N, int64_t M>
1128   bool isImmediate() const {
1129     if (!isImm()) return false;
1130     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1131     if (!CE) return false;
1132     int64_t Value = CE->getValue();
1133     return Value >= N && Value <= M;
1134   }
1135 
1136   template<int64_t N, int64_t M>
1137   bool isImmediateS4() const {
1138     if (!isImm()) return false;
1139     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1140     if (!CE) return false;
1141     int64_t Value = CE->getValue();
1142     return ((Value & 3) == 0) && Value >= N && Value <= M;
1143   }
1144   template<int64_t N, int64_t M>
1145   bool isImmediateS2() const {
1146     if (!isImm()) return false;
1147     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1148     if (!CE) return false;
1149     int64_t Value = CE->getValue();
1150     return ((Value & 1) == 0) && Value >= N && Value <= M;
1151   }
1152   bool isFBits16() const {
1153     return isImmediate<0, 17>();
1154   }
1155   bool isFBits32() const {
1156     return isImmediate<1, 33>();
1157   }
1158   bool isImm8s4() const {
1159     return isImmediateS4<-1020, 1020>();
1160   }
1161   bool isImm7s4() const {
1162     return isImmediateS4<-508, 508>();
1163   }
1164   bool isImm7Shift0() const {
1165     return isImmediate<-127, 127>();
1166   }
1167   bool isImm7Shift1() const {
1168     return isImmediateS2<-255, 255>();
1169   }
1170   bool isImm7Shift2() const {
1171     return isImmediateS4<-511, 511>();
1172   }
1173   bool isImm7() const {
1174     return isImmediate<-127, 127>();
1175   }
1176   bool isImm0_1020s4() const {
1177     return isImmediateS4<0, 1020>();
1178   }
1179   bool isImm0_508s4() const {
1180     return isImmediateS4<0, 508>();
1181   }
1182   bool isImm0_508s4Neg() const {
1183     if (!isImm()) return false;
1184     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1185     if (!CE) return false;
1186     int64_t Value = -CE->getValue();
1187     // explicitly exclude zero. we want that to use the normal 0_508 version.
1188     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1189   }
1190 
1191   bool isImm0_4095Neg() const {
1192     if (!isImm()) return false;
1193     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1194     if (!CE) return false;
1195     // isImm0_4095Neg is used with 32-bit immediates only.
1196     // 32-bit immediates are zero extended to 64-bit when parsed,
1197     // thus simple -CE->getValue() results in a big negative number,
1198     // not a small positive number as intended
1199     if ((CE->getValue() >> 32) > 0) return false;
1200     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1201     return Value > 0 && Value < 4096;
1202   }
1203 
1204   bool isImm0_7() const {
1205     return isImmediate<0, 7>();
1206   }
1207 
1208   bool isImm1_16() const {
1209     return isImmediate<1, 16>();
1210   }
1211 
1212   bool isImm1_32() const {
1213     return isImmediate<1, 32>();
1214   }
1215 
1216   bool isImm8_255() const {
1217     return isImmediate<8, 255>();
1218   }
1219 
1220   bool isImm256_65535Expr() const {
1221     if (!isImm()) return false;
1222     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1223     // If it's not a constant expression, it'll generate a fixup and be
1224     // handled later.
1225     if (!CE) return true;
1226     int64_t Value = CE->getValue();
1227     return Value >= 256 && Value < 65536;
1228   }
1229 
1230   bool isImm0_65535Expr() const {
1231     if (!isImm()) return false;
1232     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1233     // If it's not a constant expression, it'll generate a fixup and be
1234     // handled later.
1235     if (!CE) return true;
1236     int64_t Value = CE->getValue();
1237     return Value >= 0 && Value < 65536;
1238   }
1239 
1240   bool isImm24bit() const {
1241     return isImmediate<0, 0xffffff + 1>();
1242   }
1243 
1244   bool isImmThumbSR() const {
1245     return isImmediate<1, 33>();
1246   }
1247 
1248   template<int shift>
1249   bool isExpImmValue(uint64_t Value) const {
1250     uint64_t mask = (1 << shift) - 1;
1251     if ((Value & mask) != 0 || (Value >> shift) > 0xff)
1252       return false;
1253     return true;
1254   }
1255 
1256   template<int shift>
1257   bool isExpImm() const {
1258     if (!isImm()) return false;
1259     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1260     if (!CE) return false;
1261 
1262     return isExpImmValue<shift>(CE->getValue());
1263   }
1264 
1265   template<int shift, int size>
1266   bool isInvertedExpImm() const {
1267     if (!isImm()) return false;
1268     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1269     if (!CE) return false;
1270 
1271     uint64_t OriginalValue = CE->getValue();
1272     uint64_t InvertedValue = OriginalValue ^ (((uint64_t)1 << size) - 1);
1273     return isExpImmValue<shift>(InvertedValue);
1274   }
1275 
1276   bool isPKHLSLImm() const {
1277     return isImmediate<0, 32>();
1278   }
1279 
1280   bool isPKHASRImm() const {
1281     return isImmediate<0, 33>();
1282   }
1283 
1284   bool isAdrLabel() const {
1285     // If we have an immediate that's not a constant, treat it as a label
1286     // reference needing a fixup.
1287     if (isImm() && !isa<MCConstantExpr>(getImm()))
1288       return true;
1289 
1290     // If it is a constant, it must fit into a modified immediate encoding.
1291     if (!isImm()) return false;
1292     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1293     if (!CE) return false;
1294     int64_t Value = CE->getValue();
1295     return (ARM_AM::getSOImmVal(Value) != -1 ||
1296             ARM_AM::getSOImmVal(-Value) != -1);
1297   }
1298 
1299   bool isT2SOImm() const {
1300     // If we have an immediate that's not a constant, treat it as an expression
1301     // needing a fixup.
1302     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1303       // We want to avoid matching :upper16: and :lower16: as we want these
1304       // expressions to match in isImm0_65535Expr()
1305       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1306       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1307                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1308     }
1309     if (!isImm()) return false;
1310     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1311     if (!CE) return false;
1312     int64_t Value = CE->getValue();
1313     return ARM_AM::getT2SOImmVal(Value) != -1;
1314   }
1315 
1316   bool isT2SOImmNot() const {
1317     if (!isImm()) return false;
1318     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1319     if (!CE) return false;
1320     int64_t Value = CE->getValue();
1321     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1322       ARM_AM::getT2SOImmVal(~Value) != -1;
1323   }
1324 
1325   bool isT2SOImmNeg() const {
1326     if (!isImm()) return false;
1327     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1328     if (!CE) return false;
1329     int64_t Value = CE->getValue();
1330     // Only use this when not representable as a plain so_imm.
1331     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1332       ARM_AM::getT2SOImmVal(-Value) != -1;
1333   }
1334 
1335   bool isSetEndImm() const {
1336     if (!isImm()) return false;
1337     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1338     if (!CE) return false;
1339     int64_t Value = CE->getValue();
1340     return Value == 1 || Value == 0;
1341   }
1342 
1343   bool isReg() const override { return Kind == k_Register; }
1344   bool isRegList() const { return Kind == k_RegisterList; }
1345   bool isRegListWithAPSR() const {
1346     return Kind == k_RegisterListWithAPSR || Kind == k_RegisterList;
1347   }
1348   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1349   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1350   bool isFPSRegListWithVPR() const { return Kind == k_FPSRegisterListWithVPR; }
1351   bool isFPDRegListWithVPR() const { return Kind == k_FPDRegisterListWithVPR; }
1352   bool isToken() const override { return Kind == k_Token; }
1353   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1354   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1355   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
1356   bool isMem() const override {
1357       return isGPRMem() || isMVEMem();
1358   }
1359   bool isMVEMem() const {
1360     if (Kind != k_Memory)
1361       return false;
1362     if (Memory.BaseRegNum &&
1363         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum) &&
1364         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Memory.BaseRegNum))
1365       return false;
1366     if (Memory.OffsetRegNum &&
1367         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1368             Memory.OffsetRegNum))
1369       return false;
1370     return true;
1371   }
1372   bool isGPRMem() const {
1373     if (Kind != k_Memory)
1374       return false;
1375     if (Memory.BaseRegNum &&
1376         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1377       return false;
1378     if (Memory.OffsetRegNum &&
1379         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1380       return false;
1381     return true;
1382   }
1383   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1384   bool isRegShiftedReg() const {
1385     return Kind == k_ShiftedRegister &&
1386            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1387                RegShiftedReg.SrcReg) &&
1388            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1389                RegShiftedReg.ShiftReg);
1390   }
1391   bool isRegShiftedImm() const {
1392     return Kind == k_ShiftedImmediate &&
1393            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1394                RegShiftedImm.SrcReg);
1395   }
1396   bool isRotImm() const { return Kind == k_RotateImmediate; }
1397 
1398   template<unsigned Min, unsigned Max>
1399   bool isPowerTwoInRange() const {
1400     if (!isImm()) return false;
1401     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1402     if (!CE) return false;
1403     int64_t Value = CE->getValue();
1404     return Value > 0 && countPopulation((uint64_t)Value) == 1 &&
1405            Value >= Min && Value <= Max;
1406   }
1407   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1408 
1409   bool isModImmNot() const {
1410     if (!isImm()) return false;
1411     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1412     if (!CE) return false;
1413     int64_t Value = CE->getValue();
1414     return ARM_AM::getSOImmVal(~Value) != -1;
1415   }
1416 
1417   bool isModImmNeg() const {
1418     if (!isImm()) return false;
1419     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1420     if (!CE) return false;
1421     int64_t Value = CE->getValue();
1422     return ARM_AM::getSOImmVal(Value) == -1 &&
1423       ARM_AM::getSOImmVal(-Value) != -1;
1424   }
1425 
1426   bool isThumbModImmNeg1_7() const {
1427     if (!isImm()) return false;
1428     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1429     if (!CE) return false;
1430     int32_t Value = -(int32_t)CE->getValue();
1431     return 0 < Value && Value < 8;
1432   }
1433 
1434   bool isThumbModImmNeg8_255() const {
1435     if (!isImm()) return false;
1436     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1437     if (!CE) return false;
1438     int32_t Value = -(int32_t)CE->getValue();
1439     return 7 < Value && Value < 256;
1440   }
1441 
1442   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1443   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1444   bool isPostIdxRegShifted() const {
1445     return Kind == k_PostIndexRegister &&
1446            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1447   }
1448   bool isPostIdxReg() const {
1449     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1450   }
1451   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1452     if (!isGPRMem())
1453       return false;
1454     // No offset of any kind.
1455     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1456      (alignOK || Memory.Alignment == Alignment);
1457   }
1458   bool isMemNoOffsetT2(bool alignOK = false, unsigned Alignment = 0) const {
1459     if (!isGPRMem())
1460       return false;
1461 
1462     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1463             Memory.BaseRegNum))
1464       return false;
1465 
1466     // No offset of any kind.
1467     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1468      (alignOK || Memory.Alignment == Alignment);
1469   }
1470   bool isMemNoOffsetT2NoSp(bool alignOK = false, unsigned Alignment = 0) const {
1471     if (!isGPRMem())
1472       return false;
1473 
1474     if (!ARMMCRegisterClasses[ARM::rGPRRegClassID].contains(
1475             Memory.BaseRegNum))
1476       return false;
1477 
1478     // No offset of any kind.
1479     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1480      (alignOK || Memory.Alignment == Alignment);
1481   }
1482   bool isMemNoOffsetT(bool alignOK = false, unsigned Alignment = 0) const {
1483     if (!isGPRMem())
1484       return false;
1485 
1486     if (!ARMMCRegisterClasses[ARM::tGPRRegClassID].contains(
1487             Memory.BaseRegNum))
1488       return false;
1489 
1490     // No offset of any kind.
1491     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1492      (alignOK || Memory.Alignment == Alignment);
1493   }
1494   bool isMemPCRelImm12() const {
1495     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1496       return false;
1497     // Base register must be PC.
1498     if (Memory.BaseRegNum != ARM::PC)
1499       return false;
1500     // Immediate offset in range [-4095, 4095].
1501     if (!Memory.OffsetImm) return true;
1502     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1503       int64_t Val = CE->getValue();
1504       return (Val > -4096 && Val < 4096) ||
1505              (Val == std::numeric_limits<int32_t>::min());
1506     }
1507     return false;
1508   }
1509 
1510   bool isAlignedMemory() const {
1511     return isMemNoOffset(true);
1512   }
1513 
1514   bool isAlignedMemoryNone() const {
1515     return isMemNoOffset(false, 0);
1516   }
1517 
1518   bool isDupAlignedMemoryNone() const {
1519     return isMemNoOffset(false, 0);
1520   }
1521 
1522   bool isAlignedMemory16() 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 isDupAlignedMemory16() const {
1529     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1530       return true;
1531     return isMemNoOffset(false, 0);
1532   }
1533 
1534   bool isAlignedMemory32() 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 isDupAlignedMemory32() const {
1541     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1542       return true;
1543     return isMemNoOffset(false, 0);
1544   }
1545 
1546   bool isAlignedMemory64() 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 isDupAlignedMemory64() const {
1553     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1554       return true;
1555     return isMemNoOffset(false, 0);
1556   }
1557 
1558   bool isAlignedMemory64or128() const {
1559     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1560       return true;
1561     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1562       return true;
1563     return isMemNoOffset(false, 0);
1564   }
1565 
1566   bool isDupAlignedMemory64or128() const {
1567     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1568       return true;
1569     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1570       return true;
1571     return isMemNoOffset(false, 0);
1572   }
1573 
1574   bool isAlignedMemory64or128or256() const {
1575     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1576       return true;
1577     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1578       return true;
1579     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1580       return true;
1581     return isMemNoOffset(false, 0);
1582   }
1583 
1584   bool isAddrMode2() const {
1585     if (!isGPRMem() || Memory.Alignment != 0) return false;
1586     // Check for register offset.
1587     if (Memory.OffsetRegNum) return true;
1588     // Immediate offset in range [-4095, 4095].
1589     if (!Memory.OffsetImm) return true;
1590     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1591       int64_t Val = CE->getValue();
1592       return Val > -4096 && Val < 4096;
1593     }
1594     return false;
1595   }
1596 
1597   bool isAM2OffsetImm() const {
1598     if (!isImm()) return false;
1599     // Immediate offset in range [-4095, 4095].
1600     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1601     if (!CE) return false;
1602     int64_t Val = CE->getValue();
1603     return (Val == std::numeric_limits<int32_t>::min()) ||
1604            (Val > -4096 && Val < 4096);
1605   }
1606 
1607   bool isAddrMode3() const {
1608     // If we have an immediate that's not a constant, treat it as a label
1609     // reference needing a fixup. If it is a constant, it's something else
1610     // and we reject it.
1611     if (isImm() && !isa<MCConstantExpr>(getImm()))
1612       return true;
1613     if (!isGPRMem() || Memory.Alignment != 0) return false;
1614     // No shifts are legal for AM3.
1615     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1616     // Check for register offset.
1617     if (Memory.OffsetRegNum) return true;
1618     // Immediate offset in range [-255, 255].
1619     if (!Memory.OffsetImm) return true;
1620     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1621       int64_t Val = CE->getValue();
1622       // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and
1623       // we have to check for this too.
1624       return (Val > -256 && Val < 256) ||
1625              Val == std::numeric_limits<int32_t>::min();
1626     }
1627     return false;
1628   }
1629 
1630   bool isAM3Offset() const {
1631     if (isPostIdxReg())
1632       return true;
1633     if (!isImm())
1634       return false;
1635     // Immediate offset in range [-255, 255].
1636     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1637     if (!CE) return false;
1638     int64_t Val = CE->getValue();
1639     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1640     return (Val > -256 && Val < 256) ||
1641            Val == std::numeric_limits<int32_t>::min();
1642   }
1643 
1644   bool isAddrMode5() const {
1645     // If we have an immediate that's not a constant, treat it as a label
1646     // reference needing a fixup. If it is a constant, it's something else
1647     // and we reject it.
1648     if (isImm() && !isa<MCConstantExpr>(getImm()))
1649       return true;
1650     if (!isGPRMem() || Memory.Alignment != 0) return false;
1651     // Check for register offset.
1652     if (Memory.OffsetRegNum) return false;
1653     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1654     if (!Memory.OffsetImm) return true;
1655     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1656       int64_t Val = CE->getValue();
1657       return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1658              Val == std::numeric_limits<int32_t>::min();
1659     }
1660     return false;
1661   }
1662 
1663   bool isAddrMode5FP16() const {
1664     // If we have an immediate that's not a constant, treat it as a label
1665     // reference needing a fixup. If it is a constant, it's something else
1666     // and we reject it.
1667     if (isImm() && !isa<MCConstantExpr>(getImm()))
1668       return true;
1669     if (!isGPRMem() || Memory.Alignment != 0) return false;
1670     // Check for register offset.
1671     if (Memory.OffsetRegNum) return false;
1672     // Immediate offset in range [-510, 510] and a multiple of 2.
1673     if (!Memory.OffsetImm) return true;
1674     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1675       int64_t Val = CE->getValue();
1676       return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1677              Val == std::numeric_limits<int32_t>::min();
1678     }
1679     return false;
1680   }
1681 
1682   bool isMemTBB() const {
1683     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1684         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1685       return false;
1686     return true;
1687   }
1688 
1689   bool isMemTBH() const {
1690     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1691         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1692         Memory.Alignment != 0 )
1693       return false;
1694     return true;
1695   }
1696 
1697   bool isMemRegOffset() const {
1698     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1699       return false;
1700     return true;
1701   }
1702 
1703   bool isT2MemRegOffset() const {
1704     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1705         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1706       return false;
1707     // Only lsl #{0, 1, 2, 3} allowed.
1708     if (Memory.ShiftType == ARM_AM::no_shift)
1709       return true;
1710     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1711       return false;
1712     return true;
1713   }
1714 
1715   bool isMemThumbRR() const {
1716     // Thumb reg+reg addressing is simple. Just two registers, a base and
1717     // an offset. No shifts, negations or any other complicating factors.
1718     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1719         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1720       return false;
1721     return isARMLowRegister(Memory.BaseRegNum) &&
1722       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1723   }
1724 
1725   bool isMemThumbRIs4() const {
1726     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1727         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1728       return false;
1729     // Immediate offset, multiple of 4 in range [0, 124].
1730     if (!Memory.OffsetImm) return true;
1731     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1732       int64_t Val = CE->getValue();
1733       return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1734     }
1735     return false;
1736   }
1737 
1738   bool isMemThumbRIs2() const {
1739     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1740         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1741       return false;
1742     // Immediate offset, multiple of 4 in range [0, 62].
1743     if (!Memory.OffsetImm) return true;
1744     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1745       int64_t Val = CE->getValue();
1746       return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1747     }
1748     return false;
1749   }
1750 
1751   bool isMemThumbRIs1() const {
1752     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1753         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1754       return false;
1755     // Immediate offset in range [0, 31].
1756     if (!Memory.OffsetImm) return true;
1757     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1758       int64_t Val = CE->getValue();
1759       return Val >= 0 && Val <= 31;
1760     }
1761     return false;
1762   }
1763 
1764   bool isMemThumbSPI() const {
1765     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1766         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1767       return false;
1768     // Immediate offset, multiple of 4 in range [0, 1020].
1769     if (!Memory.OffsetImm) return true;
1770     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1771       int64_t Val = CE->getValue();
1772       return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1773     }
1774     return false;
1775   }
1776 
1777   bool isMemImm8s4Offset() const {
1778     // If we have an immediate that's not a constant, treat it as a label
1779     // reference needing a fixup. If it is a constant, it's something else
1780     // and we reject it.
1781     if (isImm() && !isa<MCConstantExpr>(getImm()))
1782       return true;
1783     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1784       return false;
1785     // Immediate offset a multiple of 4 in range [-1020, 1020].
1786     if (!Memory.OffsetImm) return true;
1787     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1788       int64_t Val = CE->getValue();
1789       // Special case, #-0 is std::numeric_limits<int32_t>::min().
1790       return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1791              Val == std::numeric_limits<int32_t>::min();
1792     }
1793     return false;
1794   }
1795 
1796   bool isMemImm7s4Offset() const {
1797     // If we have an immediate that's not a constant, treat it as a label
1798     // reference needing a fixup. If it is a constant, it's something else
1799     // and we reject it.
1800     if (isImm() && !isa<MCConstantExpr>(getImm()))
1801       return true;
1802     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1803         !ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1804             Memory.BaseRegNum))
1805       return false;
1806     // Immediate offset a multiple of 4 in range [-508, 508].
1807     if (!Memory.OffsetImm) return true;
1808     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1809       int64_t Val = CE->getValue();
1810       // Special case, #-0 is INT32_MIN.
1811       return (Val >= -508 && Val <= 508 && (Val & 3) == 0) || Val == INT32_MIN;
1812     }
1813     return false;
1814   }
1815 
1816   bool isMemImm0_1020s4Offset() const {
1817     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1818       return false;
1819     // Immediate offset a multiple of 4 in range [0, 1020].
1820     if (!Memory.OffsetImm) return true;
1821     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1822       int64_t Val = CE->getValue();
1823       return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1824     }
1825     return false;
1826   }
1827 
1828   bool isMemImm8Offset() const {
1829     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1830       return false;
1831     // Base reg of PC isn't allowed for these encodings.
1832     if (Memory.BaseRegNum == ARM::PC) return false;
1833     // Immediate offset in range [-255, 255].
1834     if (!Memory.OffsetImm) return true;
1835     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1836       int64_t Val = CE->getValue();
1837       return (Val == std::numeric_limits<int32_t>::min()) ||
1838              (Val > -256 && Val < 256);
1839     }
1840     return false;
1841   }
1842 
1843   template<unsigned Bits, unsigned RegClassID>
1844   bool isMemImm7ShiftedOffset() const {
1845     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1846         !ARMMCRegisterClasses[RegClassID].contains(Memory.BaseRegNum))
1847       return false;
1848 
1849     // Expect an immediate offset equal to an element of the range
1850     // [-127, 127], shifted left by Bits.
1851 
1852     if (!Memory.OffsetImm) return true;
1853     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1854       int64_t Val = CE->getValue();
1855 
1856       // INT32_MIN is a special-case value (indicating the encoding with
1857       // zero offset and the subtract bit set)
1858       if (Val == INT32_MIN)
1859         return true;
1860 
1861       unsigned Divisor = 1U << Bits;
1862 
1863       // Check that the low bits are zero
1864       if (Val % Divisor != 0)
1865         return false;
1866 
1867       // Check that the remaining offset is within range.
1868       Val /= Divisor;
1869       return (Val >= -127 && Val <= 127);
1870     }
1871     return false;
1872   }
1873 
1874   template <int shift> bool isMemRegRQOffset() const {
1875     if (!isMVEMem() || Memory.OffsetImm != 0 || Memory.Alignment != 0)
1876       return false;
1877 
1878     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1879             Memory.BaseRegNum))
1880       return false;
1881     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1882             Memory.OffsetRegNum))
1883       return false;
1884 
1885     if (shift == 0 && Memory.ShiftType != ARM_AM::no_shift)
1886       return false;
1887 
1888     if (shift > 0 &&
1889         (Memory.ShiftType != ARM_AM::uxtw || Memory.ShiftImm != shift))
1890       return false;
1891 
1892     return true;
1893   }
1894 
1895   template <int shift> bool isMemRegQOffset() const {
1896     if (!isMVEMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1897       return false;
1898 
1899     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1900             Memory.BaseRegNum))
1901       return false;
1902 
1903     if (!Memory.OffsetImm)
1904       return true;
1905     static_assert(shift < 56,
1906                   "Such that we dont shift by a value higher than 62");
1907     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1908       int64_t Val = CE->getValue();
1909 
1910       // The value must be a multiple of (1 << shift)
1911       if ((Val & ((1U << shift) - 1)) != 0)
1912         return false;
1913 
1914       // And be in the right range, depending on the amount that it is shifted
1915       // by.  Shift 0, is equal to 7 unsigned bits, the sign bit is set
1916       // separately.
1917       int64_t Range = (1U << (7 + shift)) - 1;
1918       return (Val == INT32_MIN) || (Val > -Range && Val < Range);
1919     }
1920     return false;
1921   }
1922 
1923   bool isMemPosImm8Offset() const {
1924     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1925       return false;
1926     // Immediate offset in range [0, 255].
1927     if (!Memory.OffsetImm) return true;
1928     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1929       int64_t Val = CE->getValue();
1930       return Val >= 0 && Val < 256;
1931     }
1932     return false;
1933   }
1934 
1935   bool isMemNegImm8Offset() const {
1936     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1937       return false;
1938     // Base reg of PC isn't allowed for these encodings.
1939     if (Memory.BaseRegNum == ARM::PC) return false;
1940     // Immediate offset in range [-255, -1].
1941     if (!Memory.OffsetImm) return false;
1942     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1943       int64_t Val = CE->getValue();
1944       return (Val == std::numeric_limits<int32_t>::min()) ||
1945              (Val > -256 && Val < 0);
1946     }
1947     return false;
1948   }
1949 
1950   bool isMemUImm12Offset() const {
1951     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1952       return false;
1953     // Immediate offset in range [0, 4095].
1954     if (!Memory.OffsetImm) return true;
1955     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1956       int64_t Val = CE->getValue();
1957       return (Val >= 0 && Val < 4096);
1958     }
1959     return false;
1960   }
1961 
1962   bool isMemImm12Offset() const {
1963     // If we have an immediate that's not a constant, treat it as a label
1964     // reference needing a fixup. If it is a constant, it's something else
1965     // and we reject it.
1966 
1967     if (isImm() && !isa<MCConstantExpr>(getImm()))
1968       return true;
1969 
1970     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1971       return false;
1972     // Immediate offset in range [-4095, 4095].
1973     if (!Memory.OffsetImm) return true;
1974     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1975       int64_t Val = CE->getValue();
1976       return (Val > -4096 && Val < 4096) ||
1977              (Val == std::numeric_limits<int32_t>::min());
1978     }
1979     // If we have an immediate that's not a constant, treat it as a
1980     // symbolic expression needing a fixup.
1981     return true;
1982   }
1983 
1984   bool isConstPoolAsmImm() const {
1985     // Delay processing of Constant Pool Immediate, this will turn into
1986     // a constant. Match no other operand
1987     return (isConstantPoolImm());
1988   }
1989 
1990   bool isPostIdxImm8() const {
1991     if (!isImm()) return false;
1992     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1993     if (!CE) return false;
1994     int64_t Val = CE->getValue();
1995     return (Val > -256 && Val < 256) ||
1996            (Val == std::numeric_limits<int32_t>::min());
1997   }
1998 
1999   bool isPostIdxImm8s4() const {
2000     if (!isImm()) return false;
2001     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2002     if (!CE) return false;
2003     int64_t Val = CE->getValue();
2004     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
2005            (Val == std::numeric_limits<int32_t>::min());
2006   }
2007 
2008   bool isMSRMask() const { return Kind == k_MSRMask; }
2009   bool isBankedReg() const { return Kind == k_BankedReg; }
2010   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
2011 
2012   // NEON operands.
2013   bool isSingleSpacedVectorList() const {
2014     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
2015   }
2016 
2017   bool isDoubleSpacedVectorList() const {
2018     return Kind == k_VectorList && VectorList.isDoubleSpaced;
2019   }
2020 
2021   bool isVecListOneD() const {
2022     if (!isSingleSpacedVectorList()) return false;
2023     return VectorList.Count == 1;
2024   }
2025 
2026   bool isVecListTwoMQ() const {
2027     return isSingleSpacedVectorList() && VectorList.Count == 2 &&
2028            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
2029                VectorList.RegNum);
2030   }
2031 
2032   bool isVecListDPair() const {
2033     if (!isSingleSpacedVectorList()) return false;
2034     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
2035               .contains(VectorList.RegNum));
2036   }
2037 
2038   bool isVecListThreeD() const {
2039     if (!isSingleSpacedVectorList()) return false;
2040     return VectorList.Count == 3;
2041   }
2042 
2043   bool isVecListFourD() const {
2044     if (!isSingleSpacedVectorList()) return false;
2045     return VectorList.Count == 4;
2046   }
2047 
2048   bool isVecListDPairSpaced() const {
2049     if (Kind != k_VectorList) return false;
2050     if (isSingleSpacedVectorList()) return false;
2051     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
2052               .contains(VectorList.RegNum));
2053   }
2054 
2055   bool isVecListThreeQ() const {
2056     if (!isDoubleSpacedVectorList()) return false;
2057     return VectorList.Count == 3;
2058   }
2059 
2060   bool isVecListFourQ() const {
2061     if (!isDoubleSpacedVectorList()) return false;
2062     return VectorList.Count == 4;
2063   }
2064 
2065   bool isVecListFourMQ() const {
2066     return isSingleSpacedVectorList() && VectorList.Count == 4 &&
2067            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
2068                VectorList.RegNum);
2069   }
2070 
2071   bool isSingleSpacedVectorAllLanes() const {
2072     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
2073   }
2074 
2075   bool isDoubleSpacedVectorAllLanes() const {
2076     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
2077   }
2078 
2079   bool isVecListOneDAllLanes() const {
2080     if (!isSingleSpacedVectorAllLanes()) return false;
2081     return VectorList.Count == 1;
2082   }
2083 
2084   bool isVecListDPairAllLanes() const {
2085     if (!isSingleSpacedVectorAllLanes()) return false;
2086     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
2087               .contains(VectorList.RegNum));
2088   }
2089 
2090   bool isVecListDPairSpacedAllLanes() const {
2091     if (!isDoubleSpacedVectorAllLanes()) return false;
2092     return VectorList.Count == 2;
2093   }
2094 
2095   bool isVecListThreeDAllLanes() const {
2096     if (!isSingleSpacedVectorAllLanes()) return false;
2097     return VectorList.Count == 3;
2098   }
2099 
2100   bool isVecListThreeQAllLanes() const {
2101     if (!isDoubleSpacedVectorAllLanes()) return false;
2102     return VectorList.Count == 3;
2103   }
2104 
2105   bool isVecListFourDAllLanes() const {
2106     if (!isSingleSpacedVectorAllLanes()) return false;
2107     return VectorList.Count == 4;
2108   }
2109 
2110   bool isVecListFourQAllLanes() const {
2111     if (!isDoubleSpacedVectorAllLanes()) return false;
2112     return VectorList.Count == 4;
2113   }
2114 
2115   bool isSingleSpacedVectorIndexed() const {
2116     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
2117   }
2118 
2119   bool isDoubleSpacedVectorIndexed() const {
2120     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
2121   }
2122 
2123   bool isVecListOneDByteIndexed() const {
2124     if (!isSingleSpacedVectorIndexed()) return false;
2125     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
2126   }
2127 
2128   bool isVecListOneDHWordIndexed() const {
2129     if (!isSingleSpacedVectorIndexed()) return false;
2130     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
2131   }
2132 
2133   bool isVecListOneDWordIndexed() const {
2134     if (!isSingleSpacedVectorIndexed()) return false;
2135     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
2136   }
2137 
2138   bool isVecListTwoDByteIndexed() const {
2139     if (!isSingleSpacedVectorIndexed()) return false;
2140     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
2141   }
2142 
2143   bool isVecListTwoDHWordIndexed() const {
2144     if (!isSingleSpacedVectorIndexed()) return false;
2145     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2146   }
2147 
2148   bool isVecListTwoQWordIndexed() const {
2149     if (!isDoubleSpacedVectorIndexed()) return false;
2150     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2151   }
2152 
2153   bool isVecListTwoQHWordIndexed() const {
2154     if (!isDoubleSpacedVectorIndexed()) return false;
2155     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2156   }
2157 
2158   bool isVecListTwoDWordIndexed() const {
2159     if (!isSingleSpacedVectorIndexed()) return false;
2160     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2161   }
2162 
2163   bool isVecListThreeDByteIndexed() const {
2164     if (!isSingleSpacedVectorIndexed()) return false;
2165     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
2166   }
2167 
2168   bool isVecListThreeDHWordIndexed() const {
2169     if (!isSingleSpacedVectorIndexed()) return false;
2170     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2171   }
2172 
2173   bool isVecListThreeQWordIndexed() const {
2174     if (!isDoubleSpacedVectorIndexed()) return false;
2175     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2176   }
2177 
2178   bool isVecListThreeQHWordIndexed() const {
2179     if (!isDoubleSpacedVectorIndexed()) return false;
2180     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2181   }
2182 
2183   bool isVecListThreeDWordIndexed() const {
2184     if (!isSingleSpacedVectorIndexed()) return false;
2185     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2186   }
2187 
2188   bool isVecListFourDByteIndexed() const {
2189     if (!isSingleSpacedVectorIndexed()) return false;
2190     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
2191   }
2192 
2193   bool isVecListFourDHWordIndexed() const {
2194     if (!isSingleSpacedVectorIndexed()) return false;
2195     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2196   }
2197 
2198   bool isVecListFourQWordIndexed() const {
2199     if (!isDoubleSpacedVectorIndexed()) return false;
2200     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2201   }
2202 
2203   bool isVecListFourQHWordIndexed() const {
2204     if (!isDoubleSpacedVectorIndexed()) return false;
2205     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2206   }
2207 
2208   bool isVecListFourDWordIndexed() const {
2209     if (!isSingleSpacedVectorIndexed()) return false;
2210     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2211   }
2212 
2213   bool isVectorIndex() const { return Kind == k_VectorIndex; }
2214 
2215   template <unsigned NumLanes>
2216   bool isVectorIndexInRange() const {
2217     if (Kind != k_VectorIndex) return false;
2218     return VectorIndex.Val < NumLanes;
2219   }
2220 
2221   bool isVectorIndex8()  const { return isVectorIndexInRange<8>(); }
2222   bool isVectorIndex16() const { return isVectorIndexInRange<4>(); }
2223   bool isVectorIndex32() const { return isVectorIndexInRange<2>(); }
2224   bool isVectorIndex64() const { return isVectorIndexInRange<1>(); }
2225 
2226   template<int PermittedValue, int OtherPermittedValue>
2227   bool isMVEPairVectorIndex() const {
2228     if (Kind != k_VectorIndex) return false;
2229     return VectorIndex.Val == PermittedValue ||
2230            VectorIndex.Val == OtherPermittedValue;
2231   }
2232 
2233   bool isNEONi8splat() const {
2234     if (!isImm()) return false;
2235     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2236     // Must be a constant.
2237     if (!CE) return false;
2238     int64_t Value = CE->getValue();
2239     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
2240     // value.
2241     return Value >= 0 && Value < 256;
2242   }
2243 
2244   bool isNEONi16splat() const {
2245     if (isNEONByteReplicate(2))
2246       return false; // Leave that for bytes replication and forbid by default.
2247     if (!isImm())
2248       return false;
2249     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2250     // Must be a constant.
2251     if (!CE) return false;
2252     unsigned Value = CE->getValue();
2253     return ARM_AM::isNEONi16splat(Value);
2254   }
2255 
2256   bool isNEONi16splatNot() const {
2257     if (!isImm())
2258       return false;
2259     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2260     // Must be a constant.
2261     if (!CE) return false;
2262     unsigned Value = CE->getValue();
2263     return ARM_AM::isNEONi16splat(~Value & 0xffff);
2264   }
2265 
2266   bool isNEONi32splat() const {
2267     if (isNEONByteReplicate(4))
2268       return false; // Leave that for bytes replication and forbid by default.
2269     if (!isImm())
2270       return false;
2271     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2272     // Must be a constant.
2273     if (!CE) return false;
2274     unsigned Value = CE->getValue();
2275     return ARM_AM::isNEONi32splat(Value);
2276   }
2277 
2278   bool isNEONi32splatNot() const {
2279     if (!isImm())
2280       return false;
2281     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2282     // Must be a constant.
2283     if (!CE) return false;
2284     unsigned Value = CE->getValue();
2285     return ARM_AM::isNEONi32splat(~Value);
2286   }
2287 
2288   static bool isValidNEONi32vmovImm(int64_t Value) {
2289     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
2290     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
2291     return ((Value & 0xffffffffffffff00) == 0) ||
2292            ((Value & 0xffffffffffff00ff) == 0) ||
2293            ((Value & 0xffffffffff00ffff) == 0) ||
2294            ((Value & 0xffffffff00ffffff) == 0) ||
2295            ((Value & 0xffffffffffff00ff) == 0xff) ||
2296            ((Value & 0xffffffffff00ffff) == 0xffff);
2297   }
2298 
2299   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
2300     assert((Width == 8 || Width == 16 || Width == 32) &&
2301            "Invalid element width");
2302     assert(NumElems * Width <= 64 && "Invalid result width");
2303 
2304     if (!isImm())
2305       return false;
2306     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2307     // Must be a constant.
2308     if (!CE)
2309       return false;
2310     int64_t Value = CE->getValue();
2311     if (!Value)
2312       return false; // Don't bother with zero.
2313     if (Inv)
2314       Value = ~Value;
2315 
2316     uint64_t Mask = (1ull << Width) - 1;
2317     uint64_t Elem = Value & Mask;
2318     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
2319       return false;
2320     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
2321       return false;
2322 
2323     for (unsigned i = 1; i < NumElems; ++i) {
2324       Value >>= Width;
2325       if ((Value & Mask) != Elem)
2326         return false;
2327     }
2328     return true;
2329   }
2330 
2331   bool isNEONByteReplicate(unsigned NumBytes) const {
2332     return isNEONReplicate(8, NumBytes, false);
2333   }
2334 
2335   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
2336     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
2337            "Invalid source width");
2338     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
2339            "Invalid destination width");
2340     assert(FromW < ToW && "ToW is not less than FromW");
2341   }
2342 
2343   template<unsigned FromW, unsigned ToW>
2344   bool isNEONmovReplicate() const {
2345     checkNeonReplicateArgs(FromW, ToW);
2346     if (ToW == 64 && isNEONi64splat())
2347       return false;
2348     return isNEONReplicate(FromW, ToW / FromW, false);
2349   }
2350 
2351   template<unsigned FromW, unsigned ToW>
2352   bool isNEONinvReplicate() const {
2353     checkNeonReplicateArgs(FromW, ToW);
2354     return isNEONReplicate(FromW, ToW / FromW, true);
2355   }
2356 
2357   bool isNEONi32vmov() const {
2358     if (isNEONByteReplicate(4))
2359       return false; // Let it to be classified as byte-replicate case.
2360     if (!isImm())
2361       return false;
2362     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2363     // Must be a constant.
2364     if (!CE)
2365       return false;
2366     return isValidNEONi32vmovImm(CE->getValue());
2367   }
2368 
2369   bool isNEONi32vmovNeg() const {
2370     if (!isImm()) return false;
2371     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2372     // Must be a constant.
2373     if (!CE) return false;
2374     return isValidNEONi32vmovImm(~CE->getValue());
2375   }
2376 
2377   bool isNEONi64splat() const {
2378     if (!isImm()) return false;
2379     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2380     // Must be a constant.
2381     if (!CE) return false;
2382     uint64_t Value = CE->getValue();
2383     // i64 value with each byte being either 0 or 0xff.
2384     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
2385       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
2386     return true;
2387   }
2388 
2389   template<int64_t Angle, int64_t Remainder>
2390   bool isComplexRotation() const {
2391     if (!isImm()) return false;
2392 
2393     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2394     if (!CE) return false;
2395     uint64_t Value = CE->getValue();
2396 
2397     return (Value % Angle == Remainder && Value <= 270);
2398   }
2399 
2400   bool isMVELongShift() const {
2401     if (!isImm()) return false;
2402     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2403     // Must be a constant.
2404     if (!CE) return false;
2405     uint64_t Value = CE->getValue();
2406     return Value >= 1 && Value <= 32;
2407   }
2408 
2409   bool isMveSaturateOp() const {
2410     if (!isImm()) return false;
2411     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2412     if (!CE) return false;
2413     uint64_t Value = CE->getValue();
2414     return Value == 48 || Value == 64;
2415   }
2416 
2417   bool isITCondCodeNoAL() const {
2418     if (!isITCondCode()) return false;
2419     ARMCC::CondCodes CC = getCondCode();
2420     return CC != ARMCC::AL;
2421   }
2422 
2423   bool isITCondCodeRestrictedI() const {
2424     if (!isITCondCode())
2425       return false;
2426     ARMCC::CondCodes CC = getCondCode();
2427     return CC == ARMCC::EQ || CC == ARMCC::NE;
2428   }
2429 
2430   bool isITCondCodeRestrictedS() const {
2431     if (!isITCondCode())
2432       return false;
2433     ARMCC::CondCodes CC = getCondCode();
2434     return CC == ARMCC::LT || CC == ARMCC::GT || CC == ARMCC::LE ||
2435            CC == ARMCC::GE;
2436   }
2437 
2438   bool isITCondCodeRestrictedU() const {
2439     if (!isITCondCode())
2440       return false;
2441     ARMCC::CondCodes CC = getCondCode();
2442     return CC == ARMCC::HS || CC == ARMCC::HI;
2443   }
2444 
2445   bool isITCondCodeRestrictedFP() const {
2446     if (!isITCondCode())
2447       return false;
2448     ARMCC::CondCodes CC = getCondCode();
2449     return CC == ARMCC::EQ || CC == ARMCC::NE || CC == ARMCC::LT ||
2450            CC == ARMCC::GT || CC == ARMCC::LE || CC == ARMCC::GE;
2451   }
2452 
2453   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
2454     // Add as immediates when possible.  Null MCExpr = 0.
2455     if (!Expr)
2456       Inst.addOperand(MCOperand::createImm(0));
2457     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2458       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2459     else
2460       Inst.addOperand(MCOperand::createExpr(Expr));
2461   }
2462 
2463   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2464     assert(N == 1 && "Invalid number of operands!");
2465     addExpr(Inst, getImm());
2466   }
2467 
2468   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2469     assert(N == 1 && "Invalid number of operands!");
2470     addExpr(Inst, getImm());
2471   }
2472 
2473   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2474     assert(N == 2 && "Invalid number of operands!");
2475     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2476     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2477     Inst.addOperand(MCOperand::createReg(RegNum));
2478   }
2479 
2480   void addVPTPredNOperands(MCInst &Inst, unsigned N) const {
2481     assert(N == 3 && "Invalid number of operands!");
2482     Inst.addOperand(MCOperand::createImm(unsigned(getVPTPred())));
2483     unsigned RegNum = getVPTPred() == ARMVCC::None ? 0: ARM::P0;
2484     Inst.addOperand(MCOperand::createReg(RegNum));
2485     Inst.addOperand(MCOperand::createReg(0));
2486   }
2487 
2488   void addVPTPredROperands(MCInst &Inst, unsigned N) const {
2489     assert(N == 4 && "Invalid number of operands!");
2490     addVPTPredNOperands(Inst, N-1);
2491     unsigned RegNum;
2492     if (getVPTPred() == ARMVCC::None) {
2493       RegNum = 0;
2494     } else {
2495       unsigned NextOpIndex = Inst.getNumOperands();
2496       const MCInstrDesc &MCID = ARMInsts[Inst.getOpcode()];
2497       int TiedOp = MCID.getOperandConstraint(NextOpIndex, MCOI::TIED_TO);
2498       assert(TiedOp >= 0 &&
2499              "Inactive register in vpred_r is not tied to an output!");
2500       RegNum = Inst.getOperand(TiedOp).getReg();
2501     }
2502     Inst.addOperand(MCOperand::createReg(RegNum));
2503   }
2504 
2505   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2506     assert(N == 1 && "Invalid number of operands!");
2507     Inst.addOperand(MCOperand::createImm(getCoproc()));
2508   }
2509 
2510   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2511     assert(N == 1 && "Invalid number of operands!");
2512     Inst.addOperand(MCOperand::createImm(getCoproc()));
2513   }
2514 
2515   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2516     assert(N == 1 && "Invalid number of operands!");
2517     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2518   }
2519 
2520   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2521     assert(N == 1 && "Invalid number of operands!");
2522     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2523   }
2524 
2525   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2526     assert(N == 1 && "Invalid number of operands!");
2527     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2528   }
2529 
2530   void addITCondCodeInvOperands(MCInst &Inst, unsigned N) const {
2531     assert(N == 1 && "Invalid number of operands!");
2532     Inst.addOperand(MCOperand::createImm(unsigned(ARMCC::getOppositeCondition(getCondCode()))));
2533   }
2534 
2535   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2536     assert(N == 1 && "Invalid number of operands!");
2537     Inst.addOperand(MCOperand::createReg(getReg()));
2538   }
2539 
2540   void addRegOperands(MCInst &Inst, unsigned N) const {
2541     assert(N == 1 && "Invalid number of operands!");
2542     Inst.addOperand(MCOperand::createReg(getReg()));
2543   }
2544 
2545   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2546     assert(N == 3 && "Invalid number of operands!");
2547     assert(isRegShiftedReg() &&
2548            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2549     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2550     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2551     Inst.addOperand(MCOperand::createImm(
2552       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2553   }
2554 
2555   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2556     assert(N == 2 && "Invalid number of operands!");
2557     assert(isRegShiftedImm() &&
2558            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2559     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2560     // Shift of #32 is encoded as 0 where permitted
2561     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2562     Inst.addOperand(MCOperand::createImm(
2563       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2564   }
2565 
2566   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2567     assert(N == 1 && "Invalid number of operands!");
2568     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2569                                          ShifterImm.Imm));
2570   }
2571 
2572   void addRegListOperands(MCInst &Inst, unsigned N) const {
2573     assert(N == 1 && "Invalid number of operands!");
2574     const SmallVectorImpl<unsigned> &RegList = getRegList();
2575     for (SmallVectorImpl<unsigned>::const_iterator
2576            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2577       Inst.addOperand(MCOperand::createReg(*I));
2578   }
2579 
2580   void addRegListWithAPSROperands(MCInst &Inst, unsigned N) const {
2581     assert(N == 1 && "Invalid number of operands!");
2582     const SmallVectorImpl<unsigned> &RegList = getRegList();
2583     for (SmallVectorImpl<unsigned>::const_iterator
2584            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2585       Inst.addOperand(MCOperand::createReg(*I));
2586   }
2587 
2588   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2589     addRegListOperands(Inst, N);
2590   }
2591 
2592   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2593     addRegListOperands(Inst, N);
2594   }
2595 
2596   void addFPSRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2597     addRegListOperands(Inst, N);
2598   }
2599 
2600   void addFPDRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2601     addRegListOperands(Inst, N);
2602   }
2603 
2604   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2605     assert(N == 1 && "Invalid number of operands!");
2606     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2607     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2608   }
2609 
2610   void addModImmOperands(MCInst &Inst, unsigned N) const {
2611     assert(N == 1 && "Invalid number of operands!");
2612 
2613     // Support for fixups (MCFixup)
2614     if (isImm())
2615       return addImmOperands(Inst, N);
2616 
2617     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2618   }
2619 
2620   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2621     assert(N == 1 && "Invalid number of operands!");
2622     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2623     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2624     Inst.addOperand(MCOperand::createImm(Enc));
2625   }
2626 
2627   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2628     assert(N == 1 && "Invalid number of operands!");
2629     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2630     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2631     Inst.addOperand(MCOperand::createImm(Enc));
2632   }
2633 
2634   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2635     assert(N == 1 && "Invalid number of operands!");
2636     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2637     uint32_t Val = -CE->getValue();
2638     Inst.addOperand(MCOperand::createImm(Val));
2639   }
2640 
2641   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2642     assert(N == 1 && "Invalid number of operands!");
2643     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2644     uint32_t Val = -CE->getValue();
2645     Inst.addOperand(MCOperand::createImm(Val));
2646   }
2647 
2648   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2649     assert(N == 1 && "Invalid number of operands!");
2650     // Munge the lsb/width into a bitfield mask.
2651     unsigned lsb = Bitfield.LSB;
2652     unsigned width = Bitfield.Width;
2653     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2654     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2655                       (32 - (lsb + width)));
2656     Inst.addOperand(MCOperand::createImm(Mask));
2657   }
2658 
2659   void addImmOperands(MCInst &Inst, unsigned N) const {
2660     assert(N == 1 && "Invalid number of operands!");
2661     addExpr(Inst, getImm());
2662   }
2663 
2664   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2665     assert(N == 1 && "Invalid number of operands!");
2666     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2667     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2668   }
2669 
2670   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2671     assert(N == 1 && "Invalid number of operands!");
2672     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2673     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2674   }
2675 
2676   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2677     assert(N == 1 && "Invalid number of operands!");
2678     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2679     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2680     Inst.addOperand(MCOperand::createImm(Val));
2681   }
2682 
2683   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2684     assert(N == 1 && "Invalid number of operands!");
2685     // FIXME: We really want to scale the value here, but the LDRD/STRD
2686     // instruction don't encode operands that way yet.
2687     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2688     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2689   }
2690 
2691   void addImm7s4Operands(MCInst &Inst, unsigned N) const {
2692     assert(N == 1 && "Invalid number of operands!");
2693     // FIXME: We really want to scale the value here, but the VSTR/VLDR_VSYSR
2694     // instruction don't encode operands that way yet.
2695     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2696     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2697   }
2698 
2699   void addImm7Shift0Operands(MCInst &Inst, unsigned N) const {
2700     assert(N == 1 && "Invalid number of operands!");
2701     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2702     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2703   }
2704 
2705   void addImm7Shift1Operands(MCInst &Inst, unsigned N) const {
2706     assert(N == 1 && "Invalid number of operands!");
2707     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2708     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2709   }
2710 
2711   void addImm7Shift2Operands(MCInst &Inst, unsigned N) const {
2712     assert(N == 1 && "Invalid number of operands!");
2713     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2714     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2715   }
2716 
2717   void addImm7Operands(MCInst &Inst, unsigned N) const {
2718     assert(N == 1 && "Invalid number of operands!");
2719     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2720     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2721   }
2722 
2723   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2724     assert(N == 1 && "Invalid number of operands!");
2725     // The immediate is scaled by four in the encoding and is stored
2726     // in the MCInst as such. Lop off the low two bits here.
2727     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2728     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2729   }
2730 
2731   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2732     assert(N == 1 && "Invalid number of operands!");
2733     // The immediate is scaled by four in the encoding and is stored
2734     // in the MCInst as such. Lop off the low two bits here.
2735     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2736     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2737   }
2738 
2739   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2740     assert(N == 1 && "Invalid number of operands!");
2741     // The immediate is scaled by four in the encoding and is stored
2742     // in the MCInst as such. Lop off the low two bits here.
2743     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2744     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2745   }
2746 
2747   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2748     assert(N == 1 && "Invalid number of operands!");
2749     // The constant encodes as the immediate-1, and we store in the instruction
2750     // the bits as encoded, so subtract off one here.
2751     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2752     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2753   }
2754 
2755   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2756     assert(N == 1 && "Invalid number of operands!");
2757     // The constant encodes as the immediate-1, and we store in the instruction
2758     // the bits as encoded, so subtract off one here.
2759     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2760     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2761   }
2762 
2763   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2764     assert(N == 1 && "Invalid number of operands!");
2765     // The constant encodes as the immediate, except for 32, which encodes as
2766     // zero.
2767     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2768     unsigned Imm = CE->getValue();
2769     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2770   }
2771 
2772   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2773     assert(N == 1 && "Invalid number of operands!");
2774     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2775     // the instruction as well.
2776     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2777     int Val = CE->getValue();
2778     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2779   }
2780 
2781   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2782     assert(N == 1 && "Invalid number of operands!");
2783     // The operand is actually a t2_so_imm, but we have its bitwise
2784     // negation in the assembly source, so twiddle it here.
2785     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2786     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2787   }
2788 
2789   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2790     assert(N == 1 && "Invalid number of operands!");
2791     // The operand is actually a t2_so_imm, but we have its
2792     // negation in the assembly source, so twiddle it here.
2793     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2794     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2795   }
2796 
2797   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2798     assert(N == 1 && "Invalid number of operands!");
2799     // The operand is actually an imm0_4095, but we have its
2800     // negation in the assembly source, so twiddle it here.
2801     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2802     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2803   }
2804 
2805   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2806     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2807       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2808       return;
2809     }
2810     const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2811     Inst.addOperand(MCOperand::createExpr(SR));
2812   }
2813 
2814   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2815     assert(N == 1 && "Invalid number of operands!");
2816     if (isImm()) {
2817       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2818       if (CE) {
2819         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2820         return;
2821       }
2822       const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2823       Inst.addOperand(MCOperand::createExpr(SR));
2824       return;
2825     }
2826 
2827     assert(isGPRMem()  && "Unknown value type!");
2828     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2829     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
2830       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2831     else
2832       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
2833   }
2834 
2835   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2836     assert(N == 1 && "Invalid number of operands!");
2837     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2838   }
2839 
2840   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2841     assert(N == 1 && "Invalid number of operands!");
2842     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2843   }
2844 
2845   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2846     assert(N == 1 && "Invalid number of operands!");
2847     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2848   }
2849 
2850   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2851     assert(N == 1 && "Invalid number of operands!");
2852     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2853   }
2854 
2855   void addMemNoOffsetT2Operands(MCInst &Inst, unsigned N) const {
2856     assert(N == 1 && "Invalid number of operands!");
2857     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2858   }
2859 
2860   void addMemNoOffsetT2NoSpOperands(MCInst &Inst, unsigned N) const {
2861     assert(N == 1 && "Invalid number of operands!");
2862     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2863   }
2864 
2865   void addMemNoOffsetTOperands(MCInst &Inst, unsigned N) const {
2866     assert(N == 1 && "Invalid number of operands!");
2867     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2868   }
2869 
2870   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2871     assert(N == 1 && "Invalid number of operands!");
2872     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
2873       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2874     else
2875       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
2876   }
2877 
2878   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2879     assert(N == 1 && "Invalid number of operands!");
2880     assert(isImm() && "Not an immediate!");
2881 
2882     // If we have an immediate that's not a constant, treat it as a label
2883     // reference needing a fixup.
2884     if (!isa<MCConstantExpr>(getImm())) {
2885       Inst.addOperand(MCOperand::createExpr(getImm()));
2886       return;
2887     }
2888 
2889     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2890     int Val = CE->getValue();
2891     Inst.addOperand(MCOperand::createImm(Val));
2892   }
2893 
2894   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2895     assert(N == 2 && "Invalid number of operands!");
2896     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2897     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2898   }
2899 
2900   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2901     addAlignedMemoryOperands(Inst, N);
2902   }
2903 
2904   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2905     addAlignedMemoryOperands(Inst, N);
2906   }
2907 
2908   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2909     addAlignedMemoryOperands(Inst, N);
2910   }
2911 
2912   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2913     addAlignedMemoryOperands(Inst, N);
2914   }
2915 
2916   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2917     addAlignedMemoryOperands(Inst, N);
2918   }
2919 
2920   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2921     addAlignedMemoryOperands(Inst, N);
2922   }
2923 
2924   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2925     addAlignedMemoryOperands(Inst, N);
2926   }
2927 
2928   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2929     addAlignedMemoryOperands(Inst, N);
2930   }
2931 
2932   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2933     addAlignedMemoryOperands(Inst, N);
2934   }
2935 
2936   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2937     addAlignedMemoryOperands(Inst, N);
2938   }
2939 
2940   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2941     addAlignedMemoryOperands(Inst, N);
2942   }
2943 
2944   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2945     assert(N == 3 && "Invalid number of operands!");
2946     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2947     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2948     if (!Memory.OffsetRegNum) {
2949       if (!Memory.OffsetImm)
2950         Inst.addOperand(MCOperand::createImm(0));
2951       else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
2952         int32_t Val = CE->getValue();
2953         ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2954         // Special case for #-0
2955         if (Val == std::numeric_limits<int32_t>::min())
2956           Val = 0;
2957         if (Val < 0)
2958           Val = -Val;
2959         Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2960         Inst.addOperand(MCOperand::createImm(Val));
2961       } else
2962         Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
2963     } else {
2964       // For register offset, we encode the shift type and negation flag
2965       // here.
2966       int32_t Val =
2967           ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2968                             Memory.ShiftImm, Memory.ShiftType);
2969       Inst.addOperand(MCOperand::createImm(Val));
2970     }
2971   }
2972 
2973   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2974     assert(N == 2 && "Invalid number of operands!");
2975     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2976     assert(CE && "non-constant AM2OffsetImm operand!");
2977     int32_t Val = CE->getValue();
2978     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2979     // Special case for #-0
2980     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2981     if (Val < 0) Val = -Val;
2982     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2983     Inst.addOperand(MCOperand::createReg(0));
2984     Inst.addOperand(MCOperand::createImm(Val));
2985   }
2986 
2987   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2988     assert(N == 3 && "Invalid number of operands!");
2989     // If we have an immediate that's not a constant, treat it as a label
2990     // reference needing a fixup. If it is a constant, it's something else
2991     // and we reject it.
2992     if (isImm()) {
2993       Inst.addOperand(MCOperand::createExpr(getImm()));
2994       Inst.addOperand(MCOperand::createReg(0));
2995       Inst.addOperand(MCOperand::createImm(0));
2996       return;
2997     }
2998 
2999     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3000     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3001     if (!Memory.OffsetRegNum) {
3002       if (!Memory.OffsetImm)
3003         Inst.addOperand(MCOperand::createImm(0));
3004       else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
3005         int32_t Val = CE->getValue();
3006         ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3007         // Special case for #-0
3008         if (Val == std::numeric_limits<int32_t>::min())
3009           Val = 0;
3010         if (Val < 0)
3011           Val = -Val;
3012         Val = ARM_AM::getAM3Opc(AddSub, Val);
3013         Inst.addOperand(MCOperand::createImm(Val));
3014       } else
3015         Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3016     } else {
3017       // For register offset, we encode the shift type and negation flag
3018       // here.
3019       int32_t Val =
3020           ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
3021       Inst.addOperand(MCOperand::createImm(Val));
3022     }
3023   }
3024 
3025   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
3026     assert(N == 2 && "Invalid number of operands!");
3027     if (Kind == k_PostIndexRegister) {
3028       int32_t Val =
3029         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
3030       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3031       Inst.addOperand(MCOperand::createImm(Val));
3032       return;
3033     }
3034 
3035     // Constant offset.
3036     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
3037     int32_t Val = CE->getValue();
3038     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3039     // Special case for #-0
3040     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
3041     if (Val < 0) Val = -Val;
3042     Val = ARM_AM::getAM3Opc(AddSub, Val);
3043     Inst.addOperand(MCOperand::createReg(0));
3044     Inst.addOperand(MCOperand::createImm(Val));
3045   }
3046 
3047   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
3048     assert(N == 2 && "Invalid number of operands!");
3049     // If we have an immediate that's not a constant, treat it as a label
3050     // reference needing a fixup. If it is a constant, it's something else
3051     // and we reject it.
3052     if (isImm()) {
3053       Inst.addOperand(MCOperand::createExpr(getImm()));
3054       Inst.addOperand(MCOperand::createImm(0));
3055       return;
3056     }
3057 
3058     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3059     if (!Memory.OffsetImm)
3060       Inst.addOperand(MCOperand::createImm(0));
3061     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
3062       // The lower two bits are always zero and as such are not encoded.
3063       int32_t Val = CE->getValue() / 4;
3064       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3065       // Special case for #-0
3066       if (Val == std::numeric_limits<int32_t>::min())
3067         Val = 0;
3068       if (Val < 0)
3069         Val = -Val;
3070       Val = ARM_AM::getAM5Opc(AddSub, Val);
3071       Inst.addOperand(MCOperand::createImm(Val));
3072     } else
3073       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3074   }
3075 
3076   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
3077     assert(N == 2 && "Invalid number of operands!");
3078     // If we have an immediate that's not a constant, treat it as a label
3079     // reference needing a fixup. If it is a constant, it's something else
3080     // and we reject it.
3081     if (isImm()) {
3082       Inst.addOperand(MCOperand::createExpr(getImm()));
3083       Inst.addOperand(MCOperand::createImm(0));
3084       return;
3085     }
3086 
3087     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3088     // The lower bit is always zero and as such is not encoded.
3089     if (!Memory.OffsetImm)
3090       Inst.addOperand(MCOperand::createImm(0));
3091     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
3092       int32_t Val = CE->getValue() / 2;
3093       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3094       // Special case for #-0
3095       if (Val == std::numeric_limits<int32_t>::min())
3096         Val = 0;
3097       if (Val < 0)
3098         Val = -Val;
3099       Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
3100       Inst.addOperand(MCOperand::createImm(Val));
3101     } else
3102       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3103   }
3104 
3105   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
3106     assert(N == 2 && "Invalid number of operands!");
3107     // If we have an immediate that's not a constant, treat it as a label
3108     // reference needing a fixup. If it is a constant, it's something else
3109     // and we reject it.
3110     if (isImm()) {
3111       Inst.addOperand(MCOperand::createExpr(getImm()));
3112       Inst.addOperand(MCOperand::createImm(0));
3113       return;
3114     }
3115 
3116     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3117     addExpr(Inst, Memory.OffsetImm);
3118   }
3119 
3120   void addMemImm7s4OffsetOperands(MCInst &Inst, unsigned N) const {
3121     assert(N == 2 && "Invalid number of operands!");
3122     // If we have an immediate that's not a constant, treat it as a label
3123     // reference needing a fixup. If it is a constant, it's something else
3124     // and we reject it.
3125     if (isImm()) {
3126       Inst.addOperand(MCOperand::createExpr(getImm()));
3127       Inst.addOperand(MCOperand::createImm(0));
3128       return;
3129     }
3130 
3131     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3132     addExpr(Inst, Memory.OffsetImm);
3133   }
3134 
3135   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
3136     assert(N == 2 && "Invalid number of operands!");
3137     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3138     if (!Memory.OffsetImm)
3139       Inst.addOperand(MCOperand::createImm(0));
3140     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3141       // The lower two bits are always zero and as such are not encoded.
3142       Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
3143     else
3144       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3145   }
3146 
3147   void addMemImmOffsetOperands(MCInst &Inst, unsigned N) const {
3148     assert(N == 2 && "Invalid number of operands!");
3149     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3150     addExpr(Inst, Memory.OffsetImm);
3151   }
3152 
3153   void addMemRegRQOffsetOperands(MCInst &Inst, unsigned N) const {
3154     assert(N == 2 && "Invalid number of operands!");
3155     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3156     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3157   }
3158 
3159   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3160     assert(N == 2 && "Invalid number of operands!");
3161     // If this is an immediate, it's a label reference.
3162     if (isImm()) {
3163       addExpr(Inst, getImm());
3164       Inst.addOperand(MCOperand::createImm(0));
3165       return;
3166     }
3167 
3168     // Otherwise, it's a normal memory reg+offset.
3169     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3170     addExpr(Inst, Memory.OffsetImm);
3171   }
3172 
3173   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3174     assert(N == 2 && "Invalid number of operands!");
3175     // If this is an immediate, it's a label reference.
3176     if (isImm()) {
3177       addExpr(Inst, getImm());
3178       Inst.addOperand(MCOperand::createImm(0));
3179       return;
3180     }
3181 
3182     // Otherwise, it's a normal memory reg+offset.
3183     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3184     addExpr(Inst, Memory.OffsetImm);
3185   }
3186 
3187   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
3188     assert(N == 1 && "Invalid number of operands!");
3189     // This is container for the immediate that we will create the constant
3190     // pool from
3191     addExpr(Inst, getConstantPoolImm());
3192   }
3193 
3194   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
3195     assert(N == 2 && "Invalid number of operands!");
3196     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3197     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3198   }
3199 
3200   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
3201     assert(N == 2 && "Invalid number of operands!");
3202     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3203     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3204   }
3205 
3206   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3207     assert(N == 3 && "Invalid number of operands!");
3208     unsigned Val =
3209       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
3210                         Memory.ShiftImm, Memory.ShiftType);
3211     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3212     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3213     Inst.addOperand(MCOperand::createImm(Val));
3214   }
3215 
3216   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3217     assert(N == 3 && "Invalid number of operands!");
3218     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3219     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3220     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
3221   }
3222 
3223   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
3224     assert(N == 2 && "Invalid number of operands!");
3225     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3226     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3227   }
3228 
3229   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
3230     assert(N == 2 && "Invalid number of operands!");
3231     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3232     if (!Memory.OffsetImm)
3233       Inst.addOperand(MCOperand::createImm(0));
3234     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3235       // The lower two bits are always zero and as such are not encoded.
3236       Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
3237     else
3238       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3239   }
3240 
3241   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
3242     assert(N == 2 && "Invalid number of operands!");
3243     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3244     if (!Memory.OffsetImm)
3245       Inst.addOperand(MCOperand::createImm(0));
3246     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3247       Inst.addOperand(MCOperand::createImm(CE->getValue() / 2));
3248     else
3249       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3250   }
3251 
3252   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
3253     assert(N == 2 && "Invalid number of operands!");
3254     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3255     addExpr(Inst, Memory.OffsetImm);
3256   }
3257 
3258   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
3259     assert(N == 2 && "Invalid number of operands!");
3260     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3261     if (!Memory.OffsetImm)
3262       Inst.addOperand(MCOperand::createImm(0));
3263     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3264       // The lower two bits are always zero and as such are not encoded.
3265       Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
3266     else
3267       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3268   }
3269 
3270   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
3271     assert(N == 1 && "Invalid number of operands!");
3272     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3273     assert(CE && "non-constant post-idx-imm8 operand!");
3274     int Imm = CE->getValue();
3275     bool isAdd = Imm >= 0;
3276     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3277     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
3278     Inst.addOperand(MCOperand::createImm(Imm));
3279   }
3280 
3281   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
3282     assert(N == 1 && "Invalid number of operands!");
3283     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3284     assert(CE && "non-constant post-idx-imm8s4 operand!");
3285     int Imm = CE->getValue();
3286     bool isAdd = Imm >= 0;
3287     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3288     // Immediate is scaled by 4.
3289     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
3290     Inst.addOperand(MCOperand::createImm(Imm));
3291   }
3292 
3293   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
3294     assert(N == 2 && "Invalid number of operands!");
3295     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3296     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
3297   }
3298 
3299   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
3300     assert(N == 2 && "Invalid number of operands!");
3301     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3302     // The sign, shift type, and shift amount are encoded in a single operand
3303     // using the AM2 encoding helpers.
3304     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
3305     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
3306                                      PostIdxReg.ShiftTy);
3307     Inst.addOperand(MCOperand::createImm(Imm));
3308   }
3309 
3310   void addPowerTwoOperands(MCInst &Inst, unsigned N) const {
3311     assert(N == 1 && "Invalid number of operands!");
3312     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3313     Inst.addOperand(MCOperand::createImm(CE->getValue()));
3314   }
3315 
3316   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
3317     assert(N == 1 && "Invalid number of operands!");
3318     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
3319   }
3320 
3321   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
3322     assert(N == 1 && "Invalid number of operands!");
3323     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
3324   }
3325 
3326   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
3327     assert(N == 1 && "Invalid number of operands!");
3328     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
3329   }
3330 
3331   void addVecListOperands(MCInst &Inst, unsigned N) const {
3332     assert(N == 1 && "Invalid number of operands!");
3333     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3334   }
3335 
3336   void addMVEVecListOperands(MCInst &Inst, unsigned N) const {
3337     assert(N == 1 && "Invalid number of operands!");
3338 
3339     // When we come here, the VectorList field will identify a range
3340     // of q-registers by its base register and length, and it will
3341     // have already been error-checked to be the expected length of
3342     // range and contain only q-regs in the range q0-q7. So we can
3343     // count on the base register being in the range q0-q6 (for 2
3344     // regs) or q0-q4 (for 4)
3345     //
3346     // The MVE instructions taking a register range of this kind will
3347     // need an operand in the MQQPR or MQQQQPR class, representing the
3348     // entire range as a unit. So we must translate into that class,
3349     // by finding the index of the base register in the MQPR reg
3350     // class, and returning the super-register at the corresponding
3351     // index in the target class.
3352 
3353     const MCRegisterClass *RC_in = &ARMMCRegisterClasses[ARM::MQPRRegClassID];
3354     const MCRegisterClass *RC_out =
3355         (VectorList.Count == 2) ? &ARMMCRegisterClasses[ARM::MQQPRRegClassID]
3356                                 : &ARMMCRegisterClasses[ARM::MQQQQPRRegClassID];
3357 
3358     unsigned I, E = RC_out->getNumRegs();
3359     for (I = 0; I < E; I++)
3360       if (RC_in->getRegister(I) == VectorList.RegNum)
3361         break;
3362     assert(I < E && "Invalid vector list start register!");
3363 
3364     Inst.addOperand(MCOperand::createReg(RC_out->getRegister(I)));
3365   }
3366 
3367   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
3368     assert(N == 2 && "Invalid number of operands!");
3369     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3370     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
3371   }
3372 
3373   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
3374     assert(N == 1 && "Invalid number of operands!");
3375     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3376   }
3377 
3378   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
3379     assert(N == 1 && "Invalid number of operands!");
3380     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3381   }
3382 
3383   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
3384     assert(N == 1 && "Invalid number of operands!");
3385     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3386   }
3387 
3388   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
3389     assert(N == 1 && "Invalid number of operands!");
3390     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3391   }
3392 
3393   void addMVEVectorIndexOperands(MCInst &Inst, unsigned N) const {
3394     assert(N == 1 && "Invalid number of operands!");
3395     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3396   }
3397 
3398   void addMVEPairVectorIndexOperands(MCInst &Inst, unsigned N) const {
3399     assert(N == 1 && "Invalid number of operands!");
3400     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3401   }
3402 
3403   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
3404     assert(N == 1 && "Invalid number of operands!");
3405     // The immediate encodes the type of constant as well as the value.
3406     // Mask in that this is an i8 splat.
3407     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3408     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
3409   }
3410 
3411   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
3412     assert(N == 1 && "Invalid number of operands!");
3413     // The immediate encodes the type of constant as well as the value.
3414     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3415     unsigned Value = CE->getValue();
3416     Value = ARM_AM::encodeNEONi16splat(Value);
3417     Inst.addOperand(MCOperand::createImm(Value));
3418   }
3419 
3420   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
3421     assert(N == 1 && "Invalid number of operands!");
3422     // The immediate encodes the type of constant as well as the value.
3423     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3424     unsigned Value = CE->getValue();
3425     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
3426     Inst.addOperand(MCOperand::createImm(Value));
3427   }
3428 
3429   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
3430     assert(N == 1 && "Invalid number of operands!");
3431     // The immediate encodes the type of constant as well as the value.
3432     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3433     unsigned Value = CE->getValue();
3434     Value = ARM_AM::encodeNEONi32splat(Value);
3435     Inst.addOperand(MCOperand::createImm(Value));
3436   }
3437 
3438   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
3439     assert(N == 1 && "Invalid number of operands!");
3440     // The immediate encodes the type of constant as well as the value.
3441     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3442     unsigned Value = CE->getValue();
3443     Value = ARM_AM::encodeNEONi32splat(~Value);
3444     Inst.addOperand(MCOperand::createImm(Value));
3445   }
3446 
3447   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
3448     // The immediate encodes the type of constant as well as the value.
3449     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3450     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
3451             Inst.getOpcode() == ARM::VMOVv16i8) &&
3452           "All instructions that wants to replicate non-zero byte "
3453           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
3454     unsigned Value = CE->getValue();
3455     if (Inv)
3456       Value = ~Value;
3457     unsigned B = Value & 0xff;
3458     B |= 0xe00; // cmode = 0b1110
3459     Inst.addOperand(MCOperand::createImm(B));
3460   }
3461 
3462   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3463     assert(N == 1 && "Invalid number of operands!");
3464     addNEONi8ReplicateOperands(Inst, true);
3465   }
3466 
3467   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
3468     if (Value >= 256 && Value <= 0xffff)
3469       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
3470     else if (Value > 0xffff && Value <= 0xffffff)
3471       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
3472     else if (Value > 0xffffff)
3473       Value = (Value >> 24) | 0x600;
3474     return Value;
3475   }
3476 
3477   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
3478     assert(N == 1 && "Invalid number of operands!");
3479     // The immediate encodes the type of constant as well as the value.
3480     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3481     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
3482     Inst.addOperand(MCOperand::createImm(Value));
3483   }
3484 
3485   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3486     assert(N == 1 && "Invalid number of operands!");
3487     addNEONi8ReplicateOperands(Inst, false);
3488   }
3489 
3490   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
3491     assert(N == 1 && "Invalid number of operands!");
3492     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3493     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
3494             Inst.getOpcode() == ARM::VMOVv8i16 ||
3495             Inst.getOpcode() == ARM::VMVNv4i16 ||
3496             Inst.getOpcode() == ARM::VMVNv8i16) &&
3497           "All instructions that want to replicate non-zero half-word "
3498           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
3499     uint64_t Value = CE->getValue();
3500     unsigned Elem = Value & 0xffff;
3501     if (Elem >= 256)
3502       Elem = (Elem >> 8) | 0x200;
3503     Inst.addOperand(MCOperand::createImm(Elem));
3504   }
3505 
3506   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
3507     assert(N == 1 && "Invalid number of operands!");
3508     // The immediate encodes the type of constant as well as the value.
3509     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3510     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
3511     Inst.addOperand(MCOperand::createImm(Value));
3512   }
3513 
3514   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
3515     assert(N == 1 && "Invalid number of operands!");
3516     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3517     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
3518             Inst.getOpcode() == ARM::VMOVv4i32 ||
3519             Inst.getOpcode() == ARM::VMVNv2i32 ||
3520             Inst.getOpcode() == ARM::VMVNv4i32) &&
3521           "All instructions that want to replicate non-zero word "
3522           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
3523     uint64_t Value = CE->getValue();
3524     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
3525     Inst.addOperand(MCOperand::createImm(Elem));
3526   }
3527 
3528   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
3529     assert(N == 1 && "Invalid number of operands!");
3530     // The immediate encodes the type of constant as well as the value.
3531     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3532     uint64_t Value = CE->getValue();
3533     unsigned Imm = 0;
3534     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
3535       Imm |= (Value & 1) << i;
3536     }
3537     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
3538   }
3539 
3540   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
3541     assert(N == 1 && "Invalid number of operands!");
3542     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3543     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
3544   }
3545 
3546   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
3547     assert(N == 1 && "Invalid number of operands!");
3548     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3549     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
3550   }
3551 
3552   void addMveSaturateOperands(MCInst &Inst, unsigned N) const {
3553     assert(N == 1 && "Invalid number of operands!");
3554     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3555     unsigned Imm = CE->getValue();
3556     assert((Imm == 48 || Imm == 64) && "Invalid saturate operand");
3557     Inst.addOperand(MCOperand::createImm(Imm == 48 ? 1 : 0));
3558   }
3559 
3560   void print(raw_ostream &OS) const override;
3561 
3562   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
3563     auto Op = std::make_unique<ARMOperand>(k_ITCondMask);
3564     Op->ITMask.Mask = Mask;
3565     Op->StartLoc = S;
3566     Op->EndLoc = S;
3567     return Op;
3568   }
3569 
3570   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
3571                                                     SMLoc S) {
3572     auto Op = std::make_unique<ARMOperand>(k_CondCode);
3573     Op->CC.Val = CC;
3574     Op->StartLoc = S;
3575     Op->EndLoc = S;
3576     return Op;
3577   }
3578 
3579   static std::unique_ptr<ARMOperand> CreateVPTPred(ARMVCC::VPTCodes CC,
3580                                                    SMLoc S) {
3581     auto Op = std::make_unique<ARMOperand>(k_VPTPred);
3582     Op->VCC.Val = CC;
3583     Op->StartLoc = S;
3584     Op->EndLoc = S;
3585     return Op;
3586   }
3587 
3588   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
3589     auto Op = std::make_unique<ARMOperand>(k_CoprocNum);
3590     Op->Cop.Val = CopVal;
3591     Op->StartLoc = S;
3592     Op->EndLoc = S;
3593     return Op;
3594   }
3595 
3596   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
3597     auto Op = std::make_unique<ARMOperand>(k_CoprocReg);
3598     Op->Cop.Val = CopVal;
3599     Op->StartLoc = S;
3600     Op->EndLoc = S;
3601     return Op;
3602   }
3603 
3604   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
3605                                                         SMLoc E) {
3606     auto Op = std::make_unique<ARMOperand>(k_CoprocOption);
3607     Op->Cop.Val = Val;
3608     Op->StartLoc = S;
3609     Op->EndLoc = E;
3610     return Op;
3611   }
3612 
3613   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
3614     auto Op = std::make_unique<ARMOperand>(k_CCOut);
3615     Op->Reg.RegNum = RegNum;
3616     Op->StartLoc = S;
3617     Op->EndLoc = S;
3618     return Op;
3619   }
3620 
3621   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
3622     auto Op = std::make_unique<ARMOperand>(k_Token);
3623     Op->Tok.Data = Str.data();
3624     Op->Tok.Length = Str.size();
3625     Op->StartLoc = S;
3626     Op->EndLoc = S;
3627     return Op;
3628   }
3629 
3630   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
3631                                                SMLoc E) {
3632     auto Op = std::make_unique<ARMOperand>(k_Register);
3633     Op->Reg.RegNum = RegNum;
3634     Op->StartLoc = S;
3635     Op->EndLoc = E;
3636     return Op;
3637   }
3638 
3639   static std::unique_ptr<ARMOperand>
3640   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3641                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
3642                         SMLoc E) {
3643     auto Op = std::make_unique<ARMOperand>(k_ShiftedRegister);
3644     Op->RegShiftedReg.ShiftTy = ShTy;
3645     Op->RegShiftedReg.SrcReg = SrcReg;
3646     Op->RegShiftedReg.ShiftReg = ShiftReg;
3647     Op->RegShiftedReg.ShiftImm = ShiftImm;
3648     Op->StartLoc = S;
3649     Op->EndLoc = E;
3650     return Op;
3651   }
3652 
3653   static std::unique_ptr<ARMOperand>
3654   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3655                          unsigned ShiftImm, SMLoc S, SMLoc E) {
3656     auto Op = std::make_unique<ARMOperand>(k_ShiftedImmediate);
3657     Op->RegShiftedImm.ShiftTy = ShTy;
3658     Op->RegShiftedImm.SrcReg = SrcReg;
3659     Op->RegShiftedImm.ShiftImm = ShiftImm;
3660     Op->StartLoc = S;
3661     Op->EndLoc = E;
3662     return Op;
3663   }
3664 
3665   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
3666                                                       SMLoc S, SMLoc E) {
3667     auto Op = std::make_unique<ARMOperand>(k_ShifterImmediate);
3668     Op->ShifterImm.isASR = isASR;
3669     Op->ShifterImm.Imm = Imm;
3670     Op->StartLoc = S;
3671     Op->EndLoc = E;
3672     return Op;
3673   }
3674 
3675   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3676                                                   SMLoc E) {
3677     auto Op = std::make_unique<ARMOperand>(k_RotateImmediate);
3678     Op->RotImm.Imm = Imm;
3679     Op->StartLoc = S;
3680     Op->EndLoc = E;
3681     return Op;
3682   }
3683 
3684   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3685                                                   SMLoc S, SMLoc E) {
3686     auto Op = std::make_unique<ARMOperand>(k_ModifiedImmediate);
3687     Op->ModImm.Bits = Bits;
3688     Op->ModImm.Rot = Rot;
3689     Op->StartLoc = S;
3690     Op->EndLoc = E;
3691     return Op;
3692   }
3693 
3694   static std::unique_ptr<ARMOperand>
3695   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3696     auto Op = std::make_unique<ARMOperand>(k_ConstantPoolImmediate);
3697     Op->Imm.Val = Val;
3698     Op->StartLoc = S;
3699     Op->EndLoc = E;
3700     return Op;
3701   }
3702 
3703   static std::unique_ptr<ARMOperand>
3704   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3705     auto Op = std::make_unique<ARMOperand>(k_BitfieldDescriptor);
3706     Op->Bitfield.LSB = LSB;
3707     Op->Bitfield.Width = Width;
3708     Op->StartLoc = S;
3709     Op->EndLoc = E;
3710     return Op;
3711   }
3712 
3713   static std::unique_ptr<ARMOperand>
3714   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3715                 SMLoc StartLoc, SMLoc EndLoc) {
3716     assert(Regs.size() > 0 && "RegList contains no registers?");
3717     KindTy Kind = k_RegisterList;
3718 
3719     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
3720             Regs.front().second)) {
3721       if (Regs.back().second == ARM::VPR)
3722         Kind = k_FPDRegisterListWithVPR;
3723       else
3724         Kind = k_DPRRegisterList;
3725     } else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
3726                    Regs.front().second)) {
3727       if (Regs.back().second == ARM::VPR)
3728         Kind = k_FPSRegisterListWithVPR;
3729       else
3730         Kind = k_SPRRegisterList;
3731     }
3732 
3733     if (Kind == k_RegisterList && Regs.back().second == ARM::APSR)
3734       Kind = k_RegisterListWithAPSR;
3735 
3736     assert(llvm::is_sorted(Regs) && "Register list must be sorted by encoding");
3737 
3738     auto Op = std::make_unique<ARMOperand>(Kind);
3739     for (const auto &P : Regs)
3740       Op->Registers.push_back(P.second);
3741 
3742     Op->StartLoc = StartLoc;
3743     Op->EndLoc = EndLoc;
3744     return Op;
3745   }
3746 
3747   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3748                                                       unsigned Count,
3749                                                       bool isDoubleSpaced,
3750                                                       SMLoc S, SMLoc E) {
3751     auto Op = std::make_unique<ARMOperand>(k_VectorList);
3752     Op->VectorList.RegNum = RegNum;
3753     Op->VectorList.Count = Count;
3754     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3755     Op->StartLoc = S;
3756     Op->EndLoc = E;
3757     return Op;
3758   }
3759 
3760   static std::unique_ptr<ARMOperand>
3761   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3762                            SMLoc S, SMLoc E) {
3763     auto Op = std::make_unique<ARMOperand>(k_VectorListAllLanes);
3764     Op->VectorList.RegNum = RegNum;
3765     Op->VectorList.Count = Count;
3766     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3767     Op->StartLoc = S;
3768     Op->EndLoc = E;
3769     return Op;
3770   }
3771 
3772   static std::unique_ptr<ARMOperand>
3773   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3774                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3775     auto Op = std::make_unique<ARMOperand>(k_VectorListIndexed);
3776     Op->VectorList.RegNum = RegNum;
3777     Op->VectorList.Count = Count;
3778     Op->VectorList.LaneIndex = Index;
3779     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3780     Op->StartLoc = S;
3781     Op->EndLoc = E;
3782     return Op;
3783   }
3784 
3785   static std::unique_ptr<ARMOperand>
3786   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3787     auto Op = std::make_unique<ARMOperand>(k_VectorIndex);
3788     Op->VectorIndex.Val = Idx;
3789     Op->StartLoc = S;
3790     Op->EndLoc = E;
3791     return Op;
3792   }
3793 
3794   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3795                                                SMLoc E) {
3796     auto Op = std::make_unique<ARMOperand>(k_Immediate);
3797     Op->Imm.Val = Val;
3798     Op->StartLoc = S;
3799     Op->EndLoc = E;
3800     return Op;
3801   }
3802 
3803   static std::unique_ptr<ARMOperand>
3804   CreateMem(unsigned BaseRegNum, const MCExpr *OffsetImm, unsigned OffsetRegNum,
3805             ARM_AM::ShiftOpc ShiftType, unsigned ShiftImm, unsigned Alignment,
3806             bool isNegative, SMLoc S, SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3807     auto Op = std::make_unique<ARMOperand>(k_Memory);
3808     Op->Memory.BaseRegNum = BaseRegNum;
3809     Op->Memory.OffsetImm = OffsetImm;
3810     Op->Memory.OffsetRegNum = OffsetRegNum;
3811     Op->Memory.ShiftType = ShiftType;
3812     Op->Memory.ShiftImm = ShiftImm;
3813     Op->Memory.Alignment = Alignment;
3814     Op->Memory.isNegative = isNegative;
3815     Op->StartLoc = S;
3816     Op->EndLoc = E;
3817     Op->AlignmentLoc = AlignmentLoc;
3818     return Op;
3819   }
3820 
3821   static std::unique_ptr<ARMOperand>
3822   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3823                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3824     auto Op = std::make_unique<ARMOperand>(k_PostIndexRegister);
3825     Op->PostIdxReg.RegNum = RegNum;
3826     Op->PostIdxReg.isAdd = isAdd;
3827     Op->PostIdxReg.ShiftTy = ShiftTy;
3828     Op->PostIdxReg.ShiftImm = ShiftImm;
3829     Op->StartLoc = S;
3830     Op->EndLoc = E;
3831     return Op;
3832   }
3833 
3834   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3835                                                          SMLoc S) {
3836     auto Op = std::make_unique<ARMOperand>(k_MemBarrierOpt);
3837     Op->MBOpt.Val = Opt;
3838     Op->StartLoc = S;
3839     Op->EndLoc = S;
3840     return Op;
3841   }
3842 
3843   static std::unique_ptr<ARMOperand>
3844   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3845     auto Op = std::make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3846     Op->ISBOpt.Val = Opt;
3847     Op->StartLoc = S;
3848     Op->EndLoc = S;
3849     return Op;
3850   }
3851 
3852   static std::unique_ptr<ARMOperand>
3853   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3854     auto Op = std::make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3855     Op->TSBOpt.Val = Opt;
3856     Op->StartLoc = S;
3857     Op->EndLoc = S;
3858     return Op;
3859   }
3860 
3861   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3862                                                       SMLoc S) {
3863     auto Op = std::make_unique<ARMOperand>(k_ProcIFlags);
3864     Op->IFlags.Val = IFlags;
3865     Op->StartLoc = S;
3866     Op->EndLoc = S;
3867     return Op;
3868   }
3869 
3870   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3871     auto Op = std::make_unique<ARMOperand>(k_MSRMask);
3872     Op->MMask.Val = MMask;
3873     Op->StartLoc = S;
3874     Op->EndLoc = S;
3875     return Op;
3876   }
3877 
3878   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3879     auto Op = std::make_unique<ARMOperand>(k_BankedReg);
3880     Op->BankedReg.Val = Reg;
3881     Op->StartLoc = S;
3882     Op->EndLoc = S;
3883     return Op;
3884   }
3885 };
3886 
3887 } // end anonymous namespace.
3888 
3889 void ARMOperand::print(raw_ostream &OS) const {
3890   auto RegName = [](unsigned Reg) {
3891     if (Reg)
3892       return ARMInstPrinter::getRegisterName(Reg);
3893     else
3894       return "noreg";
3895   };
3896 
3897   switch (Kind) {
3898   case k_CondCode:
3899     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3900     break;
3901   case k_VPTPred:
3902     OS << "<ARMVCC::" << ARMVPTPredToString(getVPTPred()) << ">";
3903     break;
3904   case k_CCOut:
3905     OS << "<ccout " << RegName(getReg()) << ">";
3906     break;
3907   case k_ITCondMask: {
3908     static const char *const MaskStr[] = {
3909       "(invalid)", "(tttt)", "(ttt)", "(ttte)",
3910       "(tt)",      "(ttet)", "(tte)", "(ttee)",
3911       "(t)",       "(tett)", "(tet)", "(tete)",
3912       "(te)",      "(teet)", "(tee)", "(teee)",
3913     };
3914     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3915     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3916     break;
3917   }
3918   case k_CoprocNum:
3919     OS << "<coprocessor number: " << getCoproc() << ">";
3920     break;
3921   case k_CoprocReg:
3922     OS << "<coprocessor register: " << getCoproc() << ">";
3923     break;
3924   case k_CoprocOption:
3925     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3926     break;
3927   case k_MSRMask:
3928     OS << "<mask: " << getMSRMask() << ">";
3929     break;
3930   case k_BankedReg:
3931     OS << "<banked reg: " << getBankedReg() << ">";
3932     break;
3933   case k_Immediate:
3934     OS << *getImm();
3935     break;
3936   case k_MemBarrierOpt:
3937     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3938     break;
3939   case k_InstSyncBarrierOpt:
3940     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3941     break;
3942   case k_TraceSyncBarrierOpt:
3943     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3944     break;
3945   case k_Memory:
3946     OS << "<memory";
3947     if (Memory.BaseRegNum)
3948       OS << " base:" << RegName(Memory.BaseRegNum);
3949     if (Memory.OffsetImm)
3950       OS << " offset-imm:" << *Memory.OffsetImm;
3951     if (Memory.OffsetRegNum)
3952       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3953          << RegName(Memory.OffsetRegNum);
3954     if (Memory.ShiftType != ARM_AM::no_shift) {
3955       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3956       OS << " shift-imm:" << Memory.ShiftImm;
3957     }
3958     if (Memory.Alignment)
3959       OS << " alignment:" << Memory.Alignment;
3960     OS << ">";
3961     break;
3962   case k_PostIndexRegister:
3963     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3964        << RegName(PostIdxReg.RegNum);
3965     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3966       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3967          << PostIdxReg.ShiftImm;
3968     OS << ">";
3969     break;
3970   case k_ProcIFlags: {
3971     OS << "<ARM_PROC::";
3972     unsigned IFlags = getProcIFlags();
3973     for (int i=2; i >= 0; --i)
3974       if (IFlags & (1 << i))
3975         OS << ARM_PROC::IFlagsToString(1 << i);
3976     OS << ">";
3977     break;
3978   }
3979   case k_Register:
3980     OS << "<register " << RegName(getReg()) << ">";
3981     break;
3982   case k_ShifterImmediate:
3983     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3984        << " #" << ShifterImm.Imm << ">";
3985     break;
3986   case k_ShiftedRegister:
3987     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3988        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3989        << RegName(RegShiftedReg.ShiftReg) << ">";
3990     break;
3991   case k_ShiftedImmediate:
3992     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3993        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3994        << RegShiftedImm.ShiftImm << ">";
3995     break;
3996   case k_RotateImmediate:
3997     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3998     break;
3999   case k_ModifiedImmediate:
4000     OS << "<mod_imm #" << ModImm.Bits << ", #"
4001        <<  ModImm.Rot << ")>";
4002     break;
4003   case k_ConstantPoolImmediate:
4004     OS << "<constant_pool_imm #" << *getConstantPoolImm();
4005     break;
4006   case k_BitfieldDescriptor:
4007     OS << "<bitfield " << "lsb: " << Bitfield.LSB
4008        << ", width: " << Bitfield.Width << ">";
4009     break;
4010   case k_RegisterList:
4011   case k_RegisterListWithAPSR:
4012   case k_DPRRegisterList:
4013   case k_SPRRegisterList:
4014   case k_FPSRegisterListWithVPR:
4015   case k_FPDRegisterListWithVPR: {
4016     OS << "<register_list ";
4017 
4018     const SmallVectorImpl<unsigned> &RegList = getRegList();
4019     for (SmallVectorImpl<unsigned>::const_iterator
4020            I = RegList.begin(), E = RegList.end(); I != E; ) {
4021       OS << RegName(*I);
4022       if (++I < E) OS << ", ";
4023     }
4024 
4025     OS << ">";
4026     break;
4027   }
4028   case k_VectorList:
4029     OS << "<vector_list " << VectorList.Count << " * "
4030        << RegName(VectorList.RegNum) << ">";
4031     break;
4032   case k_VectorListAllLanes:
4033     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
4034        << RegName(VectorList.RegNum) << ">";
4035     break;
4036   case k_VectorListIndexed:
4037     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
4038        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
4039     break;
4040   case k_Token:
4041     OS << "'" << getToken() << "'";
4042     break;
4043   case k_VectorIndex:
4044     OS << "<vectorindex " << getVectorIndex() << ">";
4045     break;
4046   }
4047 }
4048 
4049 /// @name Auto-generated Match Functions
4050 /// {
4051 
4052 static unsigned MatchRegisterName(StringRef Name);
4053 
4054 /// }
4055 
4056 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
4057                                  SMLoc &StartLoc, SMLoc &EndLoc) {
4058   const AsmToken &Tok = getParser().getTok();
4059   StartLoc = Tok.getLoc();
4060   EndLoc = Tok.getEndLoc();
4061   RegNo = tryParseRegister();
4062 
4063   return (RegNo == (unsigned)-1);
4064 }
4065 
4066 OperandMatchResultTy ARMAsmParser::tryParseRegister(unsigned &RegNo,
4067                                                     SMLoc &StartLoc,
4068                                                     SMLoc &EndLoc) {
4069   if (ParseRegister(RegNo, StartLoc, EndLoc))
4070     return MatchOperand_NoMatch;
4071   return MatchOperand_Success;
4072 }
4073 
4074 /// Try to parse a register name.  The token must be an Identifier when called,
4075 /// and if it is a register name the token is eaten and the register number is
4076 /// returned.  Otherwise return -1.
4077 int ARMAsmParser::tryParseRegister() {
4078   MCAsmParser &Parser = getParser();
4079   const AsmToken &Tok = Parser.getTok();
4080   if (Tok.isNot(AsmToken::Identifier)) return -1;
4081 
4082   std::string lowerCase = Tok.getString().lower();
4083   unsigned RegNum = MatchRegisterName(lowerCase);
4084   if (!RegNum) {
4085     RegNum = StringSwitch<unsigned>(lowerCase)
4086       .Case("r13", ARM::SP)
4087       .Case("r14", ARM::LR)
4088       .Case("r15", ARM::PC)
4089       .Case("ip", ARM::R12)
4090       // Additional register name aliases for 'gas' compatibility.
4091       .Case("a1", ARM::R0)
4092       .Case("a2", ARM::R1)
4093       .Case("a3", ARM::R2)
4094       .Case("a4", ARM::R3)
4095       .Case("v1", ARM::R4)
4096       .Case("v2", ARM::R5)
4097       .Case("v3", ARM::R6)
4098       .Case("v4", ARM::R7)
4099       .Case("v5", ARM::R8)
4100       .Case("v6", ARM::R9)
4101       .Case("v7", ARM::R10)
4102       .Case("v8", ARM::R11)
4103       .Case("sb", ARM::R9)
4104       .Case("sl", ARM::R10)
4105       .Case("fp", ARM::R11)
4106       .Default(0);
4107   }
4108   if (!RegNum) {
4109     // Check for aliases registered via .req. Canonicalize to lower case.
4110     // That's more consistent since register names are case insensitive, and
4111     // it's how the original entry was passed in from MC/MCParser/AsmParser.
4112     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
4113     // If no match, return failure.
4114     if (Entry == RegisterReqs.end())
4115       return -1;
4116     Parser.Lex(); // Eat identifier token.
4117     return Entry->getValue();
4118   }
4119 
4120   // Some FPUs only have 16 D registers, so D16-D31 are invalid
4121   if (!hasD32() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
4122     return -1;
4123 
4124   Parser.Lex(); // Eat identifier token.
4125 
4126   return RegNum;
4127 }
4128 
4129 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
4130 // If a recoverable error occurs, return 1. If an irrecoverable error
4131 // occurs, return -1. An irrecoverable error is one where tokens have been
4132 // consumed in the process of trying to parse the shifter (i.e., when it is
4133 // indeed a shifter operand, but malformed).
4134 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
4135   MCAsmParser &Parser = getParser();
4136   SMLoc S = Parser.getTok().getLoc();
4137   const AsmToken &Tok = Parser.getTok();
4138   if (Tok.isNot(AsmToken::Identifier))
4139     return -1;
4140 
4141   std::string lowerCase = Tok.getString().lower();
4142   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
4143       .Case("asl", ARM_AM::lsl)
4144       .Case("lsl", ARM_AM::lsl)
4145       .Case("lsr", ARM_AM::lsr)
4146       .Case("asr", ARM_AM::asr)
4147       .Case("ror", ARM_AM::ror)
4148       .Case("rrx", ARM_AM::rrx)
4149       .Default(ARM_AM::no_shift);
4150 
4151   if (ShiftTy == ARM_AM::no_shift)
4152     return 1;
4153 
4154   Parser.Lex(); // Eat the operator.
4155 
4156   // The source register for the shift has already been added to the
4157   // operand list, so we need to pop it off and combine it into the shifted
4158   // register operand instead.
4159   std::unique_ptr<ARMOperand> PrevOp(
4160       (ARMOperand *)Operands.pop_back_val().release());
4161   if (!PrevOp->isReg())
4162     return Error(PrevOp->getStartLoc(), "shift must be of a register");
4163   int SrcReg = PrevOp->getReg();
4164 
4165   SMLoc EndLoc;
4166   int64_t Imm = 0;
4167   int ShiftReg = 0;
4168   if (ShiftTy == ARM_AM::rrx) {
4169     // RRX Doesn't have an explicit shift amount. The encoder expects
4170     // the shift register to be the same as the source register. Seems odd,
4171     // but OK.
4172     ShiftReg = SrcReg;
4173   } else {
4174     // Figure out if this is shifted by a constant or a register (for non-RRX).
4175     if (Parser.getTok().is(AsmToken::Hash) ||
4176         Parser.getTok().is(AsmToken::Dollar)) {
4177       Parser.Lex(); // Eat hash.
4178       SMLoc ImmLoc = Parser.getTok().getLoc();
4179       const MCExpr *ShiftExpr = nullptr;
4180       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
4181         Error(ImmLoc, "invalid immediate shift value");
4182         return -1;
4183       }
4184       // The expression must be evaluatable as an immediate.
4185       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
4186       if (!CE) {
4187         Error(ImmLoc, "invalid immediate shift value");
4188         return -1;
4189       }
4190       // Range check the immediate.
4191       // lsl, ror: 0 <= imm <= 31
4192       // lsr, asr: 0 <= imm <= 32
4193       Imm = CE->getValue();
4194       if (Imm < 0 ||
4195           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
4196           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
4197         Error(ImmLoc, "immediate shift value out of range");
4198         return -1;
4199       }
4200       // shift by zero is a nop. Always send it through as lsl.
4201       // ('as' compatibility)
4202       if (Imm == 0)
4203         ShiftTy = ARM_AM::lsl;
4204     } else if (Parser.getTok().is(AsmToken::Identifier)) {
4205       SMLoc L = Parser.getTok().getLoc();
4206       EndLoc = Parser.getTok().getEndLoc();
4207       ShiftReg = tryParseRegister();
4208       if (ShiftReg == -1) {
4209         Error(L, "expected immediate or register in shift operand");
4210         return -1;
4211       }
4212     } else {
4213       Error(Parser.getTok().getLoc(),
4214             "expected immediate or register in shift operand");
4215       return -1;
4216     }
4217   }
4218 
4219   if (ShiftReg && ShiftTy != ARM_AM::rrx)
4220     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
4221                                                          ShiftReg, Imm,
4222                                                          S, EndLoc));
4223   else
4224     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
4225                                                           S, EndLoc));
4226 
4227   return 0;
4228 }
4229 
4230 /// Try to parse a register name.  The token must be an Identifier when called.
4231 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
4232 /// if there is a "writeback". 'true' if it's not a register.
4233 ///
4234 /// TODO this is likely to change to allow different register types and or to
4235 /// parse for a specific register type.
4236 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
4237   MCAsmParser &Parser = getParser();
4238   SMLoc RegStartLoc = Parser.getTok().getLoc();
4239   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
4240   int RegNo = tryParseRegister();
4241   if (RegNo == -1)
4242     return true;
4243 
4244   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
4245 
4246   const AsmToken &ExclaimTok = Parser.getTok();
4247   if (ExclaimTok.is(AsmToken::Exclaim)) {
4248     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
4249                                                ExclaimTok.getLoc()));
4250     Parser.Lex(); // Eat exclaim token
4251     return false;
4252   }
4253 
4254   // Also check for an index operand. This is only legal for vector registers,
4255   // but that'll get caught OK in operand matching, so we don't need to
4256   // explicitly filter everything else out here.
4257   if (Parser.getTok().is(AsmToken::LBrac)) {
4258     SMLoc SIdx = Parser.getTok().getLoc();
4259     Parser.Lex(); // Eat left bracket token.
4260 
4261     const MCExpr *ImmVal;
4262     if (getParser().parseExpression(ImmVal))
4263       return true;
4264     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
4265     if (!MCE)
4266       return TokError("immediate value expected for vector index");
4267 
4268     if (Parser.getTok().isNot(AsmToken::RBrac))
4269       return Error(Parser.getTok().getLoc(), "']' expected");
4270 
4271     SMLoc E = Parser.getTok().getEndLoc();
4272     Parser.Lex(); // Eat right bracket token.
4273 
4274     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
4275                                                      SIdx, E,
4276                                                      getContext()));
4277   }
4278 
4279   return false;
4280 }
4281 
4282 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
4283 /// instruction with a symbolic operand name.
4284 /// We accept "crN" syntax for GAS compatibility.
4285 /// <operand-name> ::= <prefix><number>
4286 /// If CoprocOp is 'c', then:
4287 ///   <prefix> ::= c | cr
4288 /// If CoprocOp is 'p', then :
4289 ///   <prefix> ::= p
4290 /// <number> ::= integer in range [0, 15]
4291 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
4292   // Use the same layout as the tablegen'erated register name matcher. Ugly,
4293   // but efficient.
4294   if (Name.size() < 2 || Name[0] != CoprocOp)
4295     return -1;
4296   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
4297 
4298   switch (Name.size()) {
4299   default: return -1;
4300   case 1:
4301     switch (Name[0]) {
4302     default:  return -1;
4303     case '0': return 0;
4304     case '1': return 1;
4305     case '2': return 2;
4306     case '3': return 3;
4307     case '4': return 4;
4308     case '5': return 5;
4309     case '6': return 6;
4310     case '7': return 7;
4311     case '8': return 8;
4312     case '9': return 9;
4313     }
4314   case 2:
4315     if (Name[0] != '1')
4316       return -1;
4317     switch (Name[1]) {
4318     default:  return -1;
4319     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
4320     // However, old cores (v5/v6) did use them in that way.
4321     case '0': return 10;
4322     case '1': return 11;
4323     case '2': return 12;
4324     case '3': return 13;
4325     case '4': return 14;
4326     case '5': return 15;
4327     }
4328   }
4329 }
4330 
4331 /// parseITCondCode - Try to parse a condition code for an IT instruction.
4332 OperandMatchResultTy
4333 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
4334   MCAsmParser &Parser = getParser();
4335   SMLoc S = Parser.getTok().getLoc();
4336   const AsmToken &Tok = Parser.getTok();
4337   if (!Tok.is(AsmToken::Identifier))
4338     return MatchOperand_NoMatch;
4339   unsigned CC = ARMCondCodeFromString(Tok.getString());
4340   if (CC == ~0U)
4341     return MatchOperand_NoMatch;
4342   Parser.Lex(); // Eat the token.
4343 
4344   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
4345 
4346   return MatchOperand_Success;
4347 }
4348 
4349 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
4350 /// token must be an Identifier when called, and if it is a coprocessor
4351 /// number, the token is eaten and the operand is added to the operand list.
4352 OperandMatchResultTy
4353 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
4354   MCAsmParser &Parser = getParser();
4355   SMLoc S = Parser.getTok().getLoc();
4356   const AsmToken &Tok = Parser.getTok();
4357   if (Tok.isNot(AsmToken::Identifier))
4358     return MatchOperand_NoMatch;
4359 
4360   int Num = MatchCoprocessorOperandName(Tok.getString().lower(), 'p');
4361   if (Num == -1)
4362     return MatchOperand_NoMatch;
4363   if (!isValidCoprocessorNumber(Num, getSTI().getFeatureBits()))
4364     return MatchOperand_NoMatch;
4365 
4366   Parser.Lex(); // Eat identifier token.
4367   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
4368   return MatchOperand_Success;
4369 }
4370 
4371 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
4372 /// token must be an Identifier when called, and if it is a coprocessor
4373 /// number, the token is eaten and the operand is added to the operand list.
4374 OperandMatchResultTy
4375 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
4376   MCAsmParser &Parser = getParser();
4377   SMLoc S = Parser.getTok().getLoc();
4378   const AsmToken &Tok = Parser.getTok();
4379   if (Tok.isNot(AsmToken::Identifier))
4380     return MatchOperand_NoMatch;
4381 
4382   int Reg = MatchCoprocessorOperandName(Tok.getString().lower(), 'c');
4383   if (Reg == -1)
4384     return MatchOperand_NoMatch;
4385 
4386   Parser.Lex(); // Eat identifier token.
4387   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
4388   return MatchOperand_Success;
4389 }
4390 
4391 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
4392 /// coproc_option : '{' imm0_255 '}'
4393 OperandMatchResultTy
4394 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
4395   MCAsmParser &Parser = getParser();
4396   SMLoc S = Parser.getTok().getLoc();
4397 
4398   // If this isn't a '{', this isn't a coprocessor immediate operand.
4399   if (Parser.getTok().isNot(AsmToken::LCurly))
4400     return MatchOperand_NoMatch;
4401   Parser.Lex(); // Eat the '{'
4402 
4403   const MCExpr *Expr;
4404   SMLoc Loc = Parser.getTok().getLoc();
4405   if (getParser().parseExpression(Expr)) {
4406     Error(Loc, "illegal expression");
4407     return MatchOperand_ParseFail;
4408   }
4409   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4410   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
4411     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
4412     return MatchOperand_ParseFail;
4413   }
4414   int Val = CE->getValue();
4415 
4416   // Check for and consume the closing '}'
4417   if (Parser.getTok().isNot(AsmToken::RCurly))
4418     return MatchOperand_ParseFail;
4419   SMLoc E = Parser.getTok().getEndLoc();
4420   Parser.Lex(); // Eat the '}'
4421 
4422   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
4423   return MatchOperand_Success;
4424 }
4425 
4426 // For register list parsing, we need to map from raw GPR register numbering
4427 // to the enumeration values. The enumeration values aren't sorted by
4428 // register number due to our using "sp", "lr" and "pc" as canonical names.
4429 static unsigned getNextRegister(unsigned Reg) {
4430   // If this is a GPR, we need to do it manually, otherwise we can rely
4431   // on the sort ordering of the enumeration since the other reg-classes
4432   // are sane.
4433   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4434     return Reg + 1;
4435   switch(Reg) {
4436   default: llvm_unreachable("Invalid GPR number!");
4437   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
4438   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
4439   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
4440   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
4441   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
4442   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
4443   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
4444   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
4445   }
4446 }
4447 
4448 // Insert an <Encoding, Register> pair in an ordered vector. Return true on
4449 // success, or false, if duplicate encoding found.
4450 static bool
4451 insertNoDuplicates(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
4452                    unsigned Enc, unsigned Reg) {
4453   Regs.emplace_back(Enc, Reg);
4454   for (auto I = Regs.rbegin(), J = I + 1, E = Regs.rend(); J != E; ++I, ++J) {
4455     if (J->first == Enc) {
4456       Regs.erase(J.base());
4457       return false;
4458     }
4459     if (J->first < Enc)
4460       break;
4461     std::swap(*I, *J);
4462   }
4463   return true;
4464 }
4465 
4466 /// Parse a register list.
4467 bool ARMAsmParser::parseRegisterList(OperandVector &Operands,
4468                                      bool EnforceOrder) {
4469   MCAsmParser &Parser = getParser();
4470   if (Parser.getTok().isNot(AsmToken::LCurly))
4471     return TokError("Token is not a Left Curly Brace");
4472   SMLoc S = Parser.getTok().getLoc();
4473   Parser.Lex(); // Eat '{' token.
4474   SMLoc RegLoc = Parser.getTok().getLoc();
4475 
4476   // Check the first register in the list to see what register class
4477   // this is a list of.
4478   int Reg = tryParseRegister();
4479   if (Reg == -1)
4480     return Error(RegLoc, "register expected");
4481 
4482   // The reglist instructions have at most 16 registers, so reserve
4483   // space for that many.
4484   int EReg = 0;
4485   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
4486 
4487   // Allow Q regs and just interpret them as the two D sub-registers.
4488   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4489     Reg = getDRegFromQReg(Reg);
4490     EReg = MRI->getEncodingValue(Reg);
4491     Registers.emplace_back(EReg, Reg);
4492     ++Reg;
4493   }
4494   const MCRegisterClass *RC;
4495   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4496     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
4497   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
4498     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
4499   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
4500     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
4501   else if (ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4502     RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4503   else
4504     return Error(RegLoc, "invalid register in register list");
4505 
4506   // Store the register.
4507   EReg = MRI->getEncodingValue(Reg);
4508   Registers.emplace_back(EReg, Reg);
4509 
4510   // This starts immediately after the first register token in the list,
4511   // so we can see either a comma or a minus (range separator) as a legal
4512   // next token.
4513   while (Parser.getTok().is(AsmToken::Comma) ||
4514          Parser.getTok().is(AsmToken::Minus)) {
4515     if (Parser.getTok().is(AsmToken::Minus)) {
4516       Parser.Lex(); // Eat the minus.
4517       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4518       int EndReg = tryParseRegister();
4519       if (EndReg == -1)
4520         return Error(AfterMinusLoc, "register expected");
4521       // Allow Q regs and just interpret them as the two D sub-registers.
4522       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4523         EndReg = getDRegFromQReg(EndReg) + 1;
4524       // If the register is the same as the start reg, there's nothing
4525       // more to do.
4526       if (Reg == EndReg)
4527         continue;
4528       // The register must be in the same register class as the first.
4529       if (!RC->contains(EndReg))
4530         return Error(AfterMinusLoc, "invalid register in register list");
4531       // Ranges must go from low to high.
4532       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
4533         return Error(AfterMinusLoc, "bad range in register list");
4534 
4535       // Add all the registers in the range to the register list.
4536       while (Reg != EndReg) {
4537         Reg = getNextRegister(Reg);
4538         EReg = MRI->getEncodingValue(Reg);
4539         if (!insertNoDuplicates(Registers, EReg, Reg)) {
4540           Warning(AfterMinusLoc, StringRef("duplicated register (") +
4541                                      ARMInstPrinter::getRegisterName(Reg) +
4542                                      ") in register list");
4543         }
4544       }
4545       continue;
4546     }
4547     Parser.Lex(); // Eat the comma.
4548     RegLoc = Parser.getTok().getLoc();
4549     int OldReg = Reg;
4550     const AsmToken RegTok = Parser.getTok();
4551     Reg = tryParseRegister();
4552     if (Reg == -1)
4553       return Error(RegLoc, "register expected");
4554     // Allow Q regs and just interpret them as the two D sub-registers.
4555     bool isQReg = false;
4556     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4557       Reg = getDRegFromQReg(Reg);
4558       isQReg = true;
4559     }
4560     if (!RC->contains(Reg) &&
4561         RC->getID() == ARMMCRegisterClasses[ARM::GPRRegClassID].getID() &&
4562         ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg)) {
4563       // switch the register classes, as GPRwithAPSRnospRegClassID is a partial
4564       // subset of GPRRegClassId except it contains APSR as well.
4565       RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4566     }
4567     if (Reg == ARM::VPR &&
4568         (RC == &ARMMCRegisterClasses[ARM::SPRRegClassID] ||
4569          RC == &ARMMCRegisterClasses[ARM::DPRRegClassID] ||
4570          RC == &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID])) {
4571       RC = &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID];
4572       EReg = MRI->getEncodingValue(Reg);
4573       if (!insertNoDuplicates(Registers, EReg, Reg)) {
4574         Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4575                             ") in register list");
4576       }
4577       continue;
4578     }
4579     // The register must be in the same register class as the first.
4580     if (!RC->contains(Reg))
4581       return Error(RegLoc, "invalid register in register list");
4582     // In most cases, the list must be monotonically increasing. An
4583     // exception is CLRM, which is order-independent anyway, so
4584     // there's no potential for confusion if you write clrm {r2,r1}
4585     // instead of clrm {r1,r2}.
4586     if (EnforceOrder &&
4587         MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
4588       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4589         Warning(RegLoc, "register list not in ascending order");
4590       else if (!ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4591         return Error(RegLoc, "register list not in ascending order");
4592     }
4593     // VFP register lists must also be contiguous.
4594     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
4595         RC != &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID] &&
4596         Reg != OldReg + 1)
4597       return Error(RegLoc, "non-contiguous register range");
4598     EReg = MRI->getEncodingValue(Reg);
4599     if (!insertNoDuplicates(Registers, EReg, Reg)) {
4600       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4601                           ") in register list");
4602     }
4603     if (isQReg) {
4604       EReg = MRI->getEncodingValue(++Reg);
4605       Registers.emplace_back(EReg, Reg);
4606     }
4607   }
4608 
4609   if (Parser.getTok().isNot(AsmToken::RCurly))
4610     return Error(Parser.getTok().getLoc(), "'}' expected");
4611   SMLoc E = Parser.getTok().getEndLoc();
4612   Parser.Lex(); // Eat '}' token.
4613 
4614   // Push the register list operand.
4615   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
4616 
4617   // The ARM system instruction variants for LDM/STM have a '^' token here.
4618   if (Parser.getTok().is(AsmToken::Caret)) {
4619     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
4620     Parser.Lex(); // Eat '^' token.
4621   }
4622 
4623   return false;
4624 }
4625 
4626 // Helper function to parse the lane index for vector lists.
4627 OperandMatchResultTy ARMAsmParser::
4628 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
4629   MCAsmParser &Parser = getParser();
4630   Index = 0; // Always return a defined index value.
4631   if (Parser.getTok().is(AsmToken::LBrac)) {
4632     Parser.Lex(); // Eat the '['.
4633     if (Parser.getTok().is(AsmToken::RBrac)) {
4634       // "Dn[]" is the 'all lanes' syntax.
4635       LaneKind = AllLanes;
4636       EndLoc = Parser.getTok().getEndLoc();
4637       Parser.Lex(); // Eat the ']'.
4638       return MatchOperand_Success;
4639     }
4640 
4641     // There's an optional '#' token here. Normally there wouldn't be, but
4642     // inline assemble puts one in, and it's friendly to accept that.
4643     if (Parser.getTok().is(AsmToken::Hash))
4644       Parser.Lex(); // Eat '#' or '$'.
4645 
4646     const MCExpr *LaneIndex;
4647     SMLoc Loc = Parser.getTok().getLoc();
4648     if (getParser().parseExpression(LaneIndex)) {
4649       Error(Loc, "illegal expression");
4650       return MatchOperand_ParseFail;
4651     }
4652     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
4653     if (!CE) {
4654       Error(Loc, "lane index must be empty or an integer");
4655       return MatchOperand_ParseFail;
4656     }
4657     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4658       Error(Parser.getTok().getLoc(), "']' expected");
4659       return MatchOperand_ParseFail;
4660     }
4661     EndLoc = Parser.getTok().getEndLoc();
4662     Parser.Lex(); // Eat the ']'.
4663     int64_t Val = CE->getValue();
4664 
4665     // FIXME: Make this range check context sensitive for .8, .16, .32.
4666     if (Val < 0 || Val > 7) {
4667       Error(Parser.getTok().getLoc(), "lane index out of range");
4668       return MatchOperand_ParseFail;
4669     }
4670     Index = Val;
4671     LaneKind = IndexedLane;
4672     return MatchOperand_Success;
4673   }
4674   LaneKind = NoLanes;
4675   return MatchOperand_Success;
4676 }
4677 
4678 // parse a vector register list
4679 OperandMatchResultTy
4680 ARMAsmParser::parseVectorList(OperandVector &Operands) {
4681   MCAsmParser &Parser = getParser();
4682   VectorLaneTy LaneKind;
4683   unsigned LaneIndex;
4684   SMLoc S = Parser.getTok().getLoc();
4685   // As an extension (to match gas), support a plain D register or Q register
4686   // (without encosing curly braces) as a single or double entry list,
4687   // respectively.
4688   if (!hasMVE() && Parser.getTok().is(AsmToken::Identifier)) {
4689     SMLoc E = Parser.getTok().getEndLoc();
4690     int Reg = tryParseRegister();
4691     if (Reg == -1)
4692       return MatchOperand_NoMatch;
4693     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
4694       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4695       if (Res != MatchOperand_Success)
4696         return Res;
4697       switch (LaneKind) {
4698       case NoLanes:
4699         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
4700         break;
4701       case AllLanes:
4702         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
4703                                                                 S, E));
4704         break;
4705       case IndexedLane:
4706         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
4707                                                                LaneIndex,
4708                                                                false, S, E));
4709         break;
4710       }
4711       return MatchOperand_Success;
4712     }
4713     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4714       Reg = getDRegFromQReg(Reg);
4715       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4716       if (Res != MatchOperand_Success)
4717         return Res;
4718       switch (LaneKind) {
4719       case NoLanes:
4720         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4721                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4722         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
4723         break;
4724       case AllLanes:
4725         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4726                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4727         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
4728                                                                 S, E));
4729         break;
4730       case IndexedLane:
4731         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
4732                                                                LaneIndex,
4733                                                                false, S, E));
4734         break;
4735       }
4736       return MatchOperand_Success;
4737     }
4738     Error(S, "vector register expected");
4739     return MatchOperand_ParseFail;
4740   }
4741 
4742   if (Parser.getTok().isNot(AsmToken::LCurly))
4743     return MatchOperand_NoMatch;
4744 
4745   Parser.Lex(); // Eat '{' token.
4746   SMLoc RegLoc = Parser.getTok().getLoc();
4747 
4748   int Reg = tryParseRegister();
4749   if (Reg == -1) {
4750     Error(RegLoc, "register expected");
4751     return MatchOperand_ParseFail;
4752   }
4753   unsigned Count = 1;
4754   int Spacing = 0;
4755   unsigned FirstReg = Reg;
4756 
4757   if (hasMVE() && !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4758       Error(Parser.getTok().getLoc(), "vector register in range Q0-Q7 expected");
4759       return MatchOperand_ParseFail;
4760   }
4761   // The list is of D registers, but we also allow Q regs and just interpret
4762   // them as the two D sub-registers.
4763   else if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4764     FirstReg = Reg = getDRegFromQReg(Reg);
4765     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4766                  // it's ambiguous with four-register single spaced.
4767     ++Reg;
4768     ++Count;
4769   }
4770 
4771   SMLoc E;
4772   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4773     return MatchOperand_ParseFail;
4774 
4775   while (Parser.getTok().is(AsmToken::Comma) ||
4776          Parser.getTok().is(AsmToken::Minus)) {
4777     if (Parser.getTok().is(AsmToken::Minus)) {
4778       if (!Spacing)
4779         Spacing = 1; // Register range implies a single spaced list.
4780       else if (Spacing == 2) {
4781         Error(Parser.getTok().getLoc(),
4782               "sequential registers in double spaced list");
4783         return MatchOperand_ParseFail;
4784       }
4785       Parser.Lex(); // Eat the minus.
4786       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4787       int EndReg = tryParseRegister();
4788       if (EndReg == -1) {
4789         Error(AfterMinusLoc, "register expected");
4790         return MatchOperand_ParseFail;
4791       }
4792       // Allow Q regs and just interpret them as the two D sub-registers.
4793       if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4794         EndReg = getDRegFromQReg(EndReg) + 1;
4795       // If the register is the same as the start reg, there's nothing
4796       // more to do.
4797       if (Reg == EndReg)
4798         continue;
4799       // The register must be in the same register class as the first.
4800       if ((hasMVE() &&
4801            !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(EndReg)) ||
4802           (!hasMVE() &&
4803            !ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg))) {
4804         Error(AfterMinusLoc, "invalid register in register list");
4805         return MatchOperand_ParseFail;
4806       }
4807       // Ranges must go from low to high.
4808       if (Reg > EndReg) {
4809         Error(AfterMinusLoc, "bad range in register list");
4810         return MatchOperand_ParseFail;
4811       }
4812       // Parse the lane specifier if present.
4813       VectorLaneTy NextLaneKind;
4814       unsigned NextLaneIndex;
4815       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4816           MatchOperand_Success)
4817         return MatchOperand_ParseFail;
4818       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4819         Error(AfterMinusLoc, "mismatched lane index in register list");
4820         return MatchOperand_ParseFail;
4821       }
4822 
4823       // Add all the registers in the range to the register list.
4824       Count += EndReg - Reg;
4825       Reg = EndReg;
4826       continue;
4827     }
4828     Parser.Lex(); // Eat the comma.
4829     RegLoc = Parser.getTok().getLoc();
4830     int OldReg = Reg;
4831     Reg = tryParseRegister();
4832     if (Reg == -1) {
4833       Error(RegLoc, "register expected");
4834       return MatchOperand_ParseFail;
4835     }
4836 
4837     if (hasMVE()) {
4838       if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4839         Error(RegLoc, "vector register in range Q0-Q7 expected");
4840         return MatchOperand_ParseFail;
4841       }
4842       Spacing = 1;
4843     }
4844     // vector register lists must be contiguous.
4845     // It's OK to use the enumeration values directly here rather, as the
4846     // VFP register classes have the enum sorted properly.
4847     //
4848     // The list is of D registers, but we also allow Q regs and just interpret
4849     // them as the two D sub-registers.
4850     else if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4851       if (!Spacing)
4852         Spacing = 1; // Register range implies a single spaced list.
4853       else if (Spacing == 2) {
4854         Error(RegLoc,
4855               "invalid register in double-spaced list (must be 'D' register')");
4856         return MatchOperand_ParseFail;
4857       }
4858       Reg = getDRegFromQReg(Reg);
4859       if (Reg != OldReg + 1) {
4860         Error(RegLoc, "non-contiguous register range");
4861         return MatchOperand_ParseFail;
4862       }
4863       ++Reg;
4864       Count += 2;
4865       // Parse the lane specifier if present.
4866       VectorLaneTy NextLaneKind;
4867       unsigned NextLaneIndex;
4868       SMLoc LaneLoc = Parser.getTok().getLoc();
4869       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4870           MatchOperand_Success)
4871         return MatchOperand_ParseFail;
4872       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4873         Error(LaneLoc, "mismatched lane index in register list");
4874         return MatchOperand_ParseFail;
4875       }
4876       continue;
4877     }
4878     // Normal D register.
4879     // Figure out the register spacing (single or double) of the list if
4880     // we don't know it already.
4881     if (!Spacing)
4882       Spacing = 1 + (Reg == OldReg + 2);
4883 
4884     // Just check that it's contiguous and keep going.
4885     if (Reg != OldReg + Spacing) {
4886       Error(RegLoc, "non-contiguous register range");
4887       return MatchOperand_ParseFail;
4888     }
4889     ++Count;
4890     // Parse the lane specifier if present.
4891     VectorLaneTy NextLaneKind;
4892     unsigned NextLaneIndex;
4893     SMLoc EndLoc = Parser.getTok().getLoc();
4894     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4895       return MatchOperand_ParseFail;
4896     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4897       Error(EndLoc, "mismatched lane index in register list");
4898       return MatchOperand_ParseFail;
4899     }
4900   }
4901 
4902   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4903     Error(Parser.getTok().getLoc(), "'}' expected");
4904     return MatchOperand_ParseFail;
4905   }
4906   E = Parser.getTok().getEndLoc();
4907   Parser.Lex(); // Eat '}' token.
4908 
4909   switch (LaneKind) {
4910   case NoLanes:
4911   case AllLanes: {
4912     // Two-register operands have been converted to the
4913     // composite register classes.
4914     if (Count == 2 && !hasMVE()) {
4915       const MCRegisterClass *RC = (Spacing == 1) ?
4916         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4917         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4918       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4919     }
4920     auto Create = (LaneKind == NoLanes ? ARMOperand::CreateVectorList :
4921                    ARMOperand::CreateVectorListAllLanes);
4922     Operands.push_back(Create(FirstReg, Count, (Spacing == 2), S, E));
4923     break;
4924   }
4925   case IndexedLane:
4926     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4927                                                            LaneIndex,
4928                                                            (Spacing == 2),
4929                                                            S, E));
4930     break;
4931   }
4932   return MatchOperand_Success;
4933 }
4934 
4935 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4936 OperandMatchResultTy
4937 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4938   MCAsmParser &Parser = getParser();
4939   SMLoc S = Parser.getTok().getLoc();
4940   const AsmToken &Tok = Parser.getTok();
4941   unsigned Opt;
4942 
4943   if (Tok.is(AsmToken::Identifier)) {
4944     StringRef OptStr = Tok.getString();
4945 
4946     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4947       .Case("sy",    ARM_MB::SY)
4948       .Case("st",    ARM_MB::ST)
4949       .Case("ld",    ARM_MB::LD)
4950       .Case("sh",    ARM_MB::ISH)
4951       .Case("ish",   ARM_MB::ISH)
4952       .Case("shst",  ARM_MB::ISHST)
4953       .Case("ishst", ARM_MB::ISHST)
4954       .Case("ishld", ARM_MB::ISHLD)
4955       .Case("nsh",   ARM_MB::NSH)
4956       .Case("un",    ARM_MB::NSH)
4957       .Case("nshst", ARM_MB::NSHST)
4958       .Case("nshld", ARM_MB::NSHLD)
4959       .Case("unst",  ARM_MB::NSHST)
4960       .Case("osh",   ARM_MB::OSH)
4961       .Case("oshst", ARM_MB::OSHST)
4962       .Case("oshld", ARM_MB::OSHLD)
4963       .Default(~0U);
4964 
4965     // ishld, oshld, nshld and ld are only available from ARMv8.
4966     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4967                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4968       Opt = ~0U;
4969 
4970     if (Opt == ~0U)
4971       return MatchOperand_NoMatch;
4972 
4973     Parser.Lex(); // Eat identifier token.
4974   } else if (Tok.is(AsmToken::Hash) ||
4975              Tok.is(AsmToken::Dollar) ||
4976              Tok.is(AsmToken::Integer)) {
4977     if (Parser.getTok().isNot(AsmToken::Integer))
4978       Parser.Lex(); // Eat '#' or '$'.
4979     SMLoc Loc = Parser.getTok().getLoc();
4980 
4981     const MCExpr *MemBarrierID;
4982     if (getParser().parseExpression(MemBarrierID)) {
4983       Error(Loc, "illegal expression");
4984       return MatchOperand_ParseFail;
4985     }
4986 
4987     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4988     if (!CE) {
4989       Error(Loc, "constant expression expected");
4990       return MatchOperand_ParseFail;
4991     }
4992 
4993     int Val = CE->getValue();
4994     if (Val & ~0xf) {
4995       Error(Loc, "immediate value out of range");
4996       return MatchOperand_ParseFail;
4997     }
4998 
4999     Opt = ARM_MB::RESERVED_0 + Val;
5000   } else
5001     return MatchOperand_ParseFail;
5002 
5003   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
5004   return MatchOperand_Success;
5005 }
5006 
5007 OperandMatchResultTy
5008 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
5009   MCAsmParser &Parser = getParser();
5010   SMLoc S = Parser.getTok().getLoc();
5011   const AsmToken &Tok = Parser.getTok();
5012 
5013   if (Tok.isNot(AsmToken::Identifier))
5014      return MatchOperand_NoMatch;
5015 
5016   if (!Tok.getString().equals_insensitive("csync"))
5017     return MatchOperand_NoMatch;
5018 
5019   Parser.Lex(); // Eat identifier token.
5020 
5021   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
5022   return MatchOperand_Success;
5023 }
5024 
5025 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
5026 OperandMatchResultTy
5027 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
5028   MCAsmParser &Parser = getParser();
5029   SMLoc S = Parser.getTok().getLoc();
5030   const AsmToken &Tok = Parser.getTok();
5031   unsigned Opt;
5032 
5033   if (Tok.is(AsmToken::Identifier)) {
5034     StringRef OptStr = Tok.getString();
5035 
5036     if (OptStr.equals_insensitive("sy"))
5037       Opt = ARM_ISB::SY;
5038     else
5039       return MatchOperand_NoMatch;
5040 
5041     Parser.Lex(); // Eat identifier token.
5042   } else if (Tok.is(AsmToken::Hash) ||
5043              Tok.is(AsmToken::Dollar) ||
5044              Tok.is(AsmToken::Integer)) {
5045     if (Parser.getTok().isNot(AsmToken::Integer))
5046       Parser.Lex(); // Eat '#' or '$'.
5047     SMLoc Loc = Parser.getTok().getLoc();
5048 
5049     const MCExpr *ISBarrierID;
5050     if (getParser().parseExpression(ISBarrierID)) {
5051       Error(Loc, "illegal expression");
5052       return MatchOperand_ParseFail;
5053     }
5054 
5055     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
5056     if (!CE) {
5057       Error(Loc, "constant expression expected");
5058       return MatchOperand_ParseFail;
5059     }
5060 
5061     int Val = CE->getValue();
5062     if (Val & ~0xf) {
5063       Error(Loc, "immediate value out of range");
5064       return MatchOperand_ParseFail;
5065     }
5066 
5067     Opt = ARM_ISB::RESERVED_0 + Val;
5068   } else
5069     return MatchOperand_ParseFail;
5070 
5071   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
5072           (ARM_ISB::InstSyncBOpt)Opt, S));
5073   return MatchOperand_Success;
5074 }
5075 
5076 
5077 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
5078 OperandMatchResultTy
5079 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
5080   MCAsmParser &Parser = getParser();
5081   SMLoc S = Parser.getTok().getLoc();
5082   const AsmToken &Tok = Parser.getTok();
5083   if (!Tok.is(AsmToken::Identifier))
5084     return MatchOperand_NoMatch;
5085   StringRef IFlagsStr = Tok.getString();
5086 
5087   // An iflags string of "none" is interpreted to mean that none of the AIF
5088   // bits are set.  Not a terribly useful instruction, but a valid encoding.
5089   unsigned IFlags = 0;
5090   if (IFlagsStr != "none") {
5091         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
5092       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
5093         .Case("a", ARM_PROC::A)
5094         .Case("i", ARM_PROC::I)
5095         .Case("f", ARM_PROC::F)
5096         .Default(~0U);
5097 
5098       // If some specific iflag is already set, it means that some letter is
5099       // present more than once, this is not acceptable.
5100       if (Flag == ~0U || (IFlags & Flag))
5101         return MatchOperand_NoMatch;
5102 
5103       IFlags |= Flag;
5104     }
5105   }
5106 
5107   Parser.Lex(); // Eat identifier token.
5108   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
5109   return MatchOperand_Success;
5110 }
5111 
5112 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
5113 OperandMatchResultTy
5114 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
5115   MCAsmParser &Parser = getParser();
5116   SMLoc S = Parser.getTok().getLoc();
5117   const AsmToken &Tok = Parser.getTok();
5118 
5119   if (Tok.is(AsmToken::Integer)) {
5120     int64_t Val = Tok.getIntVal();
5121     if (Val > 255 || Val < 0) {
5122       return MatchOperand_NoMatch;
5123     }
5124     unsigned SYSmvalue = Val & 0xFF;
5125     Parser.Lex();
5126     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5127     return MatchOperand_Success;
5128   }
5129 
5130   if (!Tok.is(AsmToken::Identifier))
5131     return MatchOperand_NoMatch;
5132   StringRef Mask = Tok.getString();
5133 
5134   if (isMClass()) {
5135     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
5136     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
5137       return MatchOperand_NoMatch;
5138 
5139     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
5140 
5141     Parser.Lex(); // Eat identifier token.
5142     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5143     return MatchOperand_Success;
5144   }
5145 
5146   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
5147   size_t Start = 0, Next = Mask.find('_');
5148   StringRef Flags = "";
5149   std::string SpecReg = Mask.slice(Start, Next).lower();
5150   if (Next != StringRef::npos)
5151     Flags = Mask.slice(Next+1, Mask.size());
5152 
5153   // FlagsVal contains the complete mask:
5154   // 3-0: Mask
5155   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5156   unsigned FlagsVal = 0;
5157 
5158   if (SpecReg == "apsr") {
5159     FlagsVal = StringSwitch<unsigned>(Flags)
5160     .Case("nzcvq",  0x8) // same as CPSR_f
5161     .Case("g",      0x4) // same as CPSR_s
5162     .Case("nzcvqg", 0xc) // same as CPSR_fs
5163     .Default(~0U);
5164 
5165     if (FlagsVal == ~0U) {
5166       if (!Flags.empty())
5167         return MatchOperand_NoMatch;
5168       else
5169         FlagsVal = 8; // No flag
5170     }
5171   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
5172     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
5173     if (Flags == "all" || Flags == "")
5174       Flags = "fc";
5175     for (int i = 0, e = Flags.size(); i != e; ++i) {
5176       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
5177       .Case("c", 1)
5178       .Case("x", 2)
5179       .Case("s", 4)
5180       .Case("f", 8)
5181       .Default(~0U);
5182 
5183       // If some specific flag is already set, it means that some letter is
5184       // present more than once, this is not acceptable.
5185       if (Flag == ~0U || (FlagsVal & Flag))
5186         return MatchOperand_NoMatch;
5187       FlagsVal |= Flag;
5188     }
5189   } else // No match for special register.
5190     return MatchOperand_NoMatch;
5191 
5192   // Special register without flags is NOT equivalent to "fc" flags.
5193   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
5194   // two lines would enable gas compatibility at the expense of breaking
5195   // round-tripping.
5196   //
5197   // if (!FlagsVal)
5198   //  FlagsVal = 0x9;
5199 
5200   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5201   if (SpecReg == "spsr")
5202     FlagsVal |= 16;
5203 
5204   Parser.Lex(); // Eat identifier token.
5205   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
5206   return MatchOperand_Success;
5207 }
5208 
5209 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
5210 /// use in the MRS/MSR instructions added to support virtualization.
5211 OperandMatchResultTy
5212 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
5213   MCAsmParser &Parser = getParser();
5214   SMLoc S = Parser.getTok().getLoc();
5215   const AsmToken &Tok = Parser.getTok();
5216   if (!Tok.is(AsmToken::Identifier))
5217     return MatchOperand_NoMatch;
5218   StringRef RegName = Tok.getString();
5219 
5220   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
5221   if (!TheReg)
5222     return MatchOperand_NoMatch;
5223   unsigned Encoding = TheReg->Encoding;
5224 
5225   Parser.Lex(); // Eat identifier token.
5226   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
5227   return MatchOperand_Success;
5228 }
5229 
5230 OperandMatchResultTy
5231 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
5232                           int High) {
5233   MCAsmParser &Parser = getParser();
5234   const AsmToken &Tok = Parser.getTok();
5235   if (Tok.isNot(AsmToken::Identifier)) {
5236     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5237     return MatchOperand_ParseFail;
5238   }
5239   StringRef ShiftName = Tok.getString();
5240   std::string LowerOp = Op.lower();
5241   std::string UpperOp = Op.upper();
5242   if (ShiftName != LowerOp && ShiftName != UpperOp) {
5243     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5244     return MatchOperand_ParseFail;
5245   }
5246   Parser.Lex(); // Eat shift type token.
5247 
5248   // There must be a '#' and a shift amount.
5249   if (Parser.getTok().isNot(AsmToken::Hash) &&
5250       Parser.getTok().isNot(AsmToken::Dollar)) {
5251     Error(Parser.getTok().getLoc(), "'#' expected");
5252     return MatchOperand_ParseFail;
5253   }
5254   Parser.Lex(); // Eat hash token.
5255 
5256   const MCExpr *ShiftAmount;
5257   SMLoc Loc = Parser.getTok().getLoc();
5258   SMLoc EndLoc;
5259   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5260     Error(Loc, "illegal expression");
5261     return MatchOperand_ParseFail;
5262   }
5263   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5264   if (!CE) {
5265     Error(Loc, "constant expression expected");
5266     return MatchOperand_ParseFail;
5267   }
5268   int Val = CE->getValue();
5269   if (Val < Low || Val > High) {
5270     Error(Loc, "immediate value out of range");
5271     return MatchOperand_ParseFail;
5272   }
5273 
5274   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
5275 
5276   return MatchOperand_Success;
5277 }
5278 
5279 OperandMatchResultTy
5280 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
5281   MCAsmParser &Parser = getParser();
5282   const AsmToken &Tok = Parser.getTok();
5283   SMLoc S = Tok.getLoc();
5284   if (Tok.isNot(AsmToken::Identifier)) {
5285     Error(S, "'be' or 'le' operand expected");
5286     return MatchOperand_ParseFail;
5287   }
5288   int Val = StringSwitch<int>(Tok.getString().lower())
5289     .Case("be", 1)
5290     .Case("le", 0)
5291     .Default(-1);
5292   Parser.Lex(); // Eat the token.
5293 
5294   if (Val == -1) {
5295     Error(S, "'be' or 'le' operand expected");
5296     return MatchOperand_ParseFail;
5297   }
5298   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
5299                                                                   getContext()),
5300                                            S, Tok.getEndLoc()));
5301   return MatchOperand_Success;
5302 }
5303 
5304 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
5305 /// instructions. Legal values are:
5306 ///     lsl #n  'n' in [0,31]
5307 ///     asr #n  'n' in [1,32]
5308 ///             n == 32 encoded as n == 0.
5309 OperandMatchResultTy
5310 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
5311   MCAsmParser &Parser = getParser();
5312   const AsmToken &Tok = Parser.getTok();
5313   SMLoc S = Tok.getLoc();
5314   if (Tok.isNot(AsmToken::Identifier)) {
5315     Error(S, "shift operator 'asr' or 'lsl' expected");
5316     return MatchOperand_ParseFail;
5317   }
5318   StringRef ShiftName = Tok.getString();
5319   bool isASR;
5320   if (ShiftName == "lsl" || ShiftName == "LSL")
5321     isASR = false;
5322   else if (ShiftName == "asr" || ShiftName == "ASR")
5323     isASR = true;
5324   else {
5325     Error(S, "shift operator 'asr' or 'lsl' expected");
5326     return MatchOperand_ParseFail;
5327   }
5328   Parser.Lex(); // Eat the operator.
5329 
5330   // A '#' and a shift amount.
5331   if (Parser.getTok().isNot(AsmToken::Hash) &&
5332       Parser.getTok().isNot(AsmToken::Dollar)) {
5333     Error(Parser.getTok().getLoc(), "'#' expected");
5334     return MatchOperand_ParseFail;
5335   }
5336   Parser.Lex(); // Eat hash token.
5337   SMLoc ExLoc = Parser.getTok().getLoc();
5338 
5339   const MCExpr *ShiftAmount;
5340   SMLoc EndLoc;
5341   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5342     Error(ExLoc, "malformed shift expression");
5343     return MatchOperand_ParseFail;
5344   }
5345   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5346   if (!CE) {
5347     Error(ExLoc, "shift amount must be an immediate");
5348     return MatchOperand_ParseFail;
5349   }
5350 
5351   int64_t Val = CE->getValue();
5352   if (isASR) {
5353     // Shift amount must be in [1,32]
5354     if (Val < 1 || Val > 32) {
5355       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
5356       return MatchOperand_ParseFail;
5357     }
5358     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
5359     if (isThumb() && Val == 32) {
5360       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
5361       return MatchOperand_ParseFail;
5362     }
5363     if (Val == 32) Val = 0;
5364   } else {
5365     // Shift amount must be in [1,32]
5366     if (Val < 0 || Val > 31) {
5367       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
5368       return MatchOperand_ParseFail;
5369     }
5370   }
5371 
5372   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
5373 
5374   return MatchOperand_Success;
5375 }
5376 
5377 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
5378 /// of instructions. Legal values are:
5379 ///     ror #n  'n' in {0, 8, 16, 24}
5380 OperandMatchResultTy
5381 ARMAsmParser::parseRotImm(OperandVector &Operands) {
5382   MCAsmParser &Parser = getParser();
5383   const AsmToken &Tok = Parser.getTok();
5384   SMLoc S = Tok.getLoc();
5385   if (Tok.isNot(AsmToken::Identifier))
5386     return MatchOperand_NoMatch;
5387   StringRef ShiftName = Tok.getString();
5388   if (ShiftName != "ror" && ShiftName != "ROR")
5389     return MatchOperand_NoMatch;
5390   Parser.Lex(); // Eat the operator.
5391 
5392   // A '#' and a rotate amount.
5393   if (Parser.getTok().isNot(AsmToken::Hash) &&
5394       Parser.getTok().isNot(AsmToken::Dollar)) {
5395     Error(Parser.getTok().getLoc(), "'#' expected");
5396     return MatchOperand_ParseFail;
5397   }
5398   Parser.Lex(); // Eat hash token.
5399   SMLoc ExLoc = Parser.getTok().getLoc();
5400 
5401   const MCExpr *ShiftAmount;
5402   SMLoc EndLoc;
5403   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5404     Error(ExLoc, "malformed rotate expression");
5405     return MatchOperand_ParseFail;
5406   }
5407   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5408   if (!CE) {
5409     Error(ExLoc, "rotate amount must be an immediate");
5410     return MatchOperand_ParseFail;
5411   }
5412 
5413   int64_t Val = CE->getValue();
5414   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
5415   // normally, zero is represented in asm by omitting the rotate operand
5416   // entirely.
5417   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
5418     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
5419     return MatchOperand_ParseFail;
5420   }
5421 
5422   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
5423 
5424   return MatchOperand_Success;
5425 }
5426 
5427 OperandMatchResultTy
5428 ARMAsmParser::parseModImm(OperandVector &Operands) {
5429   MCAsmParser &Parser = getParser();
5430   MCAsmLexer &Lexer = getLexer();
5431   int64_t Imm1, Imm2;
5432 
5433   SMLoc S = Parser.getTok().getLoc();
5434 
5435   // 1) A mod_imm operand can appear in the place of a register name:
5436   //   add r0, #mod_imm
5437   //   add r0, r0, #mod_imm
5438   // to correctly handle the latter, we bail out as soon as we see an
5439   // identifier.
5440   //
5441   // 2) Similarly, we do not want to parse into complex operands:
5442   //   mov r0, #mod_imm
5443   //   mov r0, :lower16:(_foo)
5444   if (Parser.getTok().is(AsmToken::Identifier) ||
5445       Parser.getTok().is(AsmToken::Colon))
5446     return MatchOperand_NoMatch;
5447 
5448   // Hash (dollar) is optional as per the ARMARM
5449   if (Parser.getTok().is(AsmToken::Hash) ||
5450       Parser.getTok().is(AsmToken::Dollar)) {
5451     // Avoid parsing into complex operands (#:)
5452     if (Lexer.peekTok().is(AsmToken::Colon))
5453       return MatchOperand_NoMatch;
5454 
5455     // Eat the hash (dollar)
5456     Parser.Lex();
5457   }
5458 
5459   SMLoc Sx1, Ex1;
5460   Sx1 = Parser.getTok().getLoc();
5461   const MCExpr *Imm1Exp;
5462   if (getParser().parseExpression(Imm1Exp, Ex1)) {
5463     Error(Sx1, "malformed expression");
5464     return MatchOperand_ParseFail;
5465   }
5466 
5467   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
5468 
5469   if (CE) {
5470     // Immediate must fit within 32-bits
5471     Imm1 = CE->getValue();
5472     int Enc = ARM_AM::getSOImmVal(Imm1);
5473     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
5474       // We have a match!
5475       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
5476                                                   (Enc & 0xF00) >> 7,
5477                                                   Sx1, Ex1));
5478       return MatchOperand_Success;
5479     }
5480 
5481     // We have parsed an immediate which is not for us, fallback to a plain
5482     // immediate. This can happen for instruction aliases. For an example,
5483     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
5484     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
5485     // instruction with a mod_imm operand. The alias is defined such that the
5486     // parser method is shared, that's why we have to do this here.
5487     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
5488       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5489       return MatchOperand_Success;
5490     }
5491   } else {
5492     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
5493     // MCFixup). Fallback to a plain immediate.
5494     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5495     return MatchOperand_Success;
5496   }
5497 
5498   // From this point onward, we expect the input to be a (#bits, #rot) pair
5499   if (Parser.getTok().isNot(AsmToken::Comma)) {
5500     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
5501     return MatchOperand_ParseFail;
5502   }
5503 
5504   if (Imm1 & ~0xFF) {
5505     Error(Sx1, "immediate operand must a number in the range [0, 255]");
5506     return MatchOperand_ParseFail;
5507   }
5508 
5509   // Eat the comma
5510   Parser.Lex();
5511 
5512   // Repeat for #rot
5513   SMLoc Sx2, Ex2;
5514   Sx2 = Parser.getTok().getLoc();
5515 
5516   // Eat the optional hash (dollar)
5517   if (Parser.getTok().is(AsmToken::Hash) ||
5518       Parser.getTok().is(AsmToken::Dollar))
5519     Parser.Lex();
5520 
5521   const MCExpr *Imm2Exp;
5522   if (getParser().parseExpression(Imm2Exp, Ex2)) {
5523     Error(Sx2, "malformed expression");
5524     return MatchOperand_ParseFail;
5525   }
5526 
5527   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
5528 
5529   if (CE) {
5530     Imm2 = CE->getValue();
5531     if (!(Imm2 & ~0x1E)) {
5532       // We have a match!
5533       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
5534       return MatchOperand_Success;
5535     }
5536     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
5537     return MatchOperand_ParseFail;
5538   } else {
5539     Error(Sx2, "constant expression expected");
5540     return MatchOperand_ParseFail;
5541   }
5542 }
5543 
5544 OperandMatchResultTy
5545 ARMAsmParser::parseBitfield(OperandVector &Operands) {
5546   MCAsmParser &Parser = getParser();
5547   SMLoc S = Parser.getTok().getLoc();
5548   // The bitfield descriptor is really two operands, the LSB and the width.
5549   if (Parser.getTok().isNot(AsmToken::Hash) &&
5550       Parser.getTok().isNot(AsmToken::Dollar)) {
5551     Error(Parser.getTok().getLoc(), "'#' expected");
5552     return MatchOperand_ParseFail;
5553   }
5554   Parser.Lex(); // Eat hash token.
5555 
5556   const MCExpr *LSBExpr;
5557   SMLoc E = Parser.getTok().getLoc();
5558   if (getParser().parseExpression(LSBExpr)) {
5559     Error(E, "malformed immediate expression");
5560     return MatchOperand_ParseFail;
5561   }
5562   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
5563   if (!CE) {
5564     Error(E, "'lsb' operand must be an immediate");
5565     return MatchOperand_ParseFail;
5566   }
5567 
5568   int64_t LSB = CE->getValue();
5569   // The LSB must be in the range [0,31]
5570   if (LSB < 0 || LSB > 31) {
5571     Error(E, "'lsb' operand must be in the range [0,31]");
5572     return MatchOperand_ParseFail;
5573   }
5574   E = Parser.getTok().getLoc();
5575 
5576   // Expect another immediate operand.
5577   if (Parser.getTok().isNot(AsmToken::Comma)) {
5578     Error(Parser.getTok().getLoc(), "too few operands");
5579     return MatchOperand_ParseFail;
5580   }
5581   Parser.Lex(); // Eat hash token.
5582   if (Parser.getTok().isNot(AsmToken::Hash) &&
5583       Parser.getTok().isNot(AsmToken::Dollar)) {
5584     Error(Parser.getTok().getLoc(), "'#' expected");
5585     return MatchOperand_ParseFail;
5586   }
5587   Parser.Lex(); // Eat hash token.
5588 
5589   const MCExpr *WidthExpr;
5590   SMLoc EndLoc;
5591   if (getParser().parseExpression(WidthExpr, EndLoc)) {
5592     Error(E, "malformed immediate expression");
5593     return MatchOperand_ParseFail;
5594   }
5595   CE = dyn_cast<MCConstantExpr>(WidthExpr);
5596   if (!CE) {
5597     Error(E, "'width' operand must be an immediate");
5598     return MatchOperand_ParseFail;
5599   }
5600 
5601   int64_t Width = CE->getValue();
5602   // The LSB must be in the range [1,32-lsb]
5603   if (Width < 1 || Width > 32 - LSB) {
5604     Error(E, "'width' operand must be in the range [1,32-lsb]");
5605     return MatchOperand_ParseFail;
5606   }
5607 
5608   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
5609 
5610   return MatchOperand_Success;
5611 }
5612 
5613 OperandMatchResultTy
5614 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
5615   // Check for a post-index addressing register operand. Specifically:
5616   // postidx_reg := '+' register {, shift}
5617   //              | '-' register {, shift}
5618   //              | register {, shift}
5619 
5620   // This method must return MatchOperand_NoMatch without consuming any tokens
5621   // in the case where there is no match, as other alternatives take other
5622   // parse methods.
5623   MCAsmParser &Parser = getParser();
5624   AsmToken Tok = Parser.getTok();
5625   SMLoc S = Tok.getLoc();
5626   bool haveEaten = false;
5627   bool isAdd = true;
5628   if (Tok.is(AsmToken::Plus)) {
5629     Parser.Lex(); // Eat the '+' token.
5630     haveEaten = true;
5631   } else if (Tok.is(AsmToken::Minus)) {
5632     Parser.Lex(); // Eat the '-' token.
5633     isAdd = false;
5634     haveEaten = true;
5635   }
5636 
5637   SMLoc E = Parser.getTok().getEndLoc();
5638   int Reg = tryParseRegister();
5639   if (Reg == -1) {
5640     if (!haveEaten)
5641       return MatchOperand_NoMatch;
5642     Error(Parser.getTok().getLoc(), "register expected");
5643     return MatchOperand_ParseFail;
5644   }
5645 
5646   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
5647   unsigned ShiftImm = 0;
5648   if (Parser.getTok().is(AsmToken::Comma)) {
5649     Parser.Lex(); // Eat the ','.
5650     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
5651       return MatchOperand_ParseFail;
5652 
5653     // FIXME: Only approximates end...may include intervening whitespace.
5654     E = Parser.getTok().getLoc();
5655   }
5656 
5657   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
5658                                                   ShiftImm, S, E));
5659 
5660   return MatchOperand_Success;
5661 }
5662 
5663 OperandMatchResultTy
5664 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
5665   // Check for a post-index addressing register operand. Specifically:
5666   // am3offset := '+' register
5667   //              | '-' register
5668   //              | register
5669   //              | # imm
5670   //              | # + imm
5671   //              | # - imm
5672 
5673   // This method must return MatchOperand_NoMatch without consuming any tokens
5674   // in the case where there is no match, as other alternatives take other
5675   // parse methods.
5676   MCAsmParser &Parser = getParser();
5677   AsmToken Tok = Parser.getTok();
5678   SMLoc S = Tok.getLoc();
5679 
5680   // Do immediates first, as we always parse those if we have a '#'.
5681   if (Parser.getTok().is(AsmToken::Hash) ||
5682       Parser.getTok().is(AsmToken::Dollar)) {
5683     Parser.Lex(); // Eat '#' or '$'.
5684     // Explicitly look for a '-', as we need to encode negative zero
5685     // differently.
5686     bool isNegative = Parser.getTok().is(AsmToken::Minus);
5687     const MCExpr *Offset;
5688     SMLoc E;
5689     if (getParser().parseExpression(Offset, E))
5690       return MatchOperand_ParseFail;
5691     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5692     if (!CE) {
5693       Error(S, "constant expression expected");
5694       return MatchOperand_ParseFail;
5695     }
5696     // Negative zero is encoded as the flag value
5697     // std::numeric_limits<int32_t>::min().
5698     int32_t Val = CE->getValue();
5699     if (isNegative && Val == 0)
5700       Val = std::numeric_limits<int32_t>::min();
5701 
5702     Operands.push_back(
5703       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
5704 
5705     return MatchOperand_Success;
5706   }
5707 
5708   bool haveEaten = false;
5709   bool isAdd = true;
5710   if (Tok.is(AsmToken::Plus)) {
5711     Parser.Lex(); // Eat the '+' token.
5712     haveEaten = true;
5713   } else if (Tok.is(AsmToken::Minus)) {
5714     Parser.Lex(); // Eat the '-' token.
5715     isAdd = false;
5716     haveEaten = true;
5717   }
5718 
5719   Tok = Parser.getTok();
5720   int Reg = tryParseRegister();
5721   if (Reg == -1) {
5722     if (!haveEaten)
5723       return MatchOperand_NoMatch;
5724     Error(Tok.getLoc(), "register expected");
5725     return MatchOperand_ParseFail;
5726   }
5727 
5728   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
5729                                                   0, S, Tok.getEndLoc()));
5730 
5731   return MatchOperand_Success;
5732 }
5733 
5734 /// Convert parsed operands to MCInst.  Needed here because this instruction
5735 /// only has two register operands, but multiplication is commutative so
5736 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
5737 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
5738                                     const OperandVector &Operands) {
5739   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
5740   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
5741   // If we have a three-operand form, make sure to set Rn to be the operand
5742   // that isn't the same as Rd.
5743   unsigned RegOp = 4;
5744   if (Operands.size() == 6 &&
5745       ((ARMOperand &)*Operands[4]).getReg() ==
5746           ((ARMOperand &)*Operands[3]).getReg())
5747     RegOp = 5;
5748   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5749   Inst.addOperand(Inst.getOperand(0));
5750   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5751 }
5752 
5753 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5754                                     const OperandVector &Operands) {
5755   int CondOp = -1, ImmOp = -1;
5756   switch(Inst.getOpcode()) {
5757     case ARM::tB:
5758     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5759 
5760     case ARM::t2B:
5761     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5762 
5763     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5764   }
5765   // first decide whether or not the branch should be conditional
5766   // by looking at it's location relative to an IT block
5767   if(inITBlock()) {
5768     // inside an IT block we cannot have any conditional branches. any
5769     // such instructions needs to be converted to unconditional form
5770     switch(Inst.getOpcode()) {
5771       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5772       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5773     }
5774   } else {
5775     // outside IT blocks we can only have unconditional branches with AL
5776     // condition code or conditional branches with non-AL condition code
5777     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5778     switch(Inst.getOpcode()) {
5779       case ARM::tB:
5780       case ARM::tBcc:
5781         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5782         break;
5783       case ARM::t2B:
5784       case ARM::t2Bcc:
5785         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5786         break;
5787     }
5788   }
5789 
5790   // now decide on encoding size based on branch target range
5791   switch(Inst.getOpcode()) {
5792     // classify tB as either t2B or t1B based on range of immediate operand
5793     case ARM::tB: {
5794       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5795       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5796         Inst.setOpcode(ARM::t2B);
5797       break;
5798     }
5799     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5800     case ARM::tBcc: {
5801       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5802       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5803         Inst.setOpcode(ARM::t2Bcc);
5804       break;
5805     }
5806   }
5807   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5808   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5809 }
5810 
5811 void ARMAsmParser::cvtMVEVMOVQtoDReg(
5812   MCInst &Inst, const OperandVector &Operands) {
5813 
5814   // mnemonic, condition code, Rt, Rt2, Qd, idx, Qd again, idx2
5815   assert(Operands.size() == 8);
5816 
5817   ((ARMOperand &)*Operands[2]).addRegOperands(Inst, 1); // Rt
5818   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1); // Rt2
5819   ((ARMOperand &)*Operands[4]).addRegOperands(Inst, 1); // Qd
5820   ((ARMOperand &)*Operands[5]).addMVEPairVectorIndexOperands(Inst, 1); // idx
5821   // skip second copy of Qd in Operands[6]
5822   ((ARMOperand &)*Operands[7]).addMVEPairVectorIndexOperands(Inst, 1); // idx2
5823   ((ARMOperand &)*Operands[1]).addCondCodeOperands(Inst, 2); // condition code
5824 }
5825 
5826 /// Parse an ARM memory expression, return false if successful else return true
5827 /// or an error.  The first token must be a '[' when called.
5828 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5829   MCAsmParser &Parser = getParser();
5830   SMLoc S, E;
5831   if (Parser.getTok().isNot(AsmToken::LBrac))
5832     return TokError("Token is not a Left Bracket");
5833   S = Parser.getTok().getLoc();
5834   Parser.Lex(); // Eat left bracket token.
5835 
5836   const AsmToken &BaseRegTok = Parser.getTok();
5837   int BaseRegNum = tryParseRegister();
5838   if (BaseRegNum == -1)
5839     return Error(BaseRegTok.getLoc(), "register expected");
5840 
5841   // The next token must either be a comma, a colon or a closing bracket.
5842   const AsmToken &Tok = Parser.getTok();
5843   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5844       !Tok.is(AsmToken::RBrac))
5845     return Error(Tok.getLoc(), "malformed memory operand");
5846 
5847   if (Tok.is(AsmToken::RBrac)) {
5848     E = Tok.getEndLoc();
5849     Parser.Lex(); // Eat right bracket token.
5850 
5851     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5852                                              ARM_AM::no_shift, 0, 0, false,
5853                                              S, E));
5854 
5855     // If there's a pre-indexing writeback marker, '!', just add it as a token
5856     // operand. It's rather odd, but syntactically valid.
5857     if (Parser.getTok().is(AsmToken::Exclaim)) {
5858       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5859       Parser.Lex(); // Eat the '!'.
5860     }
5861 
5862     return false;
5863   }
5864 
5865   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5866          "Lost colon or comma in memory operand?!");
5867   if (Tok.is(AsmToken::Comma)) {
5868     Parser.Lex(); // Eat the comma.
5869   }
5870 
5871   // If we have a ':', it's an alignment specifier.
5872   if (Parser.getTok().is(AsmToken::Colon)) {
5873     Parser.Lex(); // Eat the ':'.
5874     E = Parser.getTok().getLoc();
5875     SMLoc AlignmentLoc = Tok.getLoc();
5876 
5877     const MCExpr *Expr;
5878     if (getParser().parseExpression(Expr))
5879      return true;
5880 
5881     // The expression has to be a constant. Memory references with relocations
5882     // don't come through here, as they use the <label> forms of the relevant
5883     // instructions.
5884     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5885     if (!CE)
5886       return Error (E, "constant expression expected");
5887 
5888     unsigned Align = 0;
5889     switch (CE->getValue()) {
5890     default:
5891       return Error(E,
5892                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5893     case 16:  Align = 2; break;
5894     case 32:  Align = 4; break;
5895     case 64:  Align = 8; break;
5896     case 128: Align = 16; break;
5897     case 256: Align = 32; break;
5898     }
5899 
5900     // Now we should have the closing ']'
5901     if (Parser.getTok().isNot(AsmToken::RBrac))
5902       return Error(Parser.getTok().getLoc(), "']' expected");
5903     E = Parser.getTok().getEndLoc();
5904     Parser.Lex(); // Eat right bracket token.
5905 
5906     // Don't worry about range checking the value here. That's handled by
5907     // the is*() predicates.
5908     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5909                                              ARM_AM::no_shift, 0, Align,
5910                                              false, S, E, AlignmentLoc));
5911 
5912     // If there's a pre-indexing writeback marker, '!', just add it as a token
5913     // operand.
5914     if (Parser.getTok().is(AsmToken::Exclaim)) {
5915       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5916       Parser.Lex(); // Eat the '!'.
5917     }
5918 
5919     return false;
5920   }
5921 
5922   // If we have a '#' or '$', it's an immediate offset, else assume it's a
5923   // register offset. Be friendly and also accept a plain integer or expression
5924   // (without a leading hash) for gas compatibility.
5925   if (Parser.getTok().is(AsmToken::Hash) ||
5926       Parser.getTok().is(AsmToken::Dollar) ||
5927       Parser.getTok().is(AsmToken::LParen) ||
5928       Parser.getTok().is(AsmToken::Integer)) {
5929     if (Parser.getTok().is(AsmToken::Hash) ||
5930         Parser.getTok().is(AsmToken::Dollar))
5931       Parser.Lex(); // Eat '#' or '$'
5932     E = Parser.getTok().getLoc();
5933 
5934     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5935     const MCExpr *Offset, *AdjustedOffset;
5936     if (getParser().parseExpression(Offset))
5937      return true;
5938 
5939     if (const auto *CE = dyn_cast<MCConstantExpr>(Offset)) {
5940       // If the constant was #-0, represent it as
5941       // std::numeric_limits<int32_t>::min().
5942       int32_t Val = CE->getValue();
5943       if (isNegative && Val == 0)
5944         CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5945                                     getContext());
5946       // Don't worry about range checking the value here. That's handled by
5947       // the is*() predicates.
5948       AdjustedOffset = CE;
5949     } else
5950       AdjustedOffset = Offset;
5951     Operands.push_back(ARMOperand::CreateMem(
5952         BaseRegNum, AdjustedOffset, 0, ARM_AM::no_shift, 0, 0, false, S, E));
5953 
5954     // Now we should have the closing ']'
5955     if (Parser.getTok().isNot(AsmToken::RBrac))
5956       return Error(Parser.getTok().getLoc(), "']' expected");
5957     E = Parser.getTok().getEndLoc();
5958     Parser.Lex(); // Eat right bracket token.
5959 
5960     // If there's a pre-indexing writeback marker, '!', just add it as a token
5961     // operand.
5962     if (Parser.getTok().is(AsmToken::Exclaim)) {
5963       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5964       Parser.Lex(); // Eat the '!'.
5965     }
5966 
5967     return false;
5968   }
5969 
5970   // The register offset is optionally preceded by a '+' or '-'
5971   bool isNegative = false;
5972   if (Parser.getTok().is(AsmToken::Minus)) {
5973     isNegative = true;
5974     Parser.Lex(); // Eat the '-'.
5975   } else if (Parser.getTok().is(AsmToken::Plus)) {
5976     // Nothing to do.
5977     Parser.Lex(); // Eat the '+'.
5978   }
5979 
5980   E = Parser.getTok().getLoc();
5981   int OffsetRegNum = tryParseRegister();
5982   if (OffsetRegNum == -1)
5983     return Error(E, "register expected");
5984 
5985   // If there's a shift operator, handle it.
5986   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5987   unsigned ShiftImm = 0;
5988   if (Parser.getTok().is(AsmToken::Comma)) {
5989     Parser.Lex(); // Eat the ','.
5990     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5991       return true;
5992   }
5993 
5994   // Now we should have the closing ']'
5995   if (Parser.getTok().isNot(AsmToken::RBrac))
5996     return Error(Parser.getTok().getLoc(), "']' expected");
5997   E = Parser.getTok().getEndLoc();
5998   Parser.Lex(); // Eat right bracket token.
5999 
6000   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
6001                                            ShiftType, ShiftImm, 0, isNegative,
6002                                            S, E));
6003 
6004   // If there's a pre-indexing writeback marker, '!', just add it as a token
6005   // operand.
6006   if (Parser.getTok().is(AsmToken::Exclaim)) {
6007     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
6008     Parser.Lex(); // Eat the '!'.
6009   }
6010 
6011   return false;
6012 }
6013 
6014 /// parseMemRegOffsetShift - one of these two:
6015 ///   ( lsl | lsr | asr | ror ) , # shift_amount
6016 ///   rrx
6017 /// return true if it parses a shift otherwise it returns false.
6018 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
6019                                           unsigned &Amount) {
6020   MCAsmParser &Parser = getParser();
6021   SMLoc Loc = Parser.getTok().getLoc();
6022   const AsmToken &Tok = Parser.getTok();
6023   if (Tok.isNot(AsmToken::Identifier))
6024     return Error(Loc, "illegal shift operator");
6025   StringRef ShiftName = Tok.getString();
6026   if (ShiftName == "lsl" || ShiftName == "LSL" ||
6027       ShiftName == "asl" || ShiftName == "ASL")
6028     St = ARM_AM::lsl;
6029   else if (ShiftName == "lsr" || ShiftName == "LSR")
6030     St = ARM_AM::lsr;
6031   else if (ShiftName == "asr" || ShiftName == "ASR")
6032     St = ARM_AM::asr;
6033   else if (ShiftName == "ror" || ShiftName == "ROR")
6034     St = ARM_AM::ror;
6035   else if (ShiftName == "rrx" || ShiftName == "RRX")
6036     St = ARM_AM::rrx;
6037   else if (ShiftName == "uxtw" || ShiftName == "UXTW")
6038     St = ARM_AM::uxtw;
6039   else
6040     return Error(Loc, "illegal shift operator");
6041   Parser.Lex(); // Eat shift type token.
6042 
6043   // rrx stands alone.
6044   Amount = 0;
6045   if (St != ARM_AM::rrx) {
6046     Loc = Parser.getTok().getLoc();
6047     // A '#' and a shift amount.
6048     const AsmToken &HashTok = Parser.getTok();
6049     if (HashTok.isNot(AsmToken::Hash) &&
6050         HashTok.isNot(AsmToken::Dollar))
6051       return Error(HashTok.getLoc(), "'#' expected");
6052     Parser.Lex(); // Eat hash token.
6053 
6054     const MCExpr *Expr;
6055     if (getParser().parseExpression(Expr))
6056       return true;
6057     // Range check the immediate.
6058     // lsl, ror: 0 <= imm <= 31
6059     // lsr, asr: 0 <= imm <= 32
6060     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
6061     if (!CE)
6062       return Error(Loc, "shift amount must be an immediate");
6063     int64_t Imm = CE->getValue();
6064     if (Imm < 0 ||
6065         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
6066         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
6067       return Error(Loc, "immediate shift value out of range");
6068     // If <ShiftTy> #0, turn it into a no_shift.
6069     if (Imm == 0)
6070       St = ARM_AM::lsl;
6071     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
6072     if (Imm == 32)
6073       Imm = 0;
6074     Amount = Imm;
6075   }
6076 
6077   return false;
6078 }
6079 
6080 /// parseFPImm - A floating point immediate expression operand.
6081 OperandMatchResultTy
6082 ARMAsmParser::parseFPImm(OperandVector &Operands) {
6083   MCAsmParser &Parser = getParser();
6084   // Anything that can accept a floating point constant as an operand
6085   // needs to go through here, as the regular parseExpression is
6086   // integer only.
6087   //
6088   // This routine still creates a generic Immediate operand, containing
6089   // a bitcast of the 64-bit floating point value. The various operands
6090   // that accept floats can check whether the value is valid for them
6091   // via the standard is*() predicates.
6092 
6093   SMLoc S = Parser.getTok().getLoc();
6094 
6095   if (Parser.getTok().isNot(AsmToken::Hash) &&
6096       Parser.getTok().isNot(AsmToken::Dollar))
6097     return MatchOperand_NoMatch;
6098 
6099   // Disambiguate the VMOV forms that can accept an FP immediate.
6100   // vmov.f32 <sreg>, #imm
6101   // vmov.f64 <dreg>, #imm
6102   // vmov.f32 <dreg>, #imm  @ vector f32x2
6103   // vmov.f32 <qreg>, #imm  @ vector f32x4
6104   //
6105   // There are also the NEON VMOV instructions which expect an
6106   // integer constant. Make sure we don't try to parse an FPImm
6107   // for these:
6108   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
6109   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
6110   bool isVmovf = TyOp.isToken() &&
6111                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
6112                   TyOp.getToken() == ".f16");
6113   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
6114   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
6115                                          Mnemonic.getToken() == "fconsts");
6116   if (!(isVmovf || isFconst))
6117     return MatchOperand_NoMatch;
6118 
6119   Parser.Lex(); // Eat '#' or '$'.
6120 
6121   // Handle negation, as that still comes through as a separate token.
6122   bool isNegative = false;
6123   if (Parser.getTok().is(AsmToken::Minus)) {
6124     isNegative = true;
6125     Parser.Lex();
6126   }
6127   const AsmToken &Tok = Parser.getTok();
6128   SMLoc Loc = Tok.getLoc();
6129   if (Tok.is(AsmToken::Real) && isVmovf) {
6130     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
6131     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
6132     // If we had a '-' in front, toggle the sign bit.
6133     IntVal ^= (uint64_t)isNegative << 31;
6134     Parser.Lex(); // Eat the token.
6135     Operands.push_back(ARMOperand::CreateImm(
6136           MCConstantExpr::create(IntVal, getContext()),
6137           S, Parser.getTok().getLoc()));
6138     return MatchOperand_Success;
6139   }
6140   // Also handle plain integers. Instructions which allow floating point
6141   // immediates also allow a raw encoded 8-bit value.
6142   if (Tok.is(AsmToken::Integer) && isFconst) {
6143     int64_t Val = Tok.getIntVal();
6144     Parser.Lex(); // Eat the token.
6145     if (Val > 255 || Val < 0) {
6146       Error(Loc, "encoded floating point value out of range");
6147       return MatchOperand_ParseFail;
6148     }
6149     float RealVal = ARM_AM::getFPImmFloat(Val);
6150     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
6151 
6152     Operands.push_back(ARMOperand::CreateImm(
6153         MCConstantExpr::create(Val, getContext()), S,
6154         Parser.getTok().getLoc()));
6155     return MatchOperand_Success;
6156   }
6157 
6158   Error(Loc, "invalid floating point immediate");
6159   return MatchOperand_ParseFail;
6160 }
6161 
6162 /// Parse a arm instruction operand.  For now this parses the operand regardless
6163 /// of the mnemonic.
6164 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
6165   MCAsmParser &Parser = getParser();
6166   SMLoc S, E;
6167 
6168   // Check if the current operand has a custom associated parser, if so, try to
6169   // custom parse the operand, or fallback to the general approach.
6170   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
6171   if (ResTy == MatchOperand_Success)
6172     return false;
6173   // If there wasn't a custom match, try the generic matcher below. Otherwise,
6174   // there was a match, but an error occurred, in which case, just return that
6175   // the operand parsing failed.
6176   if (ResTy == MatchOperand_ParseFail)
6177     return true;
6178 
6179   switch (getLexer().getKind()) {
6180   default:
6181     Error(Parser.getTok().getLoc(), "unexpected token in operand");
6182     return true;
6183   case AsmToken::Identifier: {
6184     // If we've seen a branch mnemonic, the next operand must be a label.  This
6185     // is true even if the label is a register name.  So "br r1" means branch to
6186     // label "r1".
6187     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
6188     if (!ExpectLabel) {
6189       if (!tryParseRegisterWithWriteBack(Operands))
6190         return false;
6191       int Res = tryParseShiftRegister(Operands);
6192       if (Res == 0) // success
6193         return false;
6194       else if (Res == -1) // irrecoverable error
6195         return true;
6196       // If this is VMRS, check for the apsr_nzcv operand.
6197       if (Mnemonic == "vmrs" &&
6198           Parser.getTok().getString().equals_insensitive("apsr_nzcv")) {
6199         S = Parser.getTok().getLoc();
6200         Parser.Lex();
6201         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
6202         return false;
6203       }
6204     }
6205 
6206     // Fall though for the Identifier case that is not a register or a
6207     // special name.
6208     LLVM_FALLTHROUGH;
6209   }
6210   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
6211   case AsmToken::Integer: // things like 1f and 2b as a branch targets
6212   case AsmToken::String:  // quoted label names.
6213   case AsmToken::Dot: {   // . as a branch target
6214     // This was not a register so parse other operands that start with an
6215     // identifier (like labels) as expressions and create them as immediates.
6216     const MCExpr *IdVal;
6217     S = Parser.getTok().getLoc();
6218     if (getParser().parseExpression(IdVal))
6219       return true;
6220     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6221     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
6222     return false;
6223   }
6224   case AsmToken::LBrac:
6225     return parseMemory(Operands);
6226   case AsmToken::LCurly:
6227     return parseRegisterList(Operands, !Mnemonic.startswith("clr"));
6228   case AsmToken::Dollar:
6229   case AsmToken::Hash: {
6230     // #42 -> immediate
6231     // $ 42 -> immediate
6232     // $foo -> symbol name
6233     // $42 -> symbol name
6234     S = Parser.getTok().getLoc();
6235 
6236     // Favor the interpretation of $-prefixed operands as symbol names.
6237     // Cases where immediates are explicitly expected are handled by their
6238     // specific ParseMethod implementations.
6239     auto AdjacentToken = getLexer().peekTok(/*ShouldSkipSpace=*/false);
6240     bool ExpectIdentifier = Parser.getTok().is(AsmToken::Dollar) &&
6241                             (AdjacentToken.is(AsmToken::Identifier) ||
6242                              AdjacentToken.is(AsmToken::Integer));
6243     if (!ExpectIdentifier) {
6244       // Token is not part of identifier. Drop leading $ or # before parsing
6245       // expression.
6246       Parser.Lex();
6247     }
6248 
6249     if (Parser.getTok().isNot(AsmToken::Colon)) {
6250       bool IsNegative = Parser.getTok().is(AsmToken::Minus);
6251       const MCExpr *ImmVal;
6252       if (getParser().parseExpression(ImmVal))
6253         return true;
6254       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
6255       if (CE) {
6256         int32_t Val = CE->getValue();
6257         if (IsNegative && Val == 0)
6258           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
6259                                           getContext());
6260       }
6261       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6262       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
6263 
6264       // There can be a trailing '!' on operands that we want as a separate
6265       // '!' Token operand. Handle that here. For example, the compatibility
6266       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
6267       if (Parser.getTok().is(AsmToken::Exclaim)) {
6268         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
6269                                                    Parser.getTok().getLoc()));
6270         Parser.Lex(); // Eat exclaim token
6271       }
6272       return false;
6273     }
6274     // w/ a ':' after the '#', it's just like a plain ':'.
6275     LLVM_FALLTHROUGH;
6276   }
6277   case AsmToken::Colon: {
6278     S = Parser.getTok().getLoc();
6279     // ":lower16:" and ":upper16:" expression prefixes
6280     // FIXME: Check it's an expression prefix,
6281     // e.g. (FOO - :lower16:BAR) isn't legal.
6282     ARMMCExpr::VariantKind RefKind;
6283     if (parsePrefix(RefKind))
6284       return true;
6285 
6286     const MCExpr *SubExprVal;
6287     if (getParser().parseExpression(SubExprVal))
6288       return true;
6289 
6290     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
6291                                               getContext());
6292     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6293     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
6294     return false;
6295   }
6296   case AsmToken::Equal: {
6297     S = Parser.getTok().getLoc();
6298     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
6299       return Error(S, "unexpected token in operand");
6300     Parser.Lex(); // Eat '='
6301     const MCExpr *SubExprVal;
6302     if (getParser().parseExpression(SubExprVal))
6303       return true;
6304     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6305 
6306     // execute-only: we assume that assembly programmers know what they are
6307     // doing and allow literal pool creation here
6308     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
6309     return false;
6310   }
6311   }
6312 }
6313 
6314 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
6315 //  :lower16: and :upper16:.
6316 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
6317   MCAsmParser &Parser = getParser();
6318   RefKind = ARMMCExpr::VK_ARM_None;
6319 
6320   // consume an optional '#' (GNU compatibility)
6321   if (getLexer().is(AsmToken::Hash))
6322     Parser.Lex();
6323 
6324   // :lower16: and :upper16: modifiers
6325   assert(getLexer().is(AsmToken::Colon) && "expected a :");
6326   Parser.Lex(); // Eat ':'
6327 
6328   if (getLexer().isNot(AsmToken::Identifier)) {
6329     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
6330     return true;
6331   }
6332 
6333   enum {
6334     COFF = (1 << MCContext::IsCOFF),
6335     ELF = (1 << MCContext::IsELF),
6336     MACHO = (1 << MCContext::IsMachO),
6337     WASM = (1 << MCContext::IsWasm),
6338   };
6339   static const struct PrefixEntry {
6340     const char *Spelling;
6341     ARMMCExpr::VariantKind VariantKind;
6342     uint8_t SupportedFormats;
6343   } PrefixEntries[] = {
6344     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
6345     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
6346   };
6347 
6348   StringRef IDVal = Parser.getTok().getIdentifier();
6349 
6350   const auto &Prefix =
6351       llvm::find_if(PrefixEntries, [&IDVal](const PrefixEntry &PE) {
6352         return PE.Spelling == IDVal;
6353       });
6354   if (Prefix == std::end(PrefixEntries)) {
6355     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
6356     return true;
6357   }
6358 
6359   uint8_t CurrentFormat;
6360   switch (getContext().getObjectFileType()) {
6361   case MCContext::IsMachO:
6362     CurrentFormat = MACHO;
6363     break;
6364   case MCContext::IsELF:
6365     CurrentFormat = ELF;
6366     break;
6367   case MCContext::IsCOFF:
6368     CurrentFormat = COFF;
6369     break;
6370   case MCContext::IsWasm:
6371     CurrentFormat = WASM;
6372     break;
6373   case MCContext::IsGOFF:
6374   case MCContext::IsXCOFF:
6375     llvm_unreachable("unexpected object format");
6376     break;
6377   }
6378 
6379   if (~Prefix->SupportedFormats & CurrentFormat) {
6380     Error(Parser.getTok().getLoc(),
6381           "cannot represent relocation in the current file format");
6382     return true;
6383   }
6384 
6385   RefKind = Prefix->VariantKind;
6386   Parser.Lex();
6387 
6388   if (getLexer().isNot(AsmToken::Colon)) {
6389     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
6390     return true;
6391   }
6392   Parser.Lex(); // Eat the last ':'
6393 
6394   return false;
6395 }
6396 
6397 /// Given a mnemonic, split out possible predication code and carry
6398 /// setting letters to form a canonical mnemonic and flags.
6399 //
6400 // FIXME: Would be nice to autogen this.
6401 // FIXME: This is a bit of a maze of special cases.
6402 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
6403                                       StringRef ExtraToken,
6404                                       unsigned &PredicationCode,
6405                                       unsigned &VPTPredicationCode,
6406                                       bool &CarrySetting,
6407                                       unsigned &ProcessorIMod,
6408                                       StringRef &ITMask) {
6409   PredicationCode = ARMCC::AL;
6410   VPTPredicationCode = ARMVCC::None;
6411   CarrySetting = false;
6412   ProcessorIMod = 0;
6413 
6414   // Ignore some mnemonics we know aren't predicated forms.
6415   //
6416   // FIXME: Would be nice to autogen this.
6417   if ((Mnemonic == "movs" && isThumb()) ||
6418       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
6419       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
6420       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
6421       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
6422       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
6423       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
6424       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
6425       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
6426       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
6427       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
6428       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
6429       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
6430       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
6431       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
6432       Mnemonic == "vdot"  || Mnemonic == "vmmla" ||
6433       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6434       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6435       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6436       Mnemonic == "wls"   || Mnemonic == "le"    || Mnemonic == "dls" ||
6437       Mnemonic == "csel"  || Mnemonic == "csinc" ||
6438       Mnemonic == "csinv" || Mnemonic == "csneg" || Mnemonic == "cinc" ||
6439       Mnemonic == "cinv"  || Mnemonic == "cneg"  || Mnemonic == "cset" ||
6440       Mnemonic == "csetm" ||
6441       Mnemonic == "aut"   || Mnemonic == "pac" || Mnemonic == "pacbti" ||
6442       Mnemonic == "bti")
6443     return Mnemonic;
6444 
6445   // First, split out any predication code. Ignore mnemonics we know aren't
6446   // predicated but do have a carry-set and so weren't caught above.
6447   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
6448       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
6449       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
6450       Mnemonic != "sbcs" && Mnemonic != "rscs" &&
6451       !(hasMVE() &&
6452         (Mnemonic == "vmine" ||
6453          Mnemonic == "vshle" || Mnemonic == "vshlt" || Mnemonic == "vshllt" ||
6454          Mnemonic == "vrshle" || Mnemonic == "vrshlt" ||
6455          Mnemonic == "vmvne" || Mnemonic == "vorne" ||
6456          Mnemonic == "vnege" || Mnemonic == "vnegt" ||
6457          Mnemonic == "vmule" || Mnemonic == "vmult" ||
6458          Mnemonic == "vrintne" ||
6459          Mnemonic == "vcmult" || Mnemonic == "vcmule" ||
6460          Mnemonic == "vpsele" || Mnemonic == "vpselt" ||
6461          Mnemonic.startswith("vq")))) {
6462     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
6463     if (CC != ~0U) {
6464       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
6465       PredicationCode = CC;
6466     }
6467   }
6468 
6469   // Next, determine if we have a carry setting bit. We explicitly ignore all
6470   // the instructions we know end in 's'.
6471   if (Mnemonic.endswith("s") &&
6472       !(Mnemonic == "cps" || Mnemonic == "mls" ||
6473         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
6474         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
6475         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
6476         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
6477         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
6478         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
6479         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
6480         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
6481         Mnemonic == "bxns" || Mnemonic == "blxns" || Mnemonic == "vfmas" ||
6482         Mnemonic == "vmlas" ||
6483         (Mnemonic == "movs" && isThumb()))) {
6484     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
6485     CarrySetting = true;
6486   }
6487 
6488   // The "cps" instruction can have a interrupt mode operand which is glued into
6489   // the mnemonic. Check if this is the case, split it and parse the imod op
6490   if (Mnemonic.startswith("cps")) {
6491     // Split out any imod code.
6492     unsigned IMod =
6493       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
6494       .Case("ie", ARM_PROC::IE)
6495       .Case("id", ARM_PROC::ID)
6496       .Default(~0U);
6497     if (IMod != ~0U) {
6498       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
6499       ProcessorIMod = IMod;
6500     }
6501   }
6502 
6503   if (isMnemonicVPTPredicable(Mnemonic, ExtraToken) && Mnemonic != "vmovlt" &&
6504       Mnemonic != "vshllt" && Mnemonic != "vrshrnt" && Mnemonic != "vshrnt" &&
6505       Mnemonic != "vqrshrunt" && Mnemonic != "vqshrunt" &&
6506       Mnemonic != "vqrshrnt" && Mnemonic != "vqshrnt" && Mnemonic != "vmullt" &&
6507       Mnemonic != "vqmovnt" && Mnemonic != "vqmovunt" &&
6508       Mnemonic != "vqmovnt" && Mnemonic != "vmovnt" && Mnemonic != "vqdmullt" &&
6509       Mnemonic != "vpnot" && Mnemonic != "vcvtt" && Mnemonic != "vcvt") {
6510     unsigned CC = ARMVectorCondCodeFromString(Mnemonic.substr(Mnemonic.size()-1));
6511     if (CC != ~0U) {
6512       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-1);
6513       VPTPredicationCode = CC;
6514     }
6515     return Mnemonic;
6516   }
6517 
6518   // The "it" instruction has the condition mask on the end of the mnemonic.
6519   if (Mnemonic.startswith("it")) {
6520     ITMask = Mnemonic.slice(2, Mnemonic.size());
6521     Mnemonic = Mnemonic.slice(0, 2);
6522   }
6523 
6524   if (Mnemonic.startswith("vpst")) {
6525     ITMask = Mnemonic.slice(4, Mnemonic.size());
6526     Mnemonic = Mnemonic.slice(0, 4);
6527   }
6528   else if (Mnemonic.startswith("vpt")) {
6529     ITMask = Mnemonic.slice(3, Mnemonic.size());
6530     Mnemonic = Mnemonic.slice(0, 3);
6531   }
6532 
6533   return Mnemonic;
6534 }
6535 
6536 /// Given a canonical mnemonic, determine if the instruction ever allows
6537 /// inclusion of carry set or predication code operands.
6538 //
6539 // FIXME: It would be nice to autogen this.
6540 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic,
6541                                          StringRef ExtraToken,
6542                                          StringRef FullInst,
6543                                          bool &CanAcceptCarrySet,
6544                                          bool &CanAcceptPredicationCode,
6545                                          bool &CanAcceptVPTPredicationCode) {
6546   CanAcceptVPTPredicationCode = isMnemonicVPTPredicable(Mnemonic, ExtraToken);
6547 
6548   CanAcceptCarrySet =
6549       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6550       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
6551       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
6552       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
6553       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
6554       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
6555       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
6556       (!isThumb() &&
6557        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
6558         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
6559 
6560   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
6561       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
6562       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
6563       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
6564       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
6565       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
6566       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
6567       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
6568       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
6569       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
6570       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
6571       Mnemonic == "vmovx" || Mnemonic == "vins" ||
6572       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6573       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6574       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6575       Mnemonic == "vfmat" || Mnemonic == "vfmab" ||
6576       Mnemonic == "vdot"  || Mnemonic == "vmmla" ||
6577       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
6578       Mnemonic == "pssbb" || Mnemonic == "vsmmla" ||
6579       Mnemonic == "vummla" || Mnemonic == "vusmmla" ||
6580       Mnemonic == "vusdot" || Mnemonic == "vsudot" ||
6581       Mnemonic == "bfcsel" || Mnemonic == "wls" ||
6582       Mnemonic == "dls" || Mnemonic == "le" || Mnemonic == "csel" ||
6583       Mnemonic == "csinc" || Mnemonic == "csinv" || Mnemonic == "csneg" ||
6584       Mnemonic == "cinc" || Mnemonic == "cinv" || Mnemonic == "cneg" ||
6585       Mnemonic == "cset" || Mnemonic == "csetm" ||
6586       (hasCDE() && MS.isCDEInstr(Mnemonic) &&
6587        !MS.isITPredicableCDEInstr(Mnemonic)) ||
6588       Mnemonic.startswith("vpt") || Mnemonic.startswith("vpst") ||
6589       Mnemonic == "pac" || Mnemonic == "pacbti" || Mnemonic == "aut" ||
6590       Mnemonic == "bti" ||
6591       (hasMVE() &&
6592        (Mnemonic.startswith("vst2") || Mnemonic.startswith("vld2") ||
6593         Mnemonic.startswith("vst4") || Mnemonic.startswith("vld4") ||
6594         Mnemonic.startswith("wlstp") || Mnemonic.startswith("dlstp") ||
6595         Mnemonic.startswith("letp")))) {
6596     // These mnemonics are never predicable
6597     CanAcceptPredicationCode = false;
6598   } else if (!isThumb()) {
6599     // Some instructions are only predicable in Thumb mode
6600     CanAcceptPredicationCode =
6601         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
6602         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
6603         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
6604         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
6605         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
6606         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
6607         Mnemonic != "tsb" &&
6608         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
6609   } else if (isThumbOne()) {
6610     if (hasV6MOps())
6611       CanAcceptPredicationCode = Mnemonic != "movs";
6612     else
6613       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
6614   } else
6615     CanAcceptPredicationCode = true;
6616 }
6617 
6618 // Some Thumb instructions have two operand forms that are not
6619 // available as three operand, convert to two operand form if possible.
6620 //
6621 // FIXME: We would really like to be able to tablegen'erate this.
6622 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
6623                                                  bool CarrySetting,
6624                                                  OperandVector &Operands) {
6625   if (Operands.size() != 6)
6626     return;
6627 
6628   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6629         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
6630   if (!Op3.isReg() || !Op4.isReg())
6631     return;
6632 
6633   auto Op3Reg = Op3.getReg();
6634   auto Op4Reg = Op4.getReg();
6635 
6636   // For most Thumb2 cases we just generate the 3 operand form and reduce
6637   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
6638   // won't accept SP or PC so we do the transformation here taking care
6639   // with immediate range in the 'add sp, sp #imm' case.
6640   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
6641   if (isThumbTwo()) {
6642     if (Mnemonic != "add")
6643       return;
6644     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
6645                         (Op5.isReg() && Op5.getReg() == ARM::PC);
6646     if (!TryTransform) {
6647       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
6648                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
6649                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
6650                        Op5.isImm() && !Op5.isImm0_508s4());
6651     }
6652     if (!TryTransform)
6653       return;
6654   } else if (!isThumbOne())
6655     return;
6656 
6657   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
6658         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6659         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
6660         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
6661     return;
6662 
6663   // If first 2 operands of a 3 operand instruction are the same
6664   // then transform to 2 operand version of the same instruction
6665   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
6666   bool Transform = Op3Reg == Op4Reg;
6667 
6668   // For communtative operations, we might be able to transform if we swap
6669   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
6670   // as tADDrsp.
6671   const ARMOperand *LastOp = &Op5;
6672   bool Swap = false;
6673   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
6674       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
6675        Mnemonic == "and" || Mnemonic == "eor" ||
6676        Mnemonic == "adc" || Mnemonic == "orr")) {
6677     Swap = true;
6678     LastOp = &Op4;
6679     Transform = true;
6680   }
6681 
6682   // If both registers are the same then remove one of them from
6683   // the operand list, with certain exceptions.
6684   if (Transform) {
6685     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
6686     // 2 operand forms don't exist.
6687     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
6688         LastOp->isReg())
6689       Transform = false;
6690 
6691     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
6692     // 3-bits because the ARMARM says not to.
6693     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
6694       Transform = false;
6695   }
6696 
6697   if (Transform) {
6698     if (Swap)
6699       std::swap(Op4, Op5);
6700     Operands.erase(Operands.begin() + 3);
6701   }
6702 }
6703 
6704 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
6705                                           OperandVector &Operands) {
6706   // FIXME: This is all horribly hacky. We really need a better way to deal
6707   // with optional operands like this in the matcher table.
6708 
6709   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
6710   // another does not. Specifically, the MOVW instruction does not. So we
6711   // special case it here and remove the defaulted (non-setting) cc_out
6712   // operand if that's the instruction we're trying to match.
6713   //
6714   // We do this as post-processing of the explicit operands rather than just
6715   // conditionally adding the cc_out in the first place because we need
6716   // to check the type of the parsed immediate operand.
6717   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
6718       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
6719       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
6720       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6721     return true;
6722 
6723   // Register-register 'add' for thumb does not have a cc_out operand
6724   // when there are only two register operands.
6725   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
6726       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6727       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6728       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6729     return true;
6730   // Register-register 'add' for thumb does not have a cc_out operand
6731   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
6732   // have to check the immediate range here since Thumb2 has a variant
6733   // that can handle a different range and has a cc_out operand.
6734   if (((isThumb() && Mnemonic == "add") ||
6735        (isThumbTwo() && Mnemonic == "sub")) &&
6736       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6737       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6738       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
6739       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6740       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
6741        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
6742     return true;
6743   // For Thumb2, add/sub immediate does not have a cc_out operand for the
6744   // imm0_4095 variant. That's the least-preferred variant when
6745   // selecting via the generic "add" mnemonic, so to know that we
6746   // should remove the cc_out operand, we have to explicitly check that
6747   // it's not one of the other variants. Ugh.
6748   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6749       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6750       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6751       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6752     // Nest conditions rather than one big 'if' statement for readability.
6753     //
6754     // If both registers are low, we're in an IT block, and the immediate is
6755     // in range, we should use encoding T1 instead, which has a cc_out.
6756     if (inITBlock() &&
6757         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
6758         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
6759         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
6760       return false;
6761     // Check against T3. If the second register is the PC, this is an
6762     // alternate form of ADR, which uses encoding T4, so check for that too.
6763     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
6764         (static_cast<ARMOperand &>(*Operands[5]).isT2SOImm() ||
6765          static_cast<ARMOperand &>(*Operands[5]).isT2SOImmNeg()))
6766       return false;
6767 
6768     // Otherwise, we use encoding T4, which does not have a cc_out
6769     // operand.
6770     return true;
6771   }
6772 
6773   // The thumb2 multiply instruction doesn't have a CCOut register, so
6774   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
6775   // use the 16-bit encoding or not.
6776   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
6777       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6778       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6779       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6780       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
6781       // If the registers aren't low regs, the destination reg isn't the
6782       // same as one of the source regs, or the cc_out operand is zero
6783       // outside of an IT block, we have to use the 32-bit encoding, so
6784       // remove the cc_out operand.
6785       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6786        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6787        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
6788        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6789                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
6790                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6791                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
6792     return true;
6793 
6794   // Also check the 'mul' syntax variant that doesn't specify an explicit
6795   // destination register.
6796   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
6797       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6798       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6799       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6800       // If the registers aren't low regs  or the cc_out operand is zero
6801       // outside of an IT block, we have to use the 32-bit encoding, so
6802       // remove the cc_out operand.
6803       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6804        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6805        !inITBlock()))
6806     return true;
6807 
6808   // Register-register 'add/sub' for thumb does not have a cc_out operand
6809   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
6810   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
6811   // right, this will result in better diagnostics (which operand is off)
6812   // anyway.
6813   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
6814       (Operands.size() == 5 || Operands.size() == 6) &&
6815       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6816       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
6817       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6818       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
6819        (Operands.size() == 6 &&
6820         static_cast<ARMOperand &>(*Operands[5]).isImm()))) {
6821     // Thumb2 (add|sub){s}{p}.w GPRnopc, sp, #{T2SOImm} has cc_out
6822     return (!(isThumbTwo() &&
6823               (static_cast<ARMOperand &>(*Operands[4]).isT2SOImm() ||
6824                static_cast<ARMOperand &>(*Operands[4]).isT2SOImmNeg())));
6825   }
6826   // Fixme: Should join all the thumb+thumb2 (add|sub) in a single if case
6827   // Thumb2 ADD r0, #4095 -> ADDW r0, r0, #4095 (T4)
6828   // Thumb2 SUB r0, #4095 -> SUBW r0, r0, #4095
6829   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6830       (Operands.size() == 5) &&
6831       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6832       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::SP &&
6833       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::PC &&
6834       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6835       static_cast<ARMOperand &>(*Operands[4]).isImm()) {
6836     const ARMOperand &IMM = static_cast<ARMOperand &>(*Operands[4]);
6837     if (IMM.isT2SOImm() || IMM.isT2SOImmNeg())
6838       return false; // add.w / sub.w
6839     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IMM.getImm())) {
6840       const int64_t Value = CE->getValue();
6841       // Thumb1 imm8 sub / add
6842       if ((Value < ((1 << 7) - 1) << 2) && inITBlock() && (!(Value & 3)) &&
6843           isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()))
6844         return false;
6845       return true; // Thumb2 T4 addw / subw
6846     }
6847   }
6848   return false;
6849 }
6850 
6851 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
6852                                               OperandVector &Operands) {
6853   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
6854   unsigned RegIdx = 3;
6855   if ((((Mnemonic == "vrintz" || Mnemonic == "vrintx") && !hasMVE()) ||
6856       Mnemonic == "vrintr") &&
6857       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
6858        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
6859     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6860         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
6861          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
6862       RegIdx = 4;
6863 
6864     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
6865         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6866              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
6867          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6868              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
6869       return true;
6870   }
6871   return false;
6872 }
6873 
6874 bool ARMAsmParser::shouldOmitVectorPredicateOperand(StringRef Mnemonic,
6875                                                     OperandVector &Operands) {
6876   if (!hasMVE() || Operands.size() < 3)
6877     return true;
6878 
6879   if (Mnemonic.startswith("vld2") || Mnemonic.startswith("vld4") ||
6880       Mnemonic.startswith("vst2") || Mnemonic.startswith("vst4"))
6881     return true;
6882 
6883   if (Mnemonic.startswith("vctp") || Mnemonic.startswith("vpnot"))
6884     return false;
6885 
6886   if (Mnemonic.startswith("vmov") &&
6887       !(Mnemonic.startswith("vmovl") || Mnemonic.startswith("vmovn") ||
6888         Mnemonic.startswith("vmovx"))) {
6889     for (auto &Operand : Operands) {
6890       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6891           ((*Operand).isReg() &&
6892            (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
6893              (*Operand).getReg()) ||
6894             ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6895               (*Operand).getReg())))) {
6896         return true;
6897       }
6898     }
6899     return false;
6900   } else {
6901     for (auto &Operand : Operands) {
6902       // We check the larger class QPR instead of just the legal class
6903       // MQPR, to more accurately report errors when using Q registers
6904       // outside of the allowed range.
6905       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6906           (Operand->isReg() &&
6907            (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6908              Operand->getReg()))))
6909         return false;
6910     }
6911     return true;
6912   }
6913 }
6914 
6915 static bool isDataTypeToken(StringRef Tok) {
6916   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
6917     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6918     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6919     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6920     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6921     Tok == ".f" || Tok == ".d";
6922 }
6923 
6924 // FIXME: This bit should probably be handled via an explicit match class
6925 // in the .td files that matches the suffix instead of having it be
6926 // a literal string token the way it is now.
6927 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6928   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6929 }
6930 
6931 static void applyMnemonicAliases(StringRef &Mnemonic,
6932                                  const FeatureBitset &Features,
6933                                  unsigned VariantID);
6934 
6935 // The GNU assembler has aliases of ldrd and strd with the second register
6936 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6937 //
6938 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6939 // the assembly parser could then generate confusing diagnostics refering to
6940 // it. If we do find anything that prevents us from doing the transformation we
6941 // bail out, and let the assembly parser report an error on the instruction as
6942 // it is written.
6943 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6944                                      OperandVector &Operands) {
6945   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6946     return;
6947   if (Operands.size() < 4)
6948     return;
6949 
6950   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6951   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6952 
6953   if (!Op2.isReg())
6954     return;
6955   if (!Op3.isGPRMem())
6956     return;
6957 
6958   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6959   if (!GPR.contains(Op2.getReg()))
6960     return;
6961 
6962   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6963   if (!isThumb() && (RtEncoding & 1)) {
6964     // In ARM mode, the registers must be from an aligned pair, this
6965     // restriction does not apply in Thumb mode.
6966     return;
6967   }
6968   if (Op2.getReg() == ARM::PC)
6969     return;
6970   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6971   if (!PairedReg || PairedReg == ARM::PC ||
6972       (PairedReg == ARM::SP && !hasV8Ops()))
6973     return;
6974 
6975   Operands.insert(
6976       Operands.begin() + 3,
6977       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6978 }
6979 
6980 // Dual-register instruction have the following syntax:
6981 // <mnemonic> <predicate>? <coproc>, <Rdest>, <Rdest+1>, <Rsrc>, ..., #imm
6982 // This function tries to remove <Rdest+1> and replace <Rdest> with a pair
6983 // operand. If the conversion fails an error is diagnosed, and the function
6984 // returns true.
6985 bool ARMAsmParser::CDEConvertDualRegOperand(StringRef Mnemonic,
6986                                             OperandVector &Operands) {
6987   assert(MS.isCDEDualRegInstr(Mnemonic));
6988   bool isPredicable =
6989       Mnemonic == "cx1da" || Mnemonic == "cx2da" || Mnemonic == "cx3da";
6990   size_t NumPredOps = isPredicable ? 1 : 0;
6991 
6992   if (Operands.size() <= 3 + NumPredOps)
6993     return false;
6994 
6995   StringRef Op2Diag(
6996       "operand must be an even-numbered register in the range [r0, r10]");
6997 
6998   const MCParsedAsmOperand &Op2 = *Operands[2 + NumPredOps];
6999   if (!Op2.isReg())
7000     return Error(Op2.getStartLoc(), Op2Diag);
7001 
7002   unsigned RNext;
7003   unsigned RPair;
7004   switch (Op2.getReg()) {
7005   default:
7006     return Error(Op2.getStartLoc(), Op2Diag);
7007   case ARM::R0:
7008     RNext = ARM::R1;
7009     RPair = ARM::R0_R1;
7010     break;
7011   case ARM::R2:
7012     RNext = ARM::R3;
7013     RPair = ARM::R2_R3;
7014     break;
7015   case ARM::R4:
7016     RNext = ARM::R5;
7017     RPair = ARM::R4_R5;
7018     break;
7019   case ARM::R6:
7020     RNext = ARM::R7;
7021     RPair = ARM::R6_R7;
7022     break;
7023   case ARM::R8:
7024     RNext = ARM::R9;
7025     RPair = ARM::R8_R9;
7026     break;
7027   case ARM::R10:
7028     RNext = ARM::R11;
7029     RPair = ARM::R10_R11;
7030     break;
7031   }
7032 
7033   const MCParsedAsmOperand &Op3 = *Operands[3 + NumPredOps];
7034   if (!Op3.isReg() || Op3.getReg() != RNext)
7035     return Error(Op3.getStartLoc(), "operand must be a consecutive register");
7036 
7037   Operands.erase(Operands.begin() + 3 + NumPredOps);
7038   Operands[2 + NumPredOps] =
7039       ARMOperand::CreateReg(RPair, Op2.getStartLoc(), Op2.getEndLoc());
7040   return false;
7041 }
7042 
7043 /// Parse an arm instruction mnemonic followed by its operands.
7044 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
7045                                     SMLoc NameLoc, OperandVector &Operands) {
7046   MCAsmParser &Parser = getParser();
7047 
7048   // Apply mnemonic aliases before doing anything else, as the destination
7049   // mnemonic may include suffices and we want to handle them normally.
7050   // The generic tblgen'erated code does this later, at the start of
7051   // MatchInstructionImpl(), but that's too late for aliases that include
7052   // any sort of suffix.
7053   const FeatureBitset &AvailableFeatures = getAvailableFeatures();
7054   unsigned AssemblerDialect = getParser().getAssemblerDialect();
7055   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
7056 
7057   // First check for the ARM-specific .req directive.
7058   if (Parser.getTok().is(AsmToken::Identifier) &&
7059       Parser.getTok().getIdentifier().lower() == ".req") {
7060     parseDirectiveReq(Name, NameLoc);
7061     // We always return 'error' for this, as we're done with this
7062     // statement and don't need to match the 'instruction."
7063     return true;
7064   }
7065 
7066   // Create the leading tokens for the mnemonic, split by '.' characters.
7067   size_t Start = 0, Next = Name.find('.');
7068   StringRef Mnemonic = Name.slice(Start, Next);
7069   StringRef ExtraToken = Name.slice(Next, Name.find(' ', Next + 1));
7070 
7071   // Split out the predication code and carry setting flag from the mnemonic.
7072   unsigned PredicationCode;
7073   unsigned VPTPredicationCode;
7074   unsigned ProcessorIMod;
7075   bool CarrySetting;
7076   StringRef ITMask;
7077   Mnemonic = splitMnemonic(Mnemonic, ExtraToken, PredicationCode, VPTPredicationCode,
7078                            CarrySetting, ProcessorIMod, ITMask);
7079 
7080   // In Thumb1, only the branch (B) instruction can be predicated.
7081   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
7082     return Error(NameLoc, "conditional execution not supported in Thumb1");
7083   }
7084 
7085   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
7086 
7087   // Handle the mask for IT and VPT instructions. In ARMOperand and
7088   // MCOperand, this is stored in a format independent of the
7089   // condition code: the lowest set bit indicates the end of the
7090   // encoding, and above that, a 1 bit indicates 'else', and an 0
7091   // indicates 'then'. E.g.
7092   //    IT    -> 1000
7093   //    ITx   -> x100    (ITT -> 0100, ITE -> 1100)
7094   //    ITxy  -> xy10    (e.g. ITET -> 1010)
7095   //    ITxyz -> xyz1    (e.g. ITEET -> 1101)
7096   // Note: See the ARM::PredBlockMask enum in
7097   //   /lib/Target/ARM/Utils/ARMBaseInfo.h
7098   if (Mnemonic == "it" || Mnemonic.startswith("vpt") ||
7099       Mnemonic.startswith("vpst")) {
7100     SMLoc Loc = Mnemonic == "it"  ? SMLoc::getFromPointer(NameLoc.getPointer() + 2) :
7101                 Mnemonic == "vpt" ? SMLoc::getFromPointer(NameLoc.getPointer() + 3) :
7102                                     SMLoc::getFromPointer(NameLoc.getPointer() + 4);
7103     if (ITMask.size() > 3) {
7104       if (Mnemonic == "it")
7105         return Error(Loc, "too many conditions on IT instruction");
7106       return Error(Loc, "too many conditions on VPT instruction");
7107     }
7108     unsigned Mask = 8;
7109     for (unsigned i = ITMask.size(); i != 0; --i) {
7110       char pos = ITMask[i - 1];
7111       if (pos != 't' && pos != 'e') {
7112         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
7113       }
7114       Mask >>= 1;
7115       if (ITMask[i - 1] == 'e')
7116         Mask |= 8;
7117     }
7118     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
7119   }
7120 
7121   // FIXME: This is all a pretty gross hack. We should automatically handle
7122   // optional operands like this via tblgen.
7123 
7124   // Next, add the CCOut and ConditionCode operands, if needed.
7125   //
7126   // For mnemonics which can ever incorporate a carry setting bit or predication
7127   // code, our matching model involves us always generating CCOut and
7128   // ConditionCode operands to match the mnemonic "as written" and then we let
7129   // the matcher deal with finding the right instruction or generating an
7130   // appropriate error.
7131   bool CanAcceptCarrySet, CanAcceptPredicationCode, CanAcceptVPTPredicationCode;
7132   getMnemonicAcceptInfo(Mnemonic, ExtraToken, Name, CanAcceptCarrySet,
7133                         CanAcceptPredicationCode, CanAcceptVPTPredicationCode);
7134 
7135   // If we had a carry-set on an instruction that can't do that, issue an
7136   // error.
7137   if (!CanAcceptCarrySet && CarrySetting) {
7138     return Error(NameLoc, "instruction '" + Mnemonic +
7139                  "' can not set flags, but 's' suffix specified");
7140   }
7141   // If we had a predication code on an instruction that can't do that, issue an
7142   // error.
7143   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
7144     return Error(NameLoc, "instruction '" + Mnemonic +
7145                  "' is not predicable, but condition code specified");
7146   }
7147 
7148   // If we had a VPT predication code on an instruction that can't do that, issue an
7149   // error.
7150   if (!CanAcceptVPTPredicationCode && VPTPredicationCode != ARMVCC::None) {
7151     return Error(NameLoc, "instruction '" + Mnemonic +
7152                  "' is not VPT predicable, but VPT code T/E is specified");
7153   }
7154 
7155   // Add the carry setting operand, if necessary.
7156   if (CanAcceptCarrySet) {
7157     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
7158     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
7159                                                Loc));
7160   }
7161 
7162   // Add the predication code operand, if necessary.
7163   if (CanAcceptPredicationCode) {
7164     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7165                                       CarrySetting);
7166     Operands.push_back(ARMOperand::CreateCondCode(
7167                        ARMCC::CondCodes(PredicationCode), Loc));
7168   }
7169 
7170   // Add the VPT predication code operand, if necessary.
7171   // FIXME: We don't add them for the instructions filtered below as these can
7172   // have custom operands which need special parsing.  This parsing requires
7173   // the operand to be in the same place in the OperandVector as their
7174   // definition in tblgen.  Since these instructions may also have the
7175   // scalar predication operand we do not add the vector one and leave until
7176   // now to fix it up.
7177   if (CanAcceptVPTPredicationCode && Mnemonic != "vmov" &&
7178       !Mnemonic.startswith("vcmp") &&
7179       !(Mnemonic.startswith("vcvt") && Mnemonic != "vcvta" &&
7180         Mnemonic != "vcvtn" && Mnemonic != "vcvtp" && Mnemonic != "vcvtm")) {
7181     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7182                                       CarrySetting);
7183     Operands.push_back(ARMOperand::CreateVPTPred(
7184                          ARMVCC::VPTCodes(VPTPredicationCode), Loc));
7185   }
7186 
7187   // Add the processor imod operand, if necessary.
7188   if (ProcessorIMod) {
7189     Operands.push_back(ARMOperand::CreateImm(
7190           MCConstantExpr::create(ProcessorIMod, getContext()),
7191                                  NameLoc, NameLoc));
7192   } else if (Mnemonic == "cps" && isMClass()) {
7193     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
7194   }
7195 
7196   // Add the remaining tokens in the mnemonic.
7197   while (Next != StringRef::npos) {
7198     Start = Next;
7199     Next = Name.find('.', Start + 1);
7200     ExtraToken = Name.slice(Start, Next);
7201 
7202     // Some NEON instructions have an optional datatype suffix that is
7203     // completely ignored. Check for that.
7204     if (isDataTypeToken(ExtraToken) &&
7205         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
7206       continue;
7207 
7208     // For for ARM mode generate an error if the .n qualifier is used.
7209     if (ExtraToken == ".n" && !isThumb()) {
7210       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7211       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
7212                    "arm mode");
7213     }
7214 
7215     // The .n qualifier is always discarded as that is what the tables
7216     // and matcher expect.  In ARM mode the .w qualifier has no effect,
7217     // so discard it to avoid errors that can be caused by the matcher.
7218     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
7219       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7220       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
7221     }
7222   }
7223 
7224   // Read the remaining operands.
7225   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7226     // Read the first operand.
7227     if (parseOperand(Operands, Mnemonic)) {
7228       return true;
7229     }
7230 
7231     while (parseOptionalToken(AsmToken::Comma)) {
7232       // Parse and remember the operand.
7233       if (parseOperand(Operands, Mnemonic)) {
7234         return true;
7235       }
7236     }
7237   }
7238 
7239   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
7240     return true;
7241 
7242   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
7243 
7244   if (hasCDE() && MS.isCDEInstr(Mnemonic)) {
7245     // Dual-register instructions use even-odd register pairs as their
7246     // destination operand, in assembly such pair is spelled as two
7247     // consecutive registers, without any special syntax. ConvertDualRegOperand
7248     // tries to convert such operand into register pair, e.g. r2, r3 -> r2_r3.
7249     // It returns true, if an error message has been emitted. If the function
7250     // returns false, the function either succeeded or an error (e.g. missing
7251     // operand) will be diagnosed elsewhere.
7252     if (MS.isCDEDualRegInstr(Mnemonic)) {
7253       bool GotError = CDEConvertDualRegOperand(Mnemonic, Operands);
7254       if (GotError)
7255         return GotError;
7256     }
7257   }
7258 
7259   // Some instructions, mostly Thumb, have forms for the same mnemonic that
7260   // do and don't have a cc_out optional-def operand. With some spot-checks
7261   // of the operand list, we can figure out which variant we're trying to
7262   // parse and adjust accordingly before actually matching. We shouldn't ever
7263   // try to remove a cc_out operand that was explicitly set on the
7264   // mnemonic, of course (CarrySetting == true). Reason number #317 the
7265   // table driven matcher doesn't fit well with the ARM instruction set.
7266   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
7267     Operands.erase(Operands.begin() + 1);
7268 
7269   // Some instructions have the same mnemonic, but don't always
7270   // have a predicate. Distinguish them here and delete the
7271   // appropriate predicate if needed.  This could be either the scalar
7272   // predication code or the vector predication code.
7273   if (PredicationCode == ARMCC::AL &&
7274       shouldOmitPredicateOperand(Mnemonic, Operands))
7275     Operands.erase(Operands.begin() + 1);
7276 
7277 
7278   if (hasMVE()) {
7279     if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands) &&
7280         Mnemonic == "vmov" && PredicationCode == ARMCC::LT) {
7281       // Very nasty hack to deal with the vector predicated variant of vmovlt
7282       // the scalar predicated vmov with condition 'lt'.  We can not tell them
7283       // apart until we have parsed their operands.
7284       Operands.erase(Operands.begin() + 1);
7285       Operands.erase(Operands.begin());
7286       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7287       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7288                                          Mnemonic.size() - 1 + CarrySetting);
7289       Operands.insert(Operands.begin(),
7290                       ARMOperand::CreateVPTPred(ARMVCC::None, PLoc));
7291       Operands.insert(Operands.begin(),
7292                       ARMOperand::CreateToken(StringRef("vmovlt"), MLoc));
7293     } else if (Mnemonic == "vcvt" && PredicationCode == ARMCC::NE &&
7294                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7295       // Another nasty hack to deal with the ambiguity between vcvt with scalar
7296       // predication 'ne' and vcvtn with vector predication 'e'.  As above we
7297       // can only distinguish between the two after we have parsed their
7298       // operands.
7299       Operands.erase(Operands.begin() + 1);
7300       Operands.erase(Operands.begin());
7301       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7302       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7303                                          Mnemonic.size() - 1 + CarrySetting);
7304       Operands.insert(Operands.begin(),
7305                       ARMOperand::CreateVPTPred(ARMVCC::Else, PLoc));
7306       Operands.insert(Operands.begin(),
7307                       ARMOperand::CreateToken(StringRef("vcvtn"), MLoc));
7308     } else if (Mnemonic == "vmul" && PredicationCode == ARMCC::LT &&
7309                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7310       // Another hack, this time to distinguish between scalar predicated vmul
7311       // with 'lt' predication code and the vector instruction vmullt with
7312       // vector predication code "none"
7313       Operands.erase(Operands.begin() + 1);
7314       Operands.erase(Operands.begin());
7315       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7316       Operands.insert(Operands.begin(),
7317                       ARMOperand::CreateToken(StringRef("vmullt"), MLoc));
7318     }
7319     // For vmov and vcmp, as mentioned earlier, we did not add the vector
7320     // predication code, since these may contain operands that require
7321     // special parsing.  So now we have to see if they require vector
7322     // predication and replace the scalar one with the vector predication
7323     // operand if that is the case.
7324     else if (Mnemonic == "vmov" || Mnemonic.startswith("vcmp") ||
7325              (Mnemonic.startswith("vcvt") && !Mnemonic.startswith("vcvta") &&
7326               !Mnemonic.startswith("vcvtn") && !Mnemonic.startswith("vcvtp") &&
7327               !Mnemonic.startswith("vcvtm"))) {
7328       if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7329         // We could not split the vector predicate off vcvt because it might
7330         // have been the scalar vcvtt instruction.  Now we know its a vector
7331         // instruction, we still need to check whether its the vector
7332         // predicated vcvt with 'Then' predication or the vector vcvtt.  We can
7333         // distinguish the two based on the suffixes, if it is any of
7334         // ".f16.f32", ".f32.f16", ".f16.f64" or ".f64.f16" then it is the vcvtt.
7335         if (Mnemonic.startswith("vcvtt") && Operands.size() >= 4) {
7336           auto Sz1 = static_cast<ARMOperand &>(*Operands[2]);
7337           auto Sz2 = static_cast<ARMOperand &>(*Operands[3]);
7338           if (!(Sz1.isToken() && Sz1.getToken().startswith(".f") &&
7339               Sz2.isToken() && Sz2.getToken().startswith(".f"))) {
7340             Operands.erase(Operands.begin());
7341             SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7342             VPTPredicationCode = ARMVCC::Then;
7343 
7344             Mnemonic = Mnemonic.substr(0, 4);
7345             Operands.insert(Operands.begin(),
7346                             ARMOperand::CreateToken(Mnemonic, MLoc));
7347           }
7348         }
7349         Operands.erase(Operands.begin() + 1);
7350         SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7351                                           Mnemonic.size() + CarrySetting);
7352         Operands.insert(Operands.begin() + 1,
7353                         ARMOperand::CreateVPTPred(
7354                             ARMVCC::VPTCodes(VPTPredicationCode), PLoc));
7355       }
7356     } else if (CanAcceptVPTPredicationCode) {
7357       // For all other instructions, make sure only one of the two
7358       // predication operands is left behind, depending on whether we should
7359       // use the vector predication.
7360       if (shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7361         if (CanAcceptPredicationCode)
7362           Operands.erase(Operands.begin() + 2);
7363         else
7364           Operands.erase(Operands.begin() + 1);
7365       } else if (CanAcceptPredicationCode && PredicationCode == ARMCC::AL) {
7366         Operands.erase(Operands.begin() + 1);
7367       }
7368     }
7369   }
7370 
7371   if (VPTPredicationCode != ARMVCC::None) {
7372     bool usedVPTPredicationCode = false;
7373     for (unsigned I = 1; I < Operands.size(); ++I)
7374       if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7375         usedVPTPredicationCode = true;
7376     if (!usedVPTPredicationCode) {
7377       // If we have a VPT predication code and we haven't just turned it
7378       // into an operand, then it was a mistake for splitMnemonic to
7379       // separate it from the rest of the mnemonic in the first place,
7380       // and this may lead to wrong disassembly (e.g. scalar floating
7381       // point VCMPE is actually a different instruction from VCMP, so
7382       // we mustn't treat them the same). In that situation, glue it
7383       // back on.
7384       Mnemonic = Name.slice(0, Mnemonic.size() + 1);
7385       Operands.erase(Operands.begin());
7386       Operands.insert(Operands.begin(),
7387                       ARMOperand::CreateToken(Mnemonic, NameLoc));
7388     }
7389   }
7390 
7391     // ARM mode 'blx' need special handling, as the register operand version
7392     // is predicable, but the label operand version is not. So, we can't rely
7393     // on the Mnemonic based checking to correctly figure out when to put
7394     // a k_CondCode operand in the list. If we're trying to match the label
7395     // version, remove the k_CondCode operand here.
7396     if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
7397         static_cast<ARMOperand &>(*Operands[2]).isImm())
7398       Operands.erase(Operands.begin() + 1);
7399 
7400     // Adjust operands of ldrexd/strexd to MCK_GPRPair.
7401     // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
7402     // a single GPRPair reg operand is used in the .td file to replace the two
7403     // GPRs. However, when parsing from asm, the two GRPs cannot be
7404     // automatically
7405     // expressed as a GPRPair, so we have to manually merge them.
7406     // FIXME: We would really like to be able to tablegen'erate this.
7407     if (!isThumb() && Operands.size() > 4 &&
7408         (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
7409          Mnemonic == "stlexd")) {
7410       bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
7411       unsigned Idx = isLoad ? 2 : 3;
7412       ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
7413       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
7414 
7415       const MCRegisterClass &MRC = MRI->getRegClass(ARM::GPRRegClassID);
7416       // Adjust only if Op1 and Op2 are GPRs.
7417       if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
7418           MRC.contains(Op2.getReg())) {
7419         unsigned Reg1 = Op1.getReg();
7420         unsigned Reg2 = Op2.getReg();
7421         unsigned Rt = MRI->getEncodingValue(Reg1);
7422         unsigned Rt2 = MRI->getEncodingValue(Reg2);
7423 
7424         // Rt2 must be Rt + 1 and Rt must be even.
7425         if (Rt + 1 != Rt2 || (Rt & 1)) {
7426           return Error(Op2.getStartLoc(),
7427                        isLoad ? "destination operands must be sequential"
7428                               : "source operands must be sequential");
7429         }
7430         unsigned NewReg = MRI->getMatchingSuperReg(
7431             Reg1, ARM::gsub_0, &(MRI->getRegClass(ARM::GPRPairRegClassID)));
7432         Operands[Idx] =
7433             ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
7434         Operands.erase(Operands.begin() + Idx + 1);
7435       }
7436   }
7437 
7438   // GNU Assembler extension (compatibility).
7439   fixupGNULDRDAlias(Mnemonic, Operands);
7440 
7441   // FIXME: As said above, this is all a pretty gross hack.  This instruction
7442   // does not fit with other "subs" and tblgen.
7443   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
7444   // so the Mnemonic is the original name "subs" and delete the predicate
7445   // operand so it will match the table entry.
7446   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
7447       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
7448       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
7449       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
7450       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
7451       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
7452     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
7453     Operands.erase(Operands.begin() + 1);
7454   }
7455   return false;
7456 }
7457 
7458 // Validate context-sensitive operand constraints.
7459 
7460 // return 'true' if register list contains non-low GPR registers,
7461 // 'false' otherwise. If Reg is in the register list or is HiReg, set
7462 // 'containsReg' to true.
7463 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
7464                                  unsigned Reg, unsigned HiReg,
7465                                  bool &containsReg) {
7466   containsReg = false;
7467   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
7468     unsigned OpReg = Inst.getOperand(i).getReg();
7469     if (OpReg == Reg)
7470       containsReg = true;
7471     // Anything other than a low register isn't legal here.
7472     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
7473       return true;
7474   }
7475   return false;
7476 }
7477 
7478 // Check if the specified regisgter is in the register list of the inst,
7479 // starting at the indicated operand number.
7480 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
7481   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
7482     unsigned OpReg = Inst.getOperand(i).getReg();
7483     if (OpReg == Reg)
7484       return true;
7485   }
7486   return false;
7487 }
7488 
7489 // Return true if instruction has the interesting property of being
7490 // allowed in IT blocks, but not being predicable.
7491 static bool instIsBreakpoint(const MCInst &Inst) {
7492     return Inst.getOpcode() == ARM::tBKPT ||
7493            Inst.getOpcode() == ARM::BKPT ||
7494            Inst.getOpcode() == ARM::tHLT ||
7495            Inst.getOpcode() == ARM::HLT;
7496 }
7497 
7498 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
7499                                        const OperandVector &Operands,
7500                                        unsigned ListNo, bool IsARPop) {
7501   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7502   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7503 
7504   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7505   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
7506   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7507 
7508   if (!IsARPop && ListContainsSP)
7509     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7510                  "SP may not be in the register list");
7511   else if (ListContainsPC && ListContainsLR)
7512     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7513                  "PC and LR may not be in the register list simultaneously");
7514   return false;
7515 }
7516 
7517 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
7518                                        const OperandVector &Operands,
7519                                        unsigned ListNo) {
7520   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7521   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7522 
7523   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7524   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7525 
7526   if (ListContainsSP && ListContainsPC)
7527     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7528                  "SP and PC may not be in the register list");
7529   else if (ListContainsSP)
7530     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7531                  "SP may not be in the register list");
7532   else if (ListContainsPC)
7533     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7534                  "PC may not be in the register list");
7535   return false;
7536 }
7537 
7538 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
7539                                     const OperandVector &Operands,
7540                                     bool Load, bool ARMMode, bool Writeback) {
7541   unsigned RtIndex = Load || !Writeback ? 0 : 1;
7542   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
7543   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
7544 
7545   if (ARMMode) {
7546     // Rt can't be R14.
7547     if (Rt == 14)
7548       return Error(Operands[3]->getStartLoc(),
7549                   "Rt can't be R14");
7550 
7551     // Rt must be even-numbered.
7552     if ((Rt & 1) == 1)
7553       return Error(Operands[3]->getStartLoc(),
7554                    "Rt must be even-numbered");
7555 
7556     // Rt2 must be Rt + 1.
7557     if (Rt2 != Rt + 1) {
7558       if (Load)
7559         return Error(Operands[3]->getStartLoc(),
7560                      "destination operands must be sequential");
7561       else
7562         return Error(Operands[3]->getStartLoc(),
7563                      "source operands must be sequential");
7564     }
7565 
7566     // FIXME: Diagnose m == 15
7567     // FIXME: Diagnose ldrd with m == t || m == t2.
7568   }
7569 
7570   if (!ARMMode && Load) {
7571     if (Rt2 == Rt)
7572       return Error(Operands[3]->getStartLoc(),
7573                    "destination operands can't be identical");
7574   }
7575 
7576   if (Writeback) {
7577     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7578 
7579     if (Rn == Rt || Rn == Rt2) {
7580       if (Load)
7581         return Error(Operands[3]->getStartLoc(),
7582                      "base register needs to be different from destination "
7583                      "registers");
7584       else
7585         return Error(Operands[3]->getStartLoc(),
7586                      "source register and base register can't be identical");
7587     }
7588 
7589     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
7590     // (Except the immediate form of ldrd?)
7591   }
7592 
7593   return false;
7594 }
7595 
7596 static int findFirstVectorPredOperandIdx(const MCInstrDesc &MCID) {
7597   for (unsigned i = 0; i < MCID.NumOperands; ++i) {
7598     if (ARM::isVpred(MCID.OpInfo[i].OperandType))
7599       return i;
7600   }
7601   return -1;
7602 }
7603 
7604 static bool isVectorPredicable(const MCInstrDesc &MCID) {
7605   return findFirstVectorPredOperandIdx(MCID) != -1;
7606 }
7607 
7608 // FIXME: We would really like to be able to tablegen'erate this.
7609 bool ARMAsmParser::validateInstruction(MCInst &Inst,
7610                                        const OperandVector &Operands) {
7611   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
7612   SMLoc Loc = Operands[0]->getStartLoc();
7613 
7614   // Check the IT block state first.
7615   // NOTE: BKPT and HLT instructions have the interesting property of being
7616   // allowed in IT blocks, but not being predicable. They just always execute.
7617   if (inITBlock() && !instIsBreakpoint(Inst)) {
7618     // The instruction must be predicable.
7619     if (!MCID.isPredicable())
7620       return Error(Loc, "instructions in IT block must be predicable");
7621     ARMCC::CondCodes Cond = ARMCC::CondCodes(
7622         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
7623     if (Cond != currentITCond()) {
7624       // Find the condition code Operand to get its SMLoc information.
7625       SMLoc CondLoc;
7626       for (unsigned I = 1; I < Operands.size(); ++I)
7627         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
7628           CondLoc = Operands[I]->getStartLoc();
7629       return Error(CondLoc, "incorrect condition in IT block; got '" +
7630                                 StringRef(ARMCondCodeToString(Cond)) +
7631                                 "', but expected '" +
7632                                 ARMCondCodeToString(currentITCond()) + "'");
7633     }
7634   // Check for non-'al' condition codes outside of the IT block.
7635   } else if (isThumbTwo() && MCID.isPredicable() &&
7636              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7637              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
7638              Inst.getOpcode() != ARM::t2Bcc &&
7639              Inst.getOpcode() != ARM::t2BFic) {
7640     return Error(Loc, "predicated instructions must be in IT block");
7641   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
7642              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7643                  ARMCC::AL) {
7644     return Warning(Loc, "predicated instructions should be in IT block");
7645   } else if (!MCID.isPredicable()) {
7646     // Check the instruction doesn't have a predicate operand anyway
7647     // that it's not allowed to use. Sometimes this happens in order
7648     // to keep instructions the same shape even though one cannot
7649     // legally be predicated, e.g. vmul.f16 vs vmul.f32.
7650     for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
7651       if (MCID.OpInfo[i].isPredicate()) {
7652         if (Inst.getOperand(i).getImm() != ARMCC::AL)
7653           return Error(Loc, "instruction is not predicable");
7654         break;
7655       }
7656     }
7657   }
7658 
7659   // PC-setting instructions in an IT block, but not the last instruction of
7660   // the block, are UNPREDICTABLE.
7661   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
7662     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
7663   }
7664 
7665   if (inVPTBlock() && !instIsBreakpoint(Inst)) {
7666     unsigned Bit = extractITMaskBit(VPTState.Mask, VPTState.CurPosition);
7667     if (!isVectorPredicable(MCID))
7668       return Error(Loc, "instruction in VPT block must be predicable");
7669     unsigned Pred = Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm();
7670     unsigned VPTPred = Bit ? ARMVCC::Else : ARMVCC::Then;
7671     if (Pred != VPTPred) {
7672       SMLoc PredLoc;
7673       for (unsigned I = 1; I < Operands.size(); ++I)
7674         if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7675           PredLoc = Operands[I]->getStartLoc();
7676       return Error(PredLoc, "incorrect predication in VPT block; got '" +
7677                    StringRef(ARMVPTPredToString(ARMVCC::VPTCodes(Pred))) +
7678                    "', but expected '" +
7679                    ARMVPTPredToString(ARMVCC::VPTCodes(VPTPred)) + "'");
7680     }
7681   }
7682   else if (isVectorPredicable(MCID) &&
7683            Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm() !=
7684            ARMVCC::None)
7685     return Error(Loc, "VPT predicated instructions must be in VPT block");
7686 
7687   const unsigned Opcode = Inst.getOpcode();
7688   switch (Opcode) {
7689   case ARM::t2IT: {
7690     // Encoding is unpredictable if it ever results in a notional 'NV'
7691     // predicate. Since we don't parse 'NV' directly this means an 'AL'
7692     // predicate with an "else" mask bit.
7693     unsigned Cond = Inst.getOperand(0).getImm();
7694     unsigned Mask = Inst.getOperand(1).getImm();
7695 
7696     // Conditions only allowing a 't' are those with no set bit except
7697     // the lowest-order one that indicates the end of the sequence. In
7698     // other words, powers of 2.
7699     if (Cond == ARMCC::AL && countPopulation(Mask) != 1)
7700       return Error(Loc, "unpredictable IT predicate sequence");
7701     break;
7702   }
7703   case ARM::LDRD:
7704     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7705                          /*Writeback*/false))
7706       return true;
7707     break;
7708   case ARM::LDRD_PRE:
7709   case ARM::LDRD_POST:
7710     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7711                          /*Writeback*/true))
7712       return true;
7713     break;
7714   case ARM::t2LDRDi8:
7715     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7716                          /*Writeback*/false))
7717       return true;
7718     break;
7719   case ARM::t2LDRD_PRE:
7720   case ARM::t2LDRD_POST:
7721     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7722                          /*Writeback*/true))
7723       return true;
7724     break;
7725   case ARM::t2BXJ: {
7726     const unsigned RmReg = Inst.getOperand(0).getReg();
7727     // Rm = SP is no longer unpredictable in v8-A
7728     if (RmReg == ARM::SP && !hasV8Ops())
7729       return Error(Operands[2]->getStartLoc(),
7730                    "r13 (SP) is an unpredictable operand to BXJ");
7731     return false;
7732   }
7733   case ARM::STRD:
7734     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7735                          /*Writeback*/false))
7736       return true;
7737     break;
7738   case ARM::STRD_PRE:
7739   case ARM::STRD_POST:
7740     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7741                          /*Writeback*/true))
7742       return true;
7743     break;
7744   case ARM::t2STRD_PRE:
7745   case ARM::t2STRD_POST:
7746     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
7747                          /*Writeback*/true))
7748       return true;
7749     break;
7750   case ARM::STR_PRE_IMM:
7751   case ARM::STR_PRE_REG:
7752   case ARM::t2STR_PRE:
7753   case ARM::STR_POST_IMM:
7754   case ARM::STR_POST_REG:
7755   case ARM::t2STR_POST:
7756   case ARM::STRH_PRE:
7757   case ARM::t2STRH_PRE:
7758   case ARM::STRH_POST:
7759   case ARM::t2STRH_POST:
7760   case ARM::STRB_PRE_IMM:
7761   case ARM::STRB_PRE_REG:
7762   case ARM::t2STRB_PRE:
7763   case ARM::STRB_POST_IMM:
7764   case ARM::STRB_POST_REG:
7765   case ARM::t2STRB_POST: {
7766     // Rt must be different from Rn.
7767     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7768     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7769 
7770     if (Rt == Rn)
7771       return Error(Operands[3]->getStartLoc(),
7772                    "source register and base register can't be identical");
7773     return false;
7774   }
7775   case ARM::t2LDR_PRE_imm:
7776   case ARM::t2LDR_POST_imm:
7777   case ARM::t2STR_PRE_imm:
7778   case ARM::t2STR_POST_imm: {
7779     // Rt must be different from Rn.
7780     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7781     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7782 
7783     if (Rt == Rn)
7784       return Error(Operands[3]->getStartLoc(),
7785                    "destination register and base register can't be identical");
7786     if (Inst.getOpcode() == ARM::t2LDR_POST_imm ||
7787         Inst.getOpcode() == ARM::t2STR_POST_imm) {
7788       int Imm = Inst.getOperand(2).getImm();
7789       if (Imm > 255 || Imm < -255)
7790         return Error(Operands[5]->getStartLoc(),
7791                      "operand must be in range [-255, 255]");
7792     }
7793     if (Inst.getOpcode() == ARM::t2STR_PRE_imm ||
7794         Inst.getOpcode() == ARM::t2STR_POST_imm) {
7795       if (Inst.getOperand(0).getReg() == ARM::PC) {
7796         return Error(Operands[3]->getStartLoc(),
7797                      "operand must be a register in range [r0, r14]");
7798       }
7799     }
7800     return false;
7801   }
7802   case ARM::LDR_PRE_IMM:
7803   case ARM::LDR_PRE_REG:
7804   case ARM::t2LDR_PRE:
7805   case ARM::LDR_POST_IMM:
7806   case ARM::LDR_POST_REG:
7807   case ARM::t2LDR_POST:
7808   case ARM::LDRH_PRE:
7809   case ARM::t2LDRH_PRE:
7810   case ARM::LDRH_POST:
7811   case ARM::t2LDRH_POST:
7812   case ARM::LDRSH_PRE:
7813   case ARM::t2LDRSH_PRE:
7814   case ARM::LDRSH_POST:
7815   case ARM::t2LDRSH_POST:
7816   case ARM::LDRB_PRE_IMM:
7817   case ARM::LDRB_PRE_REG:
7818   case ARM::t2LDRB_PRE:
7819   case ARM::LDRB_POST_IMM:
7820   case ARM::LDRB_POST_REG:
7821   case ARM::t2LDRB_POST:
7822   case ARM::LDRSB_PRE:
7823   case ARM::t2LDRSB_PRE:
7824   case ARM::LDRSB_POST:
7825   case ARM::t2LDRSB_POST: {
7826     // Rt must be different from Rn.
7827     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7828     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7829 
7830     if (Rt == Rn)
7831       return Error(Operands[3]->getStartLoc(),
7832                    "destination register and base register can't be identical");
7833     return false;
7834   }
7835 
7836   case ARM::MVE_VLDRBU8_rq:
7837   case ARM::MVE_VLDRBU16_rq:
7838   case ARM::MVE_VLDRBS16_rq:
7839   case ARM::MVE_VLDRBU32_rq:
7840   case ARM::MVE_VLDRBS32_rq:
7841   case ARM::MVE_VLDRHU16_rq:
7842   case ARM::MVE_VLDRHU16_rq_u:
7843   case ARM::MVE_VLDRHU32_rq:
7844   case ARM::MVE_VLDRHU32_rq_u:
7845   case ARM::MVE_VLDRHS32_rq:
7846   case ARM::MVE_VLDRHS32_rq_u:
7847   case ARM::MVE_VLDRWU32_rq:
7848   case ARM::MVE_VLDRWU32_rq_u:
7849   case ARM::MVE_VLDRDU64_rq:
7850   case ARM::MVE_VLDRDU64_rq_u:
7851   case ARM::MVE_VLDRWU32_qi:
7852   case ARM::MVE_VLDRWU32_qi_pre:
7853   case ARM::MVE_VLDRDU64_qi:
7854   case ARM::MVE_VLDRDU64_qi_pre: {
7855     // Qd must be different from Qm.
7856     unsigned QdIdx = 0, QmIdx = 2;
7857     bool QmIsPointer = false;
7858     switch (Opcode) {
7859     case ARM::MVE_VLDRWU32_qi:
7860     case ARM::MVE_VLDRDU64_qi:
7861       QmIdx = 1;
7862       QmIsPointer = true;
7863       break;
7864     case ARM::MVE_VLDRWU32_qi_pre:
7865     case ARM::MVE_VLDRDU64_qi_pre:
7866       QdIdx = 1;
7867       QmIsPointer = true;
7868       break;
7869     }
7870 
7871     const unsigned Qd = MRI->getEncodingValue(Inst.getOperand(QdIdx).getReg());
7872     const unsigned Qm = MRI->getEncodingValue(Inst.getOperand(QmIdx).getReg());
7873 
7874     if (Qd == Qm) {
7875       return Error(Operands[3]->getStartLoc(),
7876                    Twine("destination vector register and vector ") +
7877                    (QmIsPointer ? "pointer" : "offset") +
7878                    " register can't be identical");
7879     }
7880     return false;
7881   }
7882 
7883   case ARM::SBFX:
7884   case ARM::t2SBFX:
7885   case ARM::UBFX:
7886   case ARM::t2UBFX: {
7887     // Width must be in range [1, 32-lsb].
7888     unsigned LSB = Inst.getOperand(2).getImm();
7889     unsigned Widthm1 = Inst.getOperand(3).getImm();
7890     if (Widthm1 >= 32 - LSB)
7891       return Error(Operands[5]->getStartLoc(),
7892                    "bitfield width must be in range [1,32-lsb]");
7893     return false;
7894   }
7895   // Notionally handles ARM::tLDMIA_UPD too.
7896   case ARM::tLDMIA: {
7897     // If we're parsing Thumb2, the .w variant is available and handles
7898     // most cases that are normally illegal for a Thumb1 LDM instruction.
7899     // We'll make the transformation in processInstruction() if necessary.
7900     //
7901     // Thumb LDM instructions are writeback iff the base register is not
7902     // in the register list.
7903     unsigned Rn = Inst.getOperand(0).getReg();
7904     bool HasWritebackToken =
7905         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7906          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
7907     bool ListContainsBase;
7908     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
7909       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
7910                    "registers must be in range r0-r7");
7911     // If we should have writeback, then there should be a '!' token.
7912     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
7913       return Error(Operands[2]->getStartLoc(),
7914                    "writeback operator '!' expected");
7915     // If we should not have writeback, there must not be a '!'. This is
7916     // true even for the 32-bit wide encodings.
7917     if (ListContainsBase && HasWritebackToken)
7918       return Error(Operands[3]->getStartLoc(),
7919                    "writeback operator '!' not allowed when base register "
7920                    "in register list");
7921 
7922     if (validatetLDMRegList(Inst, Operands, 3))
7923       return true;
7924     break;
7925   }
7926   case ARM::LDMIA_UPD:
7927   case ARM::LDMDB_UPD:
7928   case ARM::LDMIB_UPD:
7929   case ARM::LDMDA_UPD:
7930     // ARM variants loading and updating the same register are only officially
7931     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
7932     if (!hasV7Ops())
7933       break;
7934     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7935       return Error(Operands.back()->getStartLoc(),
7936                    "writeback register not allowed in register list");
7937     break;
7938   case ARM::t2LDMIA:
7939   case ARM::t2LDMDB:
7940     if (validatetLDMRegList(Inst, Operands, 3))
7941       return true;
7942     break;
7943   case ARM::t2STMIA:
7944   case ARM::t2STMDB:
7945     if (validatetSTMRegList(Inst, Operands, 3))
7946       return true;
7947     break;
7948   case ARM::t2LDMIA_UPD:
7949   case ARM::t2LDMDB_UPD:
7950   case ARM::t2STMIA_UPD:
7951   case ARM::t2STMDB_UPD:
7952     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7953       return Error(Operands.back()->getStartLoc(),
7954                    "writeback register not allowed in register list");
7955 
7956     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
7957       if (validatetLDMRegList(Inst, Operands, 3))
7958         return true;
7959     } else {
7960       if (validatetSTMRegList(Inst, Operands, 3))
7961         return true;
7962     }
7963     break;
7964 
7965   case ARM::sysLDMIA_UPD:
7966   case ARM::sysLDMDA_UPD:
7967   case ARM::sysLDMDB_UPD:
7968   case ARM::sysLDMIB_UPD:
7969     if (!listContainsReg(Inst, 3, ARM::PC))
7970       return Error(Operands[4]->getStartLoc(),
7971                    "writeback register only allowed on system LDM "
7972                    "if PC in register-list");
7973     break;
7974   case ARM::sysSTMIA_UPD:
7975   case ARM::sysSTMDA_UPD:
7976   case ARM::sysSTMDB_UPD:
7977   case ARM::sysSTMIB_UPD:
7978     return Error(Operands[2]->getStartLoc(),
7979                  "system STM cannot have writeback register");
7980   case ARM::tMUL:
7981     // The second source operand must be the same register as the destination
7982     // operand.
7983     //
7984     // In this case, we must directly check the parsed operands because the
7985     // cvtThumbMultiply() function is written in such a way that it guarantees
7986     // this first statement is always true for the new Inst.  Essentially, the
7987     // destination is unconditionally copied into the second source operand
7988     // without checking to see if it matches what we actually parsed.
7989     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
7990                                  ((ARMOperand &)*Operands[5]).getReg()) &&
7991         (((ARMOperand &)*Operands[3]).getReg() !=
7992          ((ARMOperand &)*Operands[4]).getReg())) {
7993       return Error(Operands[3]->getStartLoc(),
7994                    "destination register must match source register");
7995     }
7996     break;
7997 
7998   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
7999   // so only issue a diagnostic for thumb1. The instructions will be
8000   // switched to the t2 encodings in processInstruction() if necessary.
8001   case ARM::tPOP: {
8002     bool ListContainsBase;
8003     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
8004         !isThumbTwo())
8005       return Error(Operands[2]->getStartLoc(),
8006                    "registers must be in range r0-r7 or pc");
8007     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
8008       return true;
8009     break;
8010   }
8011   case ARM::tPUSH: {
8012     bool ListContainsBase;
8013     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
8014         !isThumbTwo())
8015       return Error(Operands[2]->getStartLoc(),
8016                    "registers must be in range r0-r7 or lr");
8017     if (validatetSTMRegList(Inst, Operands, 2))
8018       return true;
8019     break;
8020   }
8021   case ARM::tSTMIA_UPD: {
8022     bool ListContainsBase, InvalidLowList;
8023     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
8024                                           0, ListContainsBase);
8025     if (InvalidLowList && !isThumbTwo())
8026       return Error(Operands[4]->getStartLoc(),
8027                    "registers must be in range r0-r7");
8028 
8029     // This would be converted to a 32-bit stm, but that's not valid if the
8030     // writeback register is in the list.
8031     if (InvalidLowList && ListContainsBase)
8032       return Error(Operands[4]->getStartLoc(),
8033                    "writeback operator '!' not allowed when base register "
8034                    "in register list");
8035 
8036     if (validatetSTMRegList(Inst, Operands, 4))
8037       return true;
8038     break;
8039   }
8040   case ARM::tADDrSP:
8041     // If the non-SP source operand and the destination operand are not the
8042     // same, we need thumb2 (for the wide encoding), or we have an error.
8043     if (!isThumbTwo() &&
8044         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8045       return Error(Operands[4]->getStartLoc(),
8046                    "source register must be the same as destination");
8047     }
8048     break;
8049 
8050   case ARM::t2ADDrr:
8051   case ARM::t2ADDrs:
8052   case ARM::t2SUBrr:
8053   case ARM::t2SUBrs:
8054     if (Inst.getOperand(0).getReg() == ARM::SP &&
8055         Inst.getOperand(1).getReg() != ARM::SP)
8056       return Error(Operands[4]->getStartLoc(),
8057                    "source register must be sp if destination is sp");
8058     break;
8059 
8060   // Final range checking for Thumb unconditional branch instructions.
8061   case ARM::tB:
8062     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
8063       return Error(Operands[2]->getStartLoc(), "branch target out of range");
8064     break;
8065   case ARM::t2B: {
8066     int op = (Operands[2]->isImm()) ? 2 : 3;
8067     ARMOperand &Operand = static_cast<ARMOperand &>(*Operands[op]);
8068     // Delay the checks of symbolic expressions until they are resolved.
8069     if (!isa<MCBinaryExpr>(Operand.getImm()) &&
8070         !Operand.isSignedOffset<24, 1>())
8071       return Error(Operands[op]->getStartLoc(), "branch target out of range");
8072     break;
8073   }
8074   // Final range checking for Thumb conditional branch instructions.
8075   case ARM::tBcc:
8076     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
8077       return Error(Operands[2]->getStartLoc(), "branch target out of range");
8078     break;
8079   case ARM::t2Bcc: {
8080     int Op = (Operands[2]->isImm()) ? 2 : 3;
8081     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
8082       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
8083     break;
8084   }
8085   case ARM::tCBZ:
8086   case ARM::tCBNZ: {
8087     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
8088       return Error(Operands[2]->getStartLoc(), "branch target out of range");
8089     break;
8090   }
8091   case ARM::MOVi16:
8092   case ARM::MOVTi16:
8093   case ARM::t2MOVi16:
8094   case ARM::t2MOVTi16:
8095     {
8096     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
8097     // especially when we turn it into a movw and the expression <symbol> does
8098     // not have a :lower16: or :upper16 as part of the expression.  We don't
8099     // want the behavior of silently truncating, which can be unexpected and
8100     // lead to bugs that are difficult to find since this is an easy mistake
8101     // to make.
8102     int i = (Operands[3]->isImm()) ? 3 : 4;
8103     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
8104     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
8105     if (CE) break;
8106     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
8107     if (!E) break;
8108     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
8109     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
8110                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
8111       return Error(
8112           Op.getStartLoc(),
8113           "immediate expression for mov requires :lower16: or :upper16");
8114     break;
8115   }
8116   case ARM::HINT:
8117   case ARM::t2HINT: {
8118     unsigned Imm8 = Inst.getOperand(0).getImm();
8119     unsigned Pred = Inst.getOperand(1).getImm();
8120     // ESB is not predicable (pred must be AL). Without the RAS extension, this
8121     // behaves as any other unallocated hint.
8122     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
8123       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
8124                                                "predicable, but condition "
8125                                                "code specified");
8126     if (Imm8 == 0x14 && Pred != ARMCC::AL)
8127       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
8128                                                "predicable, but condition "
8129                                                "code specified");
8130     break;
8131   }
8132   case ARM::t2BFi:
8133   case ARM::t2BFr:
8134   case ARM::t2BFLi:
8135   case ARM::t2BFLr: {
8136     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<4, 1>() ||
8137         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
8138       return Error(Operands[2]->getStartLoc(),
8139                    "branch location out of range or not a multiple of 2");
8140 
8141     if (Opcode == ARM::t2BFi) {
8142       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<16, 1>())
8143         return Error(Operands[3]->getStartLoc(),
8144                      "branch target out of range or not a multiple of 2");
8145     } else if (Opcode == ARM::t2BFLi) {
8146       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<18, 1>())
8147         return Error(Operands[3]->getStartLoc(),
8148                      "branch target out of range or not a multiple of 2");
8149     }
8150     break;
8151   }
8152   case ARM::t2BFic: {
8153     if (!static_cast<ARMOperand &>(*Operands[1]).isUnsignedOffset<4, 1>() ||
8154         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
8155       return Error(Operands[1]->getStartLoc(),
8156                    "branch location out of range or not a multiple of 2");
8157 
8158     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<16, 1>())
8159       return Error(Operands[2]->getStartLoc(),
8160                    "branch target out of range or not a multiple of 2");
8161 
8162     assert(Inst.getOperand(0).isImm() == Inst.getOperand(2).isImm() &&
8163            "branch location and else branch target should either both be "
8164            "immediates or both labels");
8165 
8166     if (Inst.getOperand(0).isImm() && Inst.getOperand(2).isImm()) {
8167       int Diff = Inst.getOperand(2).getImm() - Inst.getOperand(0).getImm();
8168       if (Diff != 4 && Diff != 2)
8169         return Error(
8170             Operands[3]->getStartLoc(),
8171             "else branch target must be 2 or 4 greater than the branch location");
8172     }
8173     break;
8174   }
8175   case ARM::t2CLRM: {
8176     for (unsigned i = 2; i < Inst.getNumOperands(); i++) {
8177       if (Inst.getOperand(i).isReg() &&
8178           !ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(
8179               Inst.getOperand(i).getReg())) {
8180         return Error(Operands[2]->getStartLoc(),
8181                      "invalid register in register list. Valid registers are "
8182                      "r0-r12, lr/r14 and APSR.");
8183       }
8184     }
8185     break;
8186   }
8187   case ARM::DSB:
8188   case ARM::t2DSB: {
8189 
8190     if (Inst.getNumOperands() < 2)
8191       break;
8192 
8193     unsigned Option = Inst.getOperand(0).getImm();
8194     unsigned Pred = Inst.getOperand(1).getImm();
8195 
8196     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
8197     if (Option == 0 && Pred != ARMCC::AL)
8198       return Error(Operands[1]->getStartLoc(),
8199                    "instruction 'ssbb' is not predicable, but condition code "
8200                    "specified");
8201     if (Option == 4 && Pred != ARMCC::AL)
8202       return Error(Operands[1]->getStartLoc(),
8203                    "instruction 'pssbb' is not predicable, but condition code "
8204                    "specified");
8205     break;
8206   }
8207   case ARM::VMOVRRS: {
8208     // Source registers must be sequential.
8209     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
8210     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
8211     if (Sm1 != Sm + 1)
8212       return Error(Operands[5]->getStartLoc(),
8213                    "source operands must be sequential");
8214     break;
8215   }
8216   case ARM::VMOVSRR: {
8217     // Destination registers must be sequential.
8218     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
8219     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
8220     if (Sm1 != Sm + 1)
8221       return Error(Operands[3]->getStartLoc(),
8222                    "destination operands must be sequential");
8223     break;
8224   }
8225   case ARM::VLDMDIA:
8226   case ARM::VSTMDIA: {
8227     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
8228     auto &RegList = Op.getRegList();
8229     if (RegList.size() < 1 || RegList.size() > 16)
8230       return Error(Operands[3]->getStartLoc(),
8231                    "list of registers must be at least 1 and at most 16");
8232     break;
8233   }
8234   case ARM::MVE_VQDMULLs32bh:
8235   case ARM::MVE_VQDMULLs32th:
8236   case ARM::MVE_VCMULf32:
8237   case ARM::MVE_VMULLBs32:
8238   case ARM::MVE_VMULLTs32:
8239   case ARM::MVE_VMULLBu32:
8240   case ARM::MVE_VMULLTu32: {
8241     if (Operands[3]->getReg() == Operands[4]->getReg()) {
8242       return Error (Operands[3]->getStartLoc(),
8243                     "Qd register and Qn register can't be identical");
8244     }
8245     if (Operands[3]->getReg() == Operands[5]->getReg()) {
8246       return Error (Operands[3]->getStartLoc(),
8247                     "Qd register and Qm register can't be identical");
8248     }
8249     break;
8250   }
8251   case ARM::MVE_VMOV_rr_q: {
8252     if (Operands[4]->getReg() != Operands[6]->getReg())
8253       return Error (Operands[4]->getStartLoc(), "Q-registers must be the same");
8254     if (static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() !=
8255         static_cast<ARMOperand &>(*Operands[7]).getVectorIndex() + 2)
8256       return Error (Operands[5]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8257     break;
8258   }
8259   case ARM::MVE_VMOV_q_rr: {
8260     if (Operands[2]->getReg() != Operands[4]->getReg())
8261       return Error (Operands[2]->getStartLoc(), "Q-registers must be the same");
8262     if (static_cast<ARMOperand &>(*Operands[3]).getVectorIndex() !=
8263         static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() + 2)
8264       return Error (Operands[3]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8265     break;
8266   }
8267   case ARM::UMAAL:
8268   case ARM::UMLAL:
8269   case ARM::UMULL:
8270   case ARM::t2UMAAL:
8271   case ARM::t2UMLAL:
8272   case ARM::t2UMULL:
8273   case ARM::SMLAL:
8274   case ARM::SMLALBB:
8275   case ARM::SMLALBT:
8276   case ARM::SMLALD:
8277   case ARM::SMLALDX:
8278   case ARM::SMLALTB:
8279   case ARM::SMLALTT:
8280   case ARM::SMLSLD:
8281   case ARM::SMLSLDX:
8282   case ARM::SMULL:
8283   case ARM::t2SMLAL:
8284   case ARM::t2SMLALBB:
8285   case ARM::t2SMLALBT:
8286   case ARM::t2SMLALD:
8287   case ARM::t2SMLALDX:
8288   case ARM::t2SMLALTB:
8289   case ARM::t2SMLALTT:
8290   case ARM::t2SMLSLD:
8291   case ARM::t2SMLSLDX:
8292   case ARM::t2SMULL: {
8293     unsigned RdHi = Inst.getOperand(0).getReg();
8294     unsigned RdLo = Inst.getOperand(1).getReg();
8295     if(RdHi == RdLo) {
8296       return Error(Loc,
8297                    "unpredictable instruction, RdHi and RdLo must be different");
8298     }
8299     break;
8300   }
8301 
8302   case ARM::CDE_CX1:
8303   case ARM::CDE_CX1A:
8304   case ARM::CDE_CX1D:
8305   case ARM::CDE_CX1DA:
8306   case ARM::CDE_CX2:
8307   case ARM::CDE_CX2A:
8308   case ARM::CDE_CX2D:
8309   case ARM::CDE_CX2DA:
8310   case ARM::CDE_CX3:
8311   case ARM::CDE_CX3A:
8312   case ARM::CDE_CX3D:
8313   case ARM::CDE_CX3DA:
8314   case ARM::CDE_VCX1_vec:
8315   case ARM::CDE_VCX1_fpsp:
8316   case ARM::CDE_VCX1_fpdp:
8317   case ARM::CDE_VCX1A_vec:
8318   case ARM::CDE_VCX1A_fpsp:
8319   case ARM::CDE_VCX1A_fpdp:
8320   case ARM::CDE_VCX2_vec:
8321   case ARM::CDE_VCX2_fpsp:
8322   case ARM::CDE_VCX2_fpdp:
8323   case ARM::CDE_VCX2A_vec:
8324   case ARM::CDE_VCX2A_fpsp:
8325   case ARM::CDE_VCX2A_fpdp:
8326   case ARM::CDE_VCX3_vec:
8327   case ARM::CDE_VCX3_fpsp:
8328   case ARM::CDE_VCX3_fpdp:
8329   case ARM::CDE_VCX3A_vec:
8330   case ARM::CDE_VCX3A_fpsp:
8331   case ARM::CDE_VCX3A_fpdp: {
8332     assert(Inst.getOperand(1).isImm() &&
8333            "CDE operand 1 must be a coprocessor ID");
8334     int64_t Coproc = Inst.getOperand(1).getImm();
8335     if (Coproc < 8 && !ARM::isCDECoproc(Coproc, *STI))
8336       return Error(Operands[1]->getStartLoc(),
8337                    "coprocessor must be configured as CDE");
8338     else if (Coproc >= 8)
8339       return Error(Operands[1]->getStartLoc(),
8340                    "coprocessor must be in the range [p0, p7]");
8341     break;
8342   }
8343 
8344   case ARM::t2CDP:
8345   case ARM::t2CDP2:
8346   case ARM::t2LDC2L_OFFSET:
8347   case ARM::t2LDC2L_OPTION:
8348   case ARM::t2LDC2L_POST:
8349   case ARM::t2LDC2L_PRE:
8350   case ARM::t2LDC2_OFFSET:
8351   case ARM::t2LDC2_OPTION:
8352   case ARM::t2LDC2_POST:
8353   case ARM::t2LDC2_PRE:
8354   case ARM::t2LDCL_OFFSET:
8355   case ARM::t2LDCL_OPTION:
8356   case ARM::t2LDCL_POST:
8357   case ARM::t2LDCL_PRE:
8358   case ARM::t2LDC_OFFSET:
8359   case ARM::t2LDC_OPTION:
8360   case ARM::t2LDC_POST:
8361   case ARM::t2LDC_PRE:
8362   case ARM::t2MCR:
8363   case ARM::t2MCR2:
8364   case ARM::t2MCRR:
8365   case ARM::t2MCRR2:
8366   case ARM::t2MRC:
8367   case ARM::t2MRC2:
8368   case ARM::t2MRRC:
8369   case ARM::t2MRRC2:
8370   case ARM::t2STC2L_OFFSET:
8371   case ARM::t2STC2L_OPTION:
8372   case ARM::t2STC2L_POST:
8373   case ARM::t2STC2L_PRE:
8374   case ARM::t2STC2_OFFSET:
8375   case ARM::t2STC2_OPTION:
8376   case ARM::t2STC2_POST:
8377   case ARM::t2STC2_PRE:
8378   case ARM::t2STCL_OFFSET:
8379   case ARM::t2STCL_OPTION:
8380   case ARM::t2STCL_POST:
8381   case ARM::t2STCL_PRE:
8382   case ARM::t2STC_OFFSET:
8383   case ARM::t2STC_OPTION:
8384   case ARM::t2STC_POST:
8385   case ARM::t2STC_PRE: {
8386     unsigned Opcode = Inst.getOpcode();
8387     // Inst.getOperand indexes operands in the (oops ...) and (iops ...) dags,
8388     // CopInd is the index of the coprocessor operand.
8389     size_t CopInd = 0;
8390     if (Opcode == ARM::t2MRRC || Opcode == ARM::t2MRRC2)
8391       CopInd = 2;
8392     else if (Opcode == ARM::t2MRC || Opcode == ARM::t2MRC2)
8393       CopInd = 1;
8394     assert(Inst.getOperand(CopInd).isImm() &&
8395            "Operand must be a coprocessor ID");
8396     int64_t Coproc = Inst.getOperand(CopInd).getImm();
8397     // Operands[2] is the coprocessor operand at syntactic level
8398     if (ARM::isCDECoproc(Coproc, *STI))
8399       return Error(Operands[2]->getStartLoc(),
8400                    "coprocessor must be configured as GCP");
8401     break;
8402   }
8403   }
8404 
8405   return false;
8406 }
8407 
8408 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
8409   switch(Opc) {
8410   default: llvm_unreachable("unexpected opcode!");
8411   // VST1LN
8412   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8413   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8414   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8415   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8416   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8417   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8418   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
8419   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
8420   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
8421 
8422   // VST2LN
8423   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8424   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8425   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8426   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8427   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8428 
8429   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8430   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8431   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8432   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8433   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8434 
8435   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
8436   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
8437   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
8438   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
8439   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
8440 
8441   // VST3LN
8442   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8443   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8444   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8445   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
8446   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8447   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8448   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8449   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8450   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
8451   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8452   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
8453   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
8454   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
8455   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
8456   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
8457 
8458   // VST3
8459   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8460   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8461   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8462   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8463   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8464   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8465   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8466   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8467   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8468   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8469   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8470   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8471   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
8472   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
8473   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
8474   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
8475   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
8476   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
8477 
8478   // VST4LN
8479   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8480   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8481   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8482   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
8483   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8484   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8485   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8486   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8487   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
8488   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8489   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
8490   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
8491   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
8492   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
8493   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
8494 
8495   // VST4
8496   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8497   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8498   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8499   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8500   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8501   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8502   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8503   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8504   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8505   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8506   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8507   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8508   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
8509   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
8510   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
8511   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
8512   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
8513   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
8514   }
8515 }
8516 
8517 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
8518   switch(Opc) {
8519   default: llvm_unreachable("unexpected opcode!");
8520   // VLD1LN
8521   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8522   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8523   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8524   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8525   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8526   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8527   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
8528   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
8529   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
8530 
8531   // VLD2LN
8532   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8533   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8534   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8535   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
8536   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8537   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8538   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8539   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8540   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
8541   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8542   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
8543   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
8544   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
8545   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
8546   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
8547 
8548   // VLD3DUP
8549   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8550   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8551   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8552   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
8553   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8554   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8555   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8556   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8557   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8558   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
8559   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8560   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8561   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
8562   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
8563   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
8564   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
8565   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
8566   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
8567 
8568   // VLD3LN
8569   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8570   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8571   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8572   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
8573   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8574   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8575   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8576   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8577   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
8578   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8579   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
8580   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
8581   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
8582   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
8583   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
8584 
8585   // VLD3
8586   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8587   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8588   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8589   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8590   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8591   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8592   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8593   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8594   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8595   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8596   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8597   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8598   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
8599   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
8600   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
8601   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
8602   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
8603   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
8604 
8605   // VLD4LN
8606   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8607   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8608   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8609   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8610   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8611   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8612   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8613   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8614   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8615   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8616   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
8617   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
8618   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
8619   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
8620   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
8621 
8622   // VLD4DUP
8623   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8624   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8625   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8626   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
8627   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
8628   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8629   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8630   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8631   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8632   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
8633   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
8634   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8635   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
8636   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
8637   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
8638   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
8639   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
8640   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
8641 
8642   // VLD4
8643   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8644   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8645   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8646   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8647   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8648   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8649   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8650   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8651   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8652   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8653   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8654   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8655   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
8656   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
8657   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
8658   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
8659   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
8660   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
8661   }
8662 }
8663 
8664 bool ARMAsmParser::processInstruction(MCInst &Inst,
8665                                       const OperandVector &Operands,
8666                                       MCStreamer &Out) {
8667   // Check if we have the wide qualifier, because if it's present we
8668   // must avoid selecting a 16-bit thumb instruction.
8669   bool HasWideQualifier = false;
8670   for (auto &Op : Operands) {
8671     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
8672     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
8673       HasWideQualifier = true;
8674       break;
8675     }
8676   }
8677 
8678   switch (Inst.getOpcode()) {
8679   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
8680   case ARM::LDRT_POST:
8681   case ARM::LDRBT_POST: {
8682     const unsigned Opcode =
8683       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
8684                                            : ARM::LDRBT_POST_IMM;
8685     MCInst TmpInst;
8686     TmpInst.setOpcode(Opcode);
8687     TmpInst.addOperand(Inst.getOperand(0));
8688     TmpInst.addOperand(Inst.getOperand(1));
8689     TmpInst.addOperand(Inst.getOperand(1));
8690     TmpInst.addOperand(MCOperand::createReg(0));
8691     TmpInst.addOperand(MCOperand::createImm(0));
8692     TmpInst.addOperand(Inst.getOperand(2));
8693     TmpInst.addOperand(Inst.getOperand(3));
8694     Inst = TmpInst;
8695     return true;
8696   }
8697   // Alias for 'ldr{sb,h,sh}t Rt, [Rn] {, #imm}' for ommitted immediate.
8698   case ARM::LDRSBTii:
8699   case ARM::LDRHTii:
8700   case ARM::LDRSHTii: {
8701     MCInst TmpInst;
8702 
8703     if (Inst.getOpcode() == ARM::LDRSBTii)
8704       TmpInst.setOpcode(ARM::LDRSBTi);
8705     else if (Inst.getOpcode() == ARM::LDRHTii)
8706       TmpInst.setOpcode(ARM::LDRHTi);
8707     else if (Inst.getOpcode() == ARM::LDRSHTii)
8708       TmpInst.setOpcode(ARM::LDRSHTi);
8709     TmpInst.addOperand(Inst.getOperand(0));
8710     TmpInst.addOperand(Inst.getOperand(1));
8711     TmpInst.addOperand(Inst.getOperand(1));
8712     TmpInst.addOperand(MCOperand::createImm(256));
8713     TmpInst.addOperand(Inst.getOperand(2));
8714     Inst = TmpInst;
8715     return true;
8716   }
8717   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
8718   case ARM::STRT_POST:
8719   case ARM::STRBT_POST: {
8720     const unsigned Opcode =
8721       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
8722                                            : ARM::STRBT_POST_IMM;
8723     MCInst TmpInst;
8724     TmpInst.setOpcode(Opcode);
8725     TmpInst.addOperand(Inst.getOperand(1));
8726     TmpInst.addOperand(Inst.getOperand(0));
8727     TmpInst.addOperand(Inst.getOperand(1));
8728     TmpInst.addOperand(MCOperand::createReg(0));
8729     TmpInst.addOperand(MCOperand::createImm(0));
8730     TmpInst.addOperand(Inst.getOperand(2));
8731     TmpInst.addOperand(Inst.getOperand(3));
8732     Inst = TmpInst;
8733     return true;
8734   }
8735   // Alias for alternate form of 'ADR Rd, #imm' instruction.
8736   case ARM::ADDri: {
8737     if (Inst.getOperand(1).getReg() != ARM::PC ||
8738         Inst.getOperand(5).getReg() != 0 ||
8739         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
8740       return false;
8741     MCInst TmpInst;
8742     TmpInst.setOpcode(ARM::ADR);
8743     TmpInst.addOperand(Inst.getOperand(0));
8744     if (Inst.getOperand(2).isImm()) {
8745       // Immediate (mod_imm) will be in its encoded form, we must unencode it
8746       // before passing it to the ADR instruction.
8747       unsigned Enc = Inst.getOperand(2).getImm();
8748       TmpInst.addOperand(MCOperand::createImm(
8749         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
8750     } else {
8751       // Turn PC-relative expression into absolute expression.
8752       // Reading PC provides the start of the current instruction + 8 and
8753       // the transform to adr is biased by that.
8754       MCSymbol *Dot = getContext().createTempSymbol();
8755       Out.emitLabel(Dot);
8756       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
8757       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
8758                                                      MCSymbolRefExpr::VK_None,
8759                                                      getContext());
8760       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
8761       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
8762                                                      getContext());
8763       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
8764                                                         getContext());
8765       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
8766     }
8767     TmpInst.addOperand(Inst.getOperand(3));
8768     TmpInst.addOperand(Inst.getOperand(4));
8769     Inst = TmpInst;
8770     return true;
8771   }
8772   // Aliases for imm syntax of LDR instructions.
8773   case ARM::t2LDR_PRE_imm:
8774   case ARM::t2LDR_POST_imm: {
8775     MCInst TmpInst;
8776     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2LDR_PRE_imm ? ARM::t2LDR_PRE
8777                                                              : ARM::t2LDR_POST);
8778     TmpInst.addOperand(Inst.getOperand(0)); // Rt
8779     TmpInst.addOperand(Inst.getOperand(4)); // Rt_wb
8780     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8781     TmpInst.addOperand(Inst.getOperand(2)); // imm
8782     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8783     Inst = TmpInst;
8784     return true;
8785   }
8786   // Aliases for imm syntax of STR instructions.
8787   case ARM::t2STR_PRE_imm:
8788   case ARM::t2STR_POST_imm: {
8789     MCInst TmpInst;
8790     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2STR_PRE_imm ? ARM::t2STR_PRE
8791                                                              : ARM::t2STR_POST);
8792     TmpInst.addOperand(Inst.getOperand(4)); // Rt_wb
8793     TmpInst.addOperand(Inst.getOperand(0)); // Rt
8794     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8795     TmpInst.addOperand(Inst.getOperand(2)); // imm
8796     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8797     Inst = TmpInst;
8798     return true;
8799   }
8800   // Aliases for alternate PC+imm syntax of LDR instructions.
8801   case ARM::t2LDRpcrel:
8802     // Select the narrow version if the immediate will fit.
8803     if (Inst.getOperand(1).getImm() > 0 &&
8804         Inst.getOperand(1).getImm() <= 0xff &&
8805         !HasWideQualifier)
8806       Inst.setOpcode(ARM::tLDRpci);
8807     else
8808       Inst.setOpcode(ARM::t2LDRpci);
8809     return true;
8810   case ARM::t2LDRBpcrel:
8811     Inst.setOpcode(ARM::t2LDRBpci);
8812     return true;
8813   case ARM::t2LDRHpcrel:
8814     Inst.setOpcode(ARM::t2LDRHpci);
8815     return true;
8816   case ARM::t2LDRSBpcrel:
8817     Inst.setOpcode(ARM::t2LDRSBpci);
8818     return true;
8819   case ARM::t2LDRSHpcrel:
8820     Inst.setOpcode(ARM::t2LDRSHpci);
8821     return true;
8822   case ARM::LDRConstPool:
8823   case ARM::tLDRConstPool:
8824   case ARM::t2LDRConstPool: {
8825     // Pseudo instruction ldr rt, =immediate is converted to a
8826     // MOV rt, immediate if immediate is known and representable
8827     // otherwise we create a constant pool entry that we load from.
8828     MCInst TmpInst;
8829     if (Inst.getOpcode() == ARM::LDRConstPool)
8830       TmpInst.setOpcode(ARM::LDRi12);
8831     else if (Inst.getOpcode() == ARM::tLDRConstPool)
8832       TmpInst.setOpcode(ARM::tLDRpci);
8833     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
8834       TmpInst.setOpcode(ARM::t2LDRpci);
8835     const ARMOperand &PoolOperand =
8836       (HasWideQualifier ?
8837        static_cast<ARMOperand &>(*Operands[4]) :
8838        static_cast<ARMOperand &>(*Operands[3]));
8839     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
8840     // If SubExprVal is a constant we may be able to use a MOV
8841     if (isa<MCConstantExpr>(SubExprVal) &&
8842         Inst.getOperand(0).getReg() != ARM::PC &&
8843         Inst.getOperand(0).getReg() != ARM::SP) {
8844       int64_t Value =
8845         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
8846       bool UseMov  = true;
8847       bool MovHasS = true;
8848       if (Inst.getOpcode() == ARM::LDRConstPool) {
8849         // ARM Constant
8850         if (ARM_AM::getSOImmVal(Value) != -1) {
8851           Value = ARM_AM::getSOImmVal(Value);
8852           TmpInst.setOpcode(ARM::MOVi);
8853         }
8854         else if (ARM_AM::getSOImmVal(~Value) != -1) {
8855           Value = ARM_AM::getSOImmVal(~Value);
8856           TmpInst.setOpcode(ARM::MVNi);
8857         }
8858         else if (hasV6T2Ops() &&
8859                  Value >=0 && Value < 65536) {
8860           TmpInst.setOpcode(ARM::MOVi16);
8861           MovHasS = false;
8862         }
8863         else
8864           UseMov = false;
8865       }
8866       else {
8867         // Thumb/Thumb2 Constant
8868         if (hasThumb2() &&
8869             ARM_AM::getT2SOImmVal(Value) != -1)
8870           TmpInst.setOpcode(ARM::t2MOVi);
8871         else if (hasThumb2() &&
8872                  ARM_AM::getT2SOImmVal(~Value) != -1) {
8873           TmpInst.setOpcode(ARM::t2MVNi);
8874           Value = ~Value;
8875         }
8876         else if (hasV8MBaseline() &&
8877                  Value >=0 && Value < 65536) {
8878           TmpInst.setOpcode(ARM::t2MOVi16);
8879           MovHasS = false;
8880         }
8881         else
8882           UseMov = false;
8883       }
8884       if (UseMov) {
8885         TmpInst.addOperand(Inst.getOperand(0));           // Rt
8886         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
8887         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8888         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8889         if (MovHasS)
8890           TmpInst.addOperand(MCOperand::createReg(0));    // S
8891         Inst = TmpInst;
8892         return true;
8893       }
8894     }
8895     // No opportunity to use MOV/MVN create constant pool
8896     const MCExpr *CPLoc =
8897       getTargetStreamer().addConstantPoolEntry(SubExprVal,
8898                                                PoolOperand.getStartLoc());
8899     TmpInst.addOperand(Inst.getOperand(0));           // Rt
8900     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
8901     if (TmpInst.getOpcode() == ARM::LDRi12)
8902       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
8903     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8904     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8905     Inst = TmpInst;
8906     return true;
8907   }
8908   // Handle NEON VST complex aliases.
8909   case ARM::VST1LNdWB_register_Asm_8:
8910   case ARM::VST1LNdWB_register_Asm_16:
8911   case ARM::VST1LNdWB_register_Asm_32: {
8912     MCInst TmpInst;
8913     // Shuffle the operands around so the lane index operand is in the
8914     // right place.
8915     unsigned Spacing;
8916     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8917     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8918     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8919     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8920     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8921     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8922     TmpInst.addOperand(Inst.getOperand(1)); // lane
8923     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8924     TmpInst.addOperand(Inst.getOperand(6));
8925     Inst = TmpInst;
8926     return true;
8927   }
8928 
8929   case ARM::VST2LNdWB_register_Asm_8:
8930   case ARM::VST2LNdWB_register_Asm_16:
8931   case ARM::VST2LNdWB_register_Asm_32:
8932   case ARM::VST2LNqWB_register_Asm_16:
8933   case ARM::VST2LNqWB_register_Asm_32: {
8934     MCInst TmpInst;
8935     // Shuffle the operands around so the lane index operand is in the
8936     // right place.
8937     unsigned Spacing;
8938     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8939     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8940     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8941     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8942     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8943     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8944     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8945                                             Spacing));
8946     TmpInst.addOperand(Inst.getOperand(1)); // lane
8947     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8948     TmpInst.addOperand(Inst.getOperand(6));
8949     Inst = TmpInst;
8950     return true;
8951   }
8952 
8953   case ARM::VST3LNdWB_register_Asm_8:
8954   case ARM::VST3LNdWB_register_Asm_16:
8955   case ARM::VST3LNdWB_register_Asm_32:
8956   case ARM::VST3LNqWB_register_Asm_16:
8957   case ARM::VST3LNqWB_register_Asm_32: {
8958     MCInst TmpInst;
8959     // Shuffle the operands around so the lane index operand is in the
8960     // right place.
8961     unsigned Spacing;
8962     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8963     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8964     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8965     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8966     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8967     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8968     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8969                                             Spacing));
8970     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8971                                             Spacing * 2));
8972     TmpInst.addOperand(Inst.getOperand(1)); // lane
8973     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8974     TmpInst.addOperand(Inst.getOperand(6));
8975     Inst = TmpInst;
8976     return true;
8977   }
8978 
8979   case ARM::VST4LNdWB_register_Asm_8:
8980   case ARM::VST4LNdWB_register_Asm_16:
8981   case ARM::VST4LNdWB_register_Asm_32:
8982   case ARM::VST4LNqWB_register_Asm_16:
8983   case ARM::VST4LNqWB_register_Asm_32: {
8984     MCInst TmpInst;
8985     // Shuffle the operands around so the lane index operand is in the
8986     // right place.
8987     unsigned Spacing;
8988     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8989     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8990     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8991     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8992     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8993     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8994     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8995                                             Spacing));
8996     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8997                                             Spacing * 2));
8998     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8999                                             Spacing * 3));
9000     TmpInst.addOperand(Inst.getOperand(1)); // lane
9001     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9002     TmpInst.addOperand(Inst.getOperand(6));
9003     Inst = TmpInst;
9004     return true;
9005   }
9006 
9007   case ARM::VST1LNdWB_fixed_Asm_8:
9008   case ARM::VST1LNdWB_fixed_Asm_16:
9009   case ARM::VST1LNdWB_fixed_Asm_32: {
9010     MCInst TmpInst;
9011     // Shuffle the operands around so the lane index operand is in the
9012     // right place.
9013     unsigned Spacing;
9014     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9015     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9016     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9017     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9018     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9019     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9020     TmpInst.addOperand(Inst.getOperand(1)); // lane
9021     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9022     TmpInst.addOperand(Inst.getOperand(5));
9023     Inst = TmpInst;
9024     return true;
9025   }
9026 
9027   case ARM::VST2LNdWB_fixed_Asm_8:
9028   case ARM::VST2LNdWB_fixed_Asm_16:
9029   case ARM::VST2LNdWB_fixed_Asm_32:
9030   case ARM::VST2LNqWB_fixed_Asm_16:
9031   case ARM::VST2LNqWB_fixed_Asm_32: {
9032     MCInst TmpInst;
9033     // Shuffle the operands around so the lane index operand is in the
9034     // right place.
9035     unsigned Spacing;
9036     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9037     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9038     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9039     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9040     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9041     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9042     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9043                                             Spacing));
9044     TmpInst.addOperand(Inst.getOperand(1)); // lane
9045     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9046     TmpInst.addOperand(Inst.getOperand(5));
9047     Inst = TmpInst;
9048     return true;
9049   }
9050 
9051   case ARM::VST3LNdWB_fixed_Asm_8:
9052   case ARM::VST3LNdWB_fixed_Asm_16:
9053   case ARM::VST3LNdWB_fixed_Asm_32:
9054   case ARM::VST3LNqWB_fixed_Asm_16:
9055   case ARM::VST3LNqWB_fixed_Asm_32: {
9056     MCInst TmpInst;
9057     // Shuffle the operands around so the lane index operand is in the
9058     // right place.
9059     unsigned Spacing;
9060     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9061     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9062     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9063     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9064     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9065     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9066     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9067                                             Spacing));
9068     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9069                                             Spacing * 2));
9070     TmpInst.addOperand(Inst.getOperand(1)); // lane
9071     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9072     TmpInst.addOperand(Inst.getOperand(5));
9073     Inst = TmpInst;
9074     return true;
9075   }
9076 
9077   case ARM::VST4LNdWB_fixed_Asm_8:
9078   case ARM::VST4LNdWB_fixed_Asm_16:
9079   case ARM::VST4LNdWB_fixed_Asm_32:
9080   case ARM::VST4LNqWB_fixed_Asm_16:
9081   case ARM::VST4LNqWB_fixed_Asm_32: {
9082     MCInst TmpInst;
9083     // Shuffle the operands around so the lane index operand is in the
9084     // right place.
9085     unsigned Spacing;
9086     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9087     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9088     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9089     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9090     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9091     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9092     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9093                                             Spacing));
9094     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9095                                             Spacing * 2));
9096     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9097                                             Spacing * 3));
9098     TmpInst.addOperand(Inst.getOperand(1)); // lane
9099     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9100     TmpInst.addOperand(Inst.getOperand(5));
9101     Inst = TmpInst;
9102     return true;
9103   }
9104 
9105   case ARM::VST1LNdAsm_8:
9106   case ARM::VST1LNdAsm_16:
9107   case ARM::VST1LNdAsm_32: {
9108     MCInst TmpInst;
9109     // Shuffle the operands around so the lane index operand is in the
9110     // right place.
9111     unsigned Spacing;
9112     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9113     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9114     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9115     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9116     TmpInst.addOperand(Inst.getOperand(1)); // lane
9117     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9118     TmpInst.addOperand(Inst.getOperand(5));
9119     Inst = TmpInst;
9120     return true;
9121   }
9122 
9123   case ARM::VST2LNdAsm_8:
9124   case ARM::VST2LNdAsm_16:
9125   case ARM::VST2LNdAsm_32:
9126   case ARM::VST2LNqAsm_16:
9127   case ARM::VST2LNqAsm_32: {
9128     MCInst TmpInst;
9129     // Shuffle the operands around so the lane index operand is in the
9130     // right place.
9131     unsigned Spacing;
9132     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9133     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9134     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9135     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9136     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9137                                             Spacing));
9138     TmpInst.addOperand(Inst.getOperand(1)); // lane
9139     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9140     TmpInst.addOperand(Inst.getOperand(5));
9141     Inst = TmpInst;
9142     return true;
9143   }
9144 
9145   case ARM::VST3LNdAsm_8:
9146   case ARM::VST3LNdAsm_16:
9147   case ARM::VST3LNdAsm_32:
9148   case ARM::VST3LNqAsm_16:
9149   case ARM::VST3LNqAsm_32: {
9150     MCInst TmpInst;
9151     // Shuffle the operands around so the lane index operand is in the
9152     // right place.
9153     unsigned Spacing;
9154     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9155     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9156     TmpInst.addOperand(Inst.getOperand(3)); // alignment
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(1)); // lane
9163     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9164     TmpInst.addOperand(Inst.getOperand(5));
9165     Inst = TmpInst;
9166     return true;
9167   }
9168 
9169   case ARM::VST4LNdAsm_8:
9170   case ARM::VST4LNdAsm_16:
9171   case ARM::VST4LNdAsm_32:
9172   case ARM::VST4LNqAsm_16:
9173   case ARM::VST4LNqAsm_32: {
9174     MCInst TmpInst;
9175     // Shuffle the operands around so the lane index operand is in the
9176     // right place.
9177     unsigned Spacing;
9178     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9179     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9180     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9181     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9182     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9183                                             Spacing));
9184     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9185                                             Spacing * 2));
9186     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9187                                             Spacing * 3));
9188     TmpInst.addOperand(Inst.getOperand(1)); // lane
9189     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9190     TmpInst.addOperand(Inst.getOperand(5));
9191     Inst = TmpInst;
9192     return true;
9193   }
9194 
9195   // Handle NEON VLD complex aliases.
9196   case ARM::VLD1LNdWB_register_Asm_8:
9197   case ARM::VLD1LNdWB_register_Asm_16:
9198   case ARM::VLD1LNdWB_register_Asm_32: {
9199     MCInst TmpInst;
9200     // Shuffle the operands around so the lane index operand is in the
9201     // right place.
9202     unsigned Spacing;
9203     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9204     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9205     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9206     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9207     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9208     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9209     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9210     TmpInst.addOperand(Inst.getOperand(1)); // lane
9211     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9212     TmpInst.addOperand(Inst.getOperand(6));
9213     Inst = TmpInst;
9214     return true;
9215   }
9216 
9217   case ARM::VLD2LNdWB_register_Asm_8:
9218   case ARM::VLD2LNdWB_register_Asm_16:
9219   case ARM::VLD2LNdWB_register_Asm_32:
9220   case ARM::VLD2LNqWB_register_Asm_16:
9221   case ARM::VLD2LNqWB_register_Asm_32: {
9222     MCInst TmpInst;
9223     // Shuffle the operands around so the lane index operand is in the
9224     // right place.
9225     unsigned Spacing;
9226     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9227     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9228     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9229                                             Spacing));
9230     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9231     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9232     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9233     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9234     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9235     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9236                                             Spacing));
9237     TmpInst.addOperand(Inst.getOperand(1)); // lane
9238     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9239     TmpInst.addOperand(Inst.getOperand(6));
9240     Inst = TmpInst;
9241     return true;
9242   }
9243 
9244   case ARM::VLD3LNdWB_register_Asm_8:
9245   case ARM::VLD3LNdWB_register_Asm_16:
9246   case ARM::VLD3LNdWB_register_Asm_32:
9247   case ARM::VLD3LNqWB_register_Asm_16:
9248   case ARM::VLD3LNqWB_register_Asm_32: {
9249     MCInst TmpInst;
9250     // Shuffle the operands around so the lane index operand is in the
9251     // right place.
9252     unsigned Spacing;
9253     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9254     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9255     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9256                                             Spacing));
9257     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9258                                             Spacing * 2));
9259     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9260     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9261     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9262     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9263     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9264     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9265                                             Spacing));
9266     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9267                                             Spacing * 2));
9268     TmpInst.addOperand(Inst.getOperand(1)); // lane
9269     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9270     TmpInst.addOperand(Inst.getOperand(6));
9271     Inst = TmpInst;
9272     return true;
9273   }
9274 
9275   case ARM::VLD4LNdWB_register_Asm_8:
9276   case ARM::VLD4LNdWB_register_Asm_16:
9277   case ARM::VLD4LNdWB_register_Asm_32:
9278   case ARM::VLD4LNqWB_register_Asm_16:
9279   case ARM::VLD4LNqWB_register_Asm_32: {
9280     MCInst TmpInst;
9281     // Shuffle the operands around so the lane index operand is in the
9282     // right place.
9283     unsigned Spacing;
9284     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9285     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9286     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9287                                             Spacing));
9288     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9289                                             Spacing * 2));
9290     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9291                                             Spacing * 3));
9292     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9293     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9294     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9295     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9296     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== 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(1)); // lane
9304     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9305     TmpInst.addOperand(Inst.getOperand(6));
9306     Inst = TmpInst;
9307     return true;
9308   }
9309 
9310   case ARM::VLD1LNdWB_fixed_Asm_8:
9311   case ARM::VLD1LNdWB_fixed_Asm_16:
9312   case ARM::VLD1LNdWB_fixed_Asm_32: {
9313     MCInst TmpInst;
9314     // Shuffle the operands around so the lane index operand is in the
9315     // right place.
9316     unsigned Spacing;
9317     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9318     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9319     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9320     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9321     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9322     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9323     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9324     TmpInst.addOperand(Inst.getOperand(1)); // lane
9325     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9326     TmpInst.addOperand(Inst.getOperand(5));
9327     Inst = TmpInst;
9328     return true;
9329   }
9330 
9331   case ARM::VLD2LNdWB_fixed_Asm_8:
9332   case ARM::VLD2LNdWB_fixed_Asm_16:
9333   case ARM::VLD2LNdWB_fixed_Asm_32:
9334   case ARM::VLD2LNqWB_fixed_Asm_16:
9335   case ARM::VLD2LNqWB_fixed_Asm_32: {
9336     MCInst TmpInst;
9337     // Shuffle the operands around so the lane index operand is in the
9338     // right place.
9339     unsigned Spacing;
9340     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9341     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9342     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9343                                             Spacing));
9344     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9345     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9346     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9347     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9348     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9349     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9350                                             Spacing));
9351     TmpInst.addOperand(Inst.getOperand(1)); // lane
9352     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9353     TmpInst.addOperand(Inst.getOperand(5));
9354     Inst = TmpInst;
9355     return true;
9356   }
9357 
9358   case ARM::VLD3LNdWB_fixed_Asm_8:
9359   case ARM::VLD3LNdWB_fixed_Asm_16:
9360   case ARM::VLD3LNdWB_fixed_Asm_32:
9361   case ARM::VLD3LNqWB_fixed_Asm_16:
9362   case ARM::VLD3LNqWB_fixed_Asm_32: {
9363     MCInst TmpInst;
9364     // Shuffle the operands around so the lane index operand is in the
9365     // right place.
9366     unsigned Spacing;
9367     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9368     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9369     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9370                                             Spacing));
9371     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9372                                             Spacing * 2));
9373     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9374     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9375     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9376     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9377     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9378     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9379                                             Spacing));
9380     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9381                                             Spacing * 2));
9382     TmpInst.addOperand(Inst.getOperand(1)); // lane
9383     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9384     TmpInst.addOperand(Inst.getOperand(5));
9385     Inst = TmpInst;
9386     return true;
9387   }
9388 
9389   case ARM::VLD4LNdWB_fixed_Asm_8:
9390   case ARM::VLD4LNdWB_fixed_Asm_16:
9391   case ARM::VLD4LNdWB_fixed_Asm_32:
9392   case ARM::VLD4LNqWB_fixed_Asm_16:
9393   case ARM::VLD4LNqWB_fixed_Asm_32: {
9394     MCInst TmpInst;
9395     // Shuffle the operands around so the lane index operand is in the
9396     // right place.
9397     unsigned Spacing;
9398     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9399     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9400     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9401                                             Spacing));
9402     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9403                                             Spacing * 2));
9404     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9405                                             Spacing * 3));
9406     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9407     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9408     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9409     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9410     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9411     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9412                                             Spacing));
9413     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9414                                             Spacing * 2));
9415     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9416                                             Spacing * 3));
9417     TmpInst.addOperand(Inst.getOperand(1)); // lane
9418     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9419     TmpInst.addOperand(Inst.getOperand(5));
9420     Inst = TmpInst;
9421     return true;
9422   }
9423 
9424   case ARM::VLD1LNdAsm_8:
9425   case ARM::VLD1LNdAsm_16:
9426   case ARM::VLD1LNdAsm_32: {
9427     MCInst TmpInst;
9428     // Shuffle the operands around so the lane index operand is in the
9429     // right place.
9430     unsigned Spacing;
9431     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9432     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9433     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9434     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9435     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9436     TmpInst.addOperand(Inst.getOperand(1)); // lane
9437     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9438     TmpInst.addOperand(Inst.getOperand(5));
9439     Inst = TmpInst;
9440     return true;
9441   }
9442 
9443   case ARM::VLD2LNdAsm_8:
9444   case ARM::VLD2LNdAsm_16:
9445   case ARM::VLD2LNdAsm_32:
9446   case ARM::VLD2LNqAsm_16:
9447   case ARM::VLD2LNqAsm_32: {
9448     MCInst TmpInst;
9449     // Shuffle the operands around so the lane index operand is in the
9450     // right place.
9451     unsigned Spacing;
9452     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9453     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9454     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9455                                             Spacing));
9456     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9457     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9458     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9459     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9460                                             Spacing));
9461     TmpInst.addOperand(Inst.getOperand(1)); // lane
9462     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9463     TmpInst.addOperand(Inst.getOperand(5));
9464     Inst = TmpInst;
9465     return true;
9466   }
9467 
9468   case ARM::VLD3LNdAsm_8:
9469   case ARM::VLD3LNdAsm_16:
9470   case ARM::VLD3LNdAsm_32:
9471   case ARM::VLD3LNqAsm_16:
9472   case ARM::VLD3LNqAsm_32: {
9473     MCInst TmpInst;
9474     // Shuffle the operands around so the lane index operand is in the
9475     // right place.
9476     unsigned Spacing;
9477     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9478     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9479     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9480                                             Spacing));
9481     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9482                                             Spacing * 2));
9483     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9484     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9485     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9486     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9487                                             Spacing));
9488     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9489                                             Spacing * 2));
9490     TmpInst.addOperand(Inst.getOperand(1)); // lane
9491     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9492     TmpInst.addOperand(Inst.getOperand(5));
9493     Inst = TmpInst;
9494     return true;
9495   }
9496 
9497   case ARM::VLD4LNdAsm_8:
9498   case ARM::VLD4LNdAsm_16:
9499   case ARM::VLD4LNdAsm_32:
9500   case ARM::VLD4LNqAsm_16:
9501   case ARM::VLD4LNqAsm_32: {
9502     MCInst TmpInst;
9503     // Shuffle the operands around so the lane index operand is in the
9504     // right place.
9505     unsigned Spacing;
9506     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9507     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9508     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9509                                             Spacing));
9510     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9511                                             Spacing * 2));
9512     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9513                                             Spacing * 3));
9514     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9515     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9516     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9517     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9518                                             Spacing));
9519     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9520                                             Spacing * 2));
9521     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9522                                             Spacing * 3));
9523     TmpInst.addOperand(Inst.getOperand(1)); // lane
9524     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9525     TmpInst.addOperand(Inst.getOperand(5));
9526     Inst = TmpInst;
9527     return true;
9528   }
9529 
9530   // VLD3DUP single 3-element structure to all lanes instructions.
9531   case ARM::VLD3DUPdAsm_8:
9532   case ARM::VLD3DUPdAsm_16:
9533   case ARM::VLD3DUPdAsm_32:
9534   case ARM::VLD3DUPqAsm_8:
9535   case ARM::VLD3DUPqAsm_16:
9536   case ARM::VLD3DUPqAsm_32: {
9537     MCInst TmpInst;
9538     unsigned Spacing;
9539     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9540     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9541     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9542                                             Spacing));
9543     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9544                                             Spacing * 2));
9545     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9546     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9547     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9548     TmpInst.addOperand(Inst.getOperand(4));
9549     Inst = TmpInst;
9550     return true;
9551   }
9552 
9553   case ARM::VLD3DUPdWB_fixed_Asm_8:
9554   case ARM::VLD3DUPdWB_fixed_Asm_16:
9555   case ARM::VLD3DUPdWB_fixed_Asm_32:
9556   case ARM::VLD3DUPqWB_fixed_Asm_8:
9557   case ARM::VLD3DUPqWB_fixed_Asm_16:
9558   case ARM::VLD3DUPqWB_fixed_Asm_32: {
9559     MCInst TmpInst;
9560     unsigned Spacing;
9561     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9562     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9563     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9564                                             Spacing));
9565     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9566                                             Spacing * 2));
9567     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9568     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9569     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9570     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9571     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9572     TmpInst.addOperand(Inst.getOperand(4));
9573     Inst = TmpInst;
9574     return true;
9575   }
9576 
9577   case ARM::VLD3DUPdWB_register_Asm_8:
9578   case ARM::VLD3DUPdWB_register_Asm_16:
9579   case ARM::VLD3DUPdWB_register_Asm_32:
9580   case ARM::VLD3DUPqWB_register_Asm_8:
9581   case ARM::VLD3DUPqWB_register_Asm_16:
9582   case ARM::VLD3DUPqWB_register_Asm_32: {
9583     MCInst TmpInst;
9584     unsigned Spacing;
9585     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9586     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9587     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9588                                             Spacing));
9589     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9590                                             Spacing * 2));
9591     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9592     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9593     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9594     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9595     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9596     TmpInst.addOperand(Inst.getOperand(5));
9597     Inst = TmpInst;
9598     return true;
9599   }
9600 
9601   // VLD3 multiple 3-element structure instructions.
9602   case ARM::VLD3dAsm_8:
9603   case ARM::VLD3dAsm_16:
9604   case ARM::VLD3dAsm_32:
9605   case ARM::VLD3qAsm_8:
9606   case ARM::VLD3qAsm_16:
9607   case ARM::VLD3qAsm_32: {
9608     MCInst TmpInst;
9609     unsigned Spacing;
9610     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9611     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9612     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9613                                             Spacing));
9614     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9615                                             Spacing * 2));
9616     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9617     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9618     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9619     TmpInst.addOperand(Inst.getOperand(4));
9620     Inst = TmpInst;
9621     return true;
9622   }
9623 
9624   case ARM::VLD3dWB_fixed_Asm_8:
9625   case ARM::VLD3dWB_fixed_Asm_16:
9626   case ARM::VLD3dWB_fixed_Asm_32:
9627   case ARM::VLD3qWB_fixed_Asm_8:
9628   case ARM::VLD3qWB_fixed_Asm_16:
9629   case ARM::VLD3qWB_fixed_Asm_32: {
9630     MCInst TmpInst;
9631     unsigned Spacing;
9632     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9633     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9634     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9635                                             Spacing));
9636     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9637                                             Spacing * 2));
9638     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9639     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9640     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9641     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9642     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9643     TmpInst.addOperand(Inst.getOperand(4));
9644     Inst = TmpInst;
9645     return true;
9646   }
9647 
9648   case ARM::VLD3dWB_register_Asm_8:
9649   case ARM::VLD3dWB_register_Asm_16:
9650   case ARM::VLD3dWB_register_Asm_32:
9651   case ARM::VLD3qWB_register_Asm_8:
9652   case ARM::VLD3qWB_register_Asm_16:
9653   case ARM::VLD3qWB_register_Asm_32: {
9654     MCInst TmpInst;
9655     unsigned Spacing;
9656     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9657     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9658     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9659                                             Spacing));
9660     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9661                                             Spacing * 2));
9662     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9663     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9664     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9665     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9666     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9667     TmpInst.addOperand(Inst.getOperand(5));
9668     Inst = TmpInst;
9669     return true;
9670   }
9671 
9672   // VLD4DUP single 3-element structure to all lanes instructions.
9673   case ARM::VLD4DUPdAsm_8:
9674   case ARM::VLD4DUPdAsm_16:
9675   case ARM::VLD4DUPdAsm_32:
9676   case ARM::VLD4DUPqAsm_8:
9677   case ARM::VLD4DUPqAsm_16:
9678   case ARM::VLD4DUPqAsm_32: {
9679     MCInst TmpInst;
9680     unsigned Spacing;
9681     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9682     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9683     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9684                                             Spacing));
9685     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9686                                             Spacing * 2));
9687     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9688                                             Spacing * 3));
9689     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9690     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9691     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9692     TmpInst.addOperand(Inst.getOperand(4));
9693     Inst = TmpInst;
9694     return true;
9695   }
9696 
9697   case ARM::VLD4DUPdWB_fixed_Asm_8:
9698   case ARM::VLD4DUPdWB_fixed_Asm_16:
9699   case ARM::VLD4DUPdWB_fixed_Asm_32:
9700   case ARM::VLD4DUPqWB_fixed_Asm_8:
9701   case ARM::VLD4DUPqWB_fixed_Asm_16:
9702   case ARM::VLD4DUPqWB_fixed_Asm_32: {
9703     MCInst TmpInst;
9704     unsigned Spacing;
9705     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9706     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9707     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9708                                             Spacing));
9709     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9710                                             Spacing * 2));
9711     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9712                                             Spacing * 3));
9713     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9714     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9715     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9716     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9717     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9718     TmpInst.addOperand(Inst.getOperand(4));
9719     Inst = TmpInst;
9720     return true;
9721   }
9722 
9723   case ARM::VLD4DUPdWB_register_Asm_8:
9724   case ARM::VLD4DUPdWB_register_Asm_16:
9725   case ARM::VLD4DUPdWB_register_Asm_32:
9726   case ARM::VLD4DUPqWB_register_Asm_8:
9727   case ARM::VLD4DUPqWB_register_Asm_16:
9728   case ARM::VLD4DUPqWB_register_Asm_32: {
9729     MCInst TmpInst;
9730     unsigned Spacing;
9731     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9732     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9733     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9734                                             Spacing));
9735     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9736                                             Spacing * 2));
9737     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9738                                             Spacing * 3));
9739     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9740     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9741     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9742     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9743     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9744     TmpInst.addOperand(Inst.getOperand(5));
9745     Inst = TmpInst;
9746     return true;
9747   }
9748 
9749   // VLD4 multiple 4-element structure instructions.
9750   case ARM::VLD4dAsm_8:
9751   case ARM::VLD4dAsm_16:
9752   case ARM::VLD4dAsm_32:
9753   case ARM::VLD4qAsm_8:
9754   case ARM::VLD4qAsm_16:
9755   case ARM::VLD4qAsm_32: {
9756     MCInst TmpInst;
9757     unsigned Spacing;
9758     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9759     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9760     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9761                                             Spacing));
9762     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9763                                             Spacing * 2));
9764     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9765                                             Spacing * 3));
9766     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9767     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9768     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9769     TmpInst.addOperand(Inst.getOperand(4));
9770     Inst = TmpInst;
9771     return true;
9772   }
9773 
9774   case ARM::VLD4dWB_fixed_Asm_8:
9775   case ARM::VLD4dWB_fixed_Asm_16:
9776   case ARM::VLD4dWB_fixed_Asm_32:
9777   case ARM::VLD4qWB_fixed_Asm_8:
9778   case ARM::VLD4qWB_fixed_Asm_16:
9779   case ARM::VLD4qWB_fixed_Asm_32: {
9780     MCInst TmpInst;
9781     unsigned Spacing;
9782     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9783     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9784     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9785                                             Spacing));
9786     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9787                                             Spacing * 2));
9788     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9789                                             Spacing * 3));
9790     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9791     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9792     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9793     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9794     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9795     TmpInst.addOperand(Inst.getOperand(4));
9796     Inst = TmpInst;
9797     return true;
9798   }
9799 
9800   case ARM::VLD4dWB_register_Asm_8:
9801   case ARM::VLD4dWB_register_Asm_16:
9802   case ARM::VLD4dWB_register_Asm_32:
9803   case ARM::VLD4qWB_register_Asm_8:
9804   case ARM::VLD4qWB_register_Asm_16:
9805   case ARM::VLD4qWB_register_Asm_32: {
9806     MCInst TmpInst;
9807     unsigned Spacing;
9808     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9809     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9810     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9811                                             Spacing));
9812     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9813                                             Spacing * 2));
9814     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9815                                             Spacing * 3));
9816     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9817     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9818     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9819     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9820     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9821     TmpInst.addOperand(Inst.getOperand(5));
9822     Inst = TmpInst;
9823     return true;
9824   }
9825 
9826   // VST3 multiple 3-element structure instructions.
9827   case ARM::VST3dAsm_8:
9828   case ARM::VST3dAsm_16:
9829   case ARM::VST3dAsm_32:
9830   case ARM::VST3qAsm_8:
9831   case ARM::VST3qAsm_16:
9832   case ARM::VST3qAsm_32: {
9833     MCInst TmpInst;
9834     unsigned Spacing;
9835     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9836     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9837     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9838     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9839     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9840                                             Spacing));
9841     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9842                                             Spacing * 2));
9843     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9844     TmpInst.addOperand(Inst.getOperand(4));
9845     Inst = TmpInst;
9846     return true;
9847   }
9848 
9849   case ARM::VST3dWB_fixed_Asm_8:
9850   case ARM::VST3dWB_fixed_Asm_16:
9851   case ARM::VST3dWB_fixed_Asm_32:
9852   case ARM::VST3qWB_fixed_Asm_8:
9853   case ARM::VST3qWB_fixed_Asm_16:
9854   case ARM::VST3qWB_fixed_Asm_32: {
9855     MCInst TmpInst;
9856     unsigned Spacing;
9857     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9858     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9859     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9860     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9861     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9862     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9863     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9864                                             Spacing));
9865     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9866                                             Spacing * 2));
9867     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9868     TmpInst.addOperand(Inst.getOperand(4));
9869     Inst = TmpInst;
9870     return true;
9871   }
9872 
9873   case ARM::VST3dWB_register_Asm_8:
9874   case ARM::VST3dWB_register_Asm_16:
9875   case ARM::VST3dWB_register_Asm_32:
9876   case ARM::VST3qWB_register_Asm_8:
9877   case ARM::VST3qWB_register_Asm_16:
9878   case ARM::VST3qWB_register_Asm_32: {
9879     MCInst TmpInst;
9880     unsigned Spacing;
9881     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9882     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9883     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9884     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9885     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9886     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9887     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9888                                             Spacing));
9889     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9890                                             Spacing * 2));
9891     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9892     TmpInst.addOperand(Inst.getOperand(5));
9893     Inst = TmpInst;
9894     return true;
9895   }
9896 
9897   // VST4 multiple 3-element structure instructions.
9898   case ARM::VST4dAsm_8:
9899   case ARM::VST4dAsm_16:
9900   case ARM::VST4dAsm_32:
9901   case ARM::VST4qAsm_8:
9902   case ARM::VST4qAsm_16:
9903   case ARM::VST4qAsm_32: {
9904     MCInst TmpInst;
9905     unsigned Spacing;
9906     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9907     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9908     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9909     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9910     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9911                                             Spacing));
9912     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9913                                             Spacing * 2));
9914     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9915                                             Spacing * 3));
9916     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9917     TmpInst.addOperand(Inst.getOperand(4));
9918     Inst = TmpInst;
9919     return true;
9920   }
9921 
9922   case ARM::VST4dWB_fixed_Asm_8:
9923   case ARM::VST4dWB_fixed_Asm_16:
9924   case ARM::VST4dWB_fixed_Asm_32:
9925   case ARM::VST4qWB_fixed_Asm_8:
9926   case ARM::VST4qWB_fixed_Asm_16:
9927   case ARM::VST4qWB_fixed_Asm_32: {
9928     MCInst TmpInst;
9929     unsigned Spacing;
9930     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9931     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9932     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9933     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9934     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9935     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9936     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9937                                             Spacing));
9938     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9939                                             Spacing * 2));
9940     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9941                                             Spacing * 3));
9942     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9943     TmpInst.addOperand(Inst.getOperand(4));
9944     Inst = TmpInst;
9945     return true;
9946   }
9947 
9948   case ARM::VST4dWB_register_Asm_8:
9949   case ARM::VST4dWB_register_Asm_16:
9950   case ARM::VST4dWB_register_Asm_32:
9951   case ARM::VST4qWB_register_Asm_8:
9952   case ARM::VST4qWB_register_Asm_16:
9953   case ARM::VST4qWB_register_Asm_32: {
9954     MCInst TmpInst;
9955     unsigned Spacing;
9956     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9957     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9958     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9959     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9960     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9961     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9962     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9963                                             Spacing));
9964     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9965                                             Spacing * 2));
9966     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9967                                             Spacing * 3));
9968     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9969     TmpInst.addOperand(Inst.getOperand(5));
9970     Inst = TmpInst;
9971     return true;
9972   }
9973 
9974   // Handle encoding choice for the shift-immediate instructions.
9975   case ARM::t2LSLri:
9976   case ARM::t2LSRri:
9977   case ARM::t2ASRri:
9978     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9979         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9980         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9981         !HasWideQualifier) {
9982       unsigned NewOpc;
9983       switch (Inst.getOpcode()) {
9984       default: llvm_unreachable("unexpected opcode");
9985       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
9986       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
9987       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
9988       }
9989       // The Thumb1 operands aren't in the same order. Awesome, eh?
9990       MCInst TmpInst;
9991       TmpInst.setOpcode(NewOpc);
9992       TmpInst.addOperand(Inst.getOperand(0));
9993       TmpInst.addOperand(Inst.getOperand(5));
9994       TmpInst.addOperand(Inst.getOperand(1));
9995       TmpInst.addOperand(Inst.getOperand(2));
9996       TmpInst.addOperand(Inst.getOperand(3));
9997       TmpInst.addOperand(Inst.getOperand(4));
9998       Inst = TmpInst;
9999       return true;
10000     }
10001     return false;
10002 
10003   // Handle the Thumb2 mode MOV complex aliases.
10004   case ARM::t2MOVsr:
10005   case ARM::t2MOVSsr: {
10006     // Which instruction to expand to depends on the CCOut operand and
10007     // whether we're in an IT block if the register operands are low
10008     // registers.
10009     bool isNarrow = false;
10010     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10011         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10012         isARMLowRegister(Inst.getOperand(2).getReg()) &&
10013         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10014         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
10015         !HasWideQualifier)
10016       isNarrow = true;
10017     MCInst TmpInst;
10018     unsigned newOpc;
10019     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
10020     default: llvm_unreachable("unexpected opcode!");
10021     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
10022     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
10023     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
10024     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
10025     }
10026     TmpInst.setOpcode(newOpc);
10027     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10028     if (isNarrow)
10029       TmpInst.addOperand(MCOperand::createReg(
10030           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
10031     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10032     TmpInst.addOperand(Inst.getOperand(2)); // Rm
10033     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
10034     TmpInst.addOperand(Inst.getOperand(5));
10035     if (!isNarrow)
10036       TmpInst.addOperand(MCOperand::createReg(
10037           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
10038     Inst = TmpInst;
10039     return true;
10040   }
10041   case ARM::t2MOVsi:
10042   case ARM::t2MOVSsi: {
10043     // Which instruction to expand to depends on the CCOut operand and
10044     // whether we're in an IT block if the register operands are low
10045     // registers.
10046     bool isNarrow = false;
10047     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10048         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10049         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
10050         !HasWideQualifier)
10051       isNarrow = true;
10052     MCInst TmpInst;
10053     unsigned newOpc;
10054     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
10055     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
10056     bool isMov = false;
10057     // MOV rd, rm, LSL #0 is actually a MOV instruction
10058     if (Shift == ARM_AM::lsl && Amount == 0) {
10059       isMov = true;
10060       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
10061       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
10062       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
10063       // instead.
10064       if (inITBlock()) {
10065         isNarrow = false;
10066       }
10067       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
10068     } else {
10069       switch(Shift) {
10070       default: llvm_unreachable("unexpected opcode!");
10071       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
10072       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
10073       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
10074       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
10075       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
10076       }
10077     }
10078     if (Amount == 32) Amount = 0;
10079     TmpInst.setOpcode(newOpc);
10080     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10081     if (isNarrow && !isMov)
10082       TmpInst.addOperand(MCOperand::createReg(
10083           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
10084     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10085     if (newOpc != ARM::t2RRX && !isMov)
10086       TmpInst.addOperand(MCOperand::createImm(Amount));
10087     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
10088     TmpInst.addOperand(Inst.getOperand(4));
10089     if (!isNarrow)
10090       TmpInst.addOperand(MCOperand::createReg(
10091           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
10092     Inst = TmpInst;
10093     return true;
10094   }
10095   // Handle the ARM mode MOV complex aliases.
10096   case ARM::ASRr:
10097   case ARM::LSRr:
10098   case ARM::LSLr:
10099   case ARM::RORr: {
10100     ARM_AM::ShiftOpc ShiftTy;
10101     switch(Inst.getOpcode()) {
10102     default: llvm_unreachable("unexpected opcode!");
10103     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
10104     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
10105     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
10106     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
10107     }
10108     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
10109     MCInst TmpInst;
10110     TmpInst.setOpcode(ARM::MOVsr);
10111     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10112     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10113     TmpInst.addOperand(Inst.getOperand(2)); // Rm
10114     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
10115     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
10116     TmpInst.addOperand(Inst.getOperand(4));
10117     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
10118     Inst = TmpInst;
10119     return true;
10120   }
10121   case ARM::ASRi:
10122   case ARM::LSRi:
10123   case ARM::LSLi:
10124   case ARM::RORi: {
10125     ARM_AM::ShiftOpc ShiftTy;
10126     switch(Inst.getOpcode()) {
10127     default: llvm_unreachable("unexpected opcode!");
10128     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
10129     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
10130     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
10131     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
10132     }
10133     // A shift by zero is a plain MOVr, not a MOVsi.
10134     unsigned Amt = Inst.getOperand(2).getImm();
10135     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
10136     // A shift by 32 should be encoded as 0 when permitted
10137     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
10138       Amt = 0;
10139     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
10140     MCInst TmpInst;
10141     TmpInst.setOpcode(Opc);
10142     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10143     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10144     if (Opc == ARM::MOVsi)
10145       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
10146     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
10147     TmpInst.addOperand(Inst.getOperand(4));
10148     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
10149     Inst = TmpInst;
10150     return true;
10151   }
10152   case ARM::RRXi: {
10153     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
10154     MCInst TmpInst;
10155     TmpInst.setOpcode(ARM::MOVsi);
10156     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10157     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10158     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
10159     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10160     TmpInst.addOperand(Inst.getOperand(3));
10161     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
10162     Inst = TmpInst;
10163     return true;
10164   }
10165   case ARM::t2LDMIA_UPD: {
10166     // If this is a load of a single register, then we should use
10167     // a post-indexed LDR instruction instead, per the ARM ARM.
10168     if (Inst.getNumOperands() != 5)
10169       return false;
10170     MCInst TmpInst;
10171     TmpInst.setOpcode(ARM::t2LDR_POST);
10172     TmpInst.addOperand(Inst.getOperand(4)); // Rt
10173     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10174     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10175     TmpInst.addOperand(MCOperand::createImm(4));
10176     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10177     TmpInst.addOperand(Inst.getOperand(3));
10178     Inst = TmpInst;
10179     return true;
10180   }
10181   case ARM::t2STMDB_UPD: {
10182     // If this is a store of a single register, then we should use
10183     // a pre-indexed STR instruction instead, per the ARM ARM.
10184     if (Inst.getNumOperands() != 5)
10185       return false;
10186     MCInst TmpInst;
10187     TmpInst.setOpcode(ARM::t2STR_PRE);
10188     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10189     TmpInst.addOperand(Inst.getOperand(4)); // Rt
10190     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10191     TmpInst.addOperand(MCOperand::createImm(-4));
10192     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10193     TmpInst.addOperand(Inst.getOperand(3));
10194     Inst = TmpInst;
10195     return true;
10196   }
10197   case ARM::LDMIA_UPD:
10198     // If this is a load of a single register via a 'pop', then we should use
10199     // a post-indexed LDR instruction instead, per the ARM ARM.
10200     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
10201         Inst.getNumOperands() == 5) {
10202       MCInst TmpInst;
10203       TmpInst.setOpcode(ARM::LDR_POST_IMM);
10204       TmpInst.addOperand(Inst.getOperand(4)); // Rt
10205       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10206       TmpInst.addOperand(Inst.getOperand(1)); // Rn
10207       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
10208       TmpInst.addOperand(MCOperand::createImm(4));
10209       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10210       TmpInst.addOperand(Inst.getOperand(3));
10211       Inst = TmpInst;
10212       return true;
10213     }
10214     break;
10215   case ARM::STMDB_UPD:
10216     // If this is a store of a single register via a 'push', then we should use
10217     // a pre-indexed STR instruction instead, per the ARM ARM.
10218     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
10219         Inst.getNumOperands() == 5) {
10220       MCInst TmpInst;
10221       TmpInst.setOpcode(ARM::STR_PRE_IMM);
10222       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10223       TmpInst.addOperand(Inst.getOperand(4)); // Rt
10224       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
10225       TmpInst.addOperand(MCOperand::createImm(-4));
10226       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10227       TmpInst.addOperand(Inst.getOperand(3));
10228       Inst = TmpInst;
10229     }
10230     break;
10231   case ARM::t2ADDri12:
10232   case ARM::t2SUBri12:
10233   case ARM::t2ADDspImm12:
10234   case ARM::t2SUBspImm12: {
10235     // If the immediate fits for encoding T3 and the generic
10236     // mnemonic was used, encoding T3 is preferred.
10237     const StringRef Token = static_cast<ARMOperand &>(*Operands[0]).getToken();
10238     if ((Token != "add" && Token != "sub") ||
10239         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
10240       break;
10241     switch (Inst.getOpcode()) {
10242     case ARM::t2ADDri12:
10243       Inst.setOpcode(ARM::t2ADDri);
10244       break;
10245     case ARM::t2SUBri12:
10246       Inst.setOpcode(ARM::t2SUBri);
10247       break;
10248     case ARM::t2ADDspImm12:
10249       Inst.setOpcode(ARM::t2ADDspImm);
10250       break;
10251     case ARM::t2SUBspImm12:
10252       Inst.setOpcode(ARM::t2SUBspImm);
10253       break;
10254     }
10255 
10256     Inst.addOperand(MCOperand::createReg(0)); // cc_out
10257     return true;
10258   }
10259   case ARM::tADDi8:
10260     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10261     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10262     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10263     // to encoding T1 if <Rd> is omitted."
10264     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10265       Inst.setOpcode(ARM::tADDi3);
10266       return true;
10267     }
10268     break;
10269   case ARM::tSUBi8:
10270     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10271     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10272     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10273     // to encoding T1 if <Rd> is omitted."
10274     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10275       Inst.setOpcode(ARM::tSUBi3);
10276       return true;
10277     }
10278     break;
10279   case ARM::t2ADDri:
10280   case ARM::t2SUBri: {
10281     // If the destination and first source operand are the same, and
10282     // the flags are compatible with the current IT status, use encoding T2
10283     // instead of T3. For compatibility with the system 'as'. Make sure the
10284     // wide encoding wasn't explicit.
10285     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
10286         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
10287         (Inst.getOperand(2).isImm() &&
10288          (unsigned)Inst.getOperand(2).getImm() > 255) ||
10289         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
10290         HasWideQualifier)
10291       break;
10292     MCInst TmpInst;
10293     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
10294                       ARM::tADDi8 : ARM::tSUBi8);
10295     TmpInst.addOperand(Inst.getOperand(0));
10296     TmpInst.addOperand(Inst.getOperand(5));
10297     TmpInst.addOperand(Inst.getOperand(0));
10298     TmpInst.addOperand(Inst.getOperand(2));
10299     TmpInst.addOperand(Inst.getOperand(3));
10300     TmpInst.addOperand(Inst.getOperand(4));
10301     Inst = TmpInst;
10302     return true;
10303   }
10304   case ARM::t2ADDspImm:
10305   case ARM::t2SUBspImm: {
10306     // Prefer T1 encoding if possible
10307     if (Inst.getOperand(5).getReg() != 0 || HasWideQualifier)
10308       break;
10309     unsigned V = Inst.getOperand(2).getImm();
10310     if (V & 3 || V > ((1 << 7) - 1) << 2)
10311       break;
10312     MCInst TmpInst;
10313     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDspImm ? ARM::tADDspi
10314                                                           : ARM::tSUBspi);
10315     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // destination reg
10316     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // source reg
10317     TmpInst.addOperand(MCOperand::createImm(V / 4));   // immediate
10318     TmpInst.addOperand(Inst.getOperand(3));            // pred
10319     TmpInst.addOperand(Inst.getOperand(4));
10320     Inst = TmpInst;
10321     return true;
10322   }
10323   case ARM::t2ADDrr: {
10324     // If the destination and first source operand are the same, and
10325     // there's no setting of the flags, use encoding T2 instead of T3.
10326     // Note that this is only for ADD, not SUB. This mirrors the system
10327     // 'as' behaviour.  Also take advantage of ADD being commutative.
10328     // Make sure the wide encoding wasn't explicit.
10329     bool Swap = false;
10330     auto DestReg = Inst.getOperand(0).getReg();
10331     bool Transform = DestReg == Inst.getOperand(1).getReg();
10332     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
10333       Transform = true;
10334       Swap = true;
10335     }
10336     if (!Transform ||
10337         Inst.getOperand(5).getReg() != 0 ||
10338         HasWideQualifier)
10339       break;
10340     MCInst TmpInst;
10341     TmpInst.setOpcode(ARM::tADDhirr);
10342     TmpInst.addOperand(Inst.getOperand(0));
10343     TmpInst.addOperand(Inst.getOperand(0));
10344     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
10345     TmpInst.addOperand(Inst.getOperand(3));
10346     TmpInst.addOperand(Inst.getOperand(4));
10347     Inst = TmpInst;
10348     return true;
10349   }
10350   case ARM::tADDrSP:
10351     // If the non-SP source operand and the destination operand are not the
10352     // same, we need to use the 32-bit encoding if it's available.
10353     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
10354       Inst.setOpcode(ARM::t2ADDrr);
10355       Inst.addOperand(MCOperand::createReg(0)); // cc_out
10356       return true;
10357     }
10358     break;
10359   case ARM::tB:
10360     // A Thumb conditional branch outside of an IT block is a tBcc.
10361     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
10362       Inst.setOpcode(ARM::tBcc);
10363       return true;
10364     }
10365     break;
10366   case ARM::t2B:
10367     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
10368     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
10369       Inst.setOpcode(ARM::t2Bcc);
10370       return true;
10371     }
10372     break;
10373   case ARM::t2Bcc:
10374     // If the conditional is AL or we're in an IT block, we really want t2B.
10375     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
10376       Inst.setOpcode(ARM::t2B);
10377       return true;
10378     }
10379     break;
10380   case ARM::tBcc:
10381     // If the conditional is AL, we really want tB.
10382     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
10383       Inst.setOpcode(ARM::tB);
10384       return true;
10385     }
10386     break;
10387   case ARM::tLDMIA: {
10388     // If the register list contains any high registers, or if the writeback
10389     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
10390     // instead if we're in Thumb2. Otherwise, this should have generated
10391     // an error in validateInstruction().
10392     unsigned Rn = Inst.getOperand(0).getReg();
10393     bool hasWritebackToken =
10394         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
10395          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
10396     bool listContainsBase;
10397     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
10398         (!listContainsBase && !hasWritebackToken) ||
10399         (listContainsBase && hasWritebackToken)) {
10400       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10401       assert(isThumbTwo());
10402       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
10403       // If we're switching to the updating version, we need to insert
10404       // the writeback tied operand.
10405       if (hasWritebackToken)
10406         Inst.insert(Inst.begin(),
10407                     MCOperand::createReg(Inst.getOperand(0).getReg()));
10408       return true;
10409     }
10410     break;
10411   }
10412   case ARM::tSTMIA_UPD: {
10413     // If the register list contains any high registers, we need to use
10414     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10415     // should have generated an error in validateInstruction().
10416     unsigned Rn = Inst.getOperand(0).getReg();
10417     bool listContainsBase;
10418     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
10419       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10420       assert(isThumbTwo());
10421       Inst.setOpcode(ARM::t2STMIA_UPD);
10422       return true;
10423     }
10424     break;
10425   }
10426   case ARM::tPOP: {
10427     bool listContainsBase;
10428     // If the register list contains any high registers, we need to use
10429     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10430     // should have generated an error in validateInstruction().
10431     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
10432       return false;
10433     assert(isThumbTwo());
10434     Inst.setOpcode(ARM::t2LDMIA_UPD);
10435     // Add the base register and writeback operands.
10436     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10437     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10438     return true;
10439   }
10440   case ARM::tPUSH: {
10441     bool listContainsBase;
10442     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
10443       return false;
10444     assert(isThumbTwo());
10445     Inst.setOpcode(ARM::t2STMDB_UPD);
10446     // Add the base register and writeback operands.
10447     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10448     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10449     return true;
10450   }
10451   case ARM::t2MOVi:
10452     // If we can use the 16-bit encoding and the user didn't explicitly
10453     // request the 32-bit variant, transform it here.
10454     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10455         (Inst.getOperand(1).isImm() &&
10456          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
10457         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10458         !HasWideQualifier) {
10459       // The operands aren't in the same order for tMOVi8...
10460       MCInst TmpInst;
10461       TmpInst.setOpcode(ARM::tMOVi8);
10462       TmpInst.addOperand(Inst.getOperand(0));
10463       TmpInst.addOperand(Inst.getOperand(4));
10464       TmpInst.addOperand(Inst.getOperand(1));
10465       TmpInst.addOperand(Inst.getOperand(2));
10466       TmpInst.addOperand(Inst.getOperand(3));
10467       Inst = TmpInst;
10468       return true;
10469     }
10470     break;
10471 
10472   case ARM::t2MOVr:
10473     // If we can use the 16-bit encoding and the user didn't explicitly
10474     // request the 32-bit variant, transform it here.
10475     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10476         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10477         Inst.getOperand(2).getImm() == ARMCC::AL &&
10478         Inst.getOperand(4).getReg() == ARM::CPSR &&
10479         !HasWideQualifier) {
10480       // The operands aren't the same for tMOV[S]r... (no cc_out)
10481       MCInst TmpInst;
10482       unsigned Op = Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr;
10483       TmpInst.setOpcode(Op);
10484       TmpInst.addOperand(Inst.getOperand(0));
10485       TmpInst.addOperand(Inst.getOperand(1));
10486       if (Op == ARM::tMOVr) {
10487         TmpInst.addOperand(Inst.getOperand(2));
10488         TmpInst.addOperand(Inst.getOperand(3));
10489       }
10490       Inst = TmpInst;
10491       return true;
10492     }
10493     break;
10494 
10495   case ARM::t2SXTH:
10496   case ARM::t2SXTB:
10497   case ARM::t2UXTH:
10498   case ARM::t2UXTB:
10499     // If we can use the 16-bit encoding and the user didn't explicitly
10500     // request the 32-bit variant, transform it here.
10501     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10502         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10503         Inst.getOperand(2).getImm() == 0 &&
10504         !HasWideQualifier) {
10505       unsigned NewOpc;
10506       switch (Inst.getOpcode()) {
10507       default: llvm_unreachable("Illegal opcode!");
10508       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
10509       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
10510       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
10511       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
10512       }
10513       // The operands aren't the same for thumb1 (no rotate operand).
10514       MCInst TmpInst;
10515       TmpInst.setOpcode(NewOpc);
10516       TmpInst.addOperand(Inst.getOperand(0));
10517       TmpInst.addOperand(Inst.getOperand(1));
10518       TmpInst.addOperand(Inst.getOperand(3));
10519       TmpInst.addOperand(Inst.getOperand(4));
10520       Inst = TmpInst;
10521       return true;
10522     }
10523     break;
10524 
10525   case ARM::MOVsi: {
10526     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
10527     // rrx shifts and asr/lsr of #32 is encoded as 0
10528     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
10529       return false;
10530     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
10531       // Shifting by zero is accepted as a vanilla 'MOVr'
10532       MCInst TmpInst;
10533       TmpInst.setOpcode(ARM::MOVr);
10534       TmpInst.addOperand(Inst.getOperand(0));
10535       TmpInst.addOperand(Inst.getOperand(1));
10536       TmpInst.addOperand(Inst.getOperand(3));
10537       TmpInst.addOperand(Inst.getOperand(4));
10538       TmpInst.addOperand(Inst.getOperand(5));
10539       Inst = TmpInst;
10540       return true;
10541     }
10542     return false;
10543   }
10544   case ARM::ANDrsi:
10545   case ARM::ORRrsi:
10546   case ARM::EORrsi:
10547   case ARM::BICrsi:
10548   case ARM::SUBrsi:
10549   case ARM::ADDrsi: {
10550     unsigned newOpc;
10551     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
10552     if (SOpc == ARM_AM::rrx) return false;
10553     switch (Inst.getOpcode()) {
10554     default: llvm_unreachable("unexpected opcode!");
10555     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
10556     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
10557     case ARM::EORrsi: newOpc = ARM::EORrr; break;
10558     case ARM::BICrsi: newOpc = ARM::BICrr; break;
10559     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
10560     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
10561     }
10562     // If the shift is by zero, use the non-shifted instruction definition.
10563     // The exception is for right shifts, where 0 == 32
10564     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
10565         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
10566       MCInst TmpInst;
10567       TmpInst.setOpcode(newOpc);
10568       TmpInst.addOperand(Inst.getOperand(0));
10569       TmpInst.addOperand(Inst.getOperand(1));
10570       TmpInst.addOperand(Inst.getOperand(2));
10571       TmpInst.addOperand(Inst.getOperand(4));
10572       TmpInst.addOperand(Inst.getOperand(5));
10573       TmpInst.addOperand(Inst.getOperand(6));
10574       Inst = TmpInst;
10575       return true;
10576     }
10577     return false;
10578   }
10579   case ARM::ITasm:
10580   case ARM::t2IT: {
10581     // Set up the IT block state according to the IT instruction we just
10582     // matched.
10583     assert(!inITBlock() && "nested IT blocks?!");
10584     startExplicitITBlock(ARMCC::CondCodes(Inst.getOperand(0).getImm()),
10585                          Inst.getOperand(1).getImm());
10586     break;
10587   }
10588   case ARM::t2LSLrr:
10589   case ARM::t2LSRrr:
10590   case ARM::t2ASRrr:
10591   case ARM::t2SBCrr:
10592   case ARM::t2RORrr:
10593   case ARM::t2BICrr:
10594     // Assemblers should use the narrow encodings of these instructions when permissible.
10595     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10596          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10597         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10598         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10599         !HasWideQualifier) {
10600       unsigned NewOpc;
10601       switch (Inst.getOpcode()) {
10602         default: llvm_unreachable("unexpected opcode");
10603         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
10604         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
10605         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
10606         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
10607         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
10608         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
10609       }
10610       MCInst TmpInst;
10611       TmpInst.setOpcode(NewOpc);
10612       TmpInst.addOperand(Inst.getOperand(0));
10613       TmpInst.addOperand(Inst.getOperand(5));
10614       TmpInst.addOperand(Inst.getOperand(1));
10615       TmpInst.addOperand(Inst.getOperand(2));
10616       TmpInst.addOperand(Inst.getOperand(3));
10617       TmpInst.addOperand(Inst.getOperand(4));
10618       Inst = TmpInst;
10619       return true;
10620     }
10621     return false;
10622 
10623   case ARM::t2ANDrr:
10624   case ARM::t2EORrr:
10625   case ARM::t2ADCrr:
10626   case ARM::t2ORRrr:
10627     // Assemblers should use the narrow encodings of these instructions when permissible.
10628     // These instructions are special in that they are commutable, so shorter encodings
10629     // are available more often.
10630     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10631          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10632         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
10633          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
10634         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10635         !HasWideQualifier) {
10636       unsigned NewOpc;
10637       switch (Inst.getOpcode()) {
10638         default: llvm_unreachable("unexpected opcode");
10639         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
10640         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
10641         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
10642         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
10643       }
10644       MCInst TmpInst;
10645       TmpInst.setOpcode(NewOpc);
10646       TmpInst.addOperand(Inst.getOperand(0));
10647       TmpInst.addOperand(Inst.getOperand(5));
10648       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
10649         TmpInst.addOperand(Inst.getOperand(1));
10650         TmpInst.addOperand(Inst.getOperand(2));
10651       } else {
10652         TmpInst.addOperand(Inst.getOperand(2));
10653         TmpInst.addOperand(Inst.getOperand(1));
10654       }
10655       TmpInst.addOperand(Inst.getOperand(3));
10656       TmpInst.addOperand(Inst.getOperand(4));
10657       Inst = TmpInst;
10658       return true;
10659     }
10660     return false;
10661   case ARM::MVE_VPST:
10662   case ARM::MVE_VPTv16i8:
10663   case ARM::MVE_VPTv8i16:
10664   case ARM::MVE_VPTv4i32:
10665   case ARM::MVE_VPTv16u8:
10666   case ARM::MVE_VPTv8u16:
10667   case ARM::MVE_VPTv4u32:
10668   case ARM::MVE_VPTv16s8:
10669   case ARM::MVE_VPTv8s16:
10670   case ARM::MVE_VPTv4s32:
10671   case ARM::MVE_VPTv4f32:
10672   case ARM::MVE_VPTv8f16:
10673   case ARM::MVE_VPTv16i8r:
10674   case ARM::MVE_VPTv8i16r:
10675   case ARM::MVE_VPTv4i32r:
10676   case ARM::MVE_VPTv16u8r:
10677   case ARM::MVE_VPTv8u16r:
10678   case ARM::MVE_VPTv4u32r:
10679   case ARM::MVE_VPTv16s8r:
10680   case ARM::MVE_VPTv8s16r:
10681   case ARM::MVE_VPTv4s32r:
10682   case ARM::MVE_VPTv4f32r:
10683   case ARM::MVE_VPTv8f16r: {
10684     assert(!inVPTBlock() && "Nested VPT blocks are not allowed");
10685     MCOperand &MO = Inst.getOperand(0);
10686     VPTState.Mask = MO.getImm();
10687     VPTState.CurPosition = 0;
10688     break;
10689   }
10690   }
10691   return false;
10692 }
10693 
10694 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
10695   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
10696   // suffix depending on whether they're in an IT block or not.
10697   unsigned Opc = Inst.getOpcode();
10698   const MCInstrDesc &MCID = MII.get(Opc);
10699   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
10700     assert(MCID.hasOptionalDef() &&
10701            "optionally flag setting instruction missing optional def operand");
10702     assert(MCID.NumOperands == Inst.getNumOperands() &&
10703            "operand count mismatch!");
10704     // Find the optional-def operand (cc_out).
10705     unsigned OpNo;
10706     for (OpNo = 0;
10707          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
10708          ++OpNo)
10709       ;
10710     // If we're parsing Thumb1, reject it completely.
10711     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
10712       return Match_RequiresFlagSetting;
10713     // If we're parsing Thumb2, which form is legal depends on whether we're
10714     // in an IT block.
10715     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
10716         !inITBlock())
10717       return Match_RequiresITBlock;
10718     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
10719         inITBlock())
10720       return Match_RequiresNotITBlock;
10721     // LSL with zero immediate is not allowed in an IT block
10722     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
10723       return Match_RequiresNotITBlock;
10724   } else if (isThumbOne()) {
10725     // Some high-register supporting Thumb1 encodings only allow both registers
10726     // to be from r0-r7 when in Thumb2.
10727     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
10728         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10729         isARMLowRegister(Inst.getOperand(2).getReg()))
10730       return Match_RequiresThumb2;
10731     // Others only require ARMv6 or later.
10732     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
10733              isARMLowRegister(Inst.getOperand(0).getReg()) &&
10734              isARMLowRegister(Inst.getOperand(1).getReg()))
10735       return Match_RequiresV6;
10736   }
10737 
10738   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
10739   // than the loop below can handle, so it uses the GPRnopc register class and
10740   // we do SP handling here.
10741   if (Opc == ARM::t2MOVr && !hasV8Ops())
10742   {
10743     // SP as both source and destination is not allowed
10744     if (Inst.getOperand(0).getReg() == ARM::SP &&
10745         Inst.getOperand(1).getReg() == ARM::SP)
10746       return Match_RequiresV8;
10747     // When flags-setting SP as either source or destination is not allowed
10748     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
10749         (Inst.getOperand(0).getReg() == ARM::SP ||
10750          Inst.getOperand(1).getReg() == ARM::SP))
10751       return Match_RequiresV8;
10752   }
10753 
10754   switch (Inst.getOpcode()) {
10755   case ARM::VMRS:
10756   case ARM::VMSR:
10757   case ARM::VMRS_FPCXTS:
10758   case ARM::VMRS_FPCXTNS:
10759   case ARM::VMSR_FPCXTS:
10760   case ARM::VMSR_FPCXTNS:
10761   case ARM::VMRS_FPSCR_NZCVQC:
10762   case ARM::VMSR_FPSCR_NZCVQC:
10763   case ARM::FMSTAT:
10764   case ARM::VMRS_VPR:
10765   case ARM::VMRS_P0:
10766   case ARM::VMSR_VPR:
10767   case ARM::VMSR_P0:
10768     // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
10769     // ARMv8-A.
10770     if (Inst.getOperand(0).isReg() && Inst.getOperand(0).getReg() == ARM::SP &&
10771         (isThumb() && !hasV8Ops()))
10772       return Match_InvalidOperand;
10773     break;
10774   case ARM::t2TBB:
10775   case ARM::t2TBH:
10776     // Rn = sp is only allowed with ARMv8-A
10777     if (!hasV8Ops() && (Inst.getOperand(0).getReg() == ARM::SP))
10778       return Match_RequiresV8;
10779     break;
10780   default:
10781     break;
10782   }
10783 
10784   for (unsigned I = 0; I < MCID.NumOperands; ++I)
10785     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
10786       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
10787       const auto &Op = Inst.getOperand(I);
10788       if (!Op.isReg()) {
10789         // This can happen in awkward cases with tied operands, e.g. a
10790         // writeback load/store with a complex addressing mode in
10791         // which there's an output operand corresponding to the
10792         // updated written-back base register: the Tablegen-generated
10793         // AsmMatcher will have written a placeholder operand to that
10794         // slot in the form of an immediate 0, because it can't
10795         // generate the register part of the complex addressing-mode
10796         // operand ahead of time.
10797         continue;
10798       }
10799 
10800       unsigned Reg = Op.getReg();
10801       if ((Reg == ARM::SP) && !hasV8Ops())
10802         return Match_RequiresV8;
10803       else if (Reg == ARM::PC)
10804         return Match_InvalidOperand;
10805     }
10806 
10807   return Match_Success;
10808 }
10809 
10810 namespace llvm {
10811 
10812 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
10813   return true; // In an assembly source, no need to second-guess
10814 }
10815 
10816 } // end namespace llvm
10817 
10818 // Returns true if Inst is unpredictable if it is in and IT block, but is not
10819 // the last instruction in the block.
10820 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
10821   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10822 
10823   // All branch & call instructions terminate IT blocks with the exception of
10824   // SVC.
10825   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
10826       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
10827     return true;
10828 
10829   // Any arithmetic instruction which writes to the PC also terminates the IT
10830   // block.
10831   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
10832     return true;
10833 
10834   return false;
10835 }
10836 
10837 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
10838                                           SmallVectorImpl<NearMissInfo> &NearMisses,
10839                                           bool MatchingInlineAsm,
10840                                           bool &EmitInITBlock,
10841                                           MCStreamer &Out) {
10842   // If we can't use an implicit IT block here, just match as normal.
10843   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
10844     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10845 
10846   // Try to match the instruction in an extension of the current IT block (if
10847   // there is one).
10848   if (inImplicitITBlock()) {
10849     extendImplicitITBlock(ITState.Cond);
10850     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10851             Match_Success) {
10852       // The match succeded, but we still have to check that the instruction is
10853       // valid in this implicit IT block.
10854       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10855       if (MCID.isPredicable()) {
10856         ARMCC::CondCodes InstCond =
10857             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10858                 .getImm();
10859         ARMCC::CondCodes ITCond = currentITCond();
10860         if (InstCond == ITCond) {
10861           EmitInITBlock = true;
10862           return Match_Success;
10863         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
10864           invertCurrentITCondition();
10865           EmitInITBlock = true;
10866           return Match_Success;
10867         }
10868       }
10869     }
10870     rewindImplicitITPosition();
10871   }
10872 
10873   // Finish the current IT block, and try to match outside any IT block.
10874   flushPendingInstructions(Out);
10875   unsigned PlainMatchResult =
10876       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10877   if (PlainMatchResult == Match_Success) {
10878     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10879     if (MCID.isPredicable()) {
10880       ARMCC::CondCodes InstCond =
10881           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10882               .getImm();
10883       // Some forms of the branch instruction have their own condition code
10884       // fields, so can be conditionally executed without an IT block.
10885       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
10886         EmitInITBlock = false;
10887         return Match_Success;
10888       }
10889       if (InstCond == ARMCC::AL) {
10890         EmitInITBlock = false;
10891         return Match_Success;
10892       }
10893     } else {
10894       EmitInITBlock = false;
10895       return Match_Success;
10896     }
10897   }
10898 
10899   // Try to match in a new IT block. The matcher doesn't check the actual
10900   // condition, so we create an IT block with a dummy condition, and fix it up
10901   // once we know the actual condition.
10902   startImplicitITBlock();
10903   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10904       Match_Success) {
10905     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10906     if (MCID.isPredicable()) {
10907       ITState.Cond =
10908           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10909               .getImm();
10910       EmitInITBlock = true;
10911       return Match_Success;
10912     }
10913   }
10914   discardImplicitITBlock();
10915 
10916   // If none of these succeed, return the error we got when trying to match
10917   // outside any IT blocks.
10918   EmitInITBlock = false;
10919   return PlainMatchResult;
10920 }
10921 
10922 static std::string ARMMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
10923                                          unsigned VariantID = 0);
10924 
10925 static const char *getSubtargetFeatureName(uint64_t Val);
10926 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
10927                                            OperandVector &Operands,
10928                                            MCStreamer &Out, uint64_t &ErrorInfo,
10929                                            bool MatchingInlineAsm) {
10930   MCInst Inst;
10931   unsigned MatchResult;
10932   bool PendConditionalInstruction = false;
10933 
10934   SmallVector<NearMissInfo, 4> NearMisses;
10935   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
10936                                  PendConditionalInstruction, Out);
10937 
10938   switch (MatchResult) {
10939   case Match_Success:
10940     LLVM_DEBUG(dbgs() << "Parsed as: ";
10941                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10942                dbgs() << "\n");
10943 
10944     // Context sensitive operand constraints aren't handled by the matcher,
10945     // so check them here.
10946     if (validateInstruction(Inst, Operands)) {
10947       // Still progress the IT block, otherwise one wrong condition causes
10948       // nasty cascading errors.
10949       forwardITPosition();
10950       forwardVPTPosition();
10951       return true;
10952     }
10953 
10954     { // processInstruction() updates inITBlock state, we need to save it away
10955       bool wasInITBlock = inITBlock();
10956 
10957       // Some instructions need post-processing to, for example, tweak which
10958       // encoding is selected. Loop on it while changes happen so the
10959       // individual transformations can chain off each other. E.g.,
10960       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
10961       while (processInstruction(Inst, Operands, Out))
10962         LLVM_DEBUG(dbgs() << "Changed to: ";
10963                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10964                    dbgs() << "\n");
10965 
10966       // Only after the instruction is fully processed, we can validate it
10967       if (wasInITBlock && hasV8Ops() && isThumb() &&
10968           !isV8EligibleForIT(&Inst) && !getTargetOptions().MCNoDeprecatedWarn) {
10969         Warning(IDLoc, "deprecated instruction in IT block");
10970       }
10971     }
10972 
10973     // Only move forward at the very end so that everything in validate
10974     // and process gets a consistent answer about whether we're in an IT
10975     // block.
10976     forwardITPosition();
10977     forwardVPTPosition();
10978 
10979     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
10980     // doesn't actually encode.
10981     if (Inst.getOpcode() == ARM::ITasm)
10982       return false;
10983 
10984     Inst.setLoc(IDLoc);
10985     if (PendConditionalInstruction) {
10986       PendingConditionalInsts.push_back(Inst);
10987       if (isITBlockFull() || isITBlockTerminator(Inst))
10988         flushPendingInstructions(Out);
10989     } else {
10990       Out.emitInstruction(Inst, getSTI());
10991     }
10992     return false;
10993   case Match_NearMisses:
10994     ReportNearMisses(NearMisses, IDLoc, Operands);
10995     return true;
10996   case Match_MnemonicFail: {
10997     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
10998     std::string Suggestion = ARMMnemonicSpellCheck(
10999       ((ARMOperand &)*Operands[0]).getToken(), FBS);
11000     return Error(IDLoc, "invalid instruction" + Suggestion,
11001                  ((ARMOperand &)*Operands[0]).getLocRange());
11002   }
11003   }
11004 
11005   llvm_unreachable("Implement any new match types added!");
11006 }
11007 
11008 /// parseDirective parses the arm specific directives
11009 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
11010   const MCContext::Environment Format = getContext().getObjectFileType();
11011   bool IsMachO = Format == MCContext::IsMachO;
11012   bool IsCOFF = Format == MCContext::IsCOFF;
11013 
11014   std::string IDVal = DirectiveID.getIdentifier().lower();
11015   if (IDVal == ".word")
11016     parseLiteralValues(4, DirectiveID.getLoc());
11017   else if (IDVal == ".short" || IDVal == ".hword")
11018     parseLiteralValues(2, DirectiveID.getLoc());
11019   else if (IDVal == ".thumb")
11020     parseDirectiveThumb(DirectiveID.getLoc());
11021   else if (IDVal == ".arm")
11022     parseDirectiveARM(DirectiveID.getLoc());
11023   else if (IDVal == ".thumb_func")
11024     parseDirectiveThumbFunc(DirectiveID.getLoc());
11025   else if (IDVal == ".code")
11026     parseDirectiveCode(DirectiveID.getLoc());
11027   else if (IDVal == ".syntax")
11028     parseDirectiveSyntax(DirectiveID.getLoc());
11029   else if (IDVal == ".unreq")
11030     parseDirectiveUnreq(DirectiveID.getLoc());
11031   else if (IDVal == ".fnend")
11032     parseDirectiveFnEnd(DirectiveID.getLoc());
11033   else if (IDVal == ".cantunwind")
11034     parseDirectiveCantUnwind(DirectiveID.getLoc());
11035   else if (IDVal == ".personality")
11036     parseDirectivePersonality(DirectiveID.getLoc());
11037   else if (IDVal == ".handlerdata")
11038     parseDirectiveHandlerData(DirectiveID.getLoc());
11039   else if (IDVal == ".setfp")
11040     parseDirectiveSetFP(DirectiveID.getLoc());
11041   else if (IDVal == ".pad")
11042     parseDirectivePad(DirectiveID.getLoc());
11043   else if (IDVal == ".save")
11044     parseDirectiveRegSave(DirectiveID.getLoc(), false);
11045   else if (IDVal == ".vsave")
11046     parseDirectiveRegSave(DirectiveID.getLoc(), true);
11047   else if (IDVal == ".ltorg" || IDVal == ".pool")
11048     parseDirectiveLtorg(DirectiveID.getLoc());
11049   else if (IDVal == ".even")
11050     parseDirectiveEven(DirectiveID.getLoc());
11051   else if (IDVal == ".personalityindex")
11052     parseDirectivePersonalityIndex(DirectiveID.getLoc());
11053   else if (IDVal == ".unwind_raw")
11054     parseDirectiveUnwindRaw(DirectiveID.getLoc());
11055   else if (IDVal == ".movsp")
11056     parseDirectiveMovSP(DirectiveID.getLoc());
11057   else if (IDVal == ".arch_extension")
11058     parseDirectiveArchExtension(DirectiveID.getLoc());
11059   else if (IDVal == ".align")
11060     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
11061   else if (IDVal == ".thumb_set")
11062     parseDirectiveThumbSet(DirectiveID.getLoc());
11063   else if (IDVal == ".inst")
11064     parseDirectiveInst(DirectiveID.getLoc());
11065   else if (IDVal == ".inst.n")
11066     parseDirectiveInst(DirectiveID.getLoc(), 'n');
11067   else if (IDVal == ".inst.w")
11068     parseDirectiveInst(DirectiveID.getLoc(), 'w');
11069   else if (!IsMachO && !IsCOFF) {
11070     if (IDVal == ".arch")
11071       parseDirectiveArch(DirectiveID.getLoc());
11072     else if (IDVal == ".cpu")
11073       parseDirectiveCPU(DirectiveID.getLoc());
11074     else if (IDVal == ".eabi_attribute")
11075       parseDirectiveEabiAttr(DirectiveID.getLoc());
11076     else if (IDVal == ".fpu")
11077       parseDirectiveFPU(DirectiveID.getLoc());
11078     else if (IDVal == ".fnstart")
11079       parseDirectiveFnStart(DirectiveID.getLoc());
11080     else if (IDVal == ".object_arch")
11081       parseDirectiveObjectArch(DirectiveID.getLoc());
11082     else if (IDVal == ".tlsdescseq")
11083       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
11084     else
11085       return true;
11086   } else
11087     return true;
11088   return false;
11089 }
11090 
11091 /// parseLiteralValues
11092 ///  ::= .hword expression [, expression]*
11093 ///  ::= .short expression [, expression]*
11094 ///  ::= .word expression [, expression]*
11095 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
11096   auto parseOne = [&]() -> bool {
11097     const MCExpr *Value;
11098     if (getParser().parseExpression(Value))
11099       return true;
11100     getParser().getStreamer().emitValue(Value, Size, L);
11101     return false;
11102   };
11103   return (parseMany(parseOne));
11104 }
11105 
11106 /// parseDirectiveThumb
11107 ///  ::= .thumb
11108 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
11109   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
11110       check(!hasThumb(), L, "target does not support Thumb mode"))
11111     return true;
11112 
11113   if (!isThumb())
11114     SwitchMode();
11115 
11116   getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11117   return false;
11118 }
11119 
11120 /// parseDirectiveARM
11121 ///  ::= .arm
11122 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
11123   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
11124       check(!hasARM(), L, "target does not support ARM mode"))
11125     return true;
11126 
11127   if (isThumb())
11128     SwitchMode();
11129   getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
11130   return false;
11131 }
11132 
11133 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
11134   // We need to flush the current implicit IT block on a label, because it is
11135   // not legal to branch into an IT block.
11136   flushPendingInstructions(getStreamer());
11137 }
11138 
11139 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
11140   if (NextSymbolIsThumb) {
11141     getParser().getStreamer().emitThumbFunc(Symbol);
11142     NextSymbolIsThumb = false;
11143   }
11144 }
11145 
11146 /// parseDirectiveThumbFunc
11147 ///  ::= .thumbfunc symbol_name
11148 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
11149   MCAsmParser &Parser = getParser();
11150   const auto Format = getContext().getObjectFileType();
11151   bool IsMachO = Format == MCContext::IsMachO;
11152 
11153   // Darwin asm has (optionally) function name after .thumb_func direction
11154   // ELF doesn't
11155 
11156   if (IsMachO) {
11157     if (Parser.getTok().is(AsmToken::Identifier) ||
11158         Parser.getTok().is(AsmToken::String)) {
11159       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
11160           Parser.getTok().getIdentifier());
11161       getParser().getStreamer().emitThumbFunc(Func);
11162       Parser.Lex();
11163       if (parseToken(AsmToken::EndOfStatement,
11164                      "unexpected token in '.thumb_func' directive"))
11165         return true;
11166       return false;
11167     }
11168   }
11169 
11170   if (parseToken(AsmToken::EndOfStatement,
11171                  "unexpected token in '.thumb_func' directive"))
11172     return true;
11173 
11174   // .thumb_func implies .thumb
11175   if (!isThumb())
11176     SwitchMode();
11177 
11178   getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11179 
11180   NextSymbolIsThumb = true;
11181   return false;
11182 }
11183 
11184 /// parseDirectiveSyntax
11185 ///  ::= .syntax unified | divided
11186 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
11187   MCAsmParser &Parser = getParser();
11188   const AsmToken &Tok = Parser.getTok();
11189   if (Tok.isNot(AsmToken::Identifier)) {
11190     Error(L, "unexpected token in .syntax directive");
11191     return false;
11192   }
11193 
11194   StringRef Mode = Tok.getString();
11195   Parser.Lex();
11196   if (check(Mode == "divided" || Mode == "DIVIDED", L,
11197             "'.syntax divided' arm assembly not supported") ||
11198       check(Mode != "unified" && Mode != "UNIFIED", L,
11199             "unrecognized syntax mode in .syntax directive") ||
11200       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11201     return true;
11202 
11203   // TODO tell the MC streamer the mode
11204   // getParser().getStreamer().Emit???();
11205   return false;
11206 }
11207 
11208 /// parseDirectiveCode
11209 ///  ::= .code 16 | 32
11210 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
11211   MCAsmParser &Parser = getParser();
11212   const AsmToken &Tok = Parser.getTok();
11213   if (Tok.isNot(AsmToken::Integer))
11214     return Error(L, "unexpected token in .code directive");
11215   int64_t Val = Parser.getTok().getIntVal();
11216   if (Val != 16 && Val != 32) {
11217     Error(L, "invalid operand to .code directive");
11218     return false;
11219   }
11220   Parser.Lex();
11221 
11222   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11223     return true;
11224 
11225   if (Val == 16) {
11226     if (!hasThumb())
11227       return Error(L, "target does not support Thumb mode");
11228 
11229     if (!isThumb())
11230       SwitchMode();
11231     getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11232   } else {
11233     if (!hasARM())
11234       return Error(L, "target does not support ARM mode");
11235 
11236     if (isThumb())
11237       SwitchMode();
11238     getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
11239   }
11240 
11241   return false;
11242 }
11243 
11244 /// parseDirectiveReq
11245 ///  ::= name .req registername
11246 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
11247   MCAsmParser &Parser = getParser();
11248   Parser.Lex(); // Eat the '.req' token.
11249   unsigned Reg;
11250   SMLoc SRegLoc, ERegLoc;
11251   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
11252             "register name expected") ||
11253       parseToken(AsmToken::EndOfStatement,
11254                  "unexpected input in .req directive."))
11255     return true;
11256 
11257   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
11258     return Error(SRegLoc,
11259                  "redefinition of '" + Name + "' does not match original.");
11260 
11261   return false;
11262 }
11263 
11264 /// parseDirectiveUneq
11265 ///  ::= .unreq registername
11266 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
11267   MCAsmParser &Parser = getParser();
11268   if (Parser.getTok().isNot(AsmToken::Identifier))
11269     return Error(L, "unexpected input in .unreq directive.");
11270   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
11271   Parser.Lex(); // Eat the identifier.
11272   if (parseToken(AsmToken::EndOfStatement,
11273                  "unexpected input in '.unreq' directive"))
11274     return true;
11275   return false;
11276 }
11277 
11278 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
11279 // before, if supported by the new target, or emit mapping symbols for the mode
11280 // switch.
11281 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
11282   if (WasThumb != isThumb()) {
11283     if (WasThumb && hasThumb()) {
11284       // Stay in Thumb mode
11285       SwitchMode();
11286     } else if (!WasThumb && hasARM()) {
11287       // Stay in ARM mode
11288       SwitchMode();
11289     } else {
11290       // Mode switch forced, because the new arch doesn't support the old mode.
11291       getParser().getStreamer().emitAssemblerFlag(isThumb() ? MCAF_Code16
11292                                                             : MCAF_Code32);
11293       // Warn about the implcit mode switch. GAS does not switch modes here,
11294       // but instead stays in the old mode, reporting an error on any following
11295       // instructions as the mode does not exist on the target.
11296       Warning(Loc, Twine("new target does not support ") +
11297                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
11298                        (!WasThumb ? "thumb" : "arm") + " mode");
11299     }
11300   }
11301 }
11302 
11303 /// parseDirectiveArch
11304 ///  ::= .arch token
11305 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
11306   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
11307   ARM::ArchKind ID = ARM::parseArch(Arch);
11308 
11309   if (ID == ARM::ArchKind::INVALID)
11310     return Error(L, "Unknown arch name");
11311 
11312   bool WasThumb = isThumb();
11313   Triple T;
11314   MCSubtargetInfo &STI = copySTI();
11315   STI.setDefaultFeatures("", /*TuneCPU*/ "",
11316                          ("+" + ARM::getArchName(ID)).str());
11317   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11318   FixModeAfterArchChange(WasThumb, L);
11319 
11320   getTargetStreamer().emitArch(ID);
11321   return false;
11322 }
11323 
11324 /// parseDirectiveEabiAttr
11325 ///  ::= .eabi_attribute int, int [, "str"]
11326 ///  ::= .eabi_attribute Tag_name, int [, "str"]
11327 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
11328   MCAsmParser &Parser = getParser();
11329   int64_t Tag;
11330   SMLoc TagLoc;
11331   TagLoc = Parser.getTok().getLoc();
11332   if (Parser.getTok().is(AsmToken::Identifier)) {
11333     StringRef Name = Parser.getTok().getIdentifier();
11334     Optional<unsigned> Ret = ELFAttrs::attrTypeFromString(
11335         Name, ARMBuildAttrs::getARMAttributeTags());
11336     if (!Ret.hasValue()) {
11337       Error(TagLoc, "attribute name not recognised: " + Name);
11338       return false;
11339     }
11340     Tag = Ret.getValue();
11341     Parser.Lex();
11342   } else {
11343     const MCExpr *AttrExpr;
11344 
11345     TagLoc = Parser.getTok().getLoc();
11346     if (Parser.parseExpression(AttrExpr))
11347       return true;
11348 
11349     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
11350     if (check(!CE, TagLoc, "expected numeric constant"))
11351       return true;
11352 
11353     Tag = CE->getValue();
11354   }
11355 
11356   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11357     return true;
11358 
11359   StringRef StringValue = "";
11360   bool IsStringValue = false;
11361 
11362   int64_t IntegerValue = 0;
11363   bool IsIntegerValue = false;
11364 
11365   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
11366     IsStringValue = true;
11367   else if (Tag == ARMBuildAttrs::compatibility) {
11368     IsStringValue = true;
11369     IsIntegerValue = true;
11370   } else if (Tag < 32 || Tag % 2 == 0)
11371     IsIntegerValue = true;
11372   else if (Tag % 2 == 1)
11373     IsStringValue = true;
11374   else
11375     llvm_unreachable("invalid tag type");
11376 
11377   if (IsIntegerValue) {
11378     const MCExpr *ValueExpr;
11379     SMLoc ValueExprLoc = Parser.getTok().getLoc();
11380     if (Parser.parseExpression(ValueExpr))
11381       return true;
11382 
11383     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
11384     if (!CE)
11385       return Error(ValueExprLoc, "expected numeric constant");
11386     IntegerValue = CE->getValue();
11387   }
11388 
11389   if (Tag == ARMBuildAttrs::compatibility) {
11390     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11391       return true;
11392   }
11393 
11394   if (IsStringValue) {
11395     if (Parser.getTok().isNot(AsmToken::String))
11396       return Error(Parser.getTok().getLoc(), "bad string constant");
11397 
11398     StringValue = Parser.getTok().getStringContents();
11399     Parser.Lex();
11400   }
11401 
11402   if (Parser.parseToken(AsmToken::EndOfStatement,
11403                         "unexpected token in '.eabi_attribute' directive"))
11404     return true;
11405 
11406   if (IsIntegerValue && IsStringValue) {
11407     assert(Tag == ARMBuildAttrs::compatibility);
11408     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
11409   } else if (IsIntegerValue)
11410     getTargetStreamer().emitAttribute(Tag, IntegerValue);
11411   else if (IsStringValue)
11412     getTargetStreamer().emitTextAttribute(Tag, StringValue);
11413   return false;
11414 }
11415 
11416 /// parseDirectiveCPU
11417 ///  ::= .cpu str
11418 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
11419   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
11420   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
11421 
11422   // FIXME: This is using table-gen data, but should be moved to
11423   // ARMTargetParser once that is table-gen'd.
11424   if (!getSTI().isCPUStringValid(CPU))
11425     return Error(L, "Unknown CPU name");
11426 
11427   bool WasThumb = isThumb();
11428   MCSubtargetInfo &STI = copySTI();
11429   STI.setDefaultFeatures(CPU, /*TuneCPU*/ CPU, "");
11430   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11431   FixModeAfterArchChange(WasThumb, L);
11432 
11433   return false;
11434 }
11435 
11436 /// parseDirectiveFPU
11437 ///  ::= .fpu str
11438 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
11439   SMLoc FPUNameLoc = getTok().getLoc();
11440   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
11441 
11442   unsigned ID = ARM::parseFPU(FPU);
11443   std::vector<StringRef> Features;
11444   if (!ARM::getFPUFeatures(ID, Features))
11445     return Error(FPUNameLoc, "Unknown FPU name");
11446 
11447   MCSubtargetInfo &STI = copySTI();
11448   for (auto Feature : Features)
11449     STI.ApplyFeatureFlag(Feature);
11450   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11451 
11452   getTargetStreamer().emitFPU(ID);
11453   return false;
11454 }
11455 
11456 /// parseDirectiveFnStart
11457 ///  ::= .fnstart
11458 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
11459   if (parseToken(AsmToken::EndOfStatement,
11460                  "unexpected token in '.fnstart' directive"))
11461     return true;
11462 
11463   if (UC.hasFnStart()) {
11464     Error(L, ".fnstart starts before the end of previous one");
11465     UC.emitFnStartLocNotes();
11466     return true;
11467   }
11468 
11469   // Reset the unwind directives parser state
11470   UC.reset();
11471 
11472   getTargetStreamer().emitFnStart();
11473 
11474   UC.recordFnStart(L);
11475   return false;
11476 }
11477 
11478 /// parseDirectiveFnEnd
11479 ///  ::= .fnend
11480 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
11481   if (parseToken(AsmToken::EndOfStatement,
11482                  "unexpected token in '.fnend' directive"))
11483     return true;
11484   // Check the ordering of unwind directives
11485   if (!UC.hasFnStart())
11486     return Error(L, ".fnstart must precede .fnend directive");
11487 
11488   // Reset the unwind directives parser state
11489   getTargetStreamer().emitFnEnd();
11490 
11491   UC.reset();
11492   return false;
11493 }
11494 
11495 /// parseDirectiveCantUnwind
11496 ///  ::= .cantunwind
11497 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
11498   if (parseToken(AsmToken::EndOfStatement,
11499                  "unexpected token in '.cantunwind' directive"))
11500     return true;
11501 
11502   UC.recordCantUnwind(L);
11503   // Check the ordering of unwind directives
11504   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
11505     return true;
11506 
11507   if (UC.hasHandlerData()) {
11508     Error(L, ".cantunwind can't be used with .handlerdata directive");
11509     UC.emitHandlerDataLocNotes();
11510     return true;
11511   }
11512   if (UC.hasPersonality()) {
11513     Error(L, ".cantunwind can't be used with .personality directive");
11514     UC.emitPersonalityLocNotes();
11515     return true;
11516   }
11517 
11518   getTargetStreamer().emitCantUnwind();
11519   return false;
11520 }
11521 
11522 /// parseDirectivePersonality
11523 ///  ::= .personality name
11524 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
11525   MCAsmParser &Parser = getParser();
11526   bool HasExistingPersonality = UC.hasPersonality();
11527 
11528   // Parse the name of the personality routine
11529   if (Parser.getTok().isNot(AsmToken::Identifier))
11530     return Error(L, "unexpected input in .personality directive.");
11531   StringRef Name(Parser.getTok().getIdentifier());
11532   Parser.Lex();
11533 
11534   if (parseToken(AsmToken::EndOfStatement,
11535                  "unexpected token in '.personality' directive"))
11536     return true;
11537 
11538   UC.recordPersonality(L);
11539 
11540   // Check the ordering of unwind directives
11541   if (!UC.hasFnStart())
11542     return Error(L, ".fnstart must precede .personality directive");
11543   if (UC.cantUnwind()) {
11544     Error(L, ".personality can't be used with .cantunwind directive");
11545     UC.emitCantUnwindLocNotes();
11546     return true;
11547   }
11548   if (UC.hasHandlerData()) {
11549     Error(L, ".personality must precede .handlerdata directive");
11550     UC.emitHandlerDataLocNotes();
11551     return true;
11552   }
11553   if (HasExistingPersonality) {
11554     Error(L, "multiple personality directives");
11555     UC.emitPersonalityLocNotes();
11556     return true;
11557   }
11558 
11559   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
11560   getTargetStreamer().emitPersonality(PR);
11561   return false;
11562 }
11563 
11564 /// parseDirectiveHandlerData
11565 ///  ::= .handlerdata
11566 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
11567   if (parseToken(AsmToken::EndOfStatement,
11568                  "unexpected token in '.handlerdata' directive"))
11569     return true;
11570 
11571   UC.recordHandlerData(L);
11572   // Check the ordering of unwind directives
11573   if (!UC.hasFnStart())
11574     return Error(L, ".fnstart must precede .personality directive");
11575   if (UC.cantUnwind()) {
11576     Error(L, ".handlerdata can't be used with .cantunwind directive");
11577     UC.emitCantUnwindLocNotes();
11578     return true;
11579   }
11580 
11581   getTargetStreamer().emitHandlerData();
11582   return false;
11583 }
11584 
11585 /// parseDirectiveSetFP
11586 ///  ::= .setfp fpreg, spreg [, offset]
11587 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
11588   MCAsmParser &Parser = getParser();
11589   // Check the ordering of unwind directives
11590   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
11591       check(UC.hasHandlerData(), L,
11592             ".setfp must precede .handlerdata directive"))
11593     return true;
11594 
11595   // Parse fpreg
11596   SMLoc FPRegLoc = Parser.getTok().getLoc();
11597   int FPReg = tryParseRegister();
11598 
11599   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
11600       Parser.parseToken(AsmToken::Comma, "comma expected"))
11601     return true;
11602 
11603   // Parse spreg
11604   SMLoc SPRegLoc = Parser.getTok().getLoc();
11605   int SPReg = tryParseRegister();
11606   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
11607       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
11608             "register should be either $sp or the latest fp register"))
11609     return true;
11610 
11611   // Update the frame pointer register
11612   UC.saveFPReg(FPReg);
11613 
11614   // Parse offset
11615   int64_t Offset = 0;
11616   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11617     if (Parser.getTok().isNot(AsmToken::Hash) &&
11618         Parser.getTok().isNot(AsmToken::Dollar))
11619       return Error(Parser.getTok().getLoc(), "'#' expected");
11620     Parser.Lex(); // skip hash token.
11621 
11622     const MCExpr *OffsetExpr;
11623     SMLoc ExLoc = Parser.getTok().getLoc();
11624     SMLoc EndLoc;
11625     if (getParser().parseExpression(OffsetExpr, EndLoc))
11626       return Error(ExLoc, "malformed setfp offset");
11627     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11628     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
11629       return true;
11630     Offset = CE->getValue();
11631   }
11632 
11633   if (Parser.parseToken(AsmToken::EndOfStatement))
11634     return true;
11635 
11636   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
11637                                 static_cast<unsigned>(SPReg), Offset);
11638   return false;
11639 }
11640 
11641 /// parseDirective
11642 ///  ::= .pad offset
11643 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
11644   MCAsmParser &Parser = getParser();
11645   // Check the ordering of unwind directives
11646   if (!UC.hasFnStart())
11647     return Error(L, ".fnstart must precede .pad directive");
11648   if (UC.hasHandlerData())
11649     return Error(L, ".pad must precede .handlerdata directive");
11650 
11651   // Parse the offset
11652   if (Parser.getTok().isNot(AsmToken::Hash) &&
11653       Parser.getTok().isNot(AsmToken::Dollar))
11654     return Error(Parser.getTok().getLoc(), "'#' expected");
11655   Parser.Lex(); // skip hash token.
11656 
11657   const MCExpr *OffsetExpr;
11658   SMLoc ExLoc = Parser.getTok().getLoc();
11659   SMLoc EndLoc;
11660   if (getParser().parseExpression(OffsetExpr, EndLoc))
11661     return Error(ExLoc, "malformed pad offset");
11662   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11663   if (!CE)
11664     return Error(ExLoc, "pad offset must be an immediate");
11665 
11666   if (parseToken(AsmToken::EndOfStatement,
11667                  "unexpected token in '.pad' directive"))
11668     return true;
11669 
11670   getTargetStreamer().emitPad(CE->getValue());
11671   return false;
11672 }
11673 
11674 /// parseDirectiveRegSave
11675 ///  ::= .save  { registers }
11676 ///  ::= .vsave { registers }
11677 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
11678   // Check the ordering of unwind directives
11679   if (!UC.hasFnStart())
11680     return Error(L, ".fnstart must precede .save or .vsave directives");
11681   if (UC.hasHandlerData())
11682     return Error(L, ".save or .vsave must precede .handlerdata directive");
11683 
11684   // RAII object to make sure parsed operands are deleted.
11685   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
11686 
11687   // Parse the register list
11688   if (parseRegisterList(Operands) ||
11689       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11690     return true;
11691   ARMOperand &Op = (ARMOperand &)*Operands[0];
11692   if (!IsVector && !Op.isRegList())
11693     return Error(L, ".save expects GPR registers");
11694   if (IsVector && !Op.isDPRRegList())
11695     return Error(L, ".vsave expects DPR registers");
11696 
11697   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
11698   return false;
11699 }
11700 
11701 /// parseDirectiveInst
11702 ///  ::= .inst opcode [, ...]
11703 ///  ::= .inst.n opcode [, ...]
11704 ///  ::= .inst.w opcode [, ...]
11705 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
11706   int Width = 4;
11707 
11708   if (isThumb()) {
11709     switch (Suffix) {
11710     case 'n':
11711       Width = 2;
11712       break;
11713     case 'w':
11714       break;
11715     default:
11716       Width = 0;
11717       break;
11718     }
11719   } else {
11720     if (Suffix)
11721       return Error(Loc, "width suffixes are invalid in ARM mode");
11722   }
11723 
11724   auto parseOne = [&]() -> bool {
11725     const MCExpr *Expr;
11726     if (getParser().parseExpression(Expr))
11727       return true;
11728     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
11729     if (!Value) {
11730       return Error(Loc, "expected constant expression");
11731     }
11732 
11733     char CurSuffix = Suffix;
11734     switch (Width) {
11735     case 2:
11736       if (Value->getValue() > 0xffff)
11737         return Error(Loc, "inst.n operand is too big, use inst.w instead");
11738       break;
11739     case 4:
11740       if (Value->getValue() > 0xffffffff)
11741         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
11742                               " operand is too big");
11743       break;
11744     case 0:
11745       // Thumb mode, no width indicated. Guess from the opcode, if possible.
11746       if (Value->getValue() < 0xe800)
11747         CurSuffix = 'n';
11748       else if (Value->getValue() >= 0xe8000000)
11749         CurSuffix = 'w';
11750       else
11751         return Error(Loc, "cannot determine Thumb instruction size, "
11752                           "use inst.n/inst.w instead");
11753       break;
11754     default:
11755       llvm_unreachable("only supported widths are 2 and 4");
11756     }
11757 
11758     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
11759     return false;
11760   };
11761 
11762   if (parseOptionalToken(AsmToken::EndOfStatement))
11763     return Error(Loc, "expected expression following directive");
11764   if (parseMany(parseOne))
11765     return true;
11766   return false;
11767 }
11768 
11769 /// parseDirectiveLtorg
11770 ///  ::= .ltorg | .pool
11771 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
11772   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11773     return true;
11774   getTargetStreamer().emitCurrentConstantPool();
11775   return false;
11776 }
11777 
11778 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
11779   const MCSection *Section = getStreamer().getCurrentSectionOnly();
11780 
11781   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11782     return true;
11783 
11784   if (!Section) {
11785     getStreamer().initSections(false, getSTI());
11786     Section = getStreamer().getCurrentSectionOnly();
11787   }
11788 
11789   assert(Section && "must have section to emit alignment");
11790   if (Section->UseCodeAlign())
11791     getStreamer().emitCodeAlignment(2, &getSTI());
11792   else
11793     getStreamer().emitValueToAlignment(2);
11794 
11795   return false;
11796 }
11797 
11798 /// parseDirectivePersonalityIndex
11799 ///   ::= .personalityindex index
11800 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
11801   MCAsmParser &Parser = getParser();
11802   bool HasExistingPersonality = UC.hasPersonality();
11803 
11804   const MCExpr *IndexExpression;
11805   SMLoc IndexLoc = Parser.getTok().getLoc();
11806   if (Parser.parseExpression(IndexExpression) ||
11807       parseToken(AsmToken::EndOfStatement,
11808                  "unexpected token in '.personalityindex' directive")) {
11809     return true;
11810   }
11811 
11812   UC.recordPersonalityIndex(L);
11813 
11814   if (!UC.hasFnStart()) {
11815     return Error(L, ".fnstart must precede .personalityindex directive");
11816   }
11817   if (UC.cantUnwind()) {
11818     Error(L, ".personalityindex cannot be used with .cantunwind");
11819     UC.emitCantUnwindLocNotes();
11820     return true;
11821   }
11822   if (UC.hasHandlerData()) {
11823     Error(L, ".personalityindex must precede .handlerdata directive");
11824     UC.emitHandlerDataLocNotes();
11825     return true;
11826   }
11827   if (HasExistingPersonality) {
11828     Error(L, "multiple personality directives");
11829     UC.emitPersonalityLocNotes();
11830     return true;
11831   }
11832 
11833   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
11834   if (!CE)
11835     return Error(IndexLoc, "index must be a constant number");
11836   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
11837     return Error(IndexLoc,
11838                  "personality routine index should be in range [0-3]");
11839 
11840   getTargetStreamer().emitPersonalityIndex(CE->getValue());
11841   return false;
11842 }
11843 
11844 /// parseDirectiveUnwindRaw
11845 ///   ::= .unwind_raw offset, opcode [, opcode...]
11846 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
11847   MCAsmParser &Parser = getParser();
11848   int64_t StackOffset;
11849   const MCExpr *OffsetExpr;
11850   SMLoc OffsetLoc = getLexer().getLoc();
11851 
11852   if (!UC.hasFnStart())
11853     return Error(L, ".fnstart must precede .unwind_raw directives");
11854   if (getParser().parseExpression(OffsetExpr))
11855     return Error(OffsetLoc, "expected expression");
11856 
11857   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11858   if (!CE)
11859     return Error(OffsetLoc, "offset must be a constant");
11860 
11861   StackOffset = CE->getValue();
11862 
11863   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
11864     return true;
11865 
11866   SmallVector<uint8_t, 16> Opcodes;
11867 
11868   auto parseOne = [&]() -> bool {
11869     const MCExpr *OE = nullptr;
11870     SMLoc OpcodeLoc = getLexer().getLoc();
11871     if (check(getLexer().is(AsmToken::EndOfStatement) ||
11872                   Parser.parseExpression(OE),
11873               OpcodeLoc, "expected opcode expression"))
11874       return true;
11875     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
11876     if (!OC)
11877       return Error(OpcodeLoc, "opcode value must be a constant");
11878     const int64_t Opcode = OC->getValue();
11879     if (Opcode & ~0xff)
11880       return Error(OpcodeLoc, "invalid opcode");
11881     Opcodes.push_back(uint8_t(Opcode));
11882     return false;
11883   };
11884 
11885   // Must have at least 1 element
11886   SMLoc OpcodeLoc = getLexer().getLoc();
11887   if (parseOptionalToken(AsmToken::EndOfStatement))
11888     return Error(OpcodeLoc, "expected opcode expression");
11889   if (parseMany(parseOne))
11890     return true;
11891 
11892   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
11893   return false;
11894 }
11895 
11896 /// parseDirectiveTLSDescSeq
11897 ///   ::= .tlsdescseq tls-variable
11898 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
11899   MCAsmParser &Parser = getParser();
11900 
11901   if (getLexer().isNot(AsmToken::Identifier))
11902     return TokError("expected variable after '.tlsdescseq' directive");
11903 
11904   const MCSymbolRefExpr *SRE =
11905     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
11906                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
11907   Lex();
11908 
11909   if (parseToken(AsmToken::EndOfStatement,
11910                  "unexpected token in '.tlsdescseq' directive"))
11911     return true;
11912 
11913   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
11914   return false;
11915 }
11916 
11917 /// parseDirectiveMovSP
11918 ///  ::= .movsp reg [, #offset]
11919 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
11920   MCAsmParser &Parser = getParser();
11921   if (!UC.hasFnStart())
11922     return Error(L, ".fnstart must precede .movsp directives");
11923   if (UC.getFPReg() != ARM::SP)
11924     return Error(L, "unexpected .movsp directive");
11925 
11926   SMLoc SPRegLoc = Parser.getTok().getLoc();
11927   int SPReg = tryParseRegister();
11928   if (SPReg == -1)
11929     return Error(SPRegLoc, "register expected");
11930   if (SPReg == ARM::SP || SPReg == ARM::PC)
11931     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
11932 
11933   int64_t Offset = 0;
11934   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11935     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
11936       return true;
11937 
11938     const MCExpr *OffsetExpr;
11939     SMLoc OffsetLoc = Parser.getTok().getLoc();
11940 
11941     if (Parser.parseExpression(OffsetExpr))
11942       return Error(OffsetLoc, "malformed offset expression");
11943 
11944     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11945     if (!CE)
11946       return Error(OffsetLoc, "offset must be an immediate constant");
11947 
11948     Offset = CE->getValue();
11949   }
11950 
11951   if (parseToken(AsmToken::EndOfStatement,
11952                  "unexpected token in '.movsp' directive"))
11953     return true;
11954 
11955   getTargetStreamer().emitMovSP(SPReg, Offset);
11956   UC.saveFPReg(SPReg);
11957 
11958   return false;
11959 }
11960 
11961 /// parseDirectiveObjectArch
11962 ///   ::= .object_arch name
11963 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
11964   MCAsmParser &Parser = getParser();
11965   if (getLexer().isNot(AsmToken::Identifier))
11966     return Error(getLexer().getLoc(), "unexpected token");
11967 
11968   StringRef Arch = Parser.getTok().getString();
11969   SMLoc ArchLoc = Parser.getTok().getLoc();
11970   Lex();
11971 
11972   ARM::ArchKind ID = ARM::parseArch(Arch);
11973 
11974   if (ID == ARM::ArchKind::INVALID)
11975     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
11976   if (parseToken(AsmToken::EndOfStatement))
11977     return true;
11978 
11979   getTargetStreamer().emitObjectArch(ID);
11980   return false;
11981 }
11982 
11983 /// parseDirectiveAlign
11984 ///   ::= .align
11985 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
11986   // NOTE: if this is not the end of the statement, fall back to the target
11987   // agnostic handling for this directive which will correctly handle this.
11988   if (parseOptionalToken(AsmToken::EndOfStatement)) {
11989     // '.align' is target specifically handled to mean 2**2 byte alignment.
11990     const MCSection *Section = getStreamer().getCurrentSectionOnly();
11991     assert(Section && "must have section to emit alignment");
11992     if (Section->UseCodeAlign())
11993       getStreamer().emitCodeAlignment(4, &getSTI(), 0);
11994     else
11995       getStreamer().emitValueToAlignment(4, 0, 1, 0);
11996     return false;
11997   }
11998   return true;
11999 }
12000 
12001 /// parseDirectiveThumbSet
12002 ///  ::= .thumb_set name, value
12003 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
12004   MCAsmParser &Parser = getParser();
12005 
12006   StringRef Name;
12007   if (check(Parser.parseIdentifier(Name),
12008             "expected identifier after '.thumb_set'") ||
12009       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
12010     return true;
12011 
12012   MCSymbol *Sym;
12013   const MCExpr *Value;
12014   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
12015                                                Parser, Sym, Value))
12016     return true;
12017 
12018   getTargetStreamer().emitThumbSet(Sym, Value);
12019   return false;
12020 }
12021 
12022 /// Force static initialization.
12023 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmParser() {
12024   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
12025   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
12026   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
12027   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
12028 }
12029 
12030 #define GET_REGISTER_MATCHER
12031 #define GET_SUBTARGET_FEATURE_NAME
12032 #define GET_MATCHER_IMPLEMENTATION
12033 #define GET_MNEMONIC_SPELL_CHECKER
12034 #include "ARMGenAsmMatcher.inc"
12035 
12036 // Some diagnostics need to vary with subtarget features, so they are handled
12037 // here. For example, the DPR class has either 16 or 32 registers, depending
12038 // on the FPU available.
12039 const char *
12040 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
12041   switch (MatchError) {
12042   // rGPR contains sp starting with ARMv8.
12043   case Match_rGPR:
12044     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
12045                       : "operand must be a register in range [r0, r12] or r14";
12046   // DPR contains 16 registers for some FPUs, and 32 for others.
12047   case Match_DPR:
12048     return hasD32() ? "operand must be a register in range [d0, d31]"
12049                     : "operand must be a register in range [d0, d15]";
12050   case Match_DPR_RegList:
12051     return hasD32() ? "operand must be a list of registers in range [d0, d31]"
12052                     : "operand must be a list of registers in range [d0, d15]";
12053 
12054   // For all other diags, use the static string from tablegen.
12055   default:
12056     return getMatchKindDiag(MatchError);
12057   }
12058 }
12059 
12060 // Process the list of near-misses, throwing away ones we don't want to report
12061 // to the user, and converting the rest to a source location and string that
12062 // should be reported.
12063 void
12064 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
12065                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
12066                                SMLoc IDLoc, OperandVector &Operands) {
12067   // TODO: If operand didn't match, sub in a dummy one and run target
12068   // predicate, so that we can avoid reporting near-misses that are invalid?
12069   // TODO: Many operand types dont have SuperClasses set, so we report
12070   // redundant ones.
12071   // TODO: Some operands are superclasses of registers (e.g.
12072   // MCK_RegShiftedImm), we don't have any way to represent that currently.
12073   // TODO: This is not all ARM-specific, can some of it be factored out?
12074 
12075   // Record some information about near-misses that we have already seen, so
12076   // that we can avoid reporting redundant ones. For example, if there are
12077   // variants of an instruction that take 8- and 16-bit immediates, we want
12078   // to only report the widest one.
12079   std::multimap<unsigned, unsigned> OperandMissesSeen;
12080   SmallSet<FeatureBitset, 4> FeatureMissesSeen;
12081   bool ReportedTooFewOperands = false;
12082 
12083   // Process the near-misses in reverse order, so that we see more general ones
12084   // first, and so can avoid emitting more specific ones.
12085   for (NearMissInfo &I : reverse(NearMissesIn)) {
12086     switch (I.getKind()) {
12087     case NearMissInfo::NearMissOperand: {
12088       SMLoc OperandLoc =
12089           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
12090       const char *OperandDiag =
12091           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
12092 
12093       // If we have already emitted a message for a superclass, don't also report
12094       // the sub-class. We consider all operand classes that we don't have a
12095       // specialised diagnostic for to be equal for the propose of this check,
12096       // so that we don't report the generic error multiple times on the same
12097       // operand.
12098       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
12099       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
12100       if (std::any_of(PrevReports.first, PrevReports.second,
12101                       [DupCheckMatchClass](
12102                           const std::pair<unsigned, unsigned> Pair) {
12103             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
12104               return Pair.second == DupCheckMatchClass;
12105             else
12106               return isSubclass((MatchClassKind)DupCheckMatchClass,
12107                                 (MatchClassKind)Pair.second);
12108           }))
12109         break;
12110       OperandMissesSeen.insert(
12111           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
12112 
12113       NearMissMessage Message;
12114       Message.Loc = OperandLoc;
12115       if (OperandDiag) {
12116         Message.Message = OperandDiag;
12117       } else if (I.getOperandClass() == InvalidMatchClass) {
12118         Message.Message = "too many operands for instruction";
12119       } else {
12120         Message.Message = "invalid operand for instruction";
12121         LLVM_DEBUG(
12122             dbgs() << "Missing diagnostic string for operand class "
12123                    << getMatchClassName((MatchClassKind)I.getOperandClass())
12124                    << I.getOperandClass() << ", error " << I.getOperandError()
12125                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
12126       }
12127       NearMissesOut.emplace_back(Message);
12128       break;
12129     }
12130     case NearMissInfo::NearMissFeature: {
12131       const FeatureBitset &MissingFeatures = I.getFeatures();
12132       // Don't report the same set of features twice.
12133       if (FeatureMissesSeen.count(MissingFeatures))
12134         break;
12135       FeatureMissesSeen.insert(MissingFeatures);
12136 
12137       // Special case: don't report a feature set which includes arm-mode for
12138       // targets that don't have ARM mode.
12139       if (MissingFeatures.test(Feature_IsARMBit) && !hasARM())
12140         break;
12141       // Don't report any near-misses that both require switching instruction
12142       // set, and adding other subtarget features.
12143       if (isThumb() && MissingFeatures.test(Feature_IsARMBit) &&
12144           MissingFeatures.count() > 1)
12145         break;
12146       if (!isThumb() && MissingFeatures.test(Feature_IsThumbBit) &&
12147           MissingFeatures.count() > 1)
12148         break;
12149       if (!isThumb() && MissingFeatures.test(Feature_IsThumb2Bit) &&
12150           (MissingFeatures & ~FeatureBitset({Feature_IsThumb2Bit,
12151                                              Feature_IsThumbBit})).any())
12152         break;
12153       if (isMClass() && MissingFeatures.test(Feature_HasNEONBit))
12154         break;
12155 
12156       NearMissMessage Message;
12157       Message.Loc = IDLoc;
12158       raw_svector_ostream OS(Message.Message);
12159 
12160       OS << "instruction requires:";
12161       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
12162         if (MissingFeatures.test(i))
12163           OS << ' ' << getSubtargetFeatureName(i);
12164 
12165       NearMissesOut.emplace_back(Message);
12166 
12167       break;
12168     }
12169     case NearMissInfo::NearMissPredicate: {
12170       NearMissMessage Message;
12171       Message.Loc = IDLoc;
12172       switch (I.getPredicateError()) {
12173       case Match_RequiresNotITBlock:
12174         Message.Message = "flag setting instruction only valid outside IT block";
12175         break;
12176       case Match_RequiresITBlock:
12177         Message.Message = "instruction only valid inside IT block";
12178         break;
12179       case Match_RequiresV6:
12180         Message.Message = "instruction variant requires ARMv6 or later";
12181         break;
12182       case Match_RequiresThumb2:
12183         Message.Message = "instruction variant requires Thumb2";
12184         break;
12185       case Match_RequiresV8:
12186         Message.Message = "instruction variant requires ARMv8 or later";
12187         break;
12188       case Match_RequiresFlagSetting:
12189         Message.Message = "no flag-preserving variant of this instruction available";
12190         break;
12191       case Match_InvalidOperand:
12192         Message.Message = "invalid operand for instruction";
12193         break;
12194       default:
12195         llvm_unreachable("Unhandled target predicate error");
12196         break;
12197       }
12198       NearMissesOut.emplace_back(Message);
12199       break;
12200     }
12201     case NearMissInfo::NearMissTooFewOperands: {
12202       if (!ReportedTooFewOperands) {
12203         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
12204         NearMissesOut.emplace_back(NearMissMessage{
12205             EndLoc, StringRef("too few operands for instruction")});
12206         ReportedTooFewOperands = true;
12207       }
12208       break;
12209     }
12210     case NearMissInfo::NoNearMiss:
12211       // This should never leave the matcher.
12212       llvm_unreachable("not a near-miss");
12213       break;
12214     }
12215   }
12216 }
12217 
12218 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
12219                                     SMLoc IDLoc, OperandVector &Operands) {
12220   SmallVector<NearMissMessage, 4> Messages;
12221   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
12222 
12223   if (Messages.size() == 0) {
12224     // No near-misses were found, so the best we can do is "invalid
12225     // instruction".
12226     Error(IDLoc, "invalid instruction");
12227   } else if (Messages.size() == 1) {
12228     // One near miss was found, report it as the sole error.
12229     Error(Messages[0].Loc, Messages[0].Message);
12230   } else {
12231     // More than one near miss, so report a generic "invalid instruction"
12232     // error, followed by notes for each of the near-misses.
12233     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
12234     for (auto &M : Messages) {
12235       Note(M.Loc, M.Message);
12236     }
12237   }
12238 }
12239 
12240 bool ARMAsmParser::enableArchExtFeature(StringRef Name, SMLoc &ExtLoc) {
12241   // FIXME: This structure should be moved inside ARMTargetParser
12242   // when we start to table-generate them, and we can use the ARM
12243   // flags below, that were generated by table-gen.
12244   static const struct {
12245     const uint64_t Kind;
12246     const FeatureBitset ArchCheck;
12247     const FeatureBitset Features;
12248   } Extensions[] = {
12249       {ARM::AEK_CRC, {Feature_HasV8Bit}, {ARM::FeatureCRC}},
12250       {ARM::AEK_AES,
12251        {Feature_HasV8Bit},
12252        {ARM::FeatureAES, ARM::FeatureNEON, ARM::FeatureFPARMv8}},
12253       {ARM::AEK_SHA2,
12254        {Feature_HasV8Bit},
12255        {ARM::FeatureSHA2, ARM::FeatureNEON, ARM::FeatureFPARMv8}},
12256       {ARM::AEK_CRYPTO,
12257        {Feature_HasV8Bit},
12258        {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8}},
12259       {ARM::AEK_FP,
12260        {Feature_HasV8Bit},
12261        {ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8}},
12262       {(ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM),
12263        {Feature_HasV7Bit, Feature_IsNotMClassBit},
12264        {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM}},
12265       {ARM::AEK_MP,
12266        {Feature_HasV7Bit, Feature_IsNotMClassBit},
12267        {ARM::FeatureMP}},
12268       {ARM::AEK_SIMD,
12269        {Feature_HasV8Bit},
12270        {ARM::FeatureNEON, ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8}},
12271       {ARM::AEK_SEC, {Feature_HasV6KBit}, {ARM::FeatureTrustZone}},
12272       // FIXME: Only available in A-class, isel not predicated
12273       {ARM::AEK_VIRT, {Feature_HasV7Bit}, {ARM::FeatureVirtualization}},
12274       {ARM::AEK_FP16,
12275        {Feature_HasV8_2aBit},
12276        {ARM::FeatureFPARMv8, ARM::FeatureFullFP16}},
12277       {ARM::AEK_RAS, {Feature_HasV8Bit}, {ARM::FeatureRAS}},
12278       {ARM::AEK_LOB, {Feature_HasV8_1MMainlineBit}, {ARM::FeatureLOB}},
12279       {ARM::AEK_PACBTI, {Feature_HasV8_1MMainlineBit}, {ARM::FeaturePACBTI}},
12280       // FIXME: Unsupported extensions.
12281       {ARM::AEK_OS, {}, {}},
12282       {ARM::AEK_IWMMXT, {}, {}},
12283       {ARM::AEK_IWMMXT2, {}, {}},
12284       {ARM::AEK_MAVERICK, {}, {}},
12285       {ARM::AEK_XSCALE, {}, {}},
12286   };
12287   bool EnableFeature = true;
12288   if (Name.startswith_insensitive("no")) {
12289     EnableFeature = false;
12290     Name = Name.substr(2);
12291   }
12292   uint64_t FeatureKind = ARM::parseArchExt(Name);
12293   if (FeatureKind == ARM::AEK_INVALID)
12294     return Error(ExtLoc, "unknown architectural extension: " + Name);
12295 
12296   for (const auto &Extension : Extensions) {
12297     if (Extension.Kind != FeatureKind)
12298       continue;
12299 
12300     if (Extension.Features.none())
12301       return Error(ExtLoc, "unsupported architectural extension: " + Name);
12302 
12303     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
12304       return Error(ExtLoc, "architectural extension '" + Name +
12305                                "' is not "
12306                                "allowed for the current base architecture");
12307 
12308     MCSubtargetInfo &STI = copySTI();
12309     if (EnableFeature) {
12310       STI.SetFeatureBitsTransitively(Extension.Features);
12311     } else {
12312       STI.ClearFeatureBitsTransitively(Extension.Features);
12313     }
12314     FeatureBitset Features = ComputeAvailableFeatures(STI.getFeatureBits());
12315     setAvailableFeatures(Features);
12316     return true;
12317   }
12318   return false;
12319 }
12320 
12321 /// parseDirectiveArchExtension
12322 ///   ::= .arch_extension [no]feature
12323 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
12324 
12325   MCAsmParser &Parser = getParser();
12326 
12327   if (getLexer().isNot(AsmToken::Identifier))
12328     return Error(getLexer().getLoc(), "expected architecture extension name");
12329 
12330   StringRef Name = Parser.getTok().getString();
12331   SMLoc ExtLoc = Parser.getTok().getLoc();
12332   Lex();
12333 
12334   if (parseToken(AsmToken::EndOfStatement,
12335                  "unexpected token in '.arch_extension' directive"))
12336     return true;
12337 
12338   if (Name == "nocrypto") {
12339     enableArchExtFeature("nosha2", ExtLoc);
12340     enableArchExtFeature("noaes", ExtLoc);
12341   }
12342 
12343   if (enableArchExtFeature(Name, ExtLoc))
12344     return false;
12345 
12346   return Error(ExtLoc, "unknown architectural extension: " + Name);
12347 }
12348 
12349 // Define this matcher function after the auto-generated include so we
12350 // have the match class enum definitions.
12351 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
12352                                                   unsigned Kind) {
12353   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
12354   // If the kind is a token for a literal immediate, check if our asm
12355   // operand matches. This is for InstAliases which have a fixed-value
12356   // immediate in the syntax.
12357   switch (Kind) {
12358   default: break;
12359   case MCK__HASH_0:
12360     if (Op.isImm())
12361       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12362         if (CE->getValue() == 0)
12363           return Match_Success;
12364     break;
12365   case MCK__HASH_8:
12366     if (Op.isImm())
12367       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12368         if (CE->getValue() == 8)
12369           return Match_Success;
12370     break;
12371   case MCK__HASH_16:
12372     if (Op.isImm())
12373       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12374         if (CE->getValue() == 16)
12375           return Match_Success;
12376     break;
12377   case MCK_ModImm:
12378     if (Op.isImm()) {
12379       const MCExpr *SOExpr = Op.getImm();
12380       int64_t Value;
12381       if (!SOExpr->evaluateAsAbsolute(Value))
12382         return Match_Success;
12383       assert((Value >= std::numeric_limits<int32_t>::min() &&
12384               Value <= std::numeric_limits<uint32_t>::max()) &&
12385              "expression value must be representable in 32 bits");
12386     }
12387     break;
12388   case MCK_rGPR:
12389     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
12390       return Match_Success;
12391     return Match_rGPR;
12392   case MCK_GPRPair:
12393     if (Op.isReg() &&
12394         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
12395       return Match_Success;
12396     break;
12397   }
12398   return Match_InvalidOperand;
12399 }
12400 
12401 bool ARMAsmParser::isMnemonicVPTPredicable(StringRef Mnemonic,
12402                                            StringRef ExtraToken) {
12403   if (!hasMVE())
12404     return false;
12405 
12406   return Mnemonic.startswith("vabav") || Mnemonic.startswith("vaddv") ||
12407          Mnemonic.startswith("vaddlv") || Mnemonic.startswith("vminnmv") ||
12408          Mnemonic.startswith("vminnmav") || Mnemonic.startswith("vminv") ||
12409          Mnemonic.startswith("vminav") || Mnemonic.startswith("vmaxnmv") ||
12410          Mnemonic.startswith("vmaxnmav") || Mnemonic.startswith("vmaxv") ||
12411          Mnemonic.startswith("vmaxav") || Mnemonic.startswith("vmladav") ||
12412          Mnemonic.startswith("vrmlaldavh") || Mnemonic.startswith("vrmlalvh") ||
12413          Mnemonic.startswith("vmlsdav") || Mnemonic.startswith("vmlav") ||
12414          Mnemonic.startswith("vmlaldav") || Mnemonic.startswith("vmlalv") ||
12415          Mnemonic.startswith("vmaxnm") || Mnemonic.startswith("vminnm") ||
12416          Mnemonic.startswith("vmax") || Mnemonic.startswith("vmin") ||
12417          Mnemonic.startswith("vshlc") || Mnemonic.startswith("vmovlt") ||
12418          Mnemonic.startswith("vmovlb") || Mnemonic.startswith("vshll") ||
12419          Mnemonic.startswith("vrshrn") || Mnemonic.startswith("vshrn") ||
12420          Mnemonic.startswith("vqrshrun") || Mnemonic.startswith("vqshrun") ||
12421          Mnemonic.startswith("vqrshrn") || Mnemonic.startswith("vqshrn") ||
12422          Mnemonic.startswith("vbic") || Mnemonic.startswith("vrev64") ||
12423          Mnemonic.startswith("vrev32") || Mnemonic.startswith("vrev16") ||
12424          Mnemonic.startswith("vmvn") || Mnemonic.startswith("veor") ||
12425          Mnemonic.startswith("vorn") || Mnemonic.startswith("vorr") ||
12426          Mnemonic.startswith("vand") || Mnemonic.startswith("vmul") ||
12427          Mnemonic.startswith("vqrdmulh") || Mnemonic.startswith("vqdmulh") ||
12428          Mnemonic.startswith("vsub") || Mnemonic.startswith("vadd") ||
12429          Mnemonic.startswith("vqsub") || Mnemonic.startswith("vqadd") ||
12430          Mnemonic.startswith("vabd") || Mnemonic.startswith("vrhadd") ||
12431          Mnemonic.startswith("vhsub") || Mnemonic.startswith("vhadd") ||
12432          Mnemonic.startswith("vdup") || Mnemonic.startswith("vcls") ||
12433          Mnemonic.startswith("vclz") || Mnemonic.startswith("vneg") ||
12434          Mnemonic.startswith("vabs") || Mnemonic.startswith("vqneg") ||
12435          Mnemonic.startswith("vqabs") ||
12436          (Mnemonic.startswith("vrint") && Mnemonic != "vrintr") ||
12437          Mnemonic.startswith("vcmla") || Mnemonic.startswith("vfma") ||
12438          Mnemonic.startswith("vfms") || Mnemonic.startswith("vcadd") ||
12439          Mnemonic.startswith("vadd") || Mnemonic.startswith("vsub") ||
12440          Mnemonic.startswith("vshl") || Mnemonic.startswith("vqshl") ||
12441          Mnemonic.startswith("vqrshl") || Mnemonic.startswith("vrshl") ||
12442          Mnemonic.startswith("vsri") || Mnemonic.startswith("vsli") ||
12443          Mnemonic.startswith("vrshr") || Mnemonic.startswith("vshr") ||
12444          Mnemonic.startswith("vpsel") || Mnemonic.startswith("vcmp") ||
12445          Mnemonic.startswith("vqdmladh") || Mnemonic.startswith("vqrdmladh") ||
12446          Mnemonic.startswith("vqdmlsdh") || Mnemonic.startswith("vqrdmlsdh") ||
12447          Mnemonic.startswith("vcmul") || Mnemonic.startswith("vrmulh") ||
12448          Mnemonic.startswith("vqmovn") || Mnemonic.startswith("vqmovun") ||
12449          Mnemonic.startswith("vmovnt") || Mnemonic.startswith("vmovnb") ||
12450          Mnemonic.startswith("vmaxa") || Mnemonic.startswith("vmaxnma") ||
12451          Mnemonic.startswith("vhcadd") || Mnemonic.startswith("vadc") ||
12452          Mnemonic.startswith("vsbc") || Mnemonic.startswith("vrshr") ||
12453          Mnemonic.startswith("vshr") || Mnemonic.startswith("vstrb") ||
12454          Mnemonic.startswith("vldrb") ||
12455          (Mnemonic.startswith("vstrh") && Mnemonic != "vstrhi") ||
12456          (Mnemonic.startswith("vldrh") && Mnemonic != "vldrhi") ||
12457          Mnemonic.startswith("vstrw") || Mnemonic.startswith("vldrw") ||
12458          Mnemonic.startswith("vldrd") || Mnemonic.startswith("vstrd") ||
12459          Mnemonic.startswith("vqdmull") || Mnemonic.startswith("vbrsr") ||
12460          Mnemonic.startswith("vfmas") || Mnemonic.startswith("vmlas") ||
12461          Mnemonic.startswith("vmla") || Mnemonic.startswith("vqdmlash") ||
12462          Mnemonic.startswith("vqdmlah") || Mnemonic.startswith("vqrdmlash") ||
12463          Mnemonic.startswith("vqrdmlah") || Mnemonic.startswith("viwdup") ||
12464          Mnemonic.startswith("vdwdup") || Mnemonic.startswith("vidup") ||
12465          Mnemonic.startswith("vddup") || Mnemonic.startswith("vctp") ||
12466          Mnemonic.startswith("vpnot") || Mnemonic.startswith("vbic") ||
12467          Mnemonic.startswith("vrmlsldavh") || Mnemonic.startswith("vmlsldav") ||
12468          Mnemonic.startswith("vcvt") ||
12469          MS.isVPTPredicableCDEInstr(Mnemonic) ||
12470          (Mnemonic.startswith("vmov") &&
12471           !(ExtraToken == ".f16" || ExtraToken == ".32" ||
12472             ExtraToken == ".16" || ExtraToken == ".8"));
12473 }
12474