1 //===- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ARMFeatures.h"
10 #include "ARMBaseInstrInfo.h"
11 #include "Utils/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMBaseInfo.h"
14 #include "MCTargetDesc/ARMInstPrinter.h"
15 #include "MCTargetDesc/ARMMCExpr.h"
16 #include "MCTargetDesc/ARMMCTargetDesc.h"
17 #include "TargetInfo/ARMTargetInfo.h"
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCObjectFileInfo.h"
36 #include "llvm/MC/MCParser/MCAsmLexer.h"
37 #include "llvm/MC/MCParser/MCAsmParser.h"
38 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
39 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
40 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
41 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
42 #include "llvm/MC/MCRegisterInfo.h"
43 #include "llvm/MC/MCSection.h"
44 #include "llvm/MC/MCStreamer.h"
45 #include "llvm/MC/MCSubtargetInfo.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/MC/SubtargetFeature.h"
48 #include "llvm/Support/ARMBuildAttributes.h"
49 #include "llvm/Support/ARMEHABI.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/SMLoc.h"
56 #include "llvm/Support/TargetParser.h"
57 #include "llvm/Support/TargetRegistry.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include <algorithm>
60 #include <cassert>
61 #include <cstddef>
62 #include <cstdint>
63 #include <iterator>
64 #include <limits>
65 #include <memory>
66 #include <string>
67 #include <utility>
68 #include <vector>
69 
70 #define DEBUG_TYPE "asm-parser"
71 
72 using namespace llvm;
73 
74 namespace llvm {
75 extern const MCInstrDesc ARMInsts[];
76 } // end namespace llvm
77 
78 namespace {
79 
80 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
81 
82 static cl::opt<ImplicitItModeTy> ImplicitItMode(
83     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
84     cl::desc("Allow conditional instructions outdside of an IT block"),
85     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
86                           "Accept in both ISAs, emit implicit ITs in Thumb"),
87                clEnumValN(ImplicitItModeTy::Never, "never",
88                           "Warn in ARM, reject in Thumb"),
89                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
90                           "Accept in ARM, reject in Thumb"),
91                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
92                           "Warn in ARM, emit implicit ITs in Thumb")));
93 
94 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
95                                         cl::init(false));
96 
97 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
98 
99 static inline unsigned extractITMaskBit(unsigned Mask, unsigned Position) {
100   // Position==0 means we're not in an IT block at all. Position==1
101   // means we want the first state bit, which is always 0 (Then).
102   // Position==2 means we want the second state bit, stored at bit 3
103   // of Mask, and so on downwards. So (5 - Position) will shift the
104   // right bit down to bit 0, including the always-0 bit at bit 4 for
105   // the mandatory initial Then.
106   return (Mask >> (5 - Position) & 1);
107 }
108 
109 class UnwindContext {
110   using Locs = SmallVector<SMLoc, 4>;
111 
112   MCAsmParser &Parser;
113   Locs FnStartLocs;
114   Locs CantUnwindLocs;
115   Locs PersonalityLocs;
116   Locs PersonalityIndexLocs;
117   Locs HandlerDataLocs;
118   int FPReg;
119 
120 public:
121   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
122 
123   bool hasFnStart() const { return !FnStartLocs.empty(); }
124   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
125   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
126 
127   bool hasPersonality() const {
128     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
129   }
130 
131   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
132   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
133   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
134   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
135   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
136 
137   void saveFPReg(int Reg) { FPReg = Reg; }
138   int getFPReg() const { return FPReg; }
139 
140   void emitFnStartLocNotes() const {
141     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
142          FI != FE; ++FI)
143       Parser.Note(*FI, ".fnstart was specified here");
144   }
145 
146   void emitCantUnwindLocNotes() const {
147     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
148                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
149       Parser.Note(*UI, ".cantunwind was specified here");
150   }
151 
152   void emitHandlerDataLocNotes() const {
153     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
154                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
155       Parser.Note(*HI, ".handlerdata was specified here");
156   }
157 
158   void emitPersonalityLocNotes() const {
159     for (Locs::const_iterator PI = PersonalityLocs.begin(),
160                               PE = PersonalityLocs.end(),
161                               PII = PersonalityIndexLocs.begin(),
162                               PIE = PersonalityIndexLocs.end();
163          PI != PE || PII != PIE;) {
164       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
165         Parser.Note(*PI++, ".personality was specified here");
166       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
167         Parser.Note(*PII++, ".personalityindex was specified here");
168       else
169         llvm_unreachable(".personality and .personalityindex cannot be "
170                          "at the same location");
171     }
172   }
173 
174   void reset() {
175     FnStartLocs = Locs();
176     CantUnwindLocs = Locs();
177     PersonalityLocs = Locs();
178     HandlerDataLocs = Locs();
179     PersonalityIndexLocs = Locs();
180     FPReg = ARM::SP;
181   }
182 };
183 
184 // Various sets of ARM instruction mnemonics which are used by the asm parser
185 class ARMMnemonicSets {
186   StringSet<> CDE;
187   StringSet<> CDEWithVPTSuffix;
188 public:
189   ARMMnemonicSets(const MCSubtargetInfo &STI);
190 
191   /// Returns true iff a given mnemonic is a CDE instruction
192   bool isCDEInstr(StringRef Mnemonic) {
193     // Quick check before searching the set
194     if (!Mnemonic.startswith("cx") && !Mnemonic.startswith("vcx"))
195       return false;
196     return CDE.count(Mnemonic);
197   }
198 
199   /// Returns true iff a given mnemonic is a VPT-predicable CDE instruction
200   /// (possibly with a predication suffix "e" or "t")
201   bool isVPTPredicableCDEInstr(StringRef Mnemonic) {
202     if (!Mnemonic.startswith("vcx"))
203       return false;
204     return CDEWithVPTSuffix.count(Mnemonic);
205   }
206 
207   /// Returns true iff a given mnemonic is an IT-predicable CDE instruction
208   /// (possibly with a condition suffix)
209   bool isITPredicableCDEInstr(StringRef Mnemonic) {
210     if (!Mnemonic.startswith("cx"))
211       return false;
212     return Mnemonic.startswith("cx1a") || Mnemonic.startswith("cx1da") ||
213            Mnemonic.startswith("cx2a") || Mnemonic.startswith("cx2da") ||
214            Mnemonic.startswith("cx3a") || Mnemonic.startswith("cx3da");
215   }
216 
217   /// Return true iff a given mnemonic is an integer CDE instruction with
218   /// dual-register destination
219   bool isCDEDualRegInstr(StringRef Mnemonic) {
220     if (!Mnemonic.startswith("cx"))
221       return false;
222     return Mnemonic == "cx1d" || Mnemonic == "cx1da" ||
223            Mnemonic == "cx2d" || Mnemonic == "cx2da" ||
224            Mnemonic == "cx3d" || Mnemonic == "cx3da";
225   }
226 };
227 
228 ARMMnemonicSets::ARMMnemonicSets(const MCSubtargetInfo &STI) {
229   for (StringRef Mnemonic: { "cx1", "cx1a", "cx1d", "cx1da",
230                              "cx2", "cx2a", "cx2d", "cx2da",
231                              "cx3", "cx3a", "cx3d", "cx3da", })
232     CDE.insert(Mnemonic);
233   for (StringRef Mnemonic :
234        {"vcx1", "vcx1a", "vcx2", "vcx2a", "vcx3", "vcx3a"}) {
235     CDE.insert(Mnemonic);
236     CDEWithVPTSuffix.insert(Mnemonic);
237     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "t");
238     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "e");
239   }
240 }
241 
242 class ARMAsmParser : public MCTargetAsmParser {
243   const MCRegisterInfo *MRI;
244   UnwindContext UC;
245   ARMMnemonicSets MS;
246 
247   ARMTargetStreamer &getTargetStreamer() {
248     assert(getParser().getStreamer().getTargetStreamer() &&
249            "do not have a target streamer");
250     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
251     return static_cast<ARMTargetStreamer &>(TS);
252   }
253 
254   // Map of register aliases registers via the .req directive.
255   StringMap<unsigned> RegisterReqs;
256 
257   bool NextSymbolIsThumb;
258 
259   bool useImplicitITThumb() const {
260     return ImplicitItMode == ImplicitItModeTy::Always ||
261            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
262   }
263 
264   bool useImplicitITARM() const {
265     return ImplicitItMode == ImplicitItModeTy::Always ||
266            ImplicitItMode == ImplicitItModeTy::ARMOnly;
267   }
268 
269   struct {
270     ARMCC::CondCodes Cond;    // Condition for IT block.
271     unsigned Mask:4;          // Condition mask for instructions.
272                               // Starting at first 1 (from lsb).
273                               //   '1'  condition as indicated in IT.
274                               //   '0'  inverse of condition (else).
275                               // Count of instructions in IT block is
276                               // 4 - trailingzeroes(mask)
277                               // Note that this does not have the same encoding
278                               // as in the IT instruction, which also depends
279                               // on the low bit of the condition code.
280 
281     unsigned CurPosition;     // Current position in parsing of IT
282                               // block. In range [0,4], with 0 being the IT
283                               // instruction itself. Initialized according to
284                               // count of instructions in block.  ~0U if no
285                               // active IT block.
286 
287     bool IsExplicit;          // true  - The IT instruction was present in the
288                               //         input, we should not modify it.
289                               // false - The IT instruction was added
290                               //         implicitly, we can extend it if that
291                               //         would be legal.
292   } ITState;
293 
294   SmallVector<MCInst, 4> PendingConditionalInsts;
295 
296   void flushPendingInstructions(MCStreamer &Out) override {
297     if (!inImplicitITBlock()) {
298       assert(PendingConditionalInsts.size() == 0);
299       return;
300     }
301 
302     // Emit the IT instruction
303     MCInst ITInst;
304     ITInst.setOpcode(ARM::t2IT);
305     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
306     ITInst.addOperand(MCOperand::createImm(ITState.Mask));
307     Out.emitInstruction(ITInst, getSTI());
308 
309     // Emit the conditonal instructions
310     assert(PendingConditionalInsts.size() <= 4);
311     for (const MCInst &Inst : PendingConditionalInsts) {
312       Out.emitInstruction(Inst, getSTI());
313     }
314     PendingConditionalInsts.clear();
315 
316     // Clear the IT state
317     ITState.Mask = 0;
318     ITState.CurPosition = ~0U;
319   }
320 
321   bool inITBlock() { return ITState.CurPosition != ~0U; }
322   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
323   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
324 
325   bool lastInITBlock() {
326     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
327   }
328 
329   void forwardITPosition() {
330     if (!inITBlock()) return;
331     // Move to the next instruction in the IT block, if there is one. If not,
332     // mark the block as done, except for implicit IT blocks, which we leave
333     // open until we find an instruction that can't be added to it.
334     unsigned TZ = countTrailingZeros(ITState.Mask);
335     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
336       ITState.CurPosition = ~0U; // Done with the IT block after this.
337   }
338 
339   // Rewind the state of the current IT block, removing the last slot from it.
340   void rewindImplicitITPosition() {
341     assert(inImplicitITBlock());
342     assert(ITState.CurPosition > 1);
343     ITState.CurPosition--;
344     unsigned TZ = countTrailingZeros(ITState.Mask);
345     unsigned NewMask = 0;
346     NewMask |= ITState.Mask & (0xC << TZ);
347     NewMask |= 0x2 << TZ;
348     ITState.Mask = NewMask;
349   }
350 
351   // Rewind the state of the current IT block, removing the last slot from it.
352   // If we were at the first slot, this closes the IT block.
353   void discardImplicitITBlock() {
354     assert(inImplicitITBlock());
355     assert(ITState.CurPosition == 1);
356     ITState.CurPosition = ~0U;
357   }
358 
359   // Return the low-subreg of a given Q register.
360   unsigned getDRegFromQReg(unsigned QReg) const {
361     return MRI->getSubReg(QReg, ARM::dsub_0);
362   }
363 
364   // Get the condition code corresponding to the current IT block slot.
365   ARMCC::CondCodes currentITCond() {
366     unsigned MaskBit = extractITMaskBit(ITState.Mask, ITState.CurPosition);
367     return MaskBit ? ARMCC::getOppositeCondition(ITState.Cond) : ITState.Cond;
368   }
369 
370   // Invert the condition of the current IT block slot without changing any
371   // other slots in the same block.
372   void invertCurrentITCondition() {
373     if (ITState.CurPosition == 1) {
374       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
375     } else {
376       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
377     }
378   }
379 
380   // Returns true if the current IT block is full (all 4 slots used).
381   bool isITBlockFull() {
382     return inITBlock() && (ITState.Mask & 1);
383   }
384 
385   // Extend the current implicit IT block to have one more slot with the given
386   // condition code.
387   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
388     assert(inImplicitITBlock());
389     assert(!isITBlockFull());
390     assert(Cond == ITState.Cond ||
391            Cond == ARMCC::getOppositeCondition(ITState.Cond));
392     unsigned TZ = countTrailingZeros(ITState.Mask);
393     unsigned NewMask = 0;
394     // Keep any existing condition bits.
395     NewMask |= ITState.Mask & (0xE << TZ);
396     // Insert the new condition bit.
397     NewMask |= (Cond != ITState.Cond) << TZ;
398     // Move the trailing 1 down one bit.
399     NewMask |= 1 << (TZ - 1);
400     ITState.Mask = NewMask;
401   }
402 
403   // Create a new implicit IT block with a dummy condition code.
404   void startImplicitITBlock() {
405     assert(!inITBlock());
406     ITState.Cond = ARMCC::AL;
407     ITState.Mask = 8;
408     ITState.CurPosition = 1;
409     ITState.IsExplicit = false;
410   }
411 
412   // Create a new explicit IT block with the given condition and mask.
413   // The mask should be in the format used in ARMOperand and
414   // MCOperand, with a 1 implying 'e', regardless of the low bit of
415   // the condition.
416   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
417     assert(!inITBlock());
418     ITState.Cond = Cond;
419     ITState.Mask = Mask;
420     ITState.CurPosition = 0;
421     ITState.IsExplicit = true;
422   }
423 
424   struct {
425     unsigned Mask : 4;
426     unsigned CurPosition;
427   } VPTState;
428   bool inVPTBlock() { return VPTState.CurPosition != ~0U; }
429   void forwardVPTPosition() {
430     if (!inVPTBlock()) return;
431     unsigned TZ = countTrailingZeros(VPTState.Mask);
432     if (++VPTState.CurPosition == 5 - TZ)
433       VPTState.CurPosition = ~0U;
434   }
435 
436   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
437     return getParser().Note(L, Msg, Range);
438   }
439 
440   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
441     return getParser().Warning(L, Msg, Range);
442   }
443 
444   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
445     return getParser().Error(L, Msg, Range);
446   }
447 
448   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
449                            unsigned ListNo, bool IsARPop = false);
450   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
451                            unsigned ListNo);
452 
453   int tryParseRegister();
454   bool tryParseRegisterWithWriteBack(OperandVector &);
455   int tryParseShiftRegister(OperandVector &);
456   bool parseRegisterList(OperandVector &, bool EnforceOrder = true);
457   bool parseMemory(OperandVector &);
458   bool parseOperand(OperandVector &, StringRef Mnemonic);
459   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
460   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
461                               unsigned &ShiftAmount);
462   bool parseLiteralValues(unsigned Size, SMLoc L);
463   bool parseDirectiveThumb(SMLoc L);
464   bool parseDirectiveARM(SMLoc L);
465   bool parseDirectiveThumbFunc(SMLoc L);
466   bool parseDirectiveCode(SMLoc L);
467   bool parseDirectiveSyntax(SMLoc L);
468   bool parseDirectiveReq(StringRef Name, SMLoc L);
469   bool parseDirectiveUnreq(SMLoc L);
470   bool parseDirectiveArch(SMLoc L);
471   bool parseDirectiveEabiAttr(SMLoc L);
472   bool parseDirectiveCPU(SMLoc L);
473   bool parseDirectiveFPU(SMLoc L);
474   bool parseDirectiveFnStart(SMLoc L);
475   bool parseDirectiveFnEnd(SMLoc L);
476   bool parseDirectiveCantUnwind(SMLoc L);
477   bool parseDirectivePersonality(SMLoc L);
478   bool parseDirectiveHandlerData(SMLoc L);
479   bool parseDirectiveSetFP(SMLoc L);
480   bool parseDirectivePad(SMLoc L);
481   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
482   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
483   bool parseDirectiveLtorg(SMLoc L);
484   bool parseDirectiveEven(SMLoc L);
485   bool parseDirectivePersonalityIndex(SMLoc L);
486   bool parseDirectiveUnwindRaw(SMLoc L);
487   bool parseDirectiveTLSDescSeq(SMLoc L);
488   bool parseDirectiveMovSP(SMLoc L);
489   bool parseDirectiveObjectArch(SMLoc L);
490   bool parseDirectiveArchExtension(SMLoc L);
491   bool parseDirectiveAlign(SMLoc L);
492   bool parseDirectiveThumbSet(SMLoc L);
493 
494   bool isMnemonicVPTPredicable(StringRef Mnemonic, StringRef ExtraToken);
495   StringRef splitMnemonic(StringRef Mnemonic, StringRef ExtraToken,
496                           unsigned &PredicationCode,
497                           unsigned &VPTPredicationCode, bool &CarrySetting,
498                           unsigned &ProcessorIMod, StringRef &ITMask);
499   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef ExtraToken,
500                              StringRef FullInst, bool &CanAcceptCarrySet,
501                              bool &CanAcceptPredicationCode,
502                              bool &CanAcceptVPTPredicationCode);
503 
504   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
505                                      OperandVector &Operands);
506   bool CDEConvertDualRegOperand(StringRef Mnemonic, OperandVector &Operands);
507 
508   bool isThumb() const {
509     // FIXME: Can tablegen auto-generate this?
510     return getSTI().getFeatureBits()[ARM::ModeThumb];
511   }
512 
513   bool isThumbOne() const {
514     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
515   }
516 
517   bool isThumbTwo() const {
518     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
519   }
520 
521   bool hasThumb() const {
522     return getSTI().getFeatureBits()[ARM::HasV4TOps];
523   }
524 
525   bool hasThumb2() const {
526     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
527   }
528 
529   bool hasV6Ops() const {
530     return getSTI().getFeatureBits()[ARM::HasV6Ops];
531   }
532 
533   bool hasV6T2Ops() const {
534     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
535   }
536 
537   bool hasV6MOps() const {
538     return getSTI().getFeatureBits()[ARM::HasV6MOps];
539   }
540 
541   bool hasV7Ops() const {
542     return getSTI().getFeatureBits()[ARM::HasV7Ops];
543   }
544 
545   bool hasV8Ops() const {
546     return getSTI().getFeatureBits()[ARM::HasV8Ops];
547   }
548 
549   bool hasV8MBaseline() const {
550     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
551   }
552 
553   bool hasV8MMainline() const {
554     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
555   }
556   bool hasV8_1MMainline() const {
557     return getSTI().getFeatureBits()[ARM::HasV8_1MMainlineOps];
558   }
559   bool hasMVE() const {
560     return getSTI().getFeatureBits()[ARM::HasMVEIntegerOps];
561   }
562   bool hasMVEFloat() const {
563     return getSTI().getFeatureBits()[ARM::HasMVEFloatOps];
564   }
565   bool hasCDE() const {
566     return getSTI().getFeatureBits()[ARM::HasCDEOps];
567   }
568   bool has8MSecExt() const {
569     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
570   }
571 
572   bool hasARM() const {
573     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
574   }
575 
576   bool hasDSP() const {
577     return getSTI().getFeatureBits()[ARM::FeatureDSP];
578   }
579 
580   bool hasD32() const {
581     return getSTI().getFeatureBits()[ARM::FeatureD32];
582   }
583 
584   bool hasV8_1aOps() const {
585     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
586   }
587 
588   bool hasRAS() const {
589     return getSTI().getFeatureBits()[ARM::FeatureRAS];
590   }
591 
592   void SwitchMode() {
593     MCSubtargetInfo &STI = copySTI();
594     auto FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
595     setAvailableFeatures(FB);
596   }
597 
598   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
599 
600   bool isMClass() const {
601     return getSTI().getFeatureBits()[ARM::FeatureMClass];
602   }
603 
604   /// @name Auto-generated Match Functions
605   /// {
606 
607 #define GET_ASSEMBLER_HEADER
608 #include "ARMGenAsmMatcher.inc"
609 
610   /// }
611 
612   OperandMatchResultTy parseITCondCode(OperandVector &);
613   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
614   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
615   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
616   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
617   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
618   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
619   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
620   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
621   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
622   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
623                                    int High);
624   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
625     return parsePKHImm(O, "lsl", 0, 31);
626   }
627   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
628     return parsePKHImm(O, "asr", 1, 32);
629   }
630   OperandMatchResultTy parseSetEndImm(OperandVector &);
631   OperandMatchResultTy parseShifterImm(OperandVector &);
632   OperandMatchResultTy parseRotImm(OperandVector &);
633   OperandMatchResultTy parseModImm(OperandVector &);
634   OperandMatchResultTy parseBitfield(OperandVector &);
635   OperandMatchResultTy parsePostIdxReg(OperandVector &);
636   OperandMatchResultTy parseAM3Offset(OperandVector &);
637   OperandMatchResultTy parseFPImm(OperandVector &);
638   OperandMatchResultTy parseVectorList(OperandVector &);
639   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
640                                        SMLoc &EndLoc);
641 
642   // Asm Match Converter Methods
643   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
644   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
645   void cvtMVEVMOVQtoDReg(MCInst &Inst, const OperandVector &);
646 
647   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
648   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
649   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
650   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
651   bool shouldOmitVectorPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
652   bool isITBlockTerminator(MCInst &Inst) const;
653   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
654   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
655                         bool Load, bool ARMMode, bool Writeback);
656 
657 public:
658   enum ARMMatchResultTy {
659     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
660     Match_RequiresNotITBlock,
661     Match_RequiresV6,
662     Match_RequiresThumb2,
663     Match_RequiresV8,
664     Match_RequiresFlagSetting,
665 #define GET_OPERAND_DIAGNOSTIC_TYPES
666 #include "ARMGenAsmMatcher.inc"
667 
668   };
669 
670   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
671                const MCInstrInfo &MII, const MCTargetOptions &Options)
672     : MCTargetAsmParser(Options, STI, MII), UC(Parser), MS(STI) {
673     MCAsmParserExtension::Initialize(Parser);
674 
675     // Cache the MCRegisterInfo.
676     MRI = getContext().getRegisterInfo();
677 
678     // Initialize the set of available features.
679     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
680 
681     // Add build attributes based on the selected target.
682     if (AddBuildAttributes)
683       getTargetStreamer().emitTargetAttributes(STI);
684 
685     // Not in an ITBlock to start with.
686     ITState.CurPosition = ~0U;
687 
688     VPTState.CurPosition = ~0U;
689 
690     NextSymbolIsThumb = false;
691   }
692 
693   // Implementation of the MCTargetAsmParser interface:
694   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
695   OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc,
696                                         SMLoc &EndLoc) override;
697   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
698                         SMLoc NameLoc, OperandVector &Operands) override;
699   bool ParseDirective(AsmToken DirectiveID) override;
700 
701   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
702                                       unsigned Kind) override;
703   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
704 
705   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
706                                OperandVector &Operands, MCStreamer &Out,
707                                uint64_t &ErrorInfo,
708                                bool MatchingInlineAsm) override;
709   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
710                             SmallVectorImpl<NearMissInfo> &NearMisses,
711                             bool MatchingInlineAsm, bool &EmitInITBlock,
712                             MCStreamer &Out);
713 
714   struct NearMissMessage {
715     SMLoc Loc;
716     SmallString<128> Message;
717   };
718 
719   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
720 
721   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
722                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
723                         SMLoc IDLoc, OperandVector &Operands);
724   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
725                         OperandVector &Operands);
726 
727   void doBeforeLabelEmit(MCSymbol *Symbol) override;
728 
729   void onLabelParsed(MCSymbol *Symbol) override;
730 };
731 
732 /// ARMOperand - Instances of this class represent a parsed ARM machine
733 /// operand.
734 class ARMOperand : public MCParsedAsmOperand {
735   enum KindTy {
736     k_CondCode,
737     k_VPTPred,
738     k_CCOut,
739     k_ITCondMask,
740     k_CoprocNum,
741     k_CoprocReg,
742     k_CoprocOption,
743     k_Immediate,
744     k_MemBarrierOpt,
745     k_InstSyncBarrierOpt,
746     k_TraceSyncBarrierOpt,
747     k_Memory,
748     k_PostIndexRegister,
749     k_MSRMask,
750     k_BankedReg,
751     k_ProcIFlags,
752     k_VectorIndex,
753     k_Register,
754     k_RegisterList,
755     k_RegisterListWithAPSR,
756     k_DPRRegisterList,
757     k_SPRRegisterList,
758     k_FPSRegisterListWithVPR,
759     k_FPDRegisterListWithVPR,
760     k_VectorList,
761     k_VectorListAllLanes,
762     k_VectorListIndexed,
763     k_ShiftedRegister,
764     k_ShiftedImmediate,
765     k_ShifterImmediate,
766     k_RotateImmediate,
767     k_ModifiedImmediate,
768     k_ConstantPoolImmediate,
769     k_BitfieldDescriptor,
770     k_Token,
771   } Kind;
772 
773   SMLoc StartLoc, EndLoc, AlignmentLoc;
774   SmallVector<unsigned, 8> Registers;
775 
776   struct CCOp {
777     ARMCC::CondCodes Val;
778   };
779 
780   struct VCCOp {
781     ARMVCC::VPTCodes Val;
782   };
783 
784   struct CopOp {
785     unsigned Val;
786   };
787 
788   struct CoprocOptionOp {
789     unsigned Val;
790   };
791 
792   struct ITMaskOp {
793     unsigned Mask:4;
794   };
795 
796   struct MBOptOp {
797     ARM_MB::MemBOpt Val;
798   };
799 
800   struct ISBOptOp {
801     ARM_ISB::InstSyncBOpt Val;
802   };
803 
804   struct TSBOptOp {
805     ARM_TSB::TraceSyncBOpt Val;
806   };
807 
808   struct IFlagsOp {
809     ARM_PROC::IFlags Val;
810   };
811 
812   struct MMaskOp {
813     unsigned Val;
814   };
815 
816   struct BankedRegOp {
817     unsigned Val;
818   };
819 
820   struct TokOp {
821     const char *Data;
822     unsigned Length;
823   };
824 
825   struct RegOp {
826     unsigned RegNum;
827   };
828 
829   // A vector register list is a sequential list of 1 to 4 registers.
830   struct VectorListOp {
831     unsigned RegNum;
832     unsigned Count;
833     unsigned LaneIndex;
834     bool isDoubleSpaced;
835   };
836 
837   struct VectorIndexOp {
838     unsigned Val;
839   };
840 
841   struct ImmOp {
842     const MCExpr *Val;
843   };
844 
845   /// Combined record for all forms of ARM address expressions.
846   struct MemoryOp {
847     unsigned BaseRegNum;
848     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
849     // was specified.
850     const MCConstantExpr *OffsetImm;  // Offset immediate value
851     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
852     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
853     unsigned ShiftImm;        // shift for OffsetReg.
854     unsigned Alignment;       // 0 = no alignment specified
855     // n = alignment in bytes (2, 4, 8, 16, or 32)
856     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
857   };
858 
859   struct PostIdxRegOp {
860     unsigned RegNum;
861     bool isAdd;
862     ARM_AM::ShiftOpc ShiftTy;
863     unsigned ShiftImm;
864   };
865 
866   struct ShifterImmOp {
867     bool isASR;
868     unsigned Imm;
869   };
870 
871   struct RegShiftedRegOp {
872     ARM_AM::ShiftOpc ShiftTy;
873     unsigned SrcReg;
874     unsigned ShiftReg;
875     unsigned ShiftImm;
876   };
877 
878   struct RegShiftedImmOp {
879     ARM_AM::ShiftOpc ShiftTy;
880     unsigned SrcReg;
881     unsigned ShiftImm;
882   };
883 
884   struct RotImmOp {
885     unsigned Imm;
886   };
887 
888   struct ModImmOp {
889     unsigned Bits;
890     unsigned Rot;
891   };
892 
893   struct BitfieldOp {
894     unsigned LSB;
895     unsigned Width;
896   };
897 
898   union {
899     struct CCOp CC;
900     struct VCCOp VCC;
901     struct CopOp Cop;
902     struct CoprocOptionOp CoprocOption;
903     struct MBOptOp MBOpt;
904     struct ISBOptOp ISBOpt;
905     struct TSBOptOp TSBOpt;
906     struct ITMaskOp ITMask;
907     struct IFlagsOp IFlags;
908     struct MMaskOp MMask;
909     struct BankedRegOp BankedReg;
910     struct TokOp Tok;
911     struct RegOp Reg;
912     struct VectorListOp VectorList;
913     struct VectorIndexOp VectorIndex;
914     struct ImmOp Imm;
915     struct MemoryOp Memory;
916     struct PostIdxRegOp PostIdxReg;
917     struct ShifterImmOp ShifterImm;
918     struct RegShiftedRegOp RegShiftedReg;
919     struct RegShiftedImmOp RegShiftedImm;
920     struct RotImmOp RotImm;
921     struct ModImmOp ModImm;
922     struct BitfieldOp Bitfield;
923   };
924 
925 public:
926   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
927 
928   /// getStartLoc - Get the location of the first token of this operand.
929   SMLoc getStartLoc() const override { return StartLoc; }
930 
931   /// getEndLoc - Get the location of the last token of this operand.
932   SMLoc getEndLoc() const override { return EndLoc; }
933 
934   /// getLocRange - Get the range between the first and last token of this
935   /// operand.
936   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
937 
938   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
939   SMLoc getAlignmentLoc() const {
940     assert(Kind == k_Memory && "Invalid access!");
941     return AlignmentLoc;
942   }
943 
944   ARMCC::CondCodes getCondCode() const {
945     assert(Kind == k_CondCode && "Invalid access!");
946     return CC.Val;
947   }
948 
949   ARMVCC::VPTCodes getVPTPred() const {
950     assert(isVPTPred() && "Invalid access!");
951     return VCC.Val;
952   }
953 
954   unsigned getCoproc() const {
955     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
956     return Cop.Val;
957   }
958 
959   StringRef getToken() const {
960     assert(Kind == k_Token && "Invalid access!");
961     return StringRef(Tok.Data, Tok.Length);
962   }
963 
964   unsigned getReg() const override {
965     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
966     return Reg.RegNum;
967   }
968 
969   const SmallVectorImpl<unsigned> &getRegList() const {
970     assert((Kind == k_RegisterList || Kind == k_RegisterListWithAPSR ||
971             Kind == k_DPRRegisterList || Kind == k_SPRRegisterList ||
972             Kind == k_FPSRegisterListWithVPR ||
973             Kind == k_FPDRegisterListWithVPR) &&
974            "Invalid access!");
975     return Registers;
976   }
977 
978   const MCExpr *getImm() const {
979     assert(isImm() && "Invalid access!");
980     return Imm.Val;
981   }
982 
983   const MCExpr *getConstantPoolImm() const {
984     assert(isConstantPoolImm() && "Invalid access!");
985     return Imm.Val;
986   }
987 
988   unsigned getVectorIndex() const {
989     assert(Kind == k_VectorIndex && "Invalid access!");
990     return VectorIndex.Val;
991   }
992 
993   ARM_MB::MemBOpt getMemBarrierOpt() const {
994     assert(Kind == k_MemBarrierOpt && "Invalid access!");
995     return MBOpt.Val;
996   }
997 
998   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
999     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
1000     return ISBOpt.Val;
1001   }
1002 
1003   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
1004     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
1005     return TSBOpt.Val;
1006   }
1007 
1008   ARM_PROC::IFlags getProcIFlags() const {
1009     assert(Kind == k_ProcIFlags && "Invalid access!");
1010     return IFlags.Val;
1011   }
1012 
1013   unsigned getMSRMask() const {
1014     assert(Kind == k_MSRMask && "Invalid access!");
1015     return MMask.Val;
1016   }
1017 
1018   unsigned getBankedReg() const {
1019     assert(Kind == k_BankedReg && "Invalid access!");
1020     return BankedReg.Val;
1021   }
1022 
1023   bool isCoprocNum() const { return Kind == k_CoprocNum; }
1024   bool isCoprocReg() const { return Kind == k_CoprocReg; }
1025   bool isCoprocOption() const { return Kind == k_CoprocOption; }
1026   bool isCondCode() const { return Kind == k_CondCode; }
1027   bool isVPTPred() const { return Kind == k_VPTPred; }
1028   bool isCCOut() const { return Kind == k_CCOut; }
1029   bool isITMask() const { return Kind == k_ITCondMask; }
1030   bool isITCondCode() const { return Kind == k_CondCode; }
1031   bool isImm() const override {
1032     return Kind == k_Immediate;
1033   }
1034 
1035   bool isARMBranchTarget() const {
1036     if (!isImm()) return false;
1037 
1038     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
1039       return CE->getValue() % 4 == 0;
1040     return true;
1041   }
1042 
1043 
1044   bool isThumbBranchTarget() const {
1045     if (!isImm()) return false;
1046 
1047     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
1048       return CE->getValue() % 2 == 0;
1049     return true;
1050   }
1051 
1052   // checks whether this operand is an unsigned offset which fits is a field
1053   // of specified width and scaled by a specific number of bits
1054   template<unsigned width, unsigned scale>
1055   bool isUnsignedOffset() const {
1056     if (!isImm()) return false;
1057     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1058     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1059       int64_t Val = CE->getValue();
1060       int64_t Align = 1LL << scale;
1061       int64_t Max = Align * ((1LL << width) - 1);
1062       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
1063     }
1064     return false;
1065   }
1066 
1067   // checks whether this operand is an signed offset which fits is a field
1068   // of specified width and scaled by a specific number of bits
1069   template<unsigned width, unsigned scale>
1070   bool isSignedOffset() const {
1071     if (!isImm()) return false;
1072     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1073     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1074       int64_t Val = CE->getValue();
1075       int64_t Align = 1LL << scale;
1076       int64_t Max = Align * ((1LL << (width-1)) - 1);
1077       int64_t Min = -Align * (1LL << (width-1));
1078       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
1079     }
1080     return false;
1081   }
1082 
1083   // checks whether this operand is an offset suitable for the LE /
1084   // LETP instructions in Arm v8.1M
1085   bool isLEOffset() const {
1086     if (!isImm()) return false;
1087     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1088     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1089       int64_t Val = CE->getValue();
1090       return Val < 0 && Val >= -4094 && (Val & 1) == 0;
1091     }
1092     return false;
1093   }
1094 
1095   // checks whether this operand is a memory operand computed as an offset
1096   // applied to PC. the offset may have 8 bits of magnitude and is represented
1097   // with two bits of shift. textually it may be either [pc, #imm], #imm or
1098   // relocable expression...
1099   bool isThumbMemPC() const {
1100     int64_t Val = 0;
1101     if (isImm()) {
1102       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1103       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
1104       if (!CE) return false;
1105       Val = CE->getValue();
1106     }
1107     else if (isGPRMem()) {
1108       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
1109       if(Memory.BaseRegNum != ARM::PC) return false;
1110       Val = Memory.OffsetImm->getValue();
1111     }
1112     else return false;
1113     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
1114   }
1115 
1116   bool isFPImm() const {
1117     if (!isImm()) return false;
1118     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1119     if (!CE) return false;
1120     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1121     return Val != -1;
1122   }
1123 
1124   template<int64_t N, int64_t M>
1125   bool isImmediate() const {
1126     if (!isImm()) return false;
1127     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1128     if (!CE) return false;
1129     int64_t Value = CE->getValue();
1130     return Value >= N && Value <= M;
1131   }
1132 
1133   template<int64_t N, int64_t M>
1134   bool isImmediateS4() const {
1135     if (!isImm()) return false;
1136     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1137     if (!CE) return false;
1138     int64_t Value = CE->getValue();
1139     return ((Value & 3) == 0) && Value >= N && Value <= M;
1140   }
1141   template<int64_t N, int64_t M>
1142   bool isImmediateS2() const {
1143     if (!isImm()) return false;
1144     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1145     if (!CE) return false;
1146     int64_t Value = CE->getValue();
1147     return ((Value & 1) == 0) && Value >= N && Value <= M;
1148   }
1149   bool isFBits16() const {
1150     return isImmediate<0, 17>();
1151   }
1152   bool isFBits32() const {
1153     return isImmediate<1, 33>();
1154   }
1155   bool isImm8s4() const {
1156     return isImmediateS4<-1020, 1020>();
1157   }
1158   bool isImm7s4() const {
1159     return isImmediateS4<-508, 508>();
1160   }
1161   bool isImm7Shift0() const {
1162     return isImmediate<-127, 127>();
1163   }
1164   bool isImm7Shift1() const {
1165     return isImmediateS2<-255, 255>();
1166   }
1167   bool isImm7Shift2() const {
1168     return isImmediateS4<-511, 511>();
1169   }
1170   bool isImm7() const {
1171     return isImmediate<-127, 127>();
1172   }
1173   bool isImm0_1020s4() const {
1174     return isImmediateS4<0, 1020>();
1175   }
1176   bool isImm0_508s4() const {
1177     return isImmediateS4<0, 508>();
1178   }
1179   bool isImm0_508s4Neg() const {
1180     if (!isImm()) return false;
1181     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1182     if (!CE) return false;
1183     int64_t Value = -CE->getValue();
1184     // explicitly exclude zero. we want that to use the normal 0_508 version.
1185     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1186   }
1187 
1188   bool isImm0_4095Neg() const {
1189     if (!isImm()) return false;
1190     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1191     if (!CE) return false;
1192     // isImm0_4095Neg is used with 32-bit immediates only.
1193     // 32-bit immediates are zero extended to 64-bit when parsed,
1194     // thus simple -CE->getValue() results in a big negative number,
1195     // not a small positive number as intended
1196     if ((CE->getValue() >> 32) > 0) return false;
1197     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1198     return Value > 0 && Value < 4096;
1199   }
1200 
1201   bool isImm0_7() const {
1202     return isImmediate<0, 7>();
1203   }
1204 
1205   bool isImm1_16() const {
1206     return isImmediate<1, 16>();
1207   }
1208 
1209   bool isImm1_32() const {
1210     return isImmediate<1, 32>();
1211   }
1212 
1213   bool isImm8_255() const {
1214     return isImmediate<8, 255>();
1215   }
1216 
1217   bool isImm256_65535Expr() const {
1218     if (!isImm()) return false;
1219     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1220     // If it's not a constant expression, it'll generate a fixup and be
1221     // handled later.
1222     if (!CE) return true;
1223     int64_t Value = CE->getValue();
1224     return Value >= 256 && Value < 65536;
1225   }
1226 
1227   bool isImm0_65535Expr() const {
1228     if (!isImm()) return false;
1229     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1230     // If it's not a constant expression, it'll generate a fixup and be
1231     // handled later.
1232     if (!CE) return true;
1233     int64_t Value = CE->getValue();
1234     return Value >= 0 && Value < 65536;
1235   }
1236 
1237   bool isImm24bit() const {
1238     return isImmediate<0, 0xffffff + 1>();
1239   }
1240 
1241   bool isImmThumbSR() const {
1242     return isImmediate<1, 33>();
1243   }
1244 
1245   template<int shift>
1246   bool isExpImmValue(uint64_t Value) const {
1247     uint64_t mask = (1 << shift) - 1;
1248     if ((Value & mask) != 0 || (Value >> shift) > 0xff)
1249       return false;
1250     return true;
1251   }
1252 
1253   template<int shift>
1254   bool isExpImm() const {
1255     if (!isImm()) return false;
1256     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1257     if (!CE) return false;
1258 
1259     return isExpImmValue<shift>(CE->getValue());
1260   }
1261 
1262   template<int shift, int size>
1263   bool isInvertedExpImm() const {
1264     if (!isImm()) return false;
1265     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1266     if (!CE) return false;
1267 
1268     uint64_t OriginalValue = CE->getValue();
1269     uint64_t InvertedValue = OriginalValue ^ (((uint64_t)1 << size) - 1);
1270     return isExpImmValue<shift>(InvertedValue);
1271   }
1272 
1273   bool isPKHLSLImm() const {
1274     return isImmediate<0, 32>();
1275   }
1276 
1277   bool isPKHASRImm() const {
1278     return isImmediate<0, 33>();
1279   }
1280 
1281   bool isAdrLabel() const {
1282     // If we have an immediate that's not a constant, treat it as a label
1283     // reference needing a fixup.
1284     if (isImm() && !isa<MCConstantExpr>(getImm()))
1285       return true;
1286 
1287     // If it is a constant, it must fit into a modified immediate encoding.
1288     if (!isImm()) return false;
1289     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1290     if (!CE) return false;
1291     int64_t Value = CE->getValue();
1292     return (ARM_AM::getSOImmVal(Value) != -1 ||
1293             ARM_AM::getSOImmVal(-Value) != -1);
1294   }
1295 
1296   bool isT2SOImm() const {
1297     // If we have an immediate that's not a constant, treat it as an expression
1298     // needing a fixup.
1299     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1300       // We want to avoid matching :upper16: and :lower16: as we want these
1301       // expressions to match in isImm0_65535Expr()
1302       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1303       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1304                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1305     }
1306     if (!isImm()) return false;
1307     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1308     if (!CE) return false;
1309     int64_t Value = CE->getValue();
1310     return ARM_AM::getT2SOImmVal(Value) != -1;
1311   }
1312 
1313   bool isT2SOImmNot() const {
1314     if (!isImm()) return false;
1315     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1316     if (!CE) return false;
1317     int64_t Value = CE->getValue();
1318     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1319       ARM_AM::getT2SOImmVal(~Value) != -1;
1320   }
1321 
1322   bool isT2SOImmNeg() const {
1323     if (!isImm()) return false;
1324     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1325     if (!CE) return false;
1326     int64_t Value = CE->getValue();
1327     // Only use this when not representable as a plain so_imm.
1328     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1329       ARM_AM::getT2SOImmVal(-Value) != -1;
1330   }
1331 
1332   bool isSetEndImm() const {
1333     if (!isImm()) return false;
1334     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1335     if (!CE) return false;
1336     int64_t Value = CE->getValue();
1337     return Value == 1 || Value == 0;
1338   }
1339 
1340   bool isReg() const override { return Kind == k_Register; }
1341   bool isRegList() const { return Kind == k_RegisterList; }
1342   bool isRegListWithAPSR() const {
1343     return Kind == k_RegisterListWithAPSR || Kind == k_RegisterList;
1344   }
1345   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1346   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1347   bool isFPSRegListWithVPR() const { return Kind == k_FPSRegisterListWithVPR; }
1348   bool isFPDRegListWithVPR() const { return Kind == k_FPDRegisterListWithVPR; }
1349   bool isToken() const override { return Kind == k_Token; }
1350   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1351   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1352   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
1353   bool isMem() const override {
1354       return isGPRMem() || isMVEMem();
1355   }
1356   bool isMVEMem() const {
1357     if (Kind != k_Memory)
1358       return false;
1359     if (Memory.BaseRegNum &&
1360         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum) &&
1361         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Memory.BaseRegNum))
1362       return false;
1363     if (Memory.OffsetRegNum &&
1364         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1365             Memory.OffsetRegNum))
1366       return false;
1367     return true;
1368   }
1369   bool isGPRMem() const {
1370     if (Kind != k_Memory)
1371       return false;
1372     if (Memory.BaseRegNum &&
1373         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1374       return false;
1375     if (Memory.OffsetRegNum &&
1376         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1377       return false;
1378     return true;
1379   }
1380   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1381   bool isRegShiftedReg() const {
1382     return Kind == k_ShiftedRegister &&
1383            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1384                RegShiftedReg.SrcReg) &&
1385            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1386                RegShiftedReg.ShiftReg);
1387   }
1388   bool isRegShiftedImm() const {
1389     return Kind == k_ShiftedImmediate &&
1390            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1391                RegShiftedImm.SrcReg);
1392   }
1393   bool isRotImm() const { return Kind == k_RotateImmediate; }
1394 
1395   template<unsigned Min, unsigned Max>
1396   bool isPowerTwoInRange() const {
1397     if (!isImm()) return false;
1398     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1399     if (!CE) return false;
1400     int64_t Value = CE->getValue();
1401     return Value > 0 && countPopulation((uint64_t)Value) == 1 &&
1402            Value >= Min && Value <= Max;
1403   }
1404   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1405 
1406   bool isModImmNot() const {
1407     if (!isImm()) return false;
1408     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1409     if (!CE) return false;
1410     int64_t Value = CE->getValue();
1411     return ARM_AM::getSOImmVal(~Value) != -1;
1412   }
1413 
1414   bool isModImmNeg() const {
1415     if (!isImm()) return false;
1416     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1417     if (!CE) return false;
1418     int64_t Value = CE->getValue();
1419     return ARM_AM::getSOImmVal(Value) == -1 &&
1420       ARM_AM::getSOImmVal(-Value) != -1;
1421   }
1422 
1423   bool isThumbModImmNeg1_7() const {
1424     if (!isImm()) return false;
1425     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1426     if (!CE) return false;
1427     int32_t Value = -(int32_t)CE->getValue();
1428     return 0 < Value && Value < 8;
1429   }
1430 
1431   bool isThumbModImmNeg8_255() const {
1432     if (!isImm()) return false;
1433     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1434     if (!CE) return false;
1435     int32_t Value = -(int32_t)CE->getValue();
1436     return 7 < Value && Value < 256;
1437   }
1438 
1439   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1440   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1441   bool isPostIdxRegShifted() const {
1442     return Kind == k_PostIndexRegister &&
1443            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1444   }
1445   bool isPostIdxReg() const {
1446     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1447   }
1448   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1449     if (!isGPRMem())
1450       return false;
1451     // No offset of any kind.
1452     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1453      (alignOK || Memory.Alignment == Alignment);
1454   }
1455   bool isMemNoOffsetT2(bool alignOK = false, unsigned Alignment = 0) const {
1456     if (!isGPRMem())
1457       return false;
1458 
1459     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1460             Memory.BaseRegNum))
1461       return false;
1462 
1463     // No offset of any kind.
1464     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1465      (alignOK || Memory.Alignment == Alignment);
1466   }
1467   bool isMemNoOffsetT2NoSp(bool alignOK = false, unsigned Alignment = 0) const {
1468     if (!isGPRMem())
1469       return false;
1470 
1471     if (!ARMMCRegisterClasses[ARM::rGPRRegClassID].contains(
1472             Memory.BaseRegNum))
1473       return false;
1474 
1475     // No offset of any kind.
1476     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1477      (alignOK || Memory.Alignment == Alignment);
1478   }
1479   bool isMemNoOffsetT(bool alignOK = false, unsigned Alignment = 0) const {
1480     if (!isGPRMem())
1481       return false;
1482 
1483     if (!ARMMCRegisterClasses[ARM::tGPRRegClassID].contains(
1484             Memory.BaseRegNum))
1485       return false;
1486 
1487     // No offset of any kind.
1488     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1489      (alignOK || Memory.Alignment == Alignment);
1490   }
1491   bool isMemPCRelImm12() const {
1492     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1493       return false;
1494     // Base register must be PC.
1495     if (Memory.BaseRegNum != ARM::PC)
1496       return false;
1497     // Immediate offset in range [-4095, 4095].
1498     if (!Memory.OffsetImm) return true;
1499     int64_t Val = Memory.OffsetImm->getValue();
1500     return (Val > -4096 && Val < 4096) ||
1501            (Val == std::numeric_limits<int32_t>::min());
1502   }
1503 
1504   bool isAlignedMemory() const {
1505     return isMemNoOffset(true);
1506   }
1507 
1508   bool isAlignedMemoryNone() const {
1509     return isMemNoOffset(false, 0);
1510   }
1511 
1512   bool isDupAlignedMemoryNone() const {
1513     return isMemNoOffset(false, 0);
1514   }
1515 
1516   bool isAlignedMemory16() const {
1517     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1518       return true;
1519     return isMemNoOffset(false, 0);
1520   }
1521 
1522   bool isDupAlignedMemory16() const {
1523     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1524       return true;
1525     return isMemNoOffset(false, 0);
1526   }
1527 
1528   bool isAlignedMemory32() const {
1529     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1530       return true;
1531     return isMemNoOffset(false, 0);
1532   }
1533 
1534   bool isDupAlignedMemory32() const {
1535     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1536       return true;
1537     return isMemNoOffset(false, 0);
1538   }
1539 
1540   bool isAlignedMemory64() const {
1541     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1542       return true;
1543     return isMemNoOffset(false, 0);
1544   }
1545 
1546   bool isDupAlignedMemory64() const {
1547     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1548       return true;
1549     return isMemNoOffset(false, 0);
1550   }
1551 
1552   bool isAlignedMemory64or128() const {
1553     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1554       return true;
1555     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1556       return true;
1557     return isMemNoOffset(false, 0);
1558   }
1559 
1560   bool isDupAlignedMemory64or128() const {
1561     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1562       return true;
1563     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1564       return true;
1565     return isMemNoOffset(false, 0);
1566   }
1567 
1568   bool isAlignedMemory64or128or256() const {
1569     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1570       return true;
1571     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1572       return true;
1573     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1574       return true;
1575     return isMemNoOffset(false, 0);
1576   }
1577 
1578   bool isAddrMode2() const {
1579     if (!isGPRMem() || Memory.Alignment != 0) return false;
1580     // Check for register offset.
1581     if (Memory.OffsetRegNum) return true;
1582     // Immediate offset in range [-4095, 4095].
1583     if (!Memory.OffsetImm) return true;
1584     int64_t Val = Memory.OffsetImm->getValue();
1585     return Val > -4096 && Val < 4096;
1586   }
1587 
1588   bool isAM2OffsetImm() const {
1589     if (!isImm()) return false;
1590     // Immediate offset in range [-4095, 4095].
1591     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1592     if (!CE) return false;
1593     int64_t Val = CE->getValue();
1594     return (Val == std::numeric_limits<int32_t>::min()) ||
1595            (Val > -4096 && Val < 4096);
1596   }
1597 
1598   bool isAddrMode3() const {
1599     // If we have an immediate that's not a constant, treat it as a label
1600     // reference needing a fixup. If it is a constant, it's something else
1601     // and we reject it.
1602     if (isImm() && !isa<MCConstantExpr>(getImm()))
1603       return true;
1604     if (!isGPRMem() || Memory.Alignment != 0) return false;
1605     // No shifts are legal for AM3.
1606     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1607     // Check for register offset.
1608     if (Memory.OffsetRegNum) return true;
1609     // Immediate offset in range [-255, 255].
1610     if (!Memory.OffsetImm) return true;
1611     int64_t Val = Memory.OffsetImm->getValue();
1612     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1613     // have to check for this too.
1614     return (Val > -256 && Val < 256) ||
1615            Val == std::numeric_limits<int32_t>::min();
1616   }
1617 
1618   bool isAM3Offset() const {
1619     if (isPostIdxReg())
1620       return true;
1621     if (!isImm())
1622       return false;
1623     // Immediate offset in range [-255, 255].
1624     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1625     if (!CE) return false;
1626     int64_t Val = CE->getValue();
1627     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1628     return (Val > -256 && Val < 256) ||
1629            Val == std::numeric_limits<int32_t>::min();
1630   }
1631 
1632   bool isAddrMode5() const {
1633     // If we have an immediate that's not a constant, treat it as a label
1634     // reference needing a fixup. If it is a constant, it's something else
1635     // and we reject it.
1636     if (isImm() && !isa<MCConstantExpr>(getImm()))
1637       return true;
1638     if (!isGPRMem() || Memory.Alignment != 0) return false;
1639     // Check for register offset.
1640     if (Memory.OffsetRegNum) return false;
1641     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1642     if (!Memory.OffsetImm) return true;
1643     int64_t Val = Memory.OffsetImm->getValue();
1644     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1645       Val == std::numeric_limits<int32_t>::min();
1646   }
1647 
1648   bool isAddrMode5FP16() const {
1649     // If we have an immediate that's not a constant, treat it as a label
1650     // reference needing a fixup. If it is a constant, it's something else
1651     // and we reject it.
1652     if (isImm() && !isa<MCConstantExpr>(getImm()))
1653       return true;
1654     if (!isGPRMem() || Memory.Alignment != 0) return false;
1655     // Check for register offset.
1656     if (Memory.OffsetRegNum) return false;
1657     // Immediate offset in range [-510, 510] and a multiple of 2.
1658     if (!Memory.OffsetImm) return true;
1659     int64_t Val = Memory.OffsetImm->getValue();
1660     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1661            Val == std::numeric_limits<int32_t>::min();
1662   }
1663 
1664   bool isMemTBB() const {
1665     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1666         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1667       return false;
1668     return true;
1669   }
1670 
1671   bool isMemTBH() const {
1672     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1673         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1674         Memory.Alignment != 0 )
1675       return false;
1676     return true;
1677   }
1678 
1679   bool isMemRegOffset() const {
1680     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1681       return false;
1682     return true;
1683   }
1684 
1685   bool isT2MemRegOffset() const {
1686     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1687         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1688       return false;
1689     // Only lsl #{0, 1, 2, 3} allowed.
1690     if (Memory.ShiftType == ARM_AM::no_shift)
1691       return true;
1692     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1693       return false;
1694     return true;
1695   }
1696 
1697   bool isMemThumbRR() const {
1698     // Thumb reg+reg addressing is simple. Just two registers, a base and
1699     // an offset. No shifts, negations or any other complicating factors.
1700     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1701         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1702       return false;
1703     return isARMLowRegister(Memory.BaseRegNum) &&
1704       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1705   }
1706 
1707   bool isMemThumbRIs4() const {
1708     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1709         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1710       return false;
1711     // Immediate offset, multiple of 4 in range [0, 124].
1712     if (!Memory.OffsetImm) return true;
1713     int64_t Val = Memory.OffsetImm->getValue();
1714     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1715   }
1716 
1717   bool isMemThumbRIs2() const {
1718     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1719         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1720       return false;
1721     // Immediate offset, multiple of 4 in range [0, 62].
1722     if (!Memory.OffsetImm) return true;
1723     int64_t Val = Memory.OffsetImm->getValue();
1724     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1725   }
1726 
1727   bool isMemThumbRIs1() const {
1728     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1729         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1730       return false;
1731     // Immediate offset in range [0, 31].
1732     if (!Memory.OffsetImm) return true;
1733     int64_t Val = Memory.OffsetImm->getValue();
1734     return Val >= 0 && Val <= 31;
1735   }
1736 
1737   bool isMemThumbSPI() const {
1738     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1739         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1740       return false;
1741     // Immediate offset, multiple of 4 in range [0, 1020].
1742     if (!Memory.OffsetImm) return true;
1743     int64_t Val = Memory.OffsetImm->getValue();
1744     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1745   }
1746 
1747   bool isMemImm8s4Offset() const {
1748     // If we have an immediate that's not a constant, treat it as a label
1749     // reference needing a fixup. If it is a constant, it's something else
1750     // and we reject it.
1751     if (isImm() && !isa<MCConstantExpr>(getImm()))
1752       return true;
1753     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1754       return false;
1755     // Immediate offset a multiple of 4 in range [-1020, 1020].
1756     if (!Memory.OffsetImm) return true;
1757     int64_t Val = Memory.OffsetImm->getValue();
1758     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1759     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1760            Val == std::numeric_limits<int32_t>::min();
1761   }
1762   bool isMemImm7s4Offset() const {
1763     // If we have an immediate that's not a constant, treat it as a label
1764     // reference needing a fixup. If it is a constant, it's something else
1765     // and we reject it.
1766     if (isImm() && !isa<MCConstantExpr>(getImm()))
1767       return true;
1768     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1769         !ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1770             Memory.BaseRegNum))
1771       return false;
1772     // Immediate offset a multiple of 4 in range [-508, 508].
1773     if (!Memory.OffsetImm) return true;
1774     int64_t Val = Memory.OffsetImm->getValue();
1775     // Special case, #-0 is INT32_MIN.
1776     return (Val >= -508 && Val <= 508 && (Val & 3) == 0) || Val == INT32_MIN;
1777   }
1778   bool isMemImm0_1020s4Offset() const {
1779     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1780       return false;
1781     // Immediate offset a multiple of 4 in range [0, 1020].
1782     if (!Memory.OffsetImm) return true;
1783     int64_t Val = Memory.OffsetImm->getValue();
1784     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1785   }
1786 
1787   bool isMemImm8Offset() const {
1788     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1789       return false;
1790     // Base reg of PC isn't allowed for these encodings.
1791     if (Memory.BaseRegNum == ARM::PC) return false;
1792     // Immediate offset in range [-255, 255].
1793     if (!Memory.OffsetImm) return true;
1794     int64_t Val = Memory.OffsetImm->getValue();
1795     return (Val == std::numeric_limits<int32_t>::min()) ||
1796            (Val > -256 && Val < 256);
1797   }
1798 
1799   template<unsigned Bits, unsigned RegClassID>
1800   bool isMemImm7ShiftedOffset() const {
1801     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1802         !ARMMCRegisterClasses[RegClassID].contains(Memory.BaseRegNum))
1803       return false;
1804 
1805     // Expect an immediate offset equal to an element of the range
1806     // [-127, 127], shifted left by Bits.
1807 
1808     if (!Memory.OffsetImm) return true;
1809     int64_t Val = Memory.OffsetImm->getValue();
1810 
1811     // INT32_MIN is a special-case value (indicating the encoding with
1812     // zero offset and the subtract bit set)
1813     if (Val == INT32_MIN)
1814       return true;
1815 
1816     unsigned Divisor = 1U << Bits;
1817 
1818     // Check that the low bits are zero
1819     if (Val % Divisor != 0)
1820       return false;
1821 
1822     // Check that the remaining offset is within range.
1823     Val /= Divisor;
1824     return (Val >= -127 && Val <= 127);
1825   }
1826 
1827   template <int shift> bool isMemRegRQOffset() const {
1828     if (!isMVEMem() || Memory.OffsetImm != 0 || Memory.Alignment != 0)
1829       return false;
1830 
1831     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1832             Memory.BaseRegNum))
1833       return false;
1834     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1835             Memory.OffsetRegNum))
1836       return false;
1837 
1838     if (shift == 0 && Memory.ShiftType != ARM_AM::no_shift)
1839       return false;
1840 
1841     if (shift > 0 &&
1842         (Memory.ShiftType != ARM_AM::uxtw || Memory.ShiftImm != shift))
1843       return false;
1844 
1845     return true;
1846   }
1847 
1848   template <int shift> bool isMemRegQOffset() const {
1849     if (!isMVEMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1850       return false;
1851 
1852     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1853             Memory.BaseRegNum))
1854       return false;
1855 
1856     if(!Memory.OffsetImm) return true;
1857     static_assert(shift < 56,
1858                   "Such that we dont shift by a value higher than 62");
1859     int64_t Val = Memory.OffsetImm->getValue();
1860 
1861     // The value must be a multiple of (1 << shift)
1862     if ((Val & ((1U << shift) - 1)) != 0)
1863       return false;
1864 
1865     // And be in the right range, depending on the amount that it is shifted
1866     // by.  Shift 0, is equal to 7 unsigned bits, the sign bit is set
1867     // separately.
1868     int64_t Range = (1U << (7+shift)) - 1;
1869     return (Val == INT32_MIN) || (Val > -Range && Val < Range);
1870   }
1871 
1872   bool isMemPosImm8Offset() const {
1873     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1874       return false;
1875     // Immediate offset in range [0, 255].
1876     if (!Memory.OffsetImm) return true;
1877     int64_t Val = Memory.OffsetImm->getValue();
1878     return Val >= 0 && Val < 256;
1879   }
1880 
1881   bool isMemNegImm8Offset() const {
1882     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1883       return false;
1884     // Base reg of PC isn't allowed for these encodings.
1885     if (Memory.BaseRegNum == ARM::PC) return false;
1886     // Immediate offset in range [-255, -1].
1887     if (!Memory.OffsetImm) return false;
1888     int64_t Val = Memory.OffsetImm->getValue();
1889     return (Val == std::numeric_limits<int32_t>::min()) ||
1890            (Val > -256 && Val < 0);
1891   }
1892 
1893   bool isMemUImm12Offset() const {
1894     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1895       return false;
1896     // Immediate offset in range [0, 4095].
1897     if (!Memory.OffsetImm) return true;
1898     int64_t Val = Memory.OffsetImm->getValue();
1899     return (Val >= 0 && Val < 4096);
1900   }
1901 
1902   bool isMemImm12Offset() const {
1903     // If we have an immediate that's not a constant, treat it as a label
1904     // reference needing a fixup. If it is a constant, it's something else
1905     // and we reject it.
1906 
1907     if (isImm() && !isa<MCConstantExpr>(getImm()))
1908       return true;
1909 
1910     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1911       return false;
1912     // Immediate offset in range [-4095, 4095].
1913     if (!Memory.OffsetImm) return true;
1914     int64_t Val = Memory.OffsetImm->getValue();
1915     return (Val > -4096 && Val < 4096) ||
1916            (Val == std::numeric_limits<int32_t>::min());
1917   }
1918 
1919   bool isConstPoolAsmImm() const {
1920     // Delay processing of Constant Pool Immediate, this will turn into
1921     // a constant. Match no other operand
1922     return (isConstantPoolImm());
1923   }
1924 
1925   bool isPostIdxImm8() const {
1926     if (!isImm()) return false;
1927     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1928     if (!CE) return false;
1929     int64_t Val = CE->getValue();
1930     return (Val > -256 && Val < 256) ||
1931            (Val == std::numeric_limits<int32_t>::min());
1932   }
1933 
1934   bool isPostIdxImm8s4() const {
1935     if (!isImm()) return false;
1936     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1937     if (!CE) return false;
1938     int64_t Val = CE->getValue();
1939     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1940            (Val == std::numeric_limits<int32_t>::min());
1941   }
1942 
1943   bool isMSRMask() const { return Kind == k_MSRMask; }
1944   bool isBankedReg() const { return Kind == k_BankedReg; }
1945   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1946 
1947   // NEON operands.
1948   bool isSingleSpacedVectorList() const {
1949     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1950   }
1951 
1952   bool isDoubleSpacedVectorList() const {
1953     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1954   }
1955 
1956   bool isVecListOneD() const {
1957     if (!isSingleSpacedVectorList()) return false;
1958     return VectorList.Count == 1;
1959   }
1960 
1961   bool isVecListTwoMQ() const {
1962     return isSingleSpacedVectorList() && VectorList.Count == 2 &&
1963            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1964                VectorList.RegNum);
1965   }
1966 
1967   bool isVecListDPair() const {
1968     if (!isSingleSpacedVectorList()) return false;
1969     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1970               .contains(VectorList.RegNum));
1971   }
1972 
1973   bool isVecListThreeD() const {
1974     if (!isSingleSpacedVectorList()) return false;
1975     return VectorList.Count == 3;
1976   }
1977 
1978   bool isVecListFourD() const {
1979     if (!isSingleSpacedVectorList()) return false;
1980     return VectorList.Count == 4;
1981   }
1982 
1983   bool isVecListDPairSpaced() const {
1984     if (Kind != k_VectorList) return false;
1985     if (isSingleSpacedVectorList()) return false;
1986     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1987               .contains(VectorList.RegNum));
1988   }
1989 
1990   bool isVecListThreeQ() const {
1991     if (!isDoubleSpacedVectorList()) return false;
1992     return VectorList.Count == 3;
1993   }
1994 
1995   bool isVecListFourQ() const {
1996     if (!isDoubleSpacedVectorList()) return false;
1997     return VectorList.Count == 4;
1998   }
1999 
2000   bool isVecListFourMQ() const {
2001     return isSingleSpacedVectorList() && VectorList.Count == 4 &&
2002            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
2003                VectorList.RegNum);
2004   }
2005 
2006   bool isSingleSpacedVectorAllLanes() const {
2007     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
2008   }
2009 
2010   bool isDoubleSpacedVectorAllLanes() const {
2011     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
2012   }
2013 
2014   bool isVecListOneDAllLanes() const {
2015     if (!isSingleSpacedVectorAllLanes()) return false;
2016     return VectorList.Count == 1;
2017   }
2018 
2019   bool isVecListDPairAllLanes() const {
2020     if (!isSingleSpacedVectorAllLanes()) return false;
2021     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
2022               .contains(VectorList.RegNum));
2023   }
2024 
2025   bool isVecListDPairSpacedAllLanes() const {
2026     if (!isDoubleSpacedVectorAllLanes()) return false;
2027     return VectorList.Count == 2;
2028   }
2029 
2030   bool isVecListThreeDAllLanes() const {
2031     if (!isSingleSpacedVectorAllLanes()) return false;
2032     return VectorList.Count == 3;
2033   }
2034 
2035   bool isVecListThreeQAllLanes() const {
2036     if (!isDoubleSpacedVectorAllLanes()) return false;
2037     return VectorList.Count == 3;
2038   }
2039 
2040   bool isVecListFourDAllLanes() const {
2041     if (!isSingleSpacedVectorAllLanes()) return false;
2042     return VectorList.Count == 4;
2043   }
2044 
2045   bool isVecListFourQAllLanes() const {
2046     if (!isDoubleSpacedVectorAllLanes()) return false;
2047     return VectorList.Count == 4;
2048   }
2049 
2050   bool isSingleSpacedVectorIndexed() const {
2051     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
2052   }
2053 
2054   bool isDoubleSpacedVectorIndexed() const {
2055     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
2056   }
2057 
2058   bool isVecListOneDByteIndexed() const {
2059     if (!isSingleSpacedVectorIndexed()) return false;
2060     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
2061   }
2062 
2063   bool isVecListOneDHWordIndexed() const {
2064     if (!isSingleSpacedVectorIndexed()) return false;
2065     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
2066   }
2067 
2068   bool isVecListOneDWordIndexed() const {
2069     if (!isSingleSpacedVectorIndexed()) return false;
2070     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
2071   }
2072 
2073   bool isVecListTwoDByteIndexed() const {
2074     if (!isSingleSpacedVectorIndexed()) return false;
2075     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
2076   }
2077 
2078   bool isVecListTwoDHWordIndexed() const {
2079     if (!isSingleSpacedVectorIndexed()) return false;
2080     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2081   }
2082 
2083   bool isVecListTwoQWordIndexed() const {
2084     if (!isDoubleSpacedVectorIndexed()) return false;
2085     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2086   }
2087 
2088   bool isVecListTwoQHWordIndexed() const {
2089     if (!isDoubleSpacedVectorIndexed()) return false;
2090     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2091   }
2092 
2093   bool isVecListTwoDWordIndexed() const {
2094     if (!isSingleSpacedVectorIndexed()) return false;
2095     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2096   }
2097 
2098   bool isVecListThreeDByteIndexed() const {
2099     if (!isSingleSpacedVectorIndexed()) return false;
2100     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
2101   }
2102 
2103   bool isVecListThreeDHWordIndexed() const {
2104     if (!isSingleSpacedVectorIndexed()) return false;
2105     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2106   }
2107 
2108   bool isVecListThreeQWordIndexed() const {
2109     if (!isDoubleSpacedVectorIndexed()) return false;
2110     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2111   }
2112 
2113   bool isVecListThreeQHWordIndexed() const {
2114     if (!isDoubleSpacedVectorIndexed()) return false;
2115     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2116   }
2117 
2118   bool isVecListThreeDWordIndexed() const {
2119     if (!isSingleSpacedVectorIndexed()) return false;
2120     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2121   }
2122 
2123   bool isVecListFourDByteIndexed() const {
2124     if (!isSingleSpacedVectorIndexed()) return false;
2125     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
2126   }
2127 
2128   bool isVecListFourDHWordIndexed() const {
2129     if (!isSingleSpacedVectorIndexed()) return false;
2130     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2131   }
2132 
2133   bool isVecListFourQWordIndexed() const {
2134     if (!isDoubleSpacedVectorIndexed()) return false;
2135     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2136   }
2137 
2138   bool isVecListFourQHWordIndexed() const {
2139     if (!isDoubleSpacedVectorIndexed()) return false;
2140     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2141   }
2142 
2143   bool isVecListFourDWordIndexed() const {
2144     if (!isSingleSpacedVectorIndexed()) return false;
2145     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2146   }
2147 
2148   bool isVectorIndex() const { return Kind == k_VectorIndex; }
2149 
2150   template <unsigned NumLanes>
2151   bool isVectorIndexInRange() const {
2152     if (Kind != k_VectorIndex) return false;
2153     return VectorIndex.Val < NumLanes;
2154   }
2155 
2156   bool isVectorIndex8()  const { return isVectorIndexInRange<8>(); }
2157   bool isVectorIndex16() const { return isVectorIndexInRange<4>(); }
2158   bool isVectorIndex32() const { return isVectorIndexInRange<2>(); }
2159   bool isVectorIndex64() const { return isVectorIndexInRange<1>(); }
2160 
2161   template<int PermittedValue, int OtherPermittedValue>
2162   bool isMVEPairVectorIndex() const {
2163     if (Kind != k_VectorIndex) return false;
2164     return VectorIndex.Val == PermittedValue ||
2165            VectorIndex.Val == OtherPermittedValue;
2166   }
2167 
2168   bool isNEONi8splat() const {
2169     if (!isImm()) return false;
2170     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2171     // Must be a constant.
2172     if (!CE) return false;
2173     int64_t Value = CE->getValue();
2174     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
2175     // value.
2176     return Value >= 0 && Value < 256;
2177   }
2178 
2179   bool isNEONi16splat() const {
2180     if (isNEONByteReplicate(2))
2181       return false; // Leave that for bytes replication and forbid by default.
2182     if (!isImm())
2183       return false;
2184     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2185     // Must be a constant.
2186     if (!CE) return false;
2187     unsigned Value = CE->getValue();
2188     return ARM_AM::isNEONi16splat(Value);
2189   }
2190 
2191   bool isNEONi16splatNot() const {
2192     if (!isImm())
2193       return false;
2194     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2195     // Must be a constant.
2196     if (!CE) return false;
2197     unsigned Value = CE->getValue();
2198     return ARM_AM::isNEONi16splat(~Value & 0xffff);
2199   }
2200 
2201   bool isNEONi32splat() const {
2202     if (isNEONByteReplicate(4))
2203       return false; // Leave that for bytes replication and forbid by default.
2204     if (!isImm())
2205       return false;
2206     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2207     // Must be a constant.
2208     if (!CE) return false;
2209     unsigned Value = CE->getValue();
2210     return ARM_AM::isNEONi32splat(Value);
2211   }
2212 
2213   bool isNEONi32splatNot() const {
2214     if (!isImm())
2215       return false;
2216     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2217     // Must be a constant.
2218     if (!CE) return false;
2219     unsigned Value = CE->getValue();
2220     return ARM_AM::isNEONi32splat(~Value);
2221   }
2222 
2223   static bool isValidNEONi32vmovImm(int64_t Value) {
2224     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
2225     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
2226     return ((Value & 0xffffffffffffff00) == 0) ||
2227            ((Value & 0xffffffffffff00ff) == 0) ||
2228            ((Value & 0xffffffffff00ffff) == 0) ||
2229            ((Value & 0xffffffff00ffffff) == 0) ||
2230            ((Value & 0xffffffffffff00ff) == 0xff) ||
2231            ((Value & 0xffffffffff00ffff) == 0xffff);
2232   }
2233 
2234   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
2235     assert((Width == 8 || Width == 16 || Width == 32) &&
2236            "Invalid element width");
2237     assert(NumElems * Width <= 64 && "Invalid result width");
2238 
2239     if (!isImm())
2240       return false;
2241     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2242     // Must be a constant.
2243     if (!CE)
2244       return false;
2245     int64_t Value = CE->getValue();
2246     if (!Value)
2247       return false; // Don't bother with zero.
2248     if (Inv)
2249       Value = ~Value;
2250 
2251     uint64_t Mask = (1ull << Width) - 1;
2252     uint64_t Elem = Value & Mask;
2253     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
2254       return false;
2255     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
2256       return false;
2257 
2258     for (unsigned i = 1; i < NumElems; ++i) {
2259       Value >>= Width;
2260       if ((Value & Mask) != Elem)
2261         return false;
2262     }
2263     return true;
2264   }
2265 
2266   bool isNEONByteReplicate(unsigned NumBytes) const {
2267     return isNEONReplicate(8, NumBytes, false);
2268   }
2269 
2270   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
2271     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
2272            "Invalid source width");
2273     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
2274            "Invalid destination width");
2275     assert(FromW < ToW && "ToW is not less than FromW");
2276   }
2277 
2278   template<unsigned FromW, unsigned ToW>
2279   bool isNEONmovReplicate() const {
2280     checkNeonReplicateArgs(FromW, ToW);
2281     if (ToW == 64 && isNEONi64splat())
2282       return false;
2283     return isNEONReplicate(FromW, ToW / FromW, false);
2284   }
2285 
2286   template<unsigned FromW, unsigned ToW>
2287   bool isNEONinvReplicate() const {
2288     checkNeonReplicateArgs(FromW, ToW);
2289     return isNEONReplicate(FromW, ToW / FromW, true);
2290   }
2291 
2292   bool isNEONi32vmov() const {
2293     if (isNEONByteReplicate(4))
2294       return false; // Let it to be classified as byte-replicate case.
2295     if (!isImm())
2296       return false;
2297     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2298     // Must be a constant.
2299     if (!CE)
2300       return false;
2301     return isValidNEONi32vmovImm(CE->getValue());
2302   }
2303 
2304   bool isNEONi32vmovNeg() const {
2305     if (!isImm()) return false;
2306     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2307     // Must be a constant.
2308     if (!CE) return false;
2309     return isValidNEONi32vmovImm(~CE->getValue());
2310   }
2311 
2312   bool isNEONi64splat() const {
2313     if (!isImm()) return false;
2314     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2315     // Must be a constant.
2316     if (!CE) return false;
2317     uint64_t Value = CE->getValue();
2318     // i64 value with each byte being either 0 or 0xff.
2319     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
2320       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
2321     return true;
2322   }
2323 
2324   template<int64_t Angle, int64_t Remainder>
2325   bool isComplexRotation() const {
2326     if (!isImm()) return false;
2327 
2328     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2329     if (!CE) return false;
2330     uint64_t Value = CE->getValue();
2331 
2332     return (Value % Angle == Remainder && Value <= 270);
2333   }
2334 
2335   bool isMVELongShift() const {
2336     if (!isImm()) return false;
2337     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2338     // Must be a constant.
2339     if (!CE) return false;
2340     uint64_t Value = CE->getValue();
2341     return Value >= 1 && Value <= 32;
2342   }
2343 
2344   bool isMveSaturateOp() const {
2345     if (!isImm()) return false;
2346     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2347     if (!CE) return false;
2348     uint64_t Value = CE->getValue();
2349     return Value == 48 || Value == 64;
2350   }
2351 
2352   bool isITCondCodeNoAL() const {
2353     if (!isITCondCode()) return false;
2354     ARMCC::CondCodes CC = getCondCode();
2355     return CC != ARMCC::AL;
2356   }
2357 
2358   bool isITCondCodeRestrictedI() const {
2359     if (!isITCondCode())
2360       return false;
2361     ARMCC::CondCodes CC = getCondCode();
2362     return CC == ARMCC::EQ || CC == ARMCC::NE;
2363   }
2364 
2365   bool isITCondCodeRestrictedS() const {
2366     if (!isITCondCode())
2367       return false;
2368     ARMCC::CondCodes CC = getCondCode();
2369     return CC == ARMCC::LT || CC == ARMCC::GT || CC == ARMCC::LE ||
2370            CC == ARMCC::GE;
2371   }
2372 
2373   bool isITCondCodeRestrictedU() const {
2374     if (!isITCondCode())
2375       return false;
2376     ARMCC::CondCodes CC = getCondCode();
2377     return CC == ARMCC::HS || CC == ARMCC::HI;
2378   }
2379 
2380   bool isITCondCodeRestrictedFP() const {
2381     if (!isITCondCode())
2382       return false;
2383     ARMCC::CondCodes CC = getCondCode();
2384     return CC == ARMCC::EQ || CC == ARMCC::NE || CC == ARMCC::LT ||
2385            CC == ARMCC::GT || CC == ARMCC::LE || CC == ARMCC::GE;
2386   }
2387 
2388   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
2389     // Add as immediates when possible.  Null MCExpr = 0.
2390     if (!Expr)
2391       Inst.addOperand(MCOperand::createImm(0));
2392     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2393       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2394     else
2395       Inst.addOperand(MCOperand::createExpr(Expr));
2396   }
2397 
2398   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2399     assert(N == 1 && "Invalid number of operands!");
2400     addExpr(Inst, getImm());
2401   }
2402 
2403   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2404     assert(N == 1 && "Invalid number of operands!");
2405     addExpr(Inst, getImm());
2406   }
2407 
2408   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2409     assert(N == 2 && "Invalid number of operands!");
2410     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2411     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2412     Inst.addOperand(MCOperand::createReg(RegNum));
2413   }
2414 
2415   void addVPTPredNOperands(MCInst &Inst, unsigned N) const {
2416     assert(N == 2 && "Invalid number of operands!");
2417     Inst.addOperand(MCOperand::createImm(unsigned(getVPTPred())));
2418     unsigned RegNum = getVPTPred() == ARMVCC::None ? 0: ARM::P0;
2419     Inst.addOperand(MCOperand::createReg(RegNum));
2420   }
2421 
2422   void addVPTPredROperands(MCInst &Inst, unsigned N) const {
2423     assert(N == 3 && "Invalid number of operands!");
2424     addVPTPredNOperands(Inst, N-1);
2425     unsigned RegNum;
2426     if (getVPTPred() == ARMVCC::None) {
2427       RegNum = 0;
2428     } else {
2429       unsigned NextOpIndex = Inst.getNumOperands();
2430       const MCInstrDesc &MCID = ARMInsts[Inst.getOpcode()];
2431       int TiedOp = MCID.getOperandConstraint(NextOpIndex, MCOI::TIED_TO);
2432       assert(TiedOp >= 0 &&
2433              "Inactive register in vpred_r is not tied to an output!");
2434       RegNum = Inst.getOperand(TiedOp).getReg();
2435     }
2436     Inst.addOperand(MCOperand::createReg(RegNum));
2437   }
2438 
2439   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2440     assert(N == 1 && "Invalid number of operands!");
2441     Inst.addOperand(MCOperand::createImm(getCoproc()));
2442   }
2443 
2444   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2445     assert(N == 1 && "Invalid number of operands!");
2446     Inst.addOperand(MCOperand::createImm(getCoproc()));
2447   }
2448 
2449   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2450     assert(N == 1 && "Invalid number of operands!");
2451     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2452   }
2453 
2454   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2455     assert(N == 1 && "Invalid number of operands!");
2456     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2457   }
2458 
2459   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2460     assert(N == 1 && "Invalid number of operands!");
2461     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2462   }
2463 
2464   void addITCondCodeInvOperands(MCInst &Inst, unsigned N) const {
2465     assert(N == 1 && "Invalid number of operands!");
2466     Inst.addOperand(MCOperand::createImm(unsigned(ARMCC::getOppositeCondition(getCondCode()))));
2467   }
2468 
2469   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2470     assert(N == 1 && "Invalid number of operands!");
2471     Inst.addOperand(MCOperand::createReg(getReg()));
2472   }
2473 
2474   void addRegOperands(MCInst &Inst, unsigned N) const {
2475     assert(N == 1 && "Invalid number of operands!");
2476     Inst.addOperand(MCOperand::createReg(getReg()));
2477   }
2478 
2479   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2480     assert(N == 3 && "Invalid number of operands!");
2481     assert(isRegShiftedReg() &&
2482            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2483     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2484     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2485     Inst.addOperand(MCOperand::createImm(
2486       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2487   }
2488 
2489   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2490     assert(N == 2 && "Invalid number of operands!");
2491     assert(isRegShiftedImm() &&
2492            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2493     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2494     // Shift of #32 is encoded as 0 where permitted
2495     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2496     Inst.addOperand(MCOperand::createImm(
2497       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2498   }
2499 
2500   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2501     assert(N == 1 && "Invalid number of operands!");
2502     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2503                                          ShifterImm.Imm));
2504   }
2505 
2506   void addRegListOperands(MCInst &Inst, unsigned N) const {
2507     assert(N == 1 && "Invalid number of operands!");
2508     const SmallVectorImpl<unsigned> &RegList = getRegList();
2509     for (SmallVectorImpl<unsigned>::const_iterator
2510            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2511       Inst.addOperand(MCOperand::createReg(*I));
2512   }
2513 
2514   void addRegListWithAPSROperands(MCInst &Inst, unsigned N) const {
2515     assert(N == 1 && "Invalid number of operands!");
2516     const SmallVectorImpl<unsigned> &RegList = getRegList();
2517     for (SmallVectorImpl<unsigned>::const_iterator
2518            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2519       Inst.addOperand(MCOperand::createReg(*I));
2520   }
2521 
2522   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2523     addRegListOperands(Inst, N);
2524   }
2525 
2526   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2527     addRegListOperands(Inst, N);
2528   }
2529 
2530   void addFPSRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2531     addRegListOperands(Inst, N);
2532   }
2533 
2534   void addFPDRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2535     addRegListOperands(Inst, N);
2536   }
2537 
2538   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2539     assert(N == 1 && "Invalid number of operands!");
2540     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2541     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2542   }
2543 
2544   void addModImmOperands(MCInst &Inst, unsigned N) const {
2545     assert(N == 1 && "Invalid number of operands!");
2546 
2547     // Support for fixups (MCFixup)
2548     if (isImm())
2549       return addImmOperands(Inst, N);
2550 
2551     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2552   }
2553 
2554   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2555     assert(N == 1 && "Invalid number of operands!");
2556     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2557     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2558     Inst.addOperand(MCOperand::createImm(Enc));
2559   }
2560 
2561   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2562     assert(N == 1 && "Invalid number of operands!");
2563     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2564     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2565     Inst.addOperand(MCOperand::createImm(Enc));
2566   }
2567 
2568   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2569     assert(N == 1 && "Invalid number of operands!");
2570     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2571     uint32_t Val = -CE->getValue();
2572     Inst.addOperand(MCOperand::createImm(Val));
2573   }
2574 
2575   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2576     assert(N == 1 && "Invalid number of operands!");
2577     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2578     uint32_t Val = -CE->getValue();
2579     Inst.addOperand(MCOperand::createImm(Val));
2580   }
2581 
2582   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2583     assert(N == 1 && "Invalid number of operands!");
2584     // Munge the lsb/width into a bitfield mask.
2585     unsigned lsb = Bitfield.LSB;
2586     unsigned width = Bitfield.Width;
2587     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2588     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2589                       (32 - (lsb + width)));
2590     Inst.addOperand(MCOperand::createImm(Mask));
2591   }
2592 
2593   void addImmOperands(MCInst &Inst, unsigned N) const {
2594     assert(N == 1 && "Invalid number of operands!");
2595     addExpr(Inst, getImm());
2596   }
2597 
2598   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2599     assert(N == 1 && "Invalid number of operands!");
2600     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2601     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2602   }
2603 
2604   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2605     assert(N == 1 && "Invalid number of operands!");
2606     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2607     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2608   }
2609 
2610   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2611     assert(N == 1 && "Invalid number of operands!");
2612     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2613     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2614     Inst.addOperand(MCOperand::createImm(Val));
2615   }
2616 
2617   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2618     assert(N == 1 && "Invalid number of operands!");
2619     // FIXME: We really want to scale the value here, but the LDRD/STRD
2620     // instruction don't encode operands that way yet.
2621     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2622     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2623   }
2624 
2625   void addImm7s4Operands(MCInst &Inst, unsigned N) const {
2626     assert(N == 1 && "Invalid number of operands!");
2627     // FIXME: We really want to scale the value here, but the VSTR/VLDR_VSYSR
2628     // instruction don't encode operands that way yet.
2629     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2630     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2631   }
2632 
2633   void addImm7Shift0Operands(MCInst &Inst, unsigned N) const {
2634     assert(N == 1 && "Invalid number of operands!");
2635     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2636     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2637   }
2638 
2639   void addImm7Shift1Operands(MCInst &Inst, unsigned N) const {
2640     assert(N == 1 && "Invalid number of operands!");
2641     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2642     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2643   }
2644 
2645   void addImm7Shift2Operands(MCInst &Inst, unsigned N) const {
2646     assert(N == 1 && "Invalid number of operands!");
2647     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2648     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2649   }
2650 
2651   void addImm7Operands(MCInst &Inst, unsigned N) const {
2652     assert(N == 1 && "Invalid number of operands!");
2653     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2654     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2655   }
2656 
2657   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2658     assert(N == 1 && "Invalid number of operands!");
2659     // The immediate is scaled by four in the encoding and is stored
2660     // in the MCInst as such. Lop off the low two bits here.
2661     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2662     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2663   }
2664 
2665   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2666     assert(N == 1 && "Invalid number of operands!");
2667     // The immediate is scaled by four in the encoding and is stored
2668     // in the MCInst as such. Lop off the low two bits here.
2669     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2670     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2671   }
2672 
2673   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2674     assert(N == 1 && "Invalid number of operands!");
2675     // The immediate is scaled by four in the encoding and is stored
2676     // in the MCInst as such. Lop off the low two bits here.
2677     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2678     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2679   }
2680 
2681   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2682     assert(N == 1 && "Invalid number of operands!");
2683     // The constant encodes as the immediate-1, and we store in the instruction
2684     // the bits as encoded, so subtract off one here.
2685     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2686     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2687   }
2688 
2689   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2690     assert(N == 1 && "Invalid number of operands!");
2691     // The constant encodes as the immediate-1, and we store in the instruction
2692     // the bits as encoded, so subtract off one here.
2693     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2694     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2695   }
2696 
2697   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2698     assert(N == 1 && "Invalid number of operands!");
2699     // The constant encodes as the immediate, except for 32, which encodes as
2700     // zero.
2701     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2702     unsigned Imm = CE->getValue();
2703     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2704   }
2705 
2706   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2707     assert(N == 1 && "Invalid number of operands!");
2708     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2709     // the instruction as well.
2710     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2711     int Val = CE->getValue();
2712     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2713   }
2714 
2715   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2716     assert(N == 1 && "Invalid number of operands!");
2717     // The operand is actually a t2_so_imm, but we have its bitwise
2718     // negation in the assembly source, so twiddle it here.
2719     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2720     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2721   }
2722 
2723   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2724     assert(N == 1 && "Invalid number of operands!");
2725     // The operand is actually a t2_so_imm, but we have its
2726     // negation in the assembly source, so twiddle it here.
2727     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2728     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2729   }
2730 
2731   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2732     assert(N == 1 && "Invalid number of operands!");
2733     // The operand is actually an imm0_4095, but we have its
2734     // negation in the assembly source, so twiddle it here.
2735     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2736     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2737   }
2738 
2739   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2740     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2741       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2742       return;
2743     }
2744     const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2745     Inst.addOperand(MCOperand::createExpr(SR));
2746   }
2747 
2748   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2749     assert(N == 1 && "Invalid number of operands!");
2750     if (isImm()) {
2751       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2752       if (CE) {
2753         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2754         return;
2755       }
2756       const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2757       Inst.addOperand(MCOperand::createExpr(SR));
2758       return;
2759     }
2760 
2761     assert(isGPRMem()  && "Unknown value type!");
2762     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2763     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2764   }
2765 
2766   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2767     assert(N == 1 && "Invalid number of operands!");
2768     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2769   }
2770 
2771   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2772     assert(N == 1 && "Invalid number of operands!");
2773     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2774   }
2775 
2776   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2777     assert(N == 1 && "Invalid number of operands!");
2778     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2779   }
2780 
2781   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2782     assert(N == 1 && "Invalid number of operands!");
2783     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2784   }
2785 
2786   void addMemNoOffsetT2Operands(MCInst &Inst, unsigned N) const {
2787     assert(N == 1 && "Invalid number of operands!");
2788     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2789   }
2790 
2791   void addMemNoOffsetT2NoSpOperands(MCInst &Inst, unsigned N) const {
2792     assert(N == 1 && "Invalid number of operands!");
2793     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2794   }
2795 
2796   void addMemNoOffsetTOperands(MCInst &Inst, unsigned N) const {
2797     assert(N == 1 && "Invalid number of operands!");
2798     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2799   }
2800 
2801   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2802     assert(N == 1 && "Invalid number of operands!");
2803     int32_t Imm = Memory.OffsetImm->getValue();
2804     Inst.addOperand(MCOperand::createImm(Imm));
2805   }
2806 
2807   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2808     assert(N == 1 && "Invalid number of operands!");
2809     assert(isImm() && "Not an immediate!");
2810 
2811     // If we have an immediate that's not a constant, treat it as a label
2812     // reference needing a fixup.
2813     if (!isa<MCConstantExpr>(getImm())) {
2814       Inst.addOperand(MCOperand::createExpr(getImm()));
2815       return;
2816     }
2817 
2818     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2819     int Val = CE->getValue();
2820     Inst.addOperand(MCOperand::createImm(Val));
2821   }
2822 
2823   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2824     assert(N == 2 && "Invalid number of operands!");
2825     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2826     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2827   }
2828 
2829   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2830     addAlignedMemoryOperands(Inst, N);
2831   }
2832 
2833   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2834     addAlignedMemoryOperands(Inst, N);
2835   }
2836 
2837   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2838     addAlignedMemoryOperands(Inst, N);
2839   }
2840 
2841   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2842     addAlignedMemoryOperands(Inst, N);
2843   }
2844 
2845   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2846     addAlignedMemoryOperands(Inst, N);
2847   }
2848 
2849   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2850     addAlignedMemoryOperands(Inst, N);
2851   }
2852 
2853   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2854     addAlignedMemoryOperands(Inst, N);
2855   }
2856 
2857   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2858     addAlignedMemoryOperands(Inst, N);
2859   }
2860 
2861   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2862     addAlignedMemoryOperands(Inst, N);
2863   }
2864 
2865   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2866     addAlignedMemoryOperands(Inst, N);
2867   }
2868 
2869   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2870     addAlignedMemoryOperands(Inst, N);
2871   }
2872 
2873   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2874     assert(N == 3 && "Invalid number of operands!");
2875     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2876     if (!Memory.OffsetRegNum) {
2877       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2878       // Special case for #-0
2879       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2880       if (Val < 0) Val = -Val;
2881       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2882     } else {
2883       // For register offset, we encode the shift type and negation flag
2884       // here.
2885       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2886                               Memory.ShiftImm, Memory.ShiftType);
2887     }
2888     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2889     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2890     Inst.addOperand(MCOperand::createImm(Val));
2891   }
2892 
2893   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2894     assert(N == 2 && "Invalid number of operands!");
2895     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2896     assert(CE && "non-constant AM2OffsetImm operand!");
2897     int32_t Val = CE->getValue();
2898     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2899     // Special case for #-0
2900     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2901     if (Val < 0) Val = -Val;
2902     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2903     Inst.addOperand(MCOperand::createReg(0));
2904     Inst.addOperand(MCOperand::createImm(Val));
2905   }
2906 
2907   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2908     assert(N == 3 && "Invalid number of operands!");
2909     // If we have an immediate that's not a constant, treat it as a label
2910     // reference needing a fixup. If it is a constant, it's something else
2911     // and we reject it.
2912     if (isImm()) {
2913       Inst.addOperand(MCOperand::createExpr(getImm()));
2914       Inst.addOperand(MCOperand::createReg(0));
2915       Inst.addOperand(MCOperand::createImm(0));
2916       return;
2917     }
2918 
2919     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2920     if (!Memory.OffsetRegNum) {
2921       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2922       // Special case for #-0
2923       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2924       if (Val < 0) Val = -Val;
2925       Val = ARM_AM::getAM3Opc(AddSub, Val);
2926     } else {
2927       // For register offset, we encode the shift type and negation flag
2928       // here.
2929       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2930     }
2931     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2932     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2933     Inst.addOperand(MCOperand::createImm(Val));
2934   }
2935 
2936   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2937     assert(N == 2 && "Invalid number of operands!");
2938     if (Kind == k_PostIndexRegister) {
2939       int32_t Val =
2940         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2941       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2942       Inst.addOperand(MCOperand::createImm(Val));
2943       return;
2944     }
2945 
2946     // Constant offset.
2947     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2948     int32_t Val = CE->getValue();
2949     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2950     // Special case for #-0
2951     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2952     if (Val < 0) Val = -Val;
2953     Val = ARM_AM::getAM3Opc(AddSub, Val);
2954     Inst.addOperand(MCOperand::createReg(0));
2955     Inst.addOperand(MCOperand::createImm(Val));
2956   }
2957 
2958   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2959     assert(N == 2 && "Invalid number of operands!");
2960     // If we have an immediate that's not a constant, treat it as a label
2961     // reference needing a fixup. If it is a constant, it's something else
2962     // and we reject it.
2963     if (isImm()) {
2964       Inst.addOperand(MCOperand::createExpr(getImm()));
2965       Inst.addOperand(MCOperand::createImm(0));
2966       return;
2967     }
2968 
2969     // The lower two bits are always zero and as such are not encoded.
2970     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2971     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2972     // Special case for #-0
2973     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2974     if (Val < 0) Val = -Val;
2975     Val = ARM_AM::getAM5Opc(AddSub, Val);
2976     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2977     Inst.addOperand(MCOperand::createImm(Val));
2978   }
2979 
2980   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2981     assert(N == 2 && "Invalid number of operands!");
2982     // If we have an immediate that's not a constant, treat it as a label
2983     // reference needing a fixup. If it is a constant, it's something else
2984     // and we reject it.
2985     if (isImm()) {
2986       Inst.addOperand(MCOperand::createExpr(getImm()));
2987       Inst.addOperand(MCOperand::createImm(0));
2988       return;
2989     }
2990 
2991     // The lower bit is always zero and as such is not encoded.
2992     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2993     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2994     // Special case for #-0
2995     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2996     if (Val < 0) Val = -Val;
2997     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2998     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2999     Inst.addOperand(MCOperand::createImm(Val));
3000   }
3001 
3002   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
3003     assert(N == 2 && "Invalid number of operands!");
3004     // If we have an immediate that's not a constant, treat it as a label
3005     // reference needing a fixup. If it is a constant, it's something else
3006     // and we reject it.
3007     if (isImm()) {
3008       Inst.addOperand(MCOperand::createExpr(getImm()));
3009       Inst.addOperand(MCOperand::createImm(0));
3010       return;
3011     }
3012 
3013     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3014     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3015     Inst.addOperand(MCOperand::createImm(Val));
3016   }
3017 
3018   void addMemImm7s4OffsetOperands(MCInst &Inst, unsigned N) const {
3019     assert(N == 2 && "Invalid number of operands!");
3020     // If we have an immediate that's not a constant, treat it as a label
3021     // reference needing a fixup. If it is a constant, it's something else
3022     // and we reject it.
3023     if (isImm()) {
3024       Inst.addOperand(MCOperand::createExpr(getImm()));
3025       Inst.addOperand(MCOperand::createImm(0));
3026       return;
3027     }
3028 
3029     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3030     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3031     Inst.addOperand(MCOperand::createImm(Val));
3032   }
3033 
3034   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
3035     assert(N == 2 && "Invalid number of operands!");
3036     // The lower two bits are always zero and as such are not encoded.
3037     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
3038     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3039     Inst.addOperand(MCOperand::createImm(Val));
3040   }
3041 
3042   void addMemImmOffsetOperands(MCInst &Inst, unsigned N) const {
3043     assert(N == 2 && "Invalid number of operands!");
3044     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3045     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3046     Inst.addOperand(MCOperand::createImm(Val));
3047   }
3048 
3049   void addMemRegRQOffsetOperands(MCInst &Inst, unsigned N) const {
3050     assert(N == 2 && "Invalid number of operands!");
3051     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3052     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3053   }
3054 
3055   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3056     assert(N == 2 && "Invalid number of operands!");
3057     // If this is an immediate, it's a label reference.
3058     if (isImm()) {
3059       addExpr(Inst, getImm());
3060       Inst.addOperand(MCOperand::createImm(0));
3061       return;
3062     }
3063 
3064     // Otherwise, it's a normal memory reg+offset.
3065     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3066     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3067     Inst.addOperand(MCOperand::createImm(Val));
3068   }
3069 
3070   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3071     assert(N == 2 && "Invalid number of operands!");
3072     // If this is an immediate, it's a label reference.
3073     if (isImm()) {
3074       addExpr(Inst, getImm());
3075       Inst.addOperand(MCOperand::createImm(0));
3076       return;
3077     }
3078 
3079     // Otherwise, it's a normal memory reg+offset.
3080     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3081     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3082     Inst.addOperand(MCOperand::createImm(Val));
3083   }
3084 
3085   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
3086     assert(N == 1 && "Invalid number of operands!");
3087     // This is container for the immediate that we will create the constant
3088     // pool from
3089     addExpr(Inst, getConstantPoolImm());
3090     return;
3091   }
3092 
3093   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
3094     assert(N == 2 && "Invalid number of operands!");
3095     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3096     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3097   }
3098 
3099   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
3100     assert(N == 2 && "Invalid number of operands!");
3101     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3102     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3103   }
3104 
3105   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3106     assert(N == 3 && "Invalid number of operands!");
3107     unsigned Val =
3108       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
3109                         Memory.ShiftImm, Memory.ShiftType);
3110     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3111     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3112     Inst.addOperand(MCOperand::createImm(Val));
3113   }
3114 
3115   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3116     assert(N == 3 && "Invalid number of operands!");
3117     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3118     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3119     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
3120   }
3121 
3122   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
3123     assert(N == 2 && "Invalid number of operands!");
3124     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3125     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3126   }
3127 
3128   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
3129     assert(N == 2 && "Invalid number of operands!");
3130     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
3131     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3132     Inst.addOperand(MCOperand::createImm(Val));
3133   }
3134 
3135   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
3136     assert(N == 2 && "Invalid number of operands!");
3137     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
3138     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3139     Inst.addOperand(MCOperand::createImm(Val));
3140   }
3141 
3142   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
3143     assert(N == 2 && "Invalid number of operands!");
3144     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
3145     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3146     Inst.addOperand(MCOperand::createImm(Val));
3147   }
3148 
3149   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
3150     assert(N == 2 && "Invalid number of operands!");
3151     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
3152     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3153     Inst.addOperand(MCOperand::createImm(Val));
3154   }
3155 
3156   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
3157     assert(N == 1 && "Invalid number of operands!");
3158     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3159     assert(CE && "non-constant post-idx-imm8 operand!");
3160     int Imm = CE->getValue();
3161     bool isAdd = Imm >= 0;
3162     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3163     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
3164     Inst.addOperand(MCOperand::createImm(Imm));
3165   }
3166 
3167   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
3168     assert(N == 1 && "Invalid number of operands!");
3169     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3170     assert(CE && "non-constant post-idx-imm8s4 operand!");
3171     int Imm = CE->getValue();
3172     bool isAdd = Imm >= 0;
3173     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3174     // Immediate is scaled by 4.
3175     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
3176     Inst.addOperand(MCOperand::createImm(Imm));
3177   }
3178 
3179   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
3180     assert(N == 2 && "Invalid number of operands!");
3181     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3182     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
3183   }
3184 
3185   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
3186     assert(N == 2 && "Invalid number of operands!");
3187     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3188     // The sign, shift type, and shift amount are encoded in a single operand
3189     // using the AM2 encoding helpers.
3190     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
3191     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
3192                                      PostIdxReg.ShiftTy);
3193     Inst.addOperand(MCOperand::createImm(Imm));
3194   }
3195 
3196   void addPowerTwoOperands(MCInst &Inst, unsigned N) const {
3197     assert(N == 1 && "Invalid number of operands!");
3198     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3199     Inst.addOperand(MCOperand::createImm(CE->getValue()));
3200   }
3201 
3202   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
3203     assert(N == 1 && "Invalid number of operands!");
3204     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
3205   }
3206 
3207   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
3208     assert(N == 1 && "Invalid number of operands!");
3209     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
3210   }
3211 
3212   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
3213     assert(N == 1 && "Invalid number of operands!");
3214     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
3215   }
3216 
3217   void addVecListOperands(MCInst &Inst, unsigned N) const {
3218     assert(N == 1 && "Invalid number of operands!");
3219     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3220   }
3221 
3222   void addMVEVecListOperands(MCInst &Inst, unsigned N) const {
3223     assert(N == 1 && "Invalid number of operands!");
3224 
3225     // When we come here, the VectorList field will identify a range
3226     // of q-registers by its base register and length, and it will
3227     // have already been error-checked to be the expected length of
3228     // range and contain only q-regs in the range q0-q7. So we can
3229     // count on the base register being in the range q0-q6 (for 2
3230     // regs) or q0-q4 (for 4)
3231     //
3232     // The MVE instructions taking a register range of this kind will
3233     // need an operand in the QQPR or QQQQPR class, representing the
3234     // entire range as a unit. So we must translate into that class,
3235     // by finding the index of the base register in the MQPR reg
3236     // class, and returning the super-register at the corresponding
3237     // index in the target class.
3238 
3239     const MCRegisterClass *RC_in = &ARMMCRegisterClasses[ARM::MQPRRegClassID];
3240     const MCRegisterClass *RC_out = (VectorList.Count == 2) ?
3241       &ARMMCRegisterClasses[ARM::QQPRRegClassID] :
3242       &ARMMCRegisterClasses[ARM::QQQQPRRegClassID];
3243 
3244     unsigned I, E = RC_out->getNumRegs();
3245     for (I = 0; I < E; I++)
3246       if (RC_in->getRegister(I) == VectorList.RegNum)
3247         break;
3248     assert(I < E && "Invalid vector list start register!");
3249 
3250     Inst.addOperand(MCOperand::createReg(RC_out->getRegister(I)));
3251   }
3252 
3253   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
3254     assert(N == 2 && "Invalid number of operands!");
3255     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3256     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
3257   }
3258 
3259   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
3260     assert(N == 1 && "Invalid number of operands!");
3261     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3262   }
3263 
3264   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
3265     assert(N == 1 && "Invalid number of operands!");
3266     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3267   }
3268 
3269   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
3270     assert(N == 1 && "Invalid number of operands!");
3271     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3272   }
3273 
3274   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
3275     assert(N == 1 && "Invalid number of operands!");
3276     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3277   }
3278 
3279   void addMVEVectorIndexOperands(MCInst &Inst, unsigned N) const {
3280     assert(N == 1 && "Invalid number of operands!");
3281     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3282   }
3283 
3284   void addMVEPairVectorIndexOperands(MCInst &Inst, unsigned N) const {
3285     assert(N == 1 && "Invalid number of operands!");
3286     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3287   }
3288 
3289   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
3290     assert(N == 1 && "Invalid number of operands!");
3291     // The immediate encodes the type of constant as well as the value.
3292     // Mask in that this is an i8 splat.
3293     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3294     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
3295   }
3296 
3297   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
3298     assert(N == 1 && "Invalid number of operands!");
3299     // The immediate encodes the type of constant as well as the value.
3300     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3301     unsigned Value = CE->getValue();
3302     Value = ARM_AM::encodeNEONi16splat(Value);
3303     Inst.addOperand(MCOperand::createImm(Value));
3304   }
3305 
3306   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
3307     assert(N == 1 && "Invalid number of operands!");
3308     // The immediate encodes the type of constant as well as the value.
3309     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3310     unsigned Value = CE->getValue();
3311     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
3312     Inst.addOperand(MCOperand::createImm(Value));
3313   }
3314 
3315   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
3316     assert(N == 1 && "Invalid number of operands!");
3317     // The immediate encodes the type of constant as well as the value.
3318     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3319     unsigned Value = CE->getValue();
3320     Value = ARM_AM::encodeNEONi32splat(Value);
3321     Inst.addOperand(MCOperand::createImm(Value));
3322   }
3323 
3324   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
3325     assert(N == 1 && "Invalid number of operands!");
3326     // The immediate encodes the type of constant as well as the value.
3327     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3328     unsigned Value = CE->getValue();
3329     Value = ARM_AM::encodeNEONi32splat(~Value);
3330     Inst.addOperand(MCOperand::createImm(Value));
3331   }
3332 
3333   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
3334     // The immediate encodes the type of constant as well as the value.
3335     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3336     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
3337             Inst.getOpcode() == ARM::VMOVv16i8) &&
3338           "All instructions that wants to replicate non-zero byte "
3339           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
3340     unsigned Value = CE->getValue();
3341     if (Inv)
3342       Value = ~Value;
3343     unsigned B = Value & 0xff;
3344     B |= 0xe00; // cmode = 0b1110
3345     Inst.addOperand(MCOperand::createImm(B));
3346   }
3347 
3348   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3349     assert(N == 1 && "Invalid number of operands!");
3350     addNEONi8ReplicateOperands(Inst, true);
3351   }
3352 
3353   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
3354     if (Value >= 256 && Value <= 0xffff)
3355       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
3356     else if (Value > 0xffff && Value <= 0xffffff)
3357       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
3358     else if (Value > 0xffffff)
3359       Value = (Value >> 24) | 0x600;
3360     return Value;
3361   }
3362 
3363   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
3364     assert(N == 1 && "Invalid number of operands!");
3365     // The immediate encodes the type of constant as well as the value.
3366     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3367     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
3368     Inst.addOperand(MCOperand::createImm(Value));
3369   }
3370 
3371   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3372     assert(N == 1 && "Invalid number of operands!");
3373     addNEONi8ReplicateOperands(Inst, false);
3374   }
3375 
3376   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
3377     assert(N == 1 && "Invalid number of operands!");
3378     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3379     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
3380             Inst.getOpcode() == ARM::VMOVv8i16 ||
3381             Inst.getOpcode() == ARM::VMVNv4i16 ||
3382             Inst.getOpcode() == ARM::VMVNv8i16) &&
3383           "All instructions that want to replicate non-zero half-word "
3384           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
3385     uint64_t Value = CE->getValue();
3386     unsigned Elem = Value & 0xffff;
3387     if (Elem >= 256)
3388       Elem = (Elem >> 8) | 0x200;
3389     Inst.addOperand(MCOperand::createImm(Elem));
3390   }
3391 
3392   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
3393     assert(N == 1 && "Invalid number of operands!");
3394     // The immediate encodes the type of constant as well as the value.
3395     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3396     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
3397     Inst.addOperand(MCOperand::createImm(Value));
3398   }
3399 
3400   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
3401     assert(N == 1 && "Invalid number of operands!");
3402     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3403     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
3404             Inst.getOpcode() == ARM::VMOVv4i32 ||
3405             Inst.getOpcode() == ARM::VMVNv2i32 ||
3406             Inst.getOpcode() == ARM::VMVNv4i32) &&
3407           "All instructions that want to replicate non-zero word "
3408           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
3409     uint64_t Value = CE->getValue();
3410     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
3411     Inst.addOperand(MCOperand::createImm(Elem));
3412   }
3413 
3414   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
3415     assert(N == 1 && "Invalid number of operands!");
3416     // The immediate encodes the type of constant as well as the value.
3417     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3418     uint64_t Value = CE->getValue();
3419     unsigned Imm = 0;
3420     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
3421       Imm |= (Value & 1) << i;
3422     }
3423     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
3424   }
3425 
3426   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
3427     assert(N == 1 && "Invalid number of operands!");
3428     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3429     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
3430   }
3431 
3432   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
3433     assert(N == 1 && "Invalid number of operands!");
3434     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3435     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
3436   }
3437 
3438   void addMveSaturateOperands(MCInst &Inst, unsigned N) const {
3439     assert(N == 1 && "Invalid number of operands!");
3440     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3441     unsigned Imm = CE->getValue();
3442     assert((Imm == 48 || Imm == 64) && "Invalid saturate operand");
3443     Inst.addOperand(MCOperand::createImm(Imm == 48 ? 1 : 0));
3444   }
3445 
3446   void print(raw_ostream &OS) const override;
3447 
3448   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
3449     auto Op = std::make_unique<ARMOperand>(k_ITCondMask);
3450     Op->ITMask.Mask = Mask;
3451     Op->StartLoc = S;
3452     Op->EndLoc = S;
3453     return Op;
3454   }
3455 
3456   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
3457                                                     SMLoc S) {
3458     auto Op = std::make_unique<ARMOperand>(k_CondCode);
3459     Op->CC.Val = CC;
3460     Op->StartLoc = S;
3461     Op->EndLoc = S;
3462     return Op;
3463   }
3464 
3465   static std::unique_ptr<ARMOperand> CreateVPTPred(ARMVCC::VPTCodes CC,
3466                                                    SMLoc S) {
3467     auto Op = std::make_unique<ARMOperand>(k_VPTPred);
3468     Op->VCC.Val = CC;
3469     Op->StartLoc = S;
3470     Op->EndLoc = S;
3471     return Op;
3472   }
3473 
3474   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
3475     auto Op = std::make_unique<ARMOperand>(k_CoprocNum);
3476     Op->Cop.Val = CopVal;
3477     Op->StartLoc = S;
3478     Op->EndLoc = S;
3479     return Op;
3480   }
3481 
3482   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
3483     auto Op = std::make_unique<ARMOperand>(k_CoprocReg);
3484     Op->Cop.Val = CopVal;
3485     Op->StartLoc = S;
3486     Op->EndLoc = S;
3487     return Op;
3488   }
3489 
3490   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
3491                                                         SMLoc E) {
3492     auto Op = std::make_unique<ARMOperand>(k_CoprocOption);
3493     Op->Cop.Val = Val;
3494     Op->StartLoc = S;
3495     Op->EndLoc = E;
3496     return Op;
3497   }
3498 
3499   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
3500     auto Op = std::make_unique<ARMOperand>(k_CCOut);
3501     Op->Reg.RegNum = RegNum;
3502     Op->StartLoc = S;
3503     Op->EndLoc = S;
3504     return Op;
3505   }
3506 
3507   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
3508     auto Op = std::make_unique<ARMOperand>(k_Token);
3509     Op->Tok.Data = Str.data();
3510     Op->Tok.Length = Str.size();
3511     Op->StartLoc = S;
3512     Op->EndLoc = S;
3513     return Op;
3514   }
3515 
3516   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
3517                                                SMLoc E) {
3518     auto Op = std::make_unique<ARMOperand>(k_Register);
3519     Op->Reg.RegNum = RegNum;
3520     Op->StartLoc = S;
3521     Op->EndLoc = E;
3522     return Op;
3523   }
3524 
3525   static std::unique_ptr<ARMOperand>
3526   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3527                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
3528                         SMLoc E) {
3529     auto Op = std::make_unique<ARMOperand>(k_ShiftedRegister);
3530     Op->RegShiftedReg.ShiftTy = ShTy;
3531     Op->RegShiftedReg.SrcReg = SrcReg;
3532     Op->RegShiftedReg.ShiftReg = ShiftReg;
3533     Op->RegShiftedReg.ShiftImm = ShiftImm;
3534     Op->StartLoc = S;
3535     Op->EndLoc = E;
3536     return Op;
3537   }
3538 
3539   static std::unique_ptr<ARMOperand>
3540   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3541                          unsigned ShiftImm, SMLoc S, SMLoc E) {
3542     auto Op = std::make_unique<ARMOperand>(k_ShiftedImmediate);
3543     Op->RegShiftedImm.ShiftTy = ShTy;
3544     Op->RegShiftedImm.SrcReg = SrcReg;
3545     Op->RegShiftedImm.ShiftImm = ShiftImm;
3546     Op->StartLoc = S;
3547     Op->EndLoc = E;
3548     return Op;
3549   }
3550 
3551   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
3552                                                       SMLoc S, SMLoc E) {
3553     auto Op = std::make_unique<ARMOperand>(k_ShifterImmediate);
3554     Op->ShifterImm.isASR = isASR;
3555     Op->ShifterImm.Imm = Imm;
3556     Op->StartLoc = S;
3557     Op->EndLoc = E;
3558     return Op;
3559   }
3560 
3561   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3562                                                   SMLoc E) {
3563     auto Op = std::make_unique<ARMOperand>(k_RotateImmediate);
3564     Op->RotImm.Imm = Imm;
3565     Op->StartLoc = S;
3566     Op->EndLoc = E;
3567     return Op;
3568   }
3569 
3570   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3571                                                   SMLoc S, SMLoc E) {
3572     auto Op = std::make_unique<ARMOperand>(k_ModifiedImmediate);
3573     Op->ModImm.Bits = Bits;
3574     Op->ModImm.Rot = Rot;
3575     Op->StartLoc = S;
3576     Op->EndLoc = E;
3577     return Op;
3578   }
3579 
3580   static std::unique_ptr<ARMOperand>
3581   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3582     auto Op = std::make_unique<ARMOperand>(k_ConstantPoolImmediate);
3583     Op->Imm.Val = Val;
3584     Op->StartLoc = S;
3585     Op->EndLoc = E;
3586     return Op;
3587   }
3588 
3589   static std::unique_ptr<ARMOperand>
3590   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3591     auto Op = std::make_unique<ARMOperand>(k_BitfieldDescriptor);
3592     Op->Bitfield.LSB = LSB;
3593     Op->Bitfield.Width = Width;
3594     Op->StartLoc = S;
3595     Op->EndLoc = E;
3596     return Op;
3597   }
3598 
3599   static std::unique_ptr<ARMOperand>
3600   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3601                 SMLoc StartLoc, SMLoc EndLoc) {
3602     assert(Regs.size() > 0 && "RegList contains no registers?");
3603     KindTy Kind = k_RegisterList;
3604 
3605     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
3606             Regs.front().second)) {
3607       if (Regs.back().second == ARM::VPR)
3608         Kind = k_FPDRegisterListWithVPR;
3609       else
3610         Kind = k_DPRRegisterList;
3611     } else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
3612                    Regs.front().second)) {
3613       if (Regs.back().second == ARM::VPR)
3614         Kind = k_FPSRegisterListWithVPR;
3615       else
3616         Kind = k_SPRRegisterList;
3617     }
3618 
3619     if (Kind == k_RegisterList && Regs.back().second == ARM::APSR)
3620       Kind = k_RegisterListWithAPSR;
3621 
3622     assert(llvm::is_sorted(Regs) && "Register list must be sorted by encoding");
3623 
3624     auto Op = std::make_unique<ARMOperand>(Kind);
3625     for (const auto &P : Regs)
3626       Op->Registers.push_back(P.second);
3627 
3628     Op->StartLoc = StartLoc;
3629     Op->EndLoc = EndLoc;
3630     return Op;
3631   }
3632 
3633   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3634                                                       unsigned Count,
3635                                                       bool isDoubleSpaced,
3636                                                       SMLoc S, SMLoc E) {
3637     auto Op = std::make_unique<ARMOperand>(k_VectorList);
3638     Op->VectorList.RegNum = RegNum;
3639     Op->VectorList.Count = Count;
3640     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3641     Op->StartLoc = S;
3642     Op->EndLoc = E;
3643     return Op;
3644   }
3645 
3646   static std::unique_ptr<ARMOperand>
3647   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3648                            SMLoc S, SMLoc E) {
3649     auto Op = std::make_unique<ARMOperand>(k_VectorListAllLanes);
3650     Op->VectorList.RegNum = RegNum;
3651     Op->VectorList.Count = Count;
3652     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3653     Op->StartLoc = S;
3654     Op->EndLoc = E;
3655     return Op;
3656   }
3657 
3658   static std::unique_ptr<ARMOperand>
3659   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3660                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3661     auto Op = std::make_unique<ARMOperand>(k_VectorListIndexed);
3662     Op->VectorList.RegNum = RegNum;
3663     Op->VectorList.Count = Count;
3664     Op->VectorList.LaneIndex = Index;
3665     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3666     Op->StartLoc = S;
3667     Op->EndLoc = E;
3668     return Op;
3669   }
3670 
3671   static std::unique_ptr<ARMOperand>
3672   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3673     auto Op = std::make_unique<ARMOperand>(k_VectorIndex);
3674     Op->VectorIndex.Val = Idx;
3675     Op->StartLoc = S;
3676     Op->EndLoc = E;
3677     return Op;
3678   }
3679 
3680   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3681                                                SMLoc E) {
3682     auto Op = std::make_unique<ARMOperand>(k_Immediate);
3683     Op->Imm.Val = Val;
3684     Op->StartLoc = S;
3685     Op->EndLoc = E;
3686     return Op;
3687   }
3688 
3689   static std::unique_ptr<ARMOperand>
3690   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3691             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3692             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3693             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3694     auto Op = std::make_unique<ARMOperand>(k_Memory);
3695     Op->Memory.BaseRegNum = BaseRegNum;
3696     Op->Memory.OffsetImm = OffsetImm;
3697     Op->Memory.OffsetRegNum = OffsetRegNum;
3698     Op->Memory.ShiftType = ShiftType;
3699     Op->Memory.ShiftImm = ShiftImm;
3700     Op->Memory.Alignment = Alignment;
3701     Op->Memory.isNegative = isNegative;
3702     Op->StartLoc = S;
3703     Op->EndLoc = E;
3704     Op->AlignmentLoc = AlignmentLoc;
3705     return Op;
3706   }
3707 
3708   static std::unique_ptr<ARMOperand>
3709   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3710                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3711     auto Op = std::make_unique<ARMOperand>(k_PostIndexRegister);
3712     Op->PostIdxReg.RegNum = RegNum;
3713     Op->PostIdxReg.isAdd = isAdd;
3714     Op->PostIdxReg.ShiftTy = ShiftTy;
3715     Op->PostIdxReg.ShiftImm = ShiftImm;
3716     Op->StartLoc = S;
3717     Op->EndLoc = E;
3718     return Op;
3719   }
3720 
3721   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3722                                                          SMLoc S) {
3723     auto Op = std::make_unique<ARMOperand>(k_MemBarrierOpt);
3724     Op->MBOpt.Val = Opt;
3725     Op->StartLoc = S;
3726     Op->EndLoc = S;
3727     return Op;
3728   }
3729 
3730   static std::unique_ptr<ARMOperand>
3731   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3732     auto Op = std::make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3733     Op->ISBOpt.Val = Opt;
3734     Op->StartLoc = S;
3735     Op->EndLoc = S;
3736     return Op;
3737   }
3738 
3739   static std::unique_ptr<ARMOperand>
3740   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3741     auto Op = std::make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3742     Op->TSBOpt.Val = Opt;
3743     Op->StartLoc = S;
3744     Op->EndLoc = S;
3745     return Op;
3746   }
3747 
3748   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3749                                                       SMLoc S) {
3750     auto Op = std::make_unique<ARMOperand>(k_ProcIFlags);
3751     Op->IFlags.Val = IFlags;
3752     Op->StartLoc = S;
3753     Op->EndLoc = S;
3754     return Op;
3755   }
3756 
3757   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3758     auto Op = std::make_unique<ARMOperand>(k_MSRMask);
3759     Op->MMask.Val = MMask;
3760     Op->StartLoc = S;
3761     Op->EndLoc = S;
3762     return Op;
3763   }
3764 
3765   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3766     auto Op = std::make_unique<ARMOperand>(k_BankedReg);
3767     Op->BankedReg.Val = Reg;
3768     Op->StartLoc = S;
3769     Op->EndLoc = S;
3770     return Op;
3771   }
3772 };
3773 
3774 } // end anonymous namespace.
3775 
3776 void ARMOperand::print(raw_ostream &OS) const {
3777   auto RegName = [](unsigned Reg) {
3778     if (Reg)
3779       return ARMInstPrinter::getRegisterName(Reg);
3780     else
3781       return "noreg";
3782   };
3783 
3784   switch (Kind) {
3785   case k_CondCode:
3786     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3787     break;
3788   case k_VPTPred:
3789     OS << "<ARMVCC::" << ARMVPTPredToString(getVPTPred()) << ">";
3790     break;
3791   case k_CCOut:
3792     OS << "<ccout " << RegName(getReg()) << ">";
3793     break;
3794   case k_ITCondMask: {
3795     static const char *const MaskStr[] = {
3796       "(invalid)", "(tttt)", "(ttt)", "(ttte)",
3797       "(tt)",      "(ttet)", "(tte)", "(ttee)",
3798       "(t)",       "(tett)", "(tet)", "(tete)",
3799       "(te)",      "(teet)", "(tee)", "(teee)",
3800     };
3801     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3802     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3803     break;
3804   }
3805   case k_CoprocNum:
3806     OS << "<coprocessor number: " << getCoproc() << ">";
3807     break;
3808   case k_CoprocReg:
3809     OS << "<coprocessor register: " << getCoproc() << ">";
3810     break;
3811   case k_CoprocOption:
3812     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3813     break;
3814   case k_MSRMask:
3815     OS << "<mask: " << getMSRMask() << ">";
3816     break;
3817   case k_BankedReg:
3818     OS << "<banked reg: " << getBankedReg() << ">";
3819     break;
3820   case k_Immediate:
3821     OS << *getImm();
3822     break;
3823   case k_MemBarrierOpt:
3824     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3825     break;
3826   case k_InstSyncBarrierOpt:
3827     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3828     break;
3829   case k_TraceSyncBarrierOpt:
3830     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3831     break;
3832   case k_Memory:
3833     OS << "<memory";
3834     if (Memory.BaseRegNum)
3835       OS << " base:" << RegName(Memory.BaseRegNum);
3836     if (Memory.OffsetImm)
3837       OS << " offset-imm:" << *Memory.OffsetImm;
3838     if (Memory.OffsetRegNum)
3839       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3840          << RegName(Memory.OffsetRegNum);
3841     if (Memory.ShiftType != ARM_AM::no_shift) {
3842       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3843       OS << " shift-imm:" << Memory.ShiftImm;
3844     }
3845     if (Memory.Alignment)
3846       OS << " alignment:" << Memory.Alignment;
3847     OS << ">";
3848     break;
3849   case k_PostIndexRegister:
3850     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3851        << RegName(PostIdxReg.RegNum);
3852     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3853       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3854          << PostIdxReg.ShiftImm;
3855     OS << ">";
3856     break;
3857   case k_ProcIFlags: {
3858     OS << "<ARM_PROC::";
3859     unsigned IFlags = getProcIFlags();
3860     for (int i=2; i >= 0; --i)
3861       if (IFlags & (1 << i))
3862         OS << ARM_PROC::IFlagsToString(1 << i);
3863     OS << ">";
3864     break;
3865   }
3866   case k_Register:
3867     OS << "<register " << RegName(getReg()) << ">";
3868     break;
3869   case k_ShifterImmediate:
3870     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3871        << " #" << ShifterImm.Imm << ">";
3872     break;
3873   case k_ShiftedRegister:
3874     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3875        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3876        << RegName(RegShiftedReg.ShiftReg) << ">";
3877     break;
3878   case k_ShiftedImmediate:
3879     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3880        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3881        << RegShiftedImm.ShiftImm << ">";
3882     break;
3883   case k_RotateImmediate:
3884     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3885     break;
3886   case k_ModifiedImmediate:
3887     OS << "<mod_imm #" << ModImm.Bits << ", #"
3888        <<  ModImm.Rot << ")>";
3889     break;
3890   case k_ConstantPoolImmediate:
3891     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3892     break;
3893   case k_BitfieldDescriptor:
3894     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3895        << ", width: " << Bitfield.Width << ">";
3896     break;
3897   case k_RegisterList:
3898   case k_RegisterListWithAPSR:
3899   case k_DPRRegisterList:
3900   case k_SPRRegisterList:
3901   case k_FPSRegisterListWithVPR:
3902   case k_FPDRegisterListWithVPR: {
3903     OS << "<register_list ";
3904 
3905     const SmallVectorImpl<unsigned> &RegList = getRegList();
3906     for (SmallVectorImpl<unsigned>::const_iterator
3907            I = RegList.begin(), E = RegList.end(); I != E; ) {
3908       OS << RegName(*I);
3909       if (++I < E) OS << ", ";
3910     }
3911 
3912     OS << ">";
3913     break;
3914   }
3915   case k_VectorList:
3916     OS << "<vector_list " << VectorList.Count << " * "
3917        << RegName(VectorList.RegNum) << ">";
3918     break;
3919   case k_VectorListAllLanes:
3920     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3921        << RegName(VectorList.RegNum) << ">";
3922     break;
3923   case k_VectorListIndexed:
3924     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3925        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
3926     break;
3927   case k_Token:
3928     OS << "'" << getToken() << "'";
3929     break;
3930   case k_VectorIndex:
3931     OS << "<vectorindex " << getVectorIndex() << ">";
3932     break;
3933   }
3934 }
3935 
3936 /// @name Auto-generated Match Functions
3937 /// {
3938 
3939 static unsigned MatchRegisterName(StringRef Name);
3940 
3941 /// }
3942 
3943 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3944                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3945   const AsmToken &Tok = getParser().getTok();
3946   StartLoc = Tok.getLoc();
3947   EndLoc = Tok.getEndLoc();
3948   RegNo = tryParseRegister();
3949 
3950   return (RegNo == (unsigned)-1);
3951 }
3952 
3953 OperandMatchResultTy ARMAsmParser::tryParseRegister(unsigned &RegNo,
3954                                                     SMLoc &StartLoc,
3955                                                     SMLoc &EndLoc) {
3956   if (ParseRegister(RegNo, StartLoc, EndLoc))
3957     return MatchOperand_NoMatch;
3958   return MatchOperand_Success;
3959 }
3960 
3961 /// Try to parse a register name.  The token must be an Identifier when called,
3962 /// and if it is a register name the token is eaten and the register number is
3963 /// returned.  Otherwise return -1.
3964 int ARMAsmParser::tryParseRegister() {
3965   MCAsmParser &Parser = getParser();
3966   const AsmToken &Tok = Parser.getTok();
3967   if (Tok.isNot(AsmToken::Identifier)) return -1;
3968 
3969   std::string lowerCase = Tok.getString().lower();
3970   unsigned RegNum = MatchRegisterName(lowerCase);
3971   if (!RegNum) {
3972     RegNum = StringSwitch<unsigned>(lowerCase)
3973       .Case("r13", ARM::SP)
3974       .Case("r14", ARM::LR)
3975       .Case("r15", ARM::PC)
3976       .Case("ip", ARM::R12)
3977       // Additional register name aliases for 'gas' compatibility.
3978       .Case("a1", ARM::R0)
3979       .Case("a2", ARM::R1)
3980       .Case("a3", ARM::R2)
3981       .Case("a4", ARM::R3)
3982       .Case("v1", ARM::R4)
3983       .Case("v2", ARM::R5)
3984       .Case("v3", ARM::R6)
3985       .Case("v4", ARM::R7)
3986       .Case("v5", ARM::R8)
3987       .Case("v6", ARM::R9)
3988       .Case("v7", ARM::R10)
3989       .Case("v8", ARM::R11)
3990       .Case("sb", ARM::R9)
3991       .Case("sl", ARM::R10)
3992       .Case("fp", ARM::R11)
3993       .Default(0);
3994   }
3995   if (!RegNum) {
3996     // Check for aliases registered via .req. Canonicalize to lower case.
3997     // That's more consistent since register names are case insensitive, and
3998     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3999     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
4000     // If no match, return failure.
4001     if (Entry == RegisterReqs.end())
4002       return -1;
4003     Parser.Lex(); // Eat identifier token.
4004     return Entry->getValue();
4005   }
4006 
4007   // Some FPUs only have 16 D registers, so D16-D31 are invalid
4008   if (!hasD32() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
4009     return -1;
4010 
4011   Parser.Lex(); // Eat identifier token.
4012 
4013   return RegNum;
4014 }
4015 
4016 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
4017 // If a recoverable error occurs, return 1. If an irrecoverable error
4018 // occurs, return -1. An irrecoverable error is one where tokens have been
4019 // consumed in the process of trying to parse the shifter (i.e., when it is
4020 // indeed a shifter operand, but malformed).
4021 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
4022   MCAsmParser &Parser = getParser();
4023   SMLoc S = Parser.getTok().getLoc();
4024   const AsmToken &Tok = Parser.getTok();
4025   if (Tok.isNot(AsmToken::Identifier))
4026     return -1;
4027 
4028   std::string lowerCase = Tok.getString().lower();
4029   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
4030       .Case("asl", ARM_AM::lsl)
4031       .Case("lsl", ARM_AM::lsl)
4032       .Case("lsr", ARM_AM::lsr)
4033       .Case("asr", ARM_AM::asr)
4034       .Case("ror", ARM_AM::ror)
4035       .Case("rrx", ARM_AM::rrx)
4036       .Default(ARM_AM::no_shift);
4037 
4038   if (ShiftTy == ARM_AM::no_shift)
4039     return 1;
4040 
4041   Parser.Lex(); // Eat the operator.
4042 
4043   // The source register for the shift has already been added to the
4044   // operand list, so we need to pop it off and combine it into the shifted
4045   // register operand instead.
4046   std::unique_ptr<ARMOperand> PrevOp(
4047       (ARMOperand *)Operands.pop_back_val().release());
4048   if (!PrevOp->isReg())
4049     return Error(PrevOp->getStartLoc(), "shift must be of a register");
4050   int SrcReg = PrevOp->getReg();
4051 
4052   SMLoc EndLoc;
4053   int64_t Imm = 0;
4054   int ShiftReg = 0;
4055   if (ShiftTy == ARM_AM::rrx) {
4056     // RRX Doesn't have an explicit shift amount. The encoder expects
4057     // the shift register to be the same as the source register. Seems odd,
4058     // but OK.
4059     ShiftReg = SrcReg;
4060   } else {
4061     // Figure out if this is shifted by a constant or a register (for non-RRX).
4062     if (Parser.getTok().is(AsmToken::Hash) ||
4063         Parser.getTok().is(AsmToken::Dollar)) {
4064       Parser.Lex(); // Eat hash.
4065       SMLoc ImmLoc = Parser.getTok().getLoc();
4066       const MCExpr *ShiftExpr = nullptr;
4067       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
4068         Error(ImmLoc, "invalid immediate shift value");
4069         return -1;
4070       }
4071       // The expression must be evaluatable as an immediate.
4072       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
4073       if (!CE) {
4074         Error(ImmLoc, "invalid immediate shift value");
4075         return -1;
4076       }
4077       // Range check the immediate.
4078       // lsl, ror: 0 <= imm <= 31
4079       // lsr, asr: 0 <= imm <= 32
4080       Imm = CE->getValue();
4081       if (Imm < 0 ||
4082           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
4083           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
4084         Error(ImmLoc, "immediate shift value out of range");
4085         return -1;
4086       }
4087       // shift by zero is a nop. Always send it through as lsl.
4088       // ('as' compatibility)
4089       if (Imm == 0)
4090         ShiftTy = ARM_AM::lsl;
4091     } else if (Parser.getTok().is(AsmToken::Identifier)) {
4092       SMLoc L = Parser.getTok().getLoc();
4093       EndLoc = Parser.getTok().getEndLoc();
4094       ShiftReg = tryParseRegister();
4095       if (ShiftReg == -1) {
4096         Error(L, "expected immediate or register in shift operand");
4097         return -1;
4098       }
4099     } else {
4100       Error(Parser.getTok().getLoc(),
4101             "expected immediate or register in shift operand");
4102       return -1;
4103     }
4104   }
4105 
4106   if (ShiftReg && ShiftTy != ARM_AM::rrx)
4107     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
4108                                                          ShiftReg, Imm,
4109                                                          S, EndLoc));
4110   else
4111     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
4112                                                           S, EndLoc));
4113 
4114   return 0;
4115 }
4116 
4117 /// Try to parse a register name.  The token must be an Identifier when called.
4118 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
4119 /// if there is a "writeback". 'true' if it's not a register.
4120 ///
4121 /// TODO this is likely to change to allow different register types and or to
4122 /// parse for a specific register type.
4123 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
4124   MCAsmParser &Parser = getParser();
4125   SMLoc RegStartLoc = Parser.getTok().getLoc();
4126   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
4127   int RegNo = tryParseRegister();
4128   if (RegNo == -1)
4129     return true;
4130 
4131   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
4132 
4133   const AsmToken &ExclaimTok = Parser.getTok();
4134   if (ExclaimTok.is(AsmToken::Exclaim)) {
4135     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
4136                                                ExclaimTok.getLoc()));
4137     Parser.Lex(); // Eat exclaim token
4138     return false;
4139   }
4140 
4141   // Also check for an index operand. This is only legal for vector registers,
4142   // but that'll get caught OK in operand matching, so we don't need to
4143   // explicitly filter everything else out here.
4144   if (Parser.getTok().is(AsmToken::LBrac)) {
4145     SMLoc SIdx = Parser.getTok().getLoc();
4146     Parser.Lex(); // Eat left bracket token.
4147 
4148     const MCExpr *ImmVal;
4149     if (getParser().parseExpression(ImmVal))
4150       return true;
4151     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
4152     if (!MCE)
4153       return TokError("immediate value expected for vector index");
4154 
4155     if (Parser.getTok().isNot(AsmToken::RBrac))
4156       return Error(Parser.getTok().getLoc(), "']' expected");
4157 
4158     SMLoc E = Parser.getTok().getEndLoc();
4159     Parser.Lex(); // Eat right bracket token.
4160 
4161     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
4162                                                      SIdx, E,
4163                                                      getContext()));
4164   }
4165 
4166   return false;
4167 }
4168 
4169 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
4170 /// instruction with a symbolic operand name.
4171 /// We accept "crN" syntax for GAS compatibility.
4172 /// <operand-name> ::= <prefix><number>
4173 /// If CoprocOp is 'c', then:
4174 ///   <prefix> ::= c | cr
4175 /// If CoprocOp is 'p', then :
4176 ///   <prefix> ::= p
4177 /// <number> ::= integer in range [0, 15]
4178 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
4179   // Use the same layout as the tablegen'erated register name matcher. Ugly,
4180   // but efficient.
4181   if (Name.size() < 2 || Name[0] != CoprocOp)
4182     return -1;
4183   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
4184 
4185   switch (Name.size()) {
4186   default: return -1;
4187   case 1:
4188     switch (Name[0]) {
4189     default:  return -1;
4190     case '0': return 0;
4191     case '1': return 1;
4192     case '2': return 2;
4193     case '3': return 3;
4194     case '4': return 4;
4195     case '5': return 5;
4196     case '6': return 6;
4197     case '7': return 7;
4198     case '8': return 8;
4199     case '9': return 9;
4200     }
4201   case 2:
4202     if (Name[0] != '1')
4203       return -1;
4204     switch (Name[1]) {
4205     default:  return -1;
4206     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
4207     // However, old cores (v5/v6) did use them in that way.
4208     case '0': return 10;
4209     case '1': return 11;
4210     case '2': return 12;
4211     case '3': return 13;
4212     case '4': return 14;
4213     case '5': return 15;
4214     }
4215   }
4216 }
4217 
4218 /// parseITCondCode - Try to parse a condition code for an IT instruction.
4219 OperandMatchResultTy
4220 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
4221   MCAsmParser &Parser = getParser();
4222   SMLoc S = Parser.getTok().getLoc();
4223   const AsmToken &Tok = Parser.getTok();
4224   if (!Tok.is(AsmToken::Identifier))
4225     return MatchOperand_NoMatch;
4226   unsigned CC = ARMCondCodeFromString(Tok.getString());
4227   if (CC == ~0U)
4228     return MatchOperand_NoMatch;
4229   Parser.Lex(); // Eat the token.
4230 
4231   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
4232 
4233   return MatchOperand_Success;
4234 }
4235 
4236 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
4237 /// token must be an Identifier when called, and if it is a coprocessor
4238 /// number, the token is eaten and the operand is added to the operand list.
4239 OperandMatchResultTy
4240 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
4241   MCAsmParser &Parser = getParser();
4242   SMLoc S = Parser.getTok().getLoc();
4243   const AsmToken &Tok = Parser.getTok();
4244   if (Tok.isNot(AsmToken::Identifier))
4245     return MatchOperand_NoMatch;
4246 
4247   int Num = MatchCoprocessorOperandName(Tok.getString().lower(), 'p');
4248   if (Num == -1)
4249     return MatchOperand_NoMatch;
4250   if (!isValidCoprocessorNumber(Num, getSTI().getFeatureBits()))
4251     return MatchOperand_NoMatch;
4252 
4253   Parser.Lex(); // Eat identifier token.
4254   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
4255   return MatchOperand_Success;
4256 }
4257 
4258 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
4259 /// token must be an Identifier when called, and if it is a coprocessor
4260 /// number, the token is eaten and the operand is added to the operand list.
4261 OperandMatchResultTy
4262 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
4263   MCAsmParser &Parser = getParser();
4264   SMLoc S = Parser.getTok().getLoc();
4265   const AsmToken &Tok = Parser.getTok();
4266   if (Tok.isNot(AsmToken::Identifier))
4267     return MatchOperand_NoMatch;
4268 
4269   int Reg = MatchCoprocessorOperandName(Tok.getString().lower(), 'c');
4270   if (Reg == -1)
4271     return MatchOperand_NoMatch;
4272 
4273   Parser.Lex(); // Eat identifier token.
4274   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
4275   return MatchOperand_Success;
4276 }
4277 
4278 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
4279 /// coproc_option : '{' imm0_255 '}'
4280 OperandMatchResultTy
4281 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
4282   MCAsmParser &Parser = getParser();
4283   SMLoc S = Parser.getTok().getLoc();
4284 
4285   // If this isn't a '{', this isn't a coprocessor immediate operand.
4286   if (Parser.getTok().isNot(AsmToken::LCurly))
4287     return MatchOperand_NoMatch;
4288   Parser.Lex(); // Eat the '{'
4289 
4290   const MCExpr *Expr;
4291   SMLoc Loc = Parser.getTok().getLoc();
4292   if (getParser().parseExpression(Expr)) {
4293     Error(Loc, "illegal expression");
4294     return MatchOperand_ParseFail;
4295   }
4296   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4297   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
4298     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
4299     return MatchOperand_ParseFail;
4300   }
4301   int Val = CE->getValue();
4302 
4303   // Check for and consume the closing '}'
4304   if (Parser.getTok().isNot(AsmToken::RCurly))
4305     return MatchOperand_ParseFail;
4306   SMLoc E = Parser.getTok().getEndLoc();
4307   Parser.Lex(); // Eat the '}'
4308 
4309   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
4310   return MatchOperand_Success;
4311 }
4312 
4313 // For register list parsing, we need to map from raw GPR register numbering
4314 // to the enumeration values. The enumeration values aren't sorted by
4315 // register number due to our using "sp", "lr" and "pc" as canonical names.
4316 static unsigned getNextRegister(unsigned Reg) {
4317   // If this is a GPR, we need to do it manually, otherwise we can rely
4318   // on the sort ordering of the enumeration since the other reg-classes
4319   // are sane.
4320   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4321     return Reg + 1;
4322   switch(Reg) {
4323   default: llvm_unreachable("Invalid GPR number!");
4324   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
4325   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
4326   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
4327   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
4328   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
4329   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
4330   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
4331   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
4332   }
4333 }
4334 
4335 // Insert an <Encoding, Register> pair in an ordered vector. Return true on
4336 // success, or false, if duplicate encoding found.
4337 static bool
4338 insertNoDuplicates(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
4339                    unsigned Enc, unsigned Reg) {
4340   Regs.emplace_back(Enc, Reg);
4341   for (auto I = Regs.rbegin(), J = I + 1, E = Regs.rend(); J != E; ++I, ++J) {
4342     if (J->first == Enc) {
4343       Regs.erase(J.base());
4344       return false;
4345     }
4346     if (J->first < Enc)
4347       break;
4348     std::swap(*I, *J);
4349   }
4350   return true;
4351 }
4352 
4353 /// Parse a register list.
4354 bool ARMAsmParser::parseRegisterList(OperandVector &Operands,
4355                                      bool EnforceOrder) {
4356   MCAsmParser &Parser = getParser();
4357   if (Parser.getTok().isNot(AsmToken::LCurly))
4358     return TokError("Token is not a Left Curly Brace");
4359   SMLoc S = Parser.getTok().getLoc();
4360   Parser.Lex(); // Eat '{' token.
4361   SMLoc RegLoc = Parser.getTok().getLoc();
4362 
4363   // Check the first register in the list to see what register class
4364   // this is a list of.
4365   int Reg = tryParseRegister();
4366   if (Reg == -1)
4367     return Error(RegLoc, "register expected");
4368 
4369   // The reglist instructions have at most 16 registers, so reserve
4370   // space for that many.
4371   int EReg = 0;
4372   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
4373 
4374   // Allow Q regs and just interpret them as the two D sub-registers.
4375   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4376     Reg = getDRegFromQReg(Reg);
4377     EReg = MRI->getEncodingValue(Reg);
4378     Registers.emplace_back(EReg, Reg);
4379     ++Reg;
4380   }
4381   const MCRegisterClass *RC;
4382   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4383     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
4384   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
4385     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
4386   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
4387     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
4388   else if (ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4389     RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4390   else
4391     return Error(RegLoc, "invalid register in register list");
4392 
4393   // Store the register.
4394   EReg = MRI->getEncodingValue(Reg);
4395   Registers.emplace_back(EReg, Reg);
4396 
4397   // This starts immediately after the first register token in the list,
4398   // so we can see either a comma or a minus (range separator) as a legal
4399   // next token.
4400   while (Parser.getTok().is(AsmToken::Comma) ||
4401          Parser.getTok().is(AsmToken::Minus)) {
4402     if (Parser.getTok().is(AsmToken::Minus)) {
4403       Parser.Lex(); // Eat the minus.
4404       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4405       int EndReg = tryParseRegister();
4406       if (EndReg == -1)
4407         return Error(AfterMinusLoc, "register expected");
4408       // Allow Q regs and just interpret them as the two D sub-registers.
4409       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4410         EndReg = getDRegFromQReg(EndReg) + 1;
4411       // If the register is the same as the start reg, there's nothing
4412       // more to do.
4413       if (Reg == EndReg)
4414         continue;
4415       // The register must be in the same register class as the first.
4416       if (!RC->contains(EndReg))
4417         return Error(AfterMinusLoc, "invalid register in register list");
4418       // Ranges must go from low to high.
4419       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
4420         return Error(AfterMinusLoc, "bad range in register list");
4421 
4422       // Add all the registers in the range to the register list.
4423       while (Reg != EndReg) {
4424         Reg = getNextRegister(Reg);
4425         EReg = MRI->getEncodingValue(Reg);
4426         if (!insertNoDuplicates(Registers, EReg, Reg)) {
4427           Warning(AfterMinusLoc, StringRef("duplicated register (") +
4428                                      ARMInstPrinter::getRegisterName(Reg) +
4429                                      ") in register list");
4430         }
4431       }
4432       continue;
4433     }
4434     Parser.Lex(); // Eat the comma.
4435     RegLoc = Parser.getTok().getLoc();
4436     int OldReg = Reg;
4437     const AsmToken RegTok = Parser.getTok();
4438     Reg = tryParseRegister();
4439     if (Reg == -1)
4440       return Error(RegLoc, "register expected");
4441     // Allow Q regs and just interpret them as the two D sub-registers.
4442     bool isQReg = false;
4443     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4444       Reg = getDRegFromQReg(Reg);
4445       isQReg = true;
4446     }
4447     if (!RC->contains(Reg) &&
4448         RC->getID() == ARMMCRegisterClasses[ARM::GPRRegClassID].getID() &&
4449         ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg)) {
4450       // switch the register classes, as GPRwithAPSRnospRegClassID is a partial
4451       // subset of GPRRegClassId except it contains APSR as well.
4452       RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4453     }
4454     if (Reg == ARM::VPR &&
4455         (RC == &ARMMCRegisterClasses[ARM::SPRRegClassID] ||
4456          RC == &ARMMCRegisterClasses[ARM::DPRRegClassID] ||
4457          RC == &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID])) {
4458       RC = &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID];
4459       EReg = MRI->getEncodingValue(Reg);
4460       if (!insertNoDuplicates(Registers, EReg, Reg)) {
4461         Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4462                             ") in register list");
4463       }
4464       continue;
4465     }
4466     // The register must be in the same register class as the first.
4467     if (!RC->contains(Reg))
4468       return Error(RegLoc, "invalid register in register list");
4469     // In most cases, the list must be monotonically increasing. An
4470     // exception is CLRM, which is order-independent anyway, so
4471     // there's no potential for confusion if you write clrm {r2,r1}
4472     // instead of clrm {r1,r2}.
4473     if (EnforceOrder &&
4474         MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
4475       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4476         Warning(RegLoc, "register list not in ascending order");
4477       else if (!ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4478         return Error(RegLoc, "register list not in ascending order");
4479     }
4480     // VFP register lists must also be contiguous.
4481     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
4482         RC != &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID] &&
4483         Reg != OldReg + 1)
4484       return Error(RegLoc, "non-contiguous register range");
4485     EReg = MRI->getEncodingValue(Reg);
4486     if (!insertNoDuplicates(Registers, EReg, Reg)) {
4487       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4488                           ") in register list");
4489     }
4490     if (isQReg) {
4491       EReg = MRI->getEncodingValue(++Reg);
4492       Registers.emplace_back(EReg, Reg);
4493     }
4494   }
4495 
4496   if (Parser.getTok().isNot(AsmToken::RCurly))
4497     return Error(Parser.getTok().getLoc(), "'}' expected");
4498   SMLoc E = Parser.getTok().getEndLoc();
4499   Parser.Lex(); // Eat '}' token.
4500 
4501   // Push the register list operand.
4502   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
4503 
4504   // The ARM system instruction variants for LDM/STM have a '^' token here.
4505   if (Parser.getTok().is(AsmToken::Caret)) {
4506     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
4507     Parser.Lex(); // Eat '^' token.
4508   }
4509 
4510   return false;
4511 }
4512 
4513 // Helper function to parse the lane index for vector lists.
4514 OperandMatchResultTy ARMAsmParser::
4515 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
4516   MCAsmParser &Parser = getParser();
4517   Index = 0; // Always return a defined index value.
4518   if (Parser.getTok().is(AsmToken::LBrac)) {
4519     Parser.Lex(); // Eat the '['.
4520     if (Parser.getTok().is(AsmToken::RBrac)) {
4521       // "Dn[]" is the 'all lanes' syntax.
4522       LaneKind = AllLanes;
4523       EndLoc = Parser.getTok().getEndLoc();
4524       Parser.Lex(); // Eat the ']'.
4525       return MatchOperand_Success;
4526     }
4527 
4528     // There's an optional '#' token here. Normally there wouldn't be, but
4529     // inline assemble puts one in, and it's friendly to accept that.
4530     if (Parser.getTok().is(AsmToken::Hash))
4531       Parser.Lex(); // Eat '#' or '$'.
4532 
4533     const MCExpr *LaneIndex;
4534     SMLoc Loc = Parser.getTok().getLoc();
4535     if (getParser().parseExpression(LaneIndex)) {
4536       Error(Loc, "illegal expression");
4537       return MatchOperand_ParseFail;
4538     }
4539     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
4540     if (!CE) {
4541       Error(Loc, "lane index must be empty or an integer");
4542       return MatchOperand_ParseFail;
4543     }
4544     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4545       Error(Parser.getTok().getLoc(), "']' expected");
4546       return MatchOperand_ParseFail;
4547     }
4548     EndLoc = Parser.getTok().getEndLoc();
4549     Parser.Lex(); // Eat the ']'.
4550     int64_t Val = CE->getValue();
4551 
4552     // FIXME: Make this range check context sensitive for .8, .16, .32.
4553     if (Val < 0 || Val > 7) {
4554       Error(Parser.getTok().getLoc(), "lane index out of range");
4555       return MatchOperand_ParseFail;
4556     }
4557     Index = Val;
4558     LaneKind = IndexedLane;
4559     return MatchOperand_Success;
4560   }
4561   LaneKind = NoLanes;
4562   return MatchOperand_Success;
4563 }
4564 
4565 // parse a vector register list
4566 OperandMatchResultTy
4567 ARMAsmParser::parseVectorList(OperandVector &Operands) {
4568   MCAsmParser &Parser = getParser();
4569   VectorLaneTy LaneKind;
4570   unsigned LaneIndex;
4571   SMLoc S = Parser.getTok().getLoc();
4572   // As an extension (to match gas), support a plain D register or Q register
4573   // (without encosing curly braces) as a single or double entry list,
4574   // respectively.
4575   if (!hasMVE() && Parser.getTok().is(AsmToken::Identifier)) {
4576     SMLoc E = Parser.getTok().getEndLoc();
4577     int Reg = tryParseRegister();
4578     if (Reg == -1)
4579       return MatchOperand_NoMatch;
4580     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
4581       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4582       if (Res != MatchOperand_Success)
4583         return Res;
4584       switch (LaneKind) {
4585       case NoLanes:
4586         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
4587         break;
4588       case AllLanes:
4589         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
4590                                                                 S, E));
4591         break;
4592       case IndexedLane:
4593         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
4594                                                                LaneIndex,
4595                                                                false, S, E));
4596         break;
4597       }
4598       return MatchOperand_Success;
4599     }
4600     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4601       Reg = getDRegFromQReg(Reg);
4602       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4603       if (Res != MatchOperand_Success)
4604         return Res;
4605       switch (LaneKind) {
4606       case NoLanes:
4607         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4608                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4609         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
4610         break;
4611       case AllLanes:
4612         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4613                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4614         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
4615                                                                 S, E));
4616         break;
4617       case IndexedLane:
4618         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
4619                                                                LaneIndex,
4620                                                                false, S, E));
4621         break;
4622       }
4623       return MatchOperand_Success;
4624     }
4625     Error(S, "vector register expected");
4626     return MatchOperand_ParseFail;
4627   }
4628 
4629   if (Parser.getTok().isNot(AsmToken::LCurly))
4630     return MatchOperand_NoMatch;
4631 
4632   Parser.Lex(); // Eat '{' token.
4633   SMLoc RegLoc = Parser.getTok().getLoc();
4634 
4635   int Reg = tryParseRegister();
4636   if (Reg == -1) {
4637     Error(RegLoc, "register expected");
4638     return MatchOperand_ParseFail;
4639   }
4640   unsigned Count = 1;
4641   int Spacing = 0;
4642   unsigned FirstReg = Reg;
4643 
4644   if (hasMVE() && !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4645       Error(Parser.getTok().getLoc(), "vector register in range Q0-Q7 expected");
4646       return MatchOperand_ParseFail;
4647   }
4648   // The list is of D registers, but we also allow Q regs and just interpret
4649   // them as the two D sub-registers.
4650   else if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4651     FirstReg = Reg = getDRegFromQReg(Reg);
4652     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4653                  // it's ambiguous with four-register single spaced.
4654     ++Reg;
4655     ++Count;
4656   }
4657 
4658   SMLoc E;
4659   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4660     return MatchOperand_ParseFail;
4661 
4662   while (Parser.getTok().is(AsmToken::Comma) ||
4663          Parser.getTok().is(AsmToken::Minus)) {
4664     if (Parser.getTok().is(AsmToken::Minus)) {
4665       if (!Spacing)
4666         Spacing = 1; // Register range implies a single spaced list.
4667       else if (Spacing == 2) {
4668         Error(Parser.getTok().getLoc(),
4669               "sequential registers in double spaced list");
4670         return MatchOperand_ParseFail;
4671       }
4672       Parser.Lex(); // Eat the minus.
4673       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4674       int EndReg = tryParseRegister();
4675       if (EndReg == -1) {
4676         Error(AfterMinusLoc, "register expected");
4677         return MatchOperand_ParseFail;
4678       }
4679       // Allow Q regs and just interpret them as the two D sub-registers.
4680       if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4681         EndReg = getDRegFromQReg(EndReg) + 1;
4682       // If the register is the same as the start reg, there's nothing
4683       // more to do.
4684       if (Reg == EndReg)
4685         continue;
4686       // The register must be in the same register class as the first.
4687       if ((hasMVE() &&
4688            !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(EndReg)) ||
4689           (!hasMVE() &&
4690            !ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg))) {
4691         Error(AfterMinusLoc, "invalid register in register list");
4692         return MatchOperand_ParseFail;
4693       }
4694       // Ranges must go from low to high.
4695       if (Reg > EndReg) {
4696         Error(AfterMinusLoc, "bad range in register list");
4697         return MatchOperand_ParseFail;
4698       }
4699       // Parse the lane specifier if present.
4700       VectorLaneTy NextLaneKind;
4701       unsigned NextLaneIndex;
4702       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4703           MatchOperand_Success)
4704         return MatchOperand_ParseFail;
4705       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4706         Error(AfterMinusLoc, "mismatched lane index in register list");
4707         return MatchOperand_ParseFail;
4708       }
4709 
4710       // Add all the registers in the range to the register list.
4711       Count += EndReg - Reg;
4712       Reg = EndReg;
4713       continue;
4714     }
4715     Parser.Lex(); // Eat the comma.
4716     RegLoc = Parser.getTok().getLoc();
4717     int OldReg = Reg;
4718     Reg = tryParseRegister();
4719     if (Reg == -1) {
4720       Error(RegLoc, "register expected");
4721       return MatchOperand_ParseFail;
4722     }
4723 
4724     if (hasMVE()) {
4725       if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4726         Error(RegLoc, "vector register in range Q0-Q7 expected");
4727         return MatchOperand_ParseFail;
4728       }
4729       Spacing = 1;
4730     }
4731     // vector register lists must be contiguous.
4732     // It's OK to use the enumeration values directly here rather, as the
4733     // VFP register classes have the enum sorted properly.
4734     //
4735     // The list is of D registers, but we also allow Q regs and just interpret
4736     // them as the two D sub-registers.
4737     else if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4738       if (!Spacing)
4739         Spacing = 1; // Register range implies a single spaced list.
4740       else if (Spacing == 2) {
4741         Error(RegLoc,
4742               "invalid register in double-spaced list (must be 'D' register')");
4743         return MatchOperand_ParseFail;
4744       }
4745       Reg = getDRegFromQReg(Reg);
4746       if (Reg != OldReg + 1) {
4747         Error(RegLoc, "non-contiguous register range");
4748         return MatchOperand_ParseFail;
4749       }
4750       ++Reg;
4751       Count += 2;
4752       // Parse the lane specifier if present.
4753       VectorLaneTy NextLaneKind;
4754       unsigned NextLaneIndex;
4755       SMLoc LaneLoc = Parser.getTok().getLoc();
4756       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4757           MatchOperand_Success)
4758         return MatchOperand_ParseFail;
4759       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4760         Error(LaneLoc, "mismatched lane index in register list");
4761         return MatchOperand_ParseFail;
4762       }
4763       continue;
4764     }
4765     // Normal D register.
4766     // Figure out the register spacing (single or double) of the list if
4767     // we don't know it already.
4768     if (!Spacing)
4769       Spacing = 1 + (Reg == OldReg + 2);
4770 
4771     // Just check that it's contiguous and keep going.
4772     if (Reg != OldReg + Spacing) {
4773       Error(RegLoc, "non-contiguous register range");
4774       return MatchOperand_ParseFail;
4775     }
4776     ++Count;
4777     // Parse the lane specifier if present.
4778     VectorLaneTy NextLaneKind;
4779     unsigned NextLaneIndex;
4780     SMLoc EndLoc = Parser.getTok().getLoc();
4781     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4782       return MatchOperand_ParseFail;
4783     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4784       Error(EndLoc, "mismatched lane index in register list");
4785       return MatchOperand_ParseFail;
4786     }
4787   }
4788 
4789   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4790     Error(Parser.getTok().getLoc(), "'}' expected");
4791     return MatchOperand_ParseFail;
4792   }
4793   E = Parser.getTok().getEndLoc();
4794   Parser.Lex(); // Eat '}' token.
4795 
4796   switch (LaneKind) {
4797   case NoLanes:
4798   case AllLanes: {
4799     // Two-register operands have been converted to the
4800     // composite register classes.
4801     if (Count == 2 && !hasMVE()) {
4802       const MCRegisterClass *RC = (Spacing == 1) ?
4803         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4804         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4805       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4806     }
4807     auto Create = (LaneKind == NoLanes ? ARMOperand::CreateVectorList :
4808                    ARMOperand::CreateVectorListAllLanes);
4809     Operands.push_back(Create(FirstReg, Count, (Spacing == 2), S, E));
4810     break;
4811   }
4812   case IndexedLane:
4813     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4814                                                            LaneIndex,
4815                                                            (Spacing == 2),
4816                                                            S, E));
4817     break;
4818   }
4819   return MatchOperand_Success;
4820 }
4821 
4822 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4823 OperandMatchResultTy
4824 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4825   MCAsmParser &Parser = getParser();
4826   SMLoc S = Parser.getTok().getLoc();
4827   const AsmToken &Tok = Parser.getTok();
4828   unsigned Opt;
4829 
4830   if (Tok.is(AsmToken::Identifier)) {
4831     StringRef OptStr = Tok.getString();
4832 
4833     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4834       .Case("sy",    ARM_MB::SY)
4835       .Case("st",    ARM_MB::ST)
4836       .Case("ld",    ARM_MB::LD)
4837       .Case("sh",    ARM_MB::ISH)
4838       .Case("ish",   ARM_MB::ISH)
4839       .Case("shst",  ARM_MB::ISHST)
4840       .Case("ishst", ARM_MB::ISHST)
4841       .Case("ishld", ARM_MB::ISHLD)
4842       .Case("nsh",   ARM_MB::NSH)
4843       .Case("un",    ARM_MB::NSH)
4844       .Case("nshst", ARM_MB::NSHST)
4845       .Case("nshld", ARM_MB::NSHLD)
4846       .Case("unst",  ARM_MB::NSHST)
4847       .Case("osh",   ARM_MB::OSH)
4848       .Case("oshst", ARM_MB::OSHST)
4849       .Case("oshld", ARM_MB::OSHLD)
4850       .Default(~0U);
4851 
4852     // ishld, oshld, nshld and ld are only available from ARMv8.
4853     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4854                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4855       Opt = ~0U;
4856 
4857     if (Opt == ~0U)
4858       return MatchOperand_NoMatch;
4859 
4860     Parser.Lex(); // Eat identifier token.
4861   } else if (Tok.is(AsmToken::Hash) ||
4862              Tok.is(AsmToken::Dollar) ||
4863              Tok.is(AsmToken::Integer)) {
4864     if (Parser.getTok().isNot(AsmToken::Integer))
4865       Parser.Lex(); // Eat '#' or '$'.
4866     SMLoc Loc = Parser.getTok().getLoc();
4867 
4868     const MCExpr *MemBarrierID;
4869     if (getParser().parseExpression(MemBarrierID)) {
4870       Error(Loc, "illegal expression");
4871       return MatchOperand_ParseFail;
4872     }
4873 
4874     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4875     if (!CE) {
4876       Error(Loc, "constant expression expected");
4877       return MatchOperand_ParseFail;
4878     }
4879 
4880     int Val = CE->getValue();
4881     if (Val & ~0xf) {
4882       Error(Loc, "immediate value out of range");
4883       return MatchOperand_ParseFail;
4884     }
4885 
4886     Opt = ARM_MB::RESERVED_0 + Val;
4887   } else
4888     return MatchOperand_ParseFail;
4889 
4890   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4891   return MatchOperand_Success;
4892 }
4893 
4894 OperandMatchResultTy
4895 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
4896   MCAsmParser &Parser = getParser();
4897   SMLoc S = Parser.getTok().getLoc();
4898   const AsmToken &Tok = Parser.getTok();
4899 
4900   if (Tok.isNot(AsmToken::Identifier))
4901      return MatchOperand_NoMatch;
4902 
4903   if (!Tok.getString().equals_lower("csync"))
4904     return MatchOperand_NoMatch;
4905 
4906   Parser.Lex(); // Eat identifier token.
4907 
4908   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
4909   return MatchOperand_Success;
4910 }
4911 
4912 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4913 OperandMatchResultTy
4914 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4915   MCAsmParser &Parser = getParser();
4916   SMLoc S = Parser.getTok().getLoc();
4917   const AsmToken &Tok = Parser.getTok();
4918   unsigned Opt;
4919 
4920   if (Tok.is(AsmToken::Identifier)) {
4921     StringRef OptStr = Tok.getString();
4922 
4923     if (OptStr.equals_lower("sy"))
4924       Opt = ARM_ISB::SY;
4925     else
4926       return MatchOperand_NoMatch;
4927 
4928     Parser.Lex(); // Eat identifier token.
4929   } else if (Tok.is(AsmToken::Hash) ||
4930              Tok.is(AsmToken::Dollar) ||
4931              Tok.is(AsmToken::Integer)) {
4932     if (Parser.getTok().isNot(AsmToken::Integer))
4933       Parser.Lex(); // Eat '#' or '$'.
4934     SMLoc Loc = Parser.getTok().getLoc();
4935 
4936     const MCExpr *ISBarrierID;
4937     if (getParser().parseExpression(ISBarrierID)) {
4938       Error(Loc, "illegal expression");
4939       return MatchOperand_ParseFail;
4940     }
4941 
4942     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4943     if (!CE) {
4944       Error(Loc, "constant expression expected");
4945       return MatchOperand_ParseFail;
4946     }
4947 
4948     int Val = CE->getValue();
4949     if (Val & ~0xf) {
4950       Error(Loc, "immediate value out of range");
4951       return MatchOperand_ParseFail;
4952     }
4953 
4954     Opt = ARM_ISB::RESERVED_0 + Val;
4955   } else
4956     return MatchOperand_ParseFail;
4957 
4958   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4959           (ARM_ISB::InstSyncBOpt)Opt, S));
4960   return MatchOperand_Success;
4961 }
4962 
4963 
4964 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4965 OperandMatchResultTy
4966 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4967   MCAsmParser &Parser = getParser();
4968   SMLoc S = Parser.getTok().getLoc();
4969   const AsmToken &Tok = Parser.getTok();
4970   if (!Tok.is(AsmToken::Identifier))
4971     return MatchOperand_NoMatch;
4972   StringRef IFlagsStr = Tok.getString();
4973 
4974   // An iflags string of "none" is interpreted to mean that none of the AIF
4975   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4976   unsigned IFlags = 0;
4977   if (IFlagsStr != "none") {
4978         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4979       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4980         .Case("a", ARM_PROC::A)
4981         .Case("i", ARM_PROC::I)
4982         .Case("f", ARM_PROC::F)
4983         .Default(~0U);
4984 
4985       // If some specific iflag is already set, it means that some letter is
4986       // present more than once, this is not acceptable.
4987       if (Flag == ~0U || (IFlags & Flag))
4988         return MatchOperand_NoMatch;
4989 
4990       IFlags |= Flag;
4991     }
4992   }
4993 
4994   Parser.Lex(); // Eat identifier token.
4995   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4996   return MatchOperand_Success;
4997 }
4998 
4999 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
5000 OperandMatchResultTy
5001 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
5002   MCAsmParser &Parser = getParser();
5003   SMLoc S = Parser.getTok().getLoc();
5004   const AsmToken &Tok = Parser.getTok();
5005 
5006   if (Tok.is(AsmToken::Integer)) {
5007     int64_t Val = Tok.getIntVal();
5008     if (Val > 255 || Val < 0) {
5009       return MatchOperand_NoMatch;
5010     }
5011     unsigned SYSmvalue = Val & 0xFF;
5012     Parser.Lex();
5013     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5014     return MatchOperand_Success;
5015   }
5016 
5017   if (!Tok.is(AsmToken::Identifier))
5018     return MatchOperand_NoMatch;
5019   StringRef Mask = Tok.getString();
5020 
5021   if (isMClass()) {
5022     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
5023     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
5024       return MatchOperand_NoMatch;
5025 
5026     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
5027 
5028     Parser.Lex(); // Eat identifier token.
5029     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5030     return MatchOperand_Success;
5031   }
5032 
5033   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
5034   size_t Start = 0, Next = Mask.find('_');
5035   StringRef Flags = "";
5036   std::string SpecReg = Mask.slice(Start, Next).lower();
5037   if (Next != StringRef::npos)
5038     Flags = Mask.slice(Next+1, Mask.size());
5039 
5040   // FlagsVal contains the complete mask:
5041   // 3-0: Mask
5042   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5043   unsigned FlagsVal = 0;
5044 
5045   if (SpecReg == "apsr") {
5046     FlagsVal = StringSwitch<unsigned>(Flags)
5047     .Case("nzcvq",  0x8) // same as CPSR_f
5048     .Case("g",      0x4) // same as CPSR_s
5049     .Case("nzcvqg", 0xc) // same as CPSR_fs
5050     .Default(~0U);
5051 
5052     if (FlagsVal == ~0U) {
5053       if (!Flags.empty())
5054         return MatchOperand_NoMatch;
5055       else
5056         FlagsVal = 8; // No flag
5057     }
5058   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
5059     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
5060     if (Flags == "all" || Flags == "")
5061       Flags = "fc";
5062     for (int i = 0, e = Flags.size(); i != e; ++i) {
5063       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
5064       .Case("c", 1)
5065       .Case("x", 2)
5066       .Case("s", 4)
5067       .Case("f", 8)
5068       .Default(~0U);
5069 
5070       // If some specific flag is already set, it means that some letter is
5071       // present more than once, this is not acceptable.
5072       if (Flag == ~0U || (FlagsVal & Flag))
5073         return MatchOperand_NoMatch;
5074       FlagsVal |= Flag;
5075     }
5076   } else // No match for special register.
5077     return MatchOperand_NoMatch;
5078 
5079   // Special register without flags is NOT equivalent to "fc" flags.
5080   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
5081   // two lines would enable gas compatibility at the expense of breaking
5082   // round-tripping.
5083   //
5084   // if (!FlagsVal)
5085   //  FlagsVal = 0x9;
5086 
5087   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5088   if (SpecReg == "spsr")
5089     FlagsVal |= 16;
5090 
5091   Parser.Lex(); // Eat identifier token.
5092   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
5093   return MatchOperand_Success;
5094 }
5095 
5096 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
5097 /// use in the MRS/MSR instructions added to support virtualization.
5098 OperandMatchResultTy
5099 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
5100   MCAsmParser &Parser = getParser();
5101   SMLoc S = Parser.getTok().getLoc();
5102   const AsmToken &Tok = Parser.getTok();
5103   if (!Tok.is(AsmToken::Identifier))
5104     return MatchOperand_NoMatch;
5105   StringRef RegName = Tok.getString();
5106 
5107   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
5108   if (!TheReg)
5109     return MatchOperand_NoMatch;
5110   unsigned Encoding = TheReg->Encoding;
5111 
5112   Parser.Lex(); // Eat identifier token.
5113   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
5114   return MatchOperand_Success;
5115 }
5116 
5117 OperandMatchResultTy
5118 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
5119                           int High) {
5120   MCAsmParser &Parser = getParser();
5121   const AsmToken &Tok = Parser.getTok();
5122   if (Tok.isNot(AsmToken::Identifier)) {
5123     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5124     return MatchOperand_ParseFail;
5125   }
5126   StringRef ShiftName = Tok.getString();
5127   std::string LowerOp = Op.lower();
5128   std::string UpperOp = Op.upper();
5129   if (ShiftName != LowerOp && ShiftName != UpperOp) {
5130     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5131     return MatchOperand_ParseFail;
5132   }
5133   Parser.Lex(); // Eat shift type token.
5134 
5135   // There must be a '#' and a shift amount.
5136   if (Parser.getTok().isNot(AsmToken::Hash) &&
5137       Parser.getTok().isNot(AsmToken::Dollar)) {
5138     Error(Parser.getTok().getLoc(), "'#' expected");
5139     return MatchOperand_ParseFail;
5140   }
5141   Parser.Lex(); // Eat hash token.
5142 
5143   const MCExpr *ShiftAmount;
5144   SMLoc Loc = Parser.getTok().getLoc();
5145   SMLoc EndLoc;
5146   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5147     Error(Loc, "illegal expression");
5148     return MatchOperand_ParseFail;
5149   }
5150   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5151   if (!CE) {
5152     Error(Loc, "constant expression expected");
5153     return MatchOperand_ParseFail;
5154   }
5155   int Val = CE->getValue();
5156   if (Val < Low || Val > High) {
5157     Error(Loc, "immediate value out of range");
5158     return MatchOperand_ParseFail;
5159   }
5160 
5161   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
5162 
5163   return MatchOperand_Success;
5164 }
5165 
5166 OperandMatchResultTy
5167 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
5168   MCAsmParser &Parser = getParser();
5169   const AsmToken &Tok = Parser.getTok();
5170   SMLoc S = Tok.getLoc();
5171   if (Tok.isNot(AsmToken::Identifier)) {
5172     Error(S, "'be' or 'le' operand expected");
5173     return MatchOperand_ParseFail;
5174   }
5175   int Val = StringSwitch<int>(Tok.getString().lower())
5176     .Case("be", 1)
5177     .Case("le", 0)
5178     .Default(-1);
5179   Parser.Lex(); // Eat the token.
5180 
5181   if (Val == -1) {
5182     Error(S, "'be' or 'le' operand expected");
5183     return MatchOperand_ParseFail;
5184   }
5185   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
5186                                                                   getContext()),
5187                                            S, Tok.getEndLoc()));
5188   return MatchOperand_Success;
5189 }
5190 
5191 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
5192 /// instructions. Legal values are:
5193 ///     lsl #n  'n' in [0,31]
5194 ///     asr #n  'n' in [1,32]
5195 ///             n == 32 encoded as n == 0.
5196 OperandMatchResultTy
5197 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
5198   MCAsmParser &Parser = getParser();
5199   const AsmToken &Tok = Parser.getTok();
5200   SMLoc S = Tok.getLoc();
5201   if (Tok.isNot(AsmToken::Identifier)) {
5202     Error(S, "shift operator 'asr' or 'lsl' expected");
5203     return MatchOperand_ParseFail;
5204   }
5205   StringRef ShiftName = Tok.getString();
5206   bool isASR;
5207   if (ShiftName == "lsl" || ShiftName == "LSL")
5208     isASR = false;
5209   else if (ShiftName == "asr" || ShiftName == "ASR")
5210     isASR = true;
5211   else {
5212     Error(S, "shift operator 'asr' or 'lsl' expected");
5213     return MatchOperand_ParseFail;
5214   }
5215   Parser.Lex(); // Eat the operator.
5216 
5217   // A '#' and a shift amount.
5218   if (Parser.getTok().isNot(AsmToken::Hash) &&
5219       Parser.getTok().isNot(AsmToken::Dollar)) {
5220     Error(Parser.getTok().getLoc(), "'#' expected");
5221     return MatchOperand_ParseFail;
5222   }
5223   Parser.Lex(); // Eat hash token.
5224   SMLoc ExLoc = Parser.getTok().getLoc();
5225 
5226   const MCExpr *ShiftAmount;
5227   SMLoc EndLoc;
5228   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5229     Error(ExLoc, "malformed shift expression");
5230     return MatchOperand_ParseFail;
5231   }
5232   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5233   if (!CE) {
5234     Error(ExLoc, "shift amount must be an immediate");
5235     return MatchOperand_ParseFail;
5236   }
5237 
5238   int64_t Val = CE->getValue();
5239   if (isASR) {
5240     // Shift amount must be in [1,32]
5241     if (Val < 1 || Val > 32) {
5242       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
5243       return MatchOperand_ParseFail;
5244     }
5245     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
5246     if (isThumb() && Val == 32) {
5247       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
5248       return MatchOperand_ParseFail;
5249     }
5250     if (Val == 32) Val = 0;
5251   } else {
5252     // Shift amount must be in [1,32]
5253     if (Val < 0 || Val > 31) {
5254       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
5255       return MatchOperand_ParseFail;
5256     }
5257   }
5258 
5259   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
5260 
5261   return MatchOperand_Success;
5262 }
5263 
5264 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
5265 /// of instructions. Legal values are:
5266 ///     ror #n  'n' in {0, 8, 16, 24}
5267 OperandMatchResultTy
5268 ARMAsmParser::parseRotImm(OperandVector &Operands) {
5269   MCAsmParser &Parser = getParser();
5270   const AsmToken &Tok = Parser.getTok();
5271   SMLoc S = Tok.getLoc();
5272   if (Tok.isNot(AsmToken::Identifier))
5273     return MatchOperand_NoMatch;
5274   StringRef ShiftName = Tok.getString();
5275   if (ShiftName != "ror" && ShiftName != "ROR")
5276     return MatchOperand_NoMatch;
5277   Parser.Lex(); // Eat the operator.
5278 
5279   // A '#' and a rotate amount.
5280   if (Parser.getTok().isNot(AsmToken::Hash) &&
5281       Parser.getTok().isNot(AsmToken::Dollar)) {
5282     Error(Parser.getTok().getLoc(), "'#' expected");
5283     return MatchOperand_ParseFail;
5284   }
5285   Parser.Lex(); // Eat hash token.
5286   SMLoc ExLoc = Parser.getTok().getLoc();
5287 
5288   const MCExpr *ShiftAmount;
5289   SMLoc EndLoc;
5290   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5291     Error(ExLoc, "malformed rotate expression");
5292     return MatchOperand_ParseFail;
5293   }
5294   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5295   if (!CE) {
5296     Error(ExLoc, "rotate amount must be an immediate");
5297     return MatchOperand_ParseFail;
5298   }
5299 
5300   int64_t Val = CE->getValue();
5301   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
5302   // normally, zero is represented in asm by omitting the rotate operand
5303   // entirely.
5304   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
5305     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
5306     return MatchOperand_ParseFail;
5307   }
5308 
5309   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
5310 
5311   return MatchOperand_Success;
5312 }
5313 
5314 OperandMatchResultTy
5315 ARMAsmParser::parseModImm(OperandVector &Operands) {
5316   MCAsmParser &Parser = getParser();
5317   MCAsmLexer &Lexer = getLexer();
5318   int64_t Imm1, Imm2;
5319 
5320   SMLoc S = Parser.getTok().getLoc();
5321 
5322   // 1) A mod_imm operand can appear in the place of a register name:
5323   //   add r0, #mod_imm
5324   //   add r0, r0, #mod_imm
5325   // to correctly handle the latter, we bail out as soon as we see an
5326   // identifier.
5327   //
5328   // 2) Similarly, we do not want to parse into complex operands:
5329   //   mov r0, #mod_imm
5330   //   mov r0, :lower16:(_foo)
5331   if (Parser.getTok().is(AsmToken::Identifier) ||
5332       Parser.getTok().is(AsmToken::Colon))
5333     return MatchOperand_NoMatch;
5334 
5335   // Hash (dollar) is optional as per the ARMARM
5336   if (Parser.getTok().is(AsmToken::Hash) ||
5337       Parser.getTok().is(AsmToken::Dollar)) {
5338     // Avoid parsing into complex operands (#:)
5339     if (Lexer.peekTok().is(AsmToken::Colon))
5340       return MatchOperand_NoMatch;
5341 
5342     // Eat the hash (dollar)
5343     Parser.Lex();
5344   }
5345 
5346   SMLoc Sx1, Ex1;
5347   Sx1 = Parser.getTok().getLoc();
5348   const MCExpr *Imm1Exp;
5349   if (getParser().parseExpression(Imm1Exp, Ex1)) {
5350     Error(Sx1, "malformed expression");
5351     return MatchOperand_ParseFail;
5352   }
5353 
5354   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
5355 
5356   if (CE) {
5357     // Immediate must fit within 32-bits
5358     Imm1 = CE->getValue();
5359     int Enc = ARM_AM::getSOImmVal(Imm1);
5360     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
5361       // We have a match!
5362       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
5363                                                   (Enc & 0xF00) >> 7,
5364                                                   Sx1, Ex1));
5365       return MatchOperand_Success;
5366     }
5367 
5368     // We have parsed an immediate which is not for us, fallback to a plain
5369     // immediate. This can happen for instruction aliases. For an example,
5370     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
5371     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
5372     // instruction with a mod_imm operand. The alias is defined such that the
5373     // parser method is shared, that's why we have to do this here.
5374     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
5375       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5376       return MatchOperand_Success;
5377     }
5378   } else {
5379     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
5380     // MCFixup). Fallback to a plain immediate.
5381     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5382     return MatchOperand_Success;
5383   }
5384 
5385   // From this point onward, we expect the input to be a (#bits, #rot) pair
5386   if (Parser.getTok().isNot(AsmToken::Comma)) {
5387     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
5388     return MatchOperand_ParseFail;
5389   }
5390 
5391   if (Imm1 & ~0xFF) {
5392     Error(Sx1, "immediate operand must a number in the range [0, 255]");
5393     return MatchOperand_ParseFail;
5394   }
5395 
5396   // Eat the comma
5397   Parser.Lex();
5398 
5399   // Repeat for #rot
5400   SMLoc Sx2, Ex2;
5401   Sx2 = Parser.getTok().getLoc();
5402 
5403   // Eat the optional hash (dollar)
5404   if (Parser.getTok().is(AsmToken::Hash) ||
5405       Parser.getTok().is(AsmToken::Dollar))
5406     Parser.Lex();
5407 
5408   const MCExpr *Imm2Exp;
5409   if (getParser().parseExpression(Imm2Exp, Ex2)) {
5410     Error(Sx2, "malformed expression");
5411     return MatchOperand_ParseFail;
5412   }
5413 
5414   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
5415 
5416   if (CE) {
5417     Imm2 = CE->getValue();
5418     if (!(Imm2 & ~0x1E)) {
5419       // We have a match!
5420       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
5421       return MatchOperand_Success;
5422     }
5423     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
5424     return MatchOperand_ParseFail;
5425   } else {
5426     Error(Sx2, "constant expression expected");
5427     return MatchOperand_ParseFail;
5428   }
5429 }
5430 
5431 OperandMatchResultTy
5432 ARMAsmParser::parseBitfield(OperandVector &Operands) {
5433   MCAsmParser &Parser = getParser();
5434   SMLoc S = Parser.getTok().getLoc();
5435   // The bitfield descriptor is really two operands, the LSB and the width.
5436   if (Parser.getTok().isNot(AsmToken::Hash) &&
5437       Parser.getTok().isNot(AsmToken::Dollar)) {
5438     Error(Parser.getTok().getLoc(), "'#' expected");
5439     return MatchOperand_ParseFail;
5440   }
5441   Parser.Lex(); // Eat hash token.
5442 
5443   const MCExpr *LSBExpr;
5444   SMLoc E = Parser.getTok().getLoc();
5445   if (getParser().parseExpression(LSBExpr)) {
5446     Error(E, "malformed immediate expression");
5447     return MatchOperand_ParseFail;
5448   }
5449   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
5450   if (!CE) {
5451     Error(E, "'lsb' operand must be an immediate");
5452     return MatchOperand_ParseFail;
5453   }
5454 
5455   int64_t LSB = CE->getValue();
5456   // The LSB must be in the range [0,31]
5457   if (LSB < 0 || LSB > 31) {
5458     Error(E, "'lsb' operand must be in the range [0,31]");
5459     return MatchOperand_ParseFail;
5460   }
5461   E = Parser.getTok().getLoc();
5462 
5463   // Expect another immediate operand.
5464   if (Parser.getTok().isNot(AsmToken::Comma)) {
5465     Error(Parser.getTok().getLoc(), "too few operands");
5466     return MatchOperand_ParseFail;
5467   }
5468   Parser.Lex(); // Eat hash token.
5469   if (Parser.getTok().isNot(AsmToken::Hash) &&
5470       Parser.getTok().isNot(AsmToken::Dollar)) {
5471     Error(Parser.getTok().getLoc(), "'#' expected");
5472     return MatchOperand_ParseFail;
5473   }
5474   Parser.Lex(); // Eat hash token.
5475 
5476   const MCExpr *WidthExpr;
5477   SMLoc EndLoc;
5478   if (getParser().parseExpression(WidthExpr, EndLoc)) {
5479     Error(E, "malformed immediate expression");
5480     return MatchOperand_ParseFail;
5481   }
5482   CE = dyn_cast<MCConstantExpr>(WidthExpr);
5483   if (!CE) {
5484     Error(E, "'width' operand must be an immediate");
5485     return MatchOperand_ParseFail;
5486   }
5487 
5488   int64_t Width = CE->getValue();
5489   // The LSB must be in the range [1,32-lsb]
5490   if (Width < 1 || Width > 32 - LSB) {
5491     Error(E, "'width' operand must be in the range [1,32-lsb]");
5492     return MatchOperand_ParseFail;
5493   }
5494 
5495   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
5496 
5497   return MatchOperand_Success;
5498 }
5499 
5500 OperandMatchResultTy
5501 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
5502   // Check for a post-index addressing register operand. Specifically:
5503   // postidx_reg := '+' register {, shift}
5504   //              | '-' register {, shift}
5505   //              | register {, shift}
5506 
5507   // This method must return MatchOperand_NoMatch without consuming any tokens
5508   // in the case where there is no match, as other alternatives take other
5509   // parse methods.
5510   MCAsmParser &Parser = getParser();
5511   AsmToken Tok = Parser.getTok();
5512   SMLoc S = Tok.getLoc();
5513   bool haveEaten = false;
5514   bool isAdd = true;
5515   if (Tok.is(AsmToken::Plus)) {
5516     Parser.Lex(); // Eat the '+' token.
5517     haveEaten = true;
5518   } else if (Tok.is(AsmToken::Minus)) {
5519     Parser.Lex(); // Eat the '-' token.
5520     isAdd = false;
5521     haveEaten = true;
5522   }
5523 
5524   SMLoc E = Parser.getTok().getEndLoc();
5525   int Reg = tryParseRegister();
5526   if (Reg == -1) {
5527     if (!haveEaten)
5528       return MatchOperand_NoMatch;
5529     Error(Parser.getTok().getLoc(), "register expected");
5530     return MatchOperand_ParseFail;
5531   }
5532 
5533   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
5534   unsigned ShiftImm = 0;
5535   if (Parser.getTok().is(AsmToken::Comma)) {
5536     Parser.Lex(); // Eat the ','.
5537     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
5538       return MatchOperand_ParseFail;
5539 
5540     // FIXME: Only approximates end...may include intervening whitespace.
5541     E = Parser.getTok().getLoc();
5542   }
5543 
5544   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
5545                                                   ShiftImm, S, E));
5546 
5547   return MatchOperand_Success;
5548 }
5549 
5550 OperandMatchResultTy
5551 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
5552   // Check for a post-index addressing register operand. Specifically:
5553   // am3offset := '+' register
5554   //              | '-' register
5555   //              | register
5556   //              | # imm
5557   //              | # + imm
5558   //              | # - imm
5559 
5560   // This method must return MatchOperand_NoMatch without consuming any tokens
5561   // in the case where there is no match, as other alternatives take other
5562   // parse methods.
5563   MCAsmParser &Parser = getParser();
5564   AsmToken Tok = Parser.getTok();
5565   SMLoc S = Tok.getLoc();
5566 
5567   // Do immediates first, as we always parse those if we have a '#'.
5568   if (Parser.getTok().is(AsmToken::Hash) ||
5569       Parser.getTok().is(AsmToken::Dollar)) {
5570     Parser.Lex(); // Eat '#' or '$'.
5571     // Explicitly look for a '-', as we need to encode negative zero
5572     // differently.
5573     bool isNegative = Parser.getTok().is(AsmToken::Minus);
5574     const MCExpr *Offset;
5575     SMLoc E;
5576     if (getParser().parseExpression(Offset, E))
5577       return MatchOperand_ParseFail;
5578     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5579     if (!CE) {
5580       Error(S, "constant expression expected");
5581       return MatchOperand_ParseFail;
5582     }
5583     // Negative zero is encoded as the flag value
5584     // std::numeric_limits<int32_t>::min().
5585     int32_t Val = CE->getValue();
5586     if (isNegative && Val == 0)
5587       Val = std::numeric_limits<int32_t>::min();
5588 
5589     Operands.push_back(
5590       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
5591 
5592     return MatchOperand_Success;
5593   }
5594 
5595   bool haveEaten = false;
5596   bool isAdd = true;
5597   if (Tok.is(AsmToken::Plus)) {
5598     Parser.Lex(); // Eat the '+' token.
5599     haveEaten = true;
5600   } else if (Tok.is(AsmToken::Minus)) {
5601     Parser.Lex(); // Eat the '-' token.
5602     isAdd = false;
5603     haveEaten = true;
5604   }
5605 
5606   Tok = Parser.getTok();
5607   int Reg = tryParseRegister();
5608   if (Reg == -1) {
5609     if (!haveEaten)
5610       return MatchOperand_NoMatch;
5611     Error(Tok.getLoc(), "register expected");
5612     return MatchOperand_ParseFail;
5613   }
5614 
5615   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
5616                                                   0, S, Tok.getEndLoc()));
5617 
5618   return MatchOperand_Success;
5619 }
5620 
5621 /// Convert parsed operands to MCInst.  Needed here because this instruction
5622 /// only has two register operands, but multiplication is commutative so
5623 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
5624 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
5625                                     const OperandVector &Operands) {
5626   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
5627   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
5628   // If we have a three-operand form, make sure to set Rn to be the operand
5629   // that isn't the same as Rd.
5630   unsigned RegOp = 4;
5631   if (Operands.size() == 6 &&
5632       ((ARMOperand &)*Operands[4]).getReg() ==
5633           ((ARMOperand &)*Operands[3]).getReg())
5634     RegOp = 5;
5635   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5636   Inst.addOperand(Inst.getOperand(0));
5637   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5638 }
5639 
5640 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5641                                     const OperandVector &Operands) {
5642   int CondOp = -1, ImmOp = -1;
5643   switch(Inst.getOpcode()) {
5644     case ARM::tB:
5645     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5646 
5647     case ARM::t2B:
5648     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5649 
5650     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5651   }
5652   // first decide whether or not the branch should be conditional
5653   // by looking at it's location relative to an IT block
5654   if(inITBlock()) {
5655     // inside an IT block we cannot have any conditional branches. any
5656     // such instructions needs to be converted to unconditional form
5657     switch(Inst.getOpcode()) {
5658       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5659       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5660     }
5661   } else {
5662     // outside IT blocks we can only have unconditional branches with AL
5663     // condition code or conditional branches with non-AL condition code
5664     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5665     switch(Inst.getOpcode()) {
5666       case ARM::tB:
5667       case ARM::tBcc:
5668         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5669         break;
5670       case ARM::t2B:
5671       case ARM::t2Bcc:
5672         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5673         break;
5674     }
5675   }
5676 
5677   // now decide on encoding size based on branch target range
5678   switch(Inst.getOpcode()) {
5679     // classify tB as either t2B or t1B based on range of immediate operand
5680     case ARM::tB: {
5681       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5682       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5683         Inst.setOpcode(ARM::t2B);
5684       break;
5685     }
5686     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5687     case ARM::tBcc: {
5688       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5689       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5690         Inst.setOpcode(ARM::t2Bcc);
5691       break;
5692     }
5693   }
5694   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5695   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5696 }
5697 
5698 void ARMAsmParser::cvtMVEVMOVQtoDReg(
5699   MCInst &Inst, const OperandVector &Operands) {
5700 
5701   // mnemonic, condition code, Rt, Rt2, Qd, idx, Qd again, idx2
5702   assert(Operands.size() == 8);
5703 
5704   ((ARMOperand &)*Operands[2]).addRegOperands(Inst, 1); // Rt
5705   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1); // Rt2
5706   ((ARMOperand &)*Operands[4]).addRegOperands(Inst, 1); // Qd
5707   ((ARMOperand &)*Operands[5]).addMVEPairVectorIndexOperands(Inst, 1); // idx
5708   // skip second copy of Qd in Operands[6]
5709   ((ARMOperand &)*Operands[7]).addMVEPairVectorIndexOperands(Inst, 1); // idx2
5710   ((ARMOperand &)*Operands[1]).addCondCodeOperands(Inst, 2); // condition code
5711 }
5712 
5713 /// Parse an ARM memory expression, return false if successful else return true
5714 /// or an error.  The first token must be a '[' when called.
5715 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5716   MCAsmParser &Parser = getParser();
5717   SMLoc S, E;
5718   if (Parser.getTok().isNot(AsmToken::LBrac))
5719     return TokError("Token is not a Left Bracket");
5720   S = Parser.getTok().getLoc();
5721   Parser.Lex(); // Eat left bracket token.
5722 
5723   const AsmToken &BaseRegTok = Parser.getTok();
5724   int BaseRegNum = tryParseRegister();
5725   if (BaseRegNum == -1)
5726     return Error(BaseRegTok.getLoc(), "register expected");
5727 
5728   // The next token must either be a comma, a colon or a closing bracket.
5729   const AsmToken &Tok = Parser.getTok();
5730   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5731       !Tok.is(AsmToken::RBrac))
5732     return Error(Tok.getLoc(), "malformed memory operand");
5733 
5734   if (Tok.is(AsmToken::RBrac)) {
5735     E = Tok.getEndLoc();
5736     Parser.Lex(); // Eat right bracket token.
5737 
5738     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5739                                              ARM_AM::no_shift, 0, 0, false,
5740                                              S, E));
5741 
5742     // If there's a pre-indexing writeback marker, '!', just add it as a token
5743     // operand. It's rather odd, but syntactically valid.
5744     if (Parser.getTok().is(AsmToken::Exclaim)) {
5745       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5746       Parser.Lex(); // Eat the '!'.
5747     }
5748 
5749     return false;
5750   }
5751 
5752   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5753          "Lost colon or comma in memory operand?!");
5754   if (Tok.is(AsmToken::Comma)) {
5755     Parser.Lex(); // Eat the comma.
5756   }
5757 
5758   // If we have a ':', it's an alignment specifier.
5759   if (Parser.getTok().is(AsmToken::Colon)) {
5760     Parser.Lex(); // Eat the ':'.
5761     E = Parser.getTok().getLoc();
5762     SMLoc AlignmentLoc = Tok.getLoc();
5763 
5764     const MCExpr *Expr;
5765     if (getParser().parseExpression(Expr))
5766      return true;
5767 
5768     // The expression has to be a constant. Memory references with relocations
5769     // don't come through here, as they use the <label> forms of the relevant
5770     // instructions.
5771     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5772     if (!CE)
5773       return Error (E, "constant expression expected");
5774 
5775     unsigned Align = 0;
5776     switch (CE->getValue()) {
5777     default:
5778       return Error(E,
5779                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5780     case 16:  Align = 2; break;
5781     case 32:  Align = 4; break;
5782     case 64:  Align = 8; break;
5783     case 128: Align = 16; break;
5784     case 256: Align = 32; break;
5785     }
5786 
5787     // Now we should have the closing ']'
5788     if (Parser.getTok().isNot(AsmToken::RBrac))
5789       return Error(Parser.getTok().getLoc(), "']' expected");
5790     E = Parser.getTok().getEndLoc();
5791     Parser.Lex(); // Eat right bracket token.
5792 
5793     // Don't worry about range checking the value here. That's handled by
5794     // the is*() predicates.
5795     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5796                                              ARM_AM::no_shift, 0, Align,
5797                                              false, S, E, AlignmentLoc));
5798 
5799     // If there's a pre-indexing writeback marker, '!', just add it as a token
5800     // operand.
5801     if (Parser.getTok().is(AsmToken::Exclaim)) {
5802       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5803       Parser.Lex(); // Eat the '!'.
5804     }
5805 
5806     return false;
5807   }
5808 
5809   // If we have a '#' or '$', it's an immediate offset, else assume it's a
5810   // register offset. Be friendly and also accept a plain integer or expression
5811   // (without a leading hash) for gas compatibility.
5812   if (Parser.getTok().is(AsmToken::Hash) ||
5813       Parser.getTok().is(AsmToken::Dollar) ||
5814       Parser.getTok().is(AsmToken::LParen) ||
5815       Parser.getTok().is(AsmToken::Integer)) {
5816     if (Parser.getTok().is(AsmToken::Hash) ||
5817         Parser.getTok().is(AsmToken::Dollar))
5818       Parser.Lex(); // Eat '#' or '$'
5819     E = Parser.getTok().getLoc();
5820 
5821     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5822     const MCExpr *Offset;
5823     if (getParser().parseExpression(Offset))
5824      return true;
5825 
5826     // The expression has to be a constant. Memory references with relocations
5827     // don't come through here, as they use the <label> forms of the relevant
5828     // instructions.
5829     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5830     if (!CE)
5831       return Error (E, "constant expression expected");
5832 
5833     // If the constant was #-0, represent it as
5834     // std::numeric_limits<int32_t>::min().
5835     int32_t Val = CE->getValue();
5836     if (isNegative && Val == 0)
5837       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5838                                   getContext());
5839 
5840     // Now we should have the closing ']'
5841     if (Parser.getTok().isNot(AsmToken::RBrac))
5842       return Error(Parser.getTok().getLoc(), "']' expected");
5843     E = Parser.getTok().getEndLoc();
5844     Parser.Lex(); // Eat right bracket token.
5845 
5846     // Don't worry about range checking the value here. That's handled by
5847     // the is*() predicates.
5848     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5849                                              ARM_AM::no_shift, 0, 0,
5850                                              false, S, E));
5851 
5852     // If there's a pre-indexing writeback marker, '!', just add it as a token
5853     // operand.
5854     if (Parser.getTok().is(AsmToken::Exclaim)) {
5855       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5856       Parser.Lex(); // Eat the '!'.
5857     }
5858 
5859     return false;
5860   }
5861 
5862   // The register offset is optionally preceded by a '+' or '-'
5863   bool isNegative = false;
5864   if (Parser.getTok().is(AsmToken::Minus)) {
5865     isNegative = true;
5866     Parser.Lex(); // Eat the '-'.
5867   } else if (Parser.getTok().is(AsmToken::Plus)) {
5868     // Nothing to do.
5869     Parser.Lex(); // Eat the '+'.
5870   }
5871 
5872   E = Parser.getTok().getLoc();
5873   int OffsetRegNum = tryParseRegister();
5874   if (OffsetRegNum == -1)
5875     return Error(E, "register expected");
5876 
5877   // If there's a shift operator, handle it.
5878   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5879   unsigned ShiftImm = 0;
5880   if (Parser.getTok().is(AsmToken::Comma)) {
5881     Parser.Lex(); // Eat the ','.
5882     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5883       return true;
5884   }
5885 
5886   // Now we should have the closing ']'
5887   if (Parser.getTok().isNot(AsmToken::RBrac))
5888     return Error(Parser.getTok().getLoc(), "']' expected");
5889   E = Parser.getTok().getEndLoc();
5890   Parser.Lex(); // Eat right bracket token.
5891 
5892   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5893                                            ShiftType, ShiftImm, 0, isNegative,
5894                                            S, E));
5895 
5896   // If there's a pre-indexing writeback marker, '!', just add it as a token
5897   // operand.
5898   if (Parser.getTok().is(AsmToken::Exclaim)) {
5899     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5900     Parser.Lex(); // Eat the '!'.
5901   }
5902 
5903   return false;
5904 }
5905 
5906 /// parseMemRegOffsetShift - one of these two:
5907 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5908 ///   rrx
5909 /// return true if it parses a shift otherwise it returns false.
5910 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5911                                           unsigned &Amount) {
5912   MCAsmParser &Parser = getParser();
5913   SMLoc Loc = Parser.getTok().getLoc();
5914   const AsmToken &Tok = Parser.getTok();
5915   if (Tok.isNot(AsmToken::Identifier))
5916     return Error(Loc, "illegal shift operator");
5917   StringRef ShiftName = Tok.getString();
5918   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5919       ShiftName == "asl" || ShiftName == "ASL")
5920     St = ARM_AM::lsl;
5921   else if (ShiftName == "lsr" || ShiftName == "LSR")
5922     St = ARM_AM::lsr;
5923   else if (ShiftName == "asr" || ShiftName == "ASR")
5924     St = ARM_AM::asr;
5925   else if (ShiftName == "ror" || ShiftName == "ROR")
5926     St = ARM_AM::ror;
5927   else if (ShiftName == "rrx" || ShiftName == "RRX")
5928     St = ARM_AM::rrx;
5929   else if (ShiftName == "uxtw" || ShiftName == "UXTW")
5930     St = ARM_AM::uxtw;
5931   else
5932     return Error(Loc, "illegal shift operator");
5933   Parser.Lex(); // Eat shift type token.
5934 
5935   // rrx stands alone.
5936   Amount = 0;
5937   if (St != ARM_AM::rrx) {
5938     Loc = Parser.getTok().getLoc();
5939     // A '#' and a shift amount.
5940     const AsmToken &HashTok = Parser.getTok();
5941     if (HashTok.isNot(AsmToken::Hash) &&
5942         HashTok.isNot(AsmToken::Dollar))
5943       return Error(HashTok.getLoc(), "'#' expected");
5944     Parser.Lex(); // Eat hash token.
5945 
5946     const MCExpr *Expr;
5947     if (getParser().parseExpression(Expr))
5948       return true;
5949     // Range check the immediate.
5950     // lsl, ror: 0 <= imm <= 31
5951     // lsr, asr: 0 <= imm <= 32
5952     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5953     if (!CE)
5954       return Error(Loc, "shift amount must be an immediate");
5955     int64_t Imm = CE->getValue();
5956     if (Imm < 0 ||
5957         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5958         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5959       return Error(Loc, "immediate shift value out of range");
5960     // If <ShiftTy> #0, turn it into a no_shift.
5961     if (Imm == 0)
5962       St = ARM_AM::lsl;
5963     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5964     if (Imm == 32)
5965       Imm = 0;
5966     Amount = Imm;
5967   }
5968 
5969   return false;
5970 }
5971 
5972 /// parseFPImm - A floating point immediate expression operand.
5973 OperandMatchResultTy
5974 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5975   MCAsmParser &Parser = getParser();
5976   // Anything that can accept a floating point constant as an operand
5977   // needs to go through here, as the regular parseExpression is
5978   // integer only.
5979   //
5980   // This routine still creates a generic Immediate operand, containing
5981   // a bitcast of the 64-bit floating point value. The various operands
5982   // that accept floats can check whether the value is valid for them
5983   // via the standard is*() predicates.
5984 
5985   SMLoc S = Parser.getTok().getLoc();
5986 
5987   if (Parser.getTok().isNot(AsmToken::Hash) &&
5988       Parser.getTok().isNot(AsmToken::Dollar))
5989     return MatchOperand_NoMatch;
5990 
5991   // Disambiguate the VMOV forms that can accept an FP immediate.
5992   // vmov.f32 <sreg>, #imm
5993   // vmov.f64 <dreg>, #imm
5994   // vmov.f32 <dreg>, #imm  @ vector f32x2
5995   // vmov.f32 <qreg>, #imm  @ vector f32x4
5996   //
5997   // There are also the NEON VMOV instructions which expect an
5998   // integer constant. Make sure we don't try to parse an FPImm
5999   // for these:
6000   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
6001   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
6002   bool isVmovf = TyOp.isToken() &&
6003                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
6004                   TyOp.getToken() == ".f16");
6005   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
6006   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
6007                                          Mnemonic.getToken() == "fconsts");
6008   if (!(isVmovf || isFconst))
6009     return MatchOperand_NoMatch;
6010 
6011   Parser.Lex(); // Eat '#' or '$'.
6012 
6013   // Handle negation, as that still comes through as a separate token.
6014   bool isNegative = false;
6015   if (Parser.getTok().is(AsmToken::Minus)) {
6016     isNegative = true;
6017     Parser.Lex();
6018   }
6019   const AsmToken &Tok = Parser.getTok();
6020   SMLoc Loc = Tok.getLoc();
6021   if (Tok.is(AsmToken::Real) && isVmovf) {
6022     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
6023     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
6024     // If we had a '-' in front, toggle the sign bit.
6025     IntVal ^= (uint64_t)isNegative << 31;
6026     Parser.Lex(); // Eat the token.
6027     Operands.push_back(ARMOperand::CreateImm(
6028           MCConstantExpr::create(IntVal, getContext()),
6029           S, Parser.getTok().getLoc()));
6030     return MatchOperand_Success;
6031   }
6032   // Also handle plain integers. Instructions which allow floating point
6033   // immediates also allow a raw encoded 8-bit value.
6034   if (Tok.is(AsmToken::Integer) && isFconst) {
6035     int64_t Val = Tok.getIntVal();
6036     Parser.Lex(); // Eat the token.
6037     if (Val > 255 || Val < 0) {
6038       Error(Loc, "encoded floating point value out of range");
6039       return MatchOperand_ParseFail;
6040     }
6041     float RealVal = ARM_AM::getFPImmFloat(Val);
6042     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
6043 
6044     Operands.push_back(ARMOperand::CreateImm(
6045         MCConstantExpr::create(Val, getContext()), S,
6046         Parser.getTok().getLoc()));
6047     return MatchOperand_Success;
6048   }
6049 
6050   Error(Loc, "invalid floating point immediate");
6051   return MatchOperand_ParseFail;
6052 }
6053 
6054 /// Parse a arm instruction operand.  For now this parses the operand regardless
6055 /// of the mnemonic.
6056 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
6057   MCAsmParser &Parser = getParser();
6058   SMLoc S, E;
6059 
6060   // Check if the current operand has a custom associated parser, if so, try to
6061   // custom parse the operand, or fallback to the general approach.
6062   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
6063   if (ResTy == MatchOperand_Success)
6064     return false;
6065   // If there wasn't a custom match, try the generic matcher below. Otherwise,
6066   // there was a match, but an error occurred, in which case, just return that
6067   // the operand parsing failed.
6068   if (ResTy == MatchOperand_ParseFail)
6069     return true;
6070 
6071   switch (getLexer().getKind()) {
6072   default:
6073     Error(Parser.getTok().getLoc(), "unexpected token in operand");
6074     return true;
6075   case AsmToken::Identifier: {
6076     // If we've seen a branch mnemonic, the next operand must be a label.  This
6077     // is true even if the label is a register name.  So "br r1" means branch to
6078     // label "r1".
6079     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
6080     if (!ExpectLabel) {
6081       if (!tryParseRegisterWithWriteBack(Operands))
6082         return false;
6083       int Res = tryParseShiftRegister(Operands);
6084       if (Res == 0) // success
6085         return false;
6086       else if (Res == -1) // irrecoverable error
6087         return true;
6088       // If this is VMRS, check for the apsr_nzcv operand.
6089       if (Mnemonic == "vmrs" &&
6090           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
6091         S = Parser.getTok().getLoc();
6092         Parser.Lex();
6093         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
6094         return false;
6095       }
6096     }
6097 
6098     // Fall though for the Identifier case that is not a register or a
6099     // special name.
6100     LLVM_FALLTHROUGH;
6101   }
6102   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
6103   case AsmToken::Integer: // things like 1f and 2b as a branch targets
6104   case AsmToken::String:  // quoted label names.
6105   case AsmToken::Dot: {   // . as a branch target
6106     // This was not a register so parse other operands that start with an
6107     // identifier (like labels) as expressions and create them as immediates.
6108     const MCExpr *IdVal;
6109     S = Parser.getTok().getLoc();
6110     if (getParser().parseExpression(IdVal))
6111       return true;
6112     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6113     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
6114     return false;
6115   }
6116   case AsmToken::LBrac:
6117     return parseMemory(Operands);
6118   case AsmToken::LCurly:
6119     return parseRegisterList(Operands, !Mnemonic.startswith("clr"));
6120   case AsmToken::Dollar:
6121   case AsmToken::Hash: {
6122     // #42 -> immediate
6123     // $ 42 -> immediate
6124     // $foo -> symbol name
6125     // $42 -> symbol name
6126     S = Parser.getTok().getLoc();
6127 
6128     // Favor the interpretation of $-prefixed operands as symbol names.
6129     // Cases where immediates are explicitly expected are handled by their
6130     // specific ParseMethod implementations.
6131     auto AdjacentToken = getLexer().peekTok(/*ShouldSkipSpace=*/false);
6132     bool ExpectIdentifier = Parser.getTok().is(AsmToken::Dollar) &&
6133                             (AdjacentToken.is(AsmToken::Identifier) ||
6134                              AdjacentToken.is(AsmToken::Integer));
6135     if (!ExpectIdentifier) {
6136       // Token is not part of identifier. Drop leading $ or # before parsing
6137       // expression.
6138       Parser.Lex();
6139     }
6140 
6141     if (Parser.getTok().isNot(AsmToken::Colon)) {
6142       bool IsNegative = Parser.getTok().is(AsmToken::Minus);
6143       const MCExpr *ImmVal;
6144       if (getParser().parseExpression(ImmVal))
6145         return true;
6146       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
6147       if (CE) {
6148         int32_t Val = CE->getValue();
6149         if (IsNegative && Val == 0)
6150           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
6151                                           getContext());
6152       }
6153       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6154       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
6155 
6156       // There can be a trailing '!' on operands that we want as a separate
6157       // '!' Token operand. Handle that here. For example, the compatibility
6158       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
6159       if (Parser.getTok().is(AsmToken::Exclaim)) {
6160         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
6161                                                    Parser.getTok().getLoc()));
6162         Parser.Lex(); // Eat exclaim token
6163       }
6164       return false;
6165     }
6166     // w/ a ':' after the '#', it's just like a plain ':'.
6167     LLVM_FALLTHROUGH;
6168   }
6169   case AsmToken::Colon: {
6170     S = Parser.getTok().getLoc();
6171     // ":lower16:" and ":upper16:" expression prefixes
6172     // FIXME: Check it's an expression prefix,
6173     // e.g. (FOO - :lower16:BAR) isn't legal.
6174     ARMMCExpr::VariantKind RefKind;
6175     if (parsePrefix(RefKind))
6176       return true;
6177 
6178     const MCExpr *SubExprVal;
6179     if (getParser().parseExpression(SubExprVal))
6180       return true;
6181 
6182     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
6183                                               getContext());
6184     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6185     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
6186     return false;
6187   }
6188   case AsmToken::Equal: {
6189     S = Parser.getTok().getLoc();
6190     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
6191       return Error(S, "unexpected token in operand");
6192     Parser.Lex(); // Eat '='
6193     const MCExpr *SubExprVal;
6194     if (getParser().parseExpression(SubExprVal))
6195       return true;
6196     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6197 
6198     // execute-only: we assume that assembly programmers know what they are
6199     // doing and allow literal pool creation here
6200     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
6201     return false;
6202   }
6203   }
6204 }
6205 
6206 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
6207 //  :lower16: and :upper16:.
6208 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
6209   MCAsmParser &Parser = getParser();
6210   RefKind = ARMMCExpr::VK_ARM_None;
6211 
6212   // consume an optional '#' (GNU compatibility)
6213   if (getLexer().is(AsmToken::Hash))
6214     Parser.Lex();
6215 
6216   // :lower16: and :upper16: modifiers
6217   assert(getLexer().is(AsmToken::Colon) && "expected a :");
6218   Parser.Lex(); // Eat ':'
6219 
6220   if (getLexer().isNot(AsmToken::Identifier)) {
6221     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
6222     return true;
6223   }
6224 
6225   enum {
6226     COFF = (1 << MCObjectFileInfo::IsCOFF),
6227     ELF = (1 << MCObjectFileInfo::IsELF),
6228     MACHO = (1 << MCObjectFileInfo::IsMachO),
6229     WASM = (1 << MCObjectFileInfo::IsWasm),
6230   };
6231   static const struct PrefixEntry {
6232     const char *Spelling;
6233     ARMMCExpr::VariantKind VariantKind;
6234     uint8_t SupportedFormats;
6235   } PrefixEntries[] = {
6236     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
6237     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
6238   };
6239 
6240   StringRef IDVal = Parser.getTok().getIdentifier();
6241 
6242   const auto &Prefix =
6243       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
6244                    [&IDVal](const PrefixEntry &PE) {
6245                       return PE.Spelling == IDVal;
6246                    });
6247   if (Prefix == std::end(PrefixEntries)) {
6248     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
6249     return true;
6250   }
6251 
6252   uint8_t CurrentFormat;
6253   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
6254   case MCObjectFileInfo::IsMachO:
6255     CurrentFormat = MACHO;
6256     break;
6257   case MCObjectFileInfo::IsELF:
6258     CurrentFormat = ELF;
6259     break;
6260   case MCObjectFileInfo::IsCOFF:
6261     CurrentFormat = COFF;
6262     break;
6263   case MCObjectFileInfo::IsWasm:
6264     CurrentFormat = WASM;
6265     break;
6266   case MCObjectFileInfo::IsXCOFF:
6267     llvm_unreachable("unexpected object format");
6268     break;
6269   }
6270 
6271   if (~Prefix->SupportedFormats & CurrentFormat) {
6272     Error(Parser.getTok().getLoc(),
6273           "cannot represent relocation in the current file format");
6274     return true;
6275   }
6276 
6277   RefKind = Prefix->VariantKind;
6278   Parser.Lex();
6279 
6280   if (getLexer().isNot(AsmToken::Colon)) {
6281     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
6282     return true;
6283   }
6284   Parser.Lex(); // Eat the last ':'
6285 
6286   return false;
6287 }
6288 
6289 /// Given a mnemonic, split out possible predication code and carry
6290 /// setting letters to form a canonical mnemonic and flags.
6291 //
6292 // FIXME: Would be nice to autogen this.
6293 // FIXME: This is a bit of a maze of special cases.
6294 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
6295                                       StringRef ExtraToken,
6296                                       unsigned &PredicationCode,
6297                                       unsigned &VPTPredicationCode,
6298                                       bool &CarrySetting,
6299                                       unsigned &ProcessorIMod,
6300                                       StringRef &ITMask) {
6301   PredicationCode = ARMCC::AL;
6302   VPTPredicationCode = ARMVCC::None;
6303   CarrySetting = false;
6304   ProcessorIMod = 0;
6305 
6306   // Ignore some mnemonics we know aren't predicated forms.
6307   //
6308   // FIXME: Would be nice to autogen this.
6309   if ((Mnemonic == "movs" && isThumb()) ||
6310       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
6311       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
6312       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
6313       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
6314       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
6315       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
6316       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
6317       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
6318       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
6319       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
6320       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
6321       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
6322       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
6323       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
6324       Mnemonic == "vdot"  || Mnemonic == "vmmla"  ||
6325       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6326       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6327       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6328       Mnemonic == "wls" || Mnemonic == "le" || Mnemonic == "dls" ||
6329       Mnemonic == "csel" || Mnemonic == "csinc" ||
6330       Mnemonic == "csinv" || Mnemonic == "csneg" || Mnemonic == "cinc" ||
6331       Mnemonic == "cinv" || Mnemonic == "cneg" || Mnemonic == "cset" ||
6332       Mnemonic == "csetm")
6333     return Mnemonic;
6334 
6335   // First, split out any predication code. Ignore mnemonics we know aren't
6336   // predicated but do have a carry-set and so weren't caught above.
6337   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
6338       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
6339       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
6340       Mnemonic != "sbcs" && Mnemonic != "rscs" &&
6341       !(hasMVE() &&
6342         (Mnemonic == "vmine" ||
6343          Mnemonic == "vshle" || Mnemonic == "vshlt" || Mnemonic == "vshllt" ||
6344          Mnemonic == "vrshle" || Mnemonic == "vrshlt" ||
6345          Mnemonic == "vmvne" || Mnemonic == "vorne" ||
6346          Mnemonic == "vnege" || Mnemonic == "vnegt" ||
6347          Mnemonic == "vmule" || Mnemonic == "vmult" ||
6348          Mnemonic == "vrintne" ||
6349          Mnemonic == "vcmult" || Mnemonic == "vcmule" ||
6350          Mnemonic == "vpsele" || Mnemonic == "vpselt" ||
6351          Mnemonic.startswith("vq")))) {
6352     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
6353     if (CC != ~0U) {
6354       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
6355       PredicationCode = CC;
6356     }
6357   }
6358 
6359   // Next, determine if we have a carry setting bit. We explicitly ignore all
6360   // the instructions we know end in 's'.
6361   if (Mnemonic.endswith("s") &&
6362       !(Mnemonic == "cps" || Mnemonic == "mls" ||
6363         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
6364         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
6365         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
6366         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
6367         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
6368         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
6369         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
6370         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
6371         Mnemonic == "bxns" || Mnemonic == "blxns" || Mnemonic == "vfmas" ||
6372         Mnemonic == "vmlas" ||
6373         (Mnemonic == "movs" && isThumb()))) {
6374     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
6375     CarrySetting = true;
6376   }
6377 
6378   // The "cps" instruction can have a interrupt mode operand which is glued into
6379   // the mnemonic. Check if this is the case, split it and parse the imod op
6380   if (Mnemonic.startswith("cps")) {
6381     // Split out any imod code.
6382     unsigned IMod =
6383       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
6384       .Case("ie", ARM_PROC::IE)
6385       .Case("id", ARM_PROC::ID)
6386       .Default(~0U);
6387     if (IMod != ~0U) {
6388       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
6389       ProcessorIMod = IMod;
6390     }
6391   }
6392 
6393   if (isMnemonicVPTPredicable(Mnemonic, ExtraToken) && Mnemonic != "vmovlt" &&
6394       Mnemonic != "vshllt" && Mnemonic != "vrshrnt" && Mnemonic != "vshrnt" &&
6395       Mnemonic != "vqrshrunt" && Mnemonic != "vqshrunt" &&
6396       Mnemonic != "vqrshrnt" && Mnemonic != "vqshrnt" && Mnemonic != "vmullt" &&
6397       Mnemonic != "vqmovnt" && Mnemonic != "vqmovunt" &&
6398       Mnemonic != "vqmovnt" && Mnemonic != "vmovnt" && Mnemonic != "vqdmullt" &&
6399       Mnemonic != "vpnot" && Mnemonic != "vcvtt" && Mnemonic != "vcvt") {
6400     unsigned CC = ARMVectorCondCodeFromString(Mnemonic.substr(Mnemonic.size()-1));
6401     if (CC != ~0U) {
6402       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-1);
6403       VPTPredicationCode = CC;
6404     }
6405     return Mnemonic;
6406   }
6407 
6408   // The "it" instruction has the condition mask on the end of the mnemonic.
6409   if (Mnemonic.startswith("it")) {
6410     ITMask = Mnemonic.slice(2, Mnemonic.size());
6411     Mnemonic = Mnemonic.slice(0, 2);
6412   }
6413 
6414   if (Mnemonic.startswith("vpst")) {
6415     ITMask = Mnemonic.slice(4, Mnemonic.size());
6416     Mnemonic = Mnemonic.slice(0, 4);
6417   }
6418   else if (Mnemonic.startswith("vpt")) {
6419     ITMask = Mnemonic.slice(3, Mnemonic.size());
6420     Mnemonic = Mnemonic.slice(0, 3);
6421   }
6422 
6423   return Mnemonic;
6424 }
6425 
6426 /// Given a canonical mnemonic, determine if the instruction ever allows
6427 /// inclusion of carry set or predication code operands.
6428 //
6429 // FIXME: It would be nice to autogen this.
6430 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic,
6431                                          StringRef ExtraToken,
6432                                          StringRef FullInst,
6433                                          bool &CanAcceptCarrySet,
6434                                          bool &CanAcceptPredicationCode,
6435                                          bool &CanAcceptVPTPredicationCode) {
6436   CanAcceptVPTPredicationCode = isMnemonicVPTPredicable(Mnemonic, ExtraToken);
6437 
6438   CanAcceptCarrySet =
6439       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6440       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
6441       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
6442       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
6443       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
6444       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
6445       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
6446       (!isThumb() &&
6447        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
6448         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
6449 
6450   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
6451       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
6452       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
6453       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
6454       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
6455       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
6456       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
6457       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
6458       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
6459       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
6460       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
6461       Mnemonic == "vmovx" || Mnemonic == "vins" ||
6462       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6463       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6464       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6465       Mnemonic == "vfmat" || Mnemonic == "vfmab" ||
6466       Mnemonic == "vdot"  || Mnemonic == "vmmla" ||
6467       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
6468       Mnemonic == "pssbb" || Mnemonic == "vsmmla" ||
6469       Mnemonic == "vummla" || Mnemonic == "vusmmla" ||
6470       Mnemonic == "vusdot" || Mnemonic == "vsudot" ||
6471       Mnemonic == "bfcsel" || Mnemonic == "wls" ||
6472       Mnemonic == "dls" || Mnemonic == "le" || Mnemonic == "csel" ||
6473       Mnemonic == "csinc" || Mnemonic == "csinv" || Mnemonic == "csneg" ||
6474       Mnemonic == "cinc" || Mnemonic == "cinv" || Mnemonic == "cneg" ||
6475       Mnemonic == "cset" || Mnemonic == "csetm" ||
6476       Mnemonic.startswith("vpt") || Mnemonic.startswith("vpst") ||
6477       (hasCDE() && MS.isCDEInstr(Mnemonic) &&
6478        !MS.isITPredicableCDEInstr(Mnemonic)) ||
6479       (hasMVE() &&
6480        (Mnemonic.startswith("vst2") || Mnemonic.startswith("vld2") ||
6481         Mnemonic.startswith("vst4") || Mnemonic.startswith("vld4") ||
6482         Mnemonic.startswith("wlstp") || Mnemonic.startswith("dlstp") ||
6483         Mnemonic.startswith("letp")))) {
6484     // These mnemonics are never predicable
6485     CanAcceptPredicationCode = false;
6486   } else if (!isThumb()) {
6487     // Some instructions are only predicable in Thumb mode
6488     CanAcceptPredicationCode =
6489         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
6490         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
6491         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
6492         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
6493         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
6494         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
6495         Mnemonic != "tsb" &&
6496         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
6497   } else if (isThumbOne()) {
6498     if (hasV6MOps())
6499       CanAcceptPredicationCode = Mnemonic != "movs";
6500     else
6501       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
6502   } else
6503     CanAcceptPredicationCode = true;
6504 }
6505 
6506 // Some Thumb instructions have two operand forms that are not
6507 // available as three operand, convert to two operand form if possible.
6508 //
6509 // FIXME: We would really like to be able to tablegen'erate this.
6510 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
6511                                                  bool CarrySetting,
6512                                                  OperandVector &Operands) {
6513   if (Operands.size() != 6)
6514     return;
6515 
6516   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6517         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
6518   if (!Op3.isReg() || !Op4.isReg())
6519     return;
6520 
6521   auto Op3Reg = Op3.getReg();
6522   auto Op4Reg = Op4.getReg();
6523 
6524   // For most Thumb2 cases we just generate the 3 operand form and reduce
6525   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
6526   // won't accept SP or PC so we do the transformation here taking care
6527   // with immediate range in the 'add sp, sp #imm' case.
6528   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
6529   if (isThumbTwo()) {
6530     if (Mnemonic != "add")
6531       return;
6532     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
6533                         (Op5.isReg() && Op5.getReg() == ARM::PC);
6534     if (!TryTransform) {
6535       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
6536                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
6537                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
6538                        Op5.isImm() && !Op5.isImm0_508s4());
6539     }
6540     if (!TryTransform)
6541       return;
6542   } else if (!isThumbOne())
6543     return;
6544 
6545   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
6546         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6547         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
6548         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
6549     return;
6550 
6551   // If first 2 operands of a 3 operand instruction are the same
6552   // then transform to 2 operand version of the same instruction
6553   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
6554   bool Transform = Op3Reg == Op4Reg;
6555 
6556   // For communtative operations, we might be able to transform if we swap
6557   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
6558   // as tADDrsp.
6559   const ARMOperand *LastOp = &Op5;
6560   bool Swap = false;
6561   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
6562       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
6563        Mnemonic == "and" || Mnemonic == "eor" ||
6564        Mnemonic == "adc" || Mnemonic == "orr")) {
6565     Swap = true;
6566     LastOp = &Op4;
6567     Transform = true;
6568   }
6569 
6570   // If both registers are the same then remove one of them from
6571   // the operand list, with certain exceptions.
6572   if (Transform) {
6573     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
6574     // 2 operand forms don't exist.
6575     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
6576         LastOp->isReg())
6577       Transform = false;
6578 
6579     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
6580     // 3-bits because the ARMARM says not to.
6581     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
6582       Transform = false;
6583   }
6584 
6585   if (Transform) {
6586     if (Swap)
6587       std::swap(Op4, Op5);
6588     Operands.erase(Operands.begin() + 3);
6589   }
6590 }
6591 
6592 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
6593                                           OperandVector &Operands) {
6594   // FIXME: This is all horribly hacky. We really need a better way to deal
6595   // with optional operands like this in the matcher table.
6596 
6597   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
6598   // another does not. Specifically, the MOVW instruction does not. So we
6599   // special case it here and remove the defaulted (non-setting) cc_out
6600   // operand if that's the instruction we're trying to match.
6601   //
6602   // We do this as post-processing of the explicit operands rather than just
6603   // conditionally adding the cc_out in the first place because we need
6604   // to check the type of the parsed immediate operand.
6605   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
6606       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
6607       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
6608       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6609     return true;
6610 
6611   // Register-register 'add' for thumb does not have a cc_out operand
6612   // when there are only two register operands.
6613   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
6614       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6615       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6616       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6617     return true;
6618   // Register-register 'add' for thumb does not have a cc_out operand
6619   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
6620   // have to check the immediate range here since Thumb2 has a variant
6621   // that can handle a different range and has a cc_out operand.
6622   if (((isThumb() && Mnemonic == "add") ||
6623        (isThumbTwo() && Mnemonic == "sub")) &&
6624       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6625       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6626       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
6627       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6628       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
6629        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
6630     return true;
6631   // For Thumb2, add/sub immediate does not have a cc_out operand for the
6632   // imm0_4095 variant. That's the least-preferred variant when
6633   // selecting via the generic "add" mnemonic, so to know that we
6634   // should remove the cc_out operand, we have to explicitly check that
6635   // it's not one of the other variants. Ugh.
6636   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6637       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6638       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6639       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6640     // Nest conditions rather than one big 'if' statement for readability.
6641     //
6642     // If both registers are low, we're in an IT block, and the immediate is
6643     // in range, we should use encoding T1 instead, which has a cc_out.
6644     if (inITBlock() &&
6645         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
6646         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
6647         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
6648       return false;
6649     // Check against T3. If the second register is the PC, this is an
6650     // alternate form of ADR, which uses encoding T4, so check for that too.
6651     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
6652         (static_cast<ARMOperand &>(*Operands[5]).isT2SOImm() ||
6653          static_cast<ARMOperand &>(*Operands[5]).isT2SOImmNeg()))
6654       return false;
6655 
6656     // Otherwise, we use encoding T4, which does not have a cc_out
6657     // operand.
6658     return true;
6659   }
6660 
6661   // The thumb2 multiply instruction doesn't have a CCOut register, so
6662   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
6663   // use the 16-bit encoding or not.
6664   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
6665       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6666       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6667       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6668       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
6669       // If the registers aren't low regs, the destination reg isn't the
6670       // same as one of the source regs, or the cc_out operand is zero
6671       // outside of an IT block, we have to use the 32-bit encoding, so
6672       // remove the cc_out operand.
6673       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6674        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6675        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
6676        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6677                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
6678                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6679                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
6680     return true;
6681 
6682   // Also check the 'mul' syntax variant that doesn't specify an explicit
6683   // destination register.
6684   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
6685       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6686       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6687       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6688       // If the registers aren't low regs  or the cc_out operand is zero
6689       // outside of an IT block, we have to use the 32-bit encoding, so
6690       // remove the cc_out operand.
6691       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6692        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6693        !inITBlock()))
6694     return true;
6695 
6696   // Register-register 'add/sub' for thumb does not have a cc_out operand
6697   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
6698   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
6699   // right, this will result in better diagnostics (which operand is off)
6700   // anyway.
6701   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
6702       (Operands.size() == 5 || Operands.size() == 6) &&
6703       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6704       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
6705       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6706       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
6707        (Operands.size() == 6 &&
6708         static_cast<ARMOperand &>(*Operands[5]).isImm()))) {
6709     // Thumb2 (add|sub){s}{p}.w GPRnopc, sp, #{T2SOImm} has cc_out
6710     return (!(isThumbTwo() &&
6711               (static_cast<ARMOperand &>(*Operands[4]).isT2SOImm() ||
6712                static_cast<ARMOperand &>(*Operands[4]).isT2SOImmNeg())));
6713   }
6714   // Fixme: Should join all the thumb+thumb2 (add|sub) in a single if case
6715   // Thumb2 ADD r0, #4095 -> ADDW r0, r0, #4095 (T4)
6716   // Thumb2 SUB r0, #4095 -> SUBW r0, r0, #4095
6717   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6718       (Operands.size() == 5) &&
6719       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6720       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::SP &&
6721       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::PC &&
6722       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6723       static_cast<ARMOperand &>(*Operands[4]).isImm()) {
6724     const ARMOperand &IMM = static_cast<ARMOperand &>(*Operands[4]);
6725     if (IMM.isT2SOImm() || IMM.isT2SOImmNeg())
6726       return false; // add.w / sub.w
6727     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IMM.getImm())) {
6728       const int64_t Value = CE->getValue();
6729       // Thumb1 imm8 sub / add
6730       if ((Value < ((1 << 7) - 1) << 2) && inITBlock() && (!(Value & 3)) &&
6731           isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()))
6732         return false;
6733       return true; // Thumb2 T4 addw / subw
6734     }
6735   }
6736   return false;
6737 }
6738 
6739 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
6740                                               OperandVector &Operands) {
6741   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
6742   unsigned RegIdx = 3;
6743   if ((((Mnemonic == "vrintz" || Mnemonic == "vrintx") && !hasMVE()) ||
6744       Mnemonic == "vrintr") &&
6745       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
6746        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
6747     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6748         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
6749          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
6750       RegIdx = 4;
6751 
6752     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
6753         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6754              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
6755          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6756              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
6757       return true;
6758   }
6759   return false;
6760 }
6761 
6762 bool ARMAsmParser::shouldOmitVectorPredicateOperand(StringRef Mnemonic,
6763                                                     OperandVector &Operands) {
6764   if (!hasMVE() || Operands.size() < 3)
6765     return true;
6766 
6767   if (Mnemonic.startswith("vld2") || Mnemonic.startswith("vld4") ||
6768       Mnemonic.startswith("vst2") || Mnemonic.startswith("vst4"))
6769     return true;
6770 
6771   if (Mnemonic.startswith("vctp") || Mnemonic.startswith("vpnot"))
6772     return false;
6773 
6774   if (Mnemonic.startswith("vmov") &&
6775       !(Mnemonic.startswith("vmovl") || Mnemonic.startswith("vmovn") ||
6776         Mnemonic.startswith("vmovx"))) {
6777     for (auto &Operand : Operands) {
6778       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6779           ((*Operand).isReg() &&
6780            (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
6781              (*Operand).getReg()) ||
6782             ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6783               (*Operand).getReg())))) {
6784         return true;
6785       }
6786     }
6787     return false;
6788   } else {
6789     for (auto &Operand : Operands) {
6790       // We check the larger class QPR instead of just the legal class
6791       // MQPR, to more accurately report errors when using Q registers
6792       // outside of the allowed range.
6793       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6794           (Operand->isReg() &&
6795            (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6796              Operand->getReg()))))
6797         return false;
6798     }
6799     return true;
6800   }
6801 }
6802 
6803 static bool isDataTypeToken(StringRef Tok) {
6804   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
6805     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6806     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6807     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6808     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6809     Tok == ".f" || Tok == ".d";
6810 }
6811 
6812 // FIXME: This bit should probably be handled via an explicit match class
6813 // in the .td files that matches the suffix instead of having it be
6814 // a literal string token the way it is now.
6815 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6816   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6817 }
6818 
6819 static void applyMnemonicAliases(StringRef &Mnemonic,
6820                                  const FeatureBitset &Features,
6821                                  unsigned VariantID);
6822 
6823 // The GNU assembler has aliases of ldrd and strd with the second register
6824 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6825 //
6826 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6827 // the assembly parser could then generate confusing diagnostics refering to
6828 // it. If we do find anything that prevents us from doing the transformation we
6829 // bail out, and let the assembly parser report an error on the instruction as
6830 // it is written.
6831 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6832                                      OperandVector &Operands) {
6833   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6834     return;
6835   if (Operands.size() < 4)
6836     return;
6837 
6838   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6839   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6840 
6841   if (!Op2.isReg())
6842     return;
6843   if (!Op3.isGPRMem())
6844     return;
6845 
6846   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6847   if (!GPR.contains(Op2.getReg()))
6848     return;
6849 
6850   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6851   if (!isThumb() && (RtEncoding & 1)) {
6852     // In ARM mode, the registers must be from an aligned pair, this
6853     // restriction does not apply in Thumb mode.
6854     return;
6855   }
6856   if (Op2.getReg() == ARM::PC)
6857     return;
6858   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6859   if (!PairedReg || PairedReg == ARM::PC ||
6860       (PairedReg == ARM::SP && !hasV8Ops()))
6861     return;
6862 
6863   Operands.insert(
6864       Operands.begin() + 3,
6865       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6866 }
6867 
6868 // Dual-register instruction have the following syntax:
6869 // <mnemonic> <predicate>? <coproc>, <Rdest>, <Rdest+1>, <Rsrc>, ..., #imm
6870 // This function tries to remove <Rdest+1> and replace <Rdest> with a pair
6871 // operand. If the conversion fails an error is diagnosed, and the function
6872 // returns true.
6873 bool ARMAsmParser::CDEConvertDualRegOperand(StringRef Mnemonic,
6874                                             OperandVector &Operands) {
6875   assert(MS.isCDEDualRegInstr(Mnemonic));
6876   bool isPredicable =
6877       Mnemonic == "cx1da" || Mnemonic == "cx2da" || Mnemonic == "cx3da";
6878   size_t NumPredOps = isPredicable ? 1 : 0;
6879 
6880   if (Operands.size() <= 3 + NumPredOps)
6881     return false;
6882 
6883   StringRef Op2Diag(
6884       "operand must be an even-numbered register in the range [r0, r10]");
6885 
6886   const MCParsedAsmOperand &Op2 = *Operands[2 + NumPredOps];
6887   if (!Op2.isReg())
6888     return Error(Op2.getStartLoc(), Op2Diag);
6889 
6890   unsigned RNext;
6891   unsigned RPair;
6892   switch (Op2.getReg()) {
6893   default:
6894     return Error(Op2.getStartLoc(), Op2Diag);
6895   case ARM::R0:
6896     RNext = ARM::R1;
6897     RPair = ARM::R0_R1;
6898     break;
6899   case ARM::R2:
6900     RNext = ARM::R3;
6901     RPair = ARM::R2_R3;
6902     break;
6903   case ARM::R4:
6904     RNext = ARM::R5;
6905     RPair = ARM::R4_R5;
6906     break;
6907   case ARM::R6:
6908     RNext = ARM::R7;
6909     RPair = ARM::R6_R7;
6910     break;
6911   case ARM::R8:
6912     RNext = ARM::R9;
6913     RPair = ARM::R8_R9;
6914     break;
6915   case ARM::R10:
6916     RNext = ARM::R11;
6917     RPair = ARM::R10_R11;
6918     break;
6919   }
6920 
6921   const MCParsedAsmOperand &Op3 = *Operands[3 + NumPredOps];
6922   if (!Op3.isReg() || Op3.getReg() != RNext)
6923     return Error(Op3.getStartLoc(), "operand must be a consecutive register");
6924 
6925   Operands.erase(Operands.begin() + 3 + NumPredOps);
6926   Operands[2 + NumPredOps] =
6927       ARMOperand::CreateReg(RPair, Op2.getStartLoc(), Op2.getEndLoc());
6928   return false;
6929 }
6930 
6931 /// Parse an arm instruction mnemonic followed by its operands.
6932 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6933                                     SMLoc NameLoc, OperandVector &Operands) {
6934   MCAsmParser &Parser = getParser();
6935 
6936   // Apply mnemonic aliases before doing anything else, as the destination
6937   // mnemonic may include suffices and we want to handle them normally.
6938   // The generic tblgen'erated code does this later, at the start of
6939   // MatchInstructionImpl(), but that's too late for aliases that include
6940   // any sort of suffix.
6941   const FeatureBitset &AvailableFeatures = getAvailableFeatures();
6942   unsigned AssemblerDialect = getParser().getAssemblerDialect();
6943   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
6944 
6945   // First check for the ARM-specific .req directive.
6946   if (Parser.getTok().is(AsmToken::Identifier) &&
6947       Parser.getTok().getIdentifier().lower() == ".req") {
6948     parseDirectiveReq(Name, NameLoc);
6949     // We always return 'error' for this, as we're done with this
6950     // statement and don't need to match the 'instruction."
6951     return true;
6952   }
6953 
6954   // Create the leading tokens for the mnemonic, split by '.' characters.
6955   size_t Start = 0, Next = Name.find('.');
6956   StringRef Mnemonic = Name.slice(Start, Next);
6957   StringRef ExtraToken = Name.slice(Next, Name.find(' ', Next + 1));
6958 
6959   // Split out the predication code and carry setting flag from the mnemonic.
6960   unsigned PredicationCode;
6961   unsigned VPTPredicationCode;
6962   unsigned ProcessorIMod;
6963   bool CarrySetting;
6964   StringRef ITMask;
6965   Mnemonic = splitMnemonic(Mnemonic, ExtraToken, PredicationCode, VPTPredicationCode,
6966                            CarrySetting, ProcessorIMod, ITMask);
6967 
6968   // In Thumb1, only the branch (B) instruction can be predicated.
6969   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
6970     return Error(NameLoc, "conditional execution not supported in Thumb1");
6971   }
6972 
6973   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
6974 
6975   // Handle the mask for IT and VPT instructions. In ARMOperand and
6976   // MCOperand, this is stored in a format independent of the
6977   // condition code: the lowest set bit indicates the end of the
6978   // encoding, and above that, a 1 bit indicates 'else', and an 0
6979   // indicates 'then'. E.g.
6980   //    IT    -> 1000
6981   //    ITx   -> x100    (ITT -> 0100, ITE -> 1100)
6982   //    ITxy  -> xy10    (e.g. ITET -> 1010)
6983   //    ITxyz -> xyz1    (e.g. ITEET -> 1101)
6984   // Note: See the ARM::PredBlockMask enum in
6985   //   /lib/Target/ARM/Utils/ARMBaseInfo.h
6986   if (Mnemonic == "it" || Mnemonic.startswith("vpt") ||
6987       Mnemonic.startswith("vpst")) {
6988     SMLoc Loc = Mnemonic == "it"  ? SMLoc::getFromPointer(NameLoc.getPointer() + 2) :
6989                 Mnemonic == "vpt" ? SMLoc::getFromPointer(NameLoc.getPointer() + 3) :
6990                                     SMLoc::getFromPointer(NameLoc.getPointer() + 4);
6991     if (ITMask.size() > 3) {
6992       if (Mnemonic == "it")
6993         return Error(Loc, "too many conditions on IT instruction");
6994       return Error(Loc, "too many conditions on VPT instruction");
6995     }
6996     unsigned Mask = 8;
6997     for (unsigned i = ITMask.size(); i != 0; --i) {
6998       char pos = ITMask[i - 1];
6999       if (pos != 't' && pos != 'e') {
7000         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
7001       }
7002       Mask >>= 1;
7003       if (ITMask[i - 1] == 'e')
7004         Mask |= 8;
7005     }
7006     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
7007   }
7008 
7009   // FIXME: This is all a pretty gross hack. We should automatically handle
7010   // optional operands like this via tblgen.
7011 
7012   // Next, add the CCOut and ConditionCode operands, if needed.
7013   //
7014   // For mnemonics which can ever incorporate a carry setting bit or predication
7015   // code, our matching model involves us always generating CCOut and
7016   // ConditionCode operands to match the mnemonic "as written" and then we let
7017   // the matcher deal with finding the right instruction or generating an
7018   // appropriate error.
7019   bool CanAcceptCarrySet, CanAcceptPredicationCode, CanAcceptVPTPredicationCode;
7020   getMnemonicAcceptInfo(Mnemonic, ExtraToken, Name, CanAcceptCarrySet,
7021                         CanAcceptPredicationCode, CanAcceptVPTPredicationCode);
7022 
7023   // If we had a carry-set on an instruction that can't do that, issue an
7024   // error.
7025   if (!CanAcceptCarrySet && CarrySetting) {
7026     return Error(NameLoc, "instruction '" + Mnemonic +
7027                  "' can not set flags, but 's' suffix specified");
7028   }
7029   // If we had a predication code on an instruction that can't do that, issue an
7030   // error.
7031   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
7032     return Error(NameLoc, "instruction '" + Mnemonic +
7033                  "' is not predicable, but condition code specified");
7034   }
7035 
7036   // If we had a VPT predication code on an instruction that can't do that, issue an
7037   // error.
7038   if (!CanAcceptVPTPredicationCode && VPTPredicationCode != ARMVCC::None) {
7039     return Error(NameLoc, "instruction '" + Mnemonic +
7040                  "' is not VPT predicable, but VPT code T/E is specified");
7041   }
7042 
7043   // Add the carry setting operand, if necessary.
7044   if (CanAcceptCarrySet) {
7045     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
7046     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
7047                                                Loc));
7048   }
7049 
7050   // Add the predication code operand, if necessary.
7051   if (CanAcceptPredicationCode) {
7052     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7053                                       CarrySetting);
7054     Operands.push_back(ARMOperand::CreateCondCode(
7055                        ARMCC::CondCodes(PredicationCode), Loc));
7056   }
7057 
7058   // Add the VPT predication code operand, if necessary.
7059   // FIXME: We don't add them for the instructions filtered below as these can
7060   // have custom operands which need special parsing.  This parsing requires
7061   // the operand to be in the same place in the OperandVector as their
7062   // definition in tblgen.  Since these instructions may also have the
7063   // scalar predication operand we do not add the vector one and leave until
7064   // now to fix it up.
7065   if (CanAcceptVPTPredicationCode && Mnemonic != "vmov" &&
7066       !Mnemonic.startswith("vcmp") &&
7067       !(Mnemonic.startswith("vcvt") && Mnemonic != "vcvta" &&
7068         Mnemonic != "vcvtn" && Mnemonic != "vcvtp" && Mnemonic != "vcvtm")) {
7069     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7070                                       CarrySetting);
7071     Operands.push_back(ARMOperand::CreateVPTPred(
7072                          ARMVCC::VPTCodes(VPTPredicationCode), Loc));
7073   }
7074 
7075   // Add the processor imod operand, if necessary.
7076   if (ProcessorIMod) {
7077     Operands.push_back(ARMOperand::CreateImm(
7078           MCConstantExpr::create(ProcessorIMod, getContext()),
7079                                  NameLoc, NameLoc));
7080   } else if (Mnemonic == "cps" && isMClass()) {
7081     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
7082   }
7083 
7084   // Add the remaining tokens in the mnemonic.
7085   while (Next != StringRef::npos) {
7086     Start = Next;
7087     Next = Name.find('.', Start + 1);
7088     ExtraToken = Name.slice(Start, Next);
7089 
7090     // Some NEON instructions have an optional datatype suffix that is
7091     // completely ignored. Check for that.
7092     if (isDataTypeToken(ExtraToken) &&
7093         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
7094       continue;
7095 
7096     // For for ARM mode generate an error if the .n qualifier is used.
7097     if (ExtraToken == ".n" && !isThumb()) {
7098       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7099       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
7100                    "arm mode");
7101     }
7102 
7103     // The .n qualifier is always discarded as that is what the tables
7104     // and matcher expect.  In ARM mode the .w qualifier has no effect,
7105     // so discard it to avoid errors that can be caused by the matcher.
7106     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
7107       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7108       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
7109     }
7110   }
7111 
7112   // Read the remaining operands.
7113   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7114     // Read the first operand.
7115     if (parseOperand(Operands, Mnemonic)) {
7116       return true;
7117     }
7118 
7119     while (parseOptionalToken(AsmToken::Comma)) {
7120       // Parse and remember the operand.
7121       if (parseOperand(Operands, Mnemonic)) {
7122         return true;
7123       }
7124     }
7125   }
7126 
7127   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
7128     return true;
7129 
7130   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
7131 
7132   if (hasCDE() && MS.isCDEInstr(Mnemonic)) {
7133     // Dual-register instructions use even-odd register pairs as their
7134     // destination operand, in assembly such pair is spelled as two
7135     // consecutive registers, without any special syntax. ConvertDualRegOperand
7136     // tries to convert such operand into register pair, e.g. r2, r3 -> r2_r3.
7137     // It returns true, if an error message has been emitted. If the function
7138     // returns false, the function either succeeded or an error (e.g. missing
7139     // operand) will be diagnosed elsewhere.
7140     if (MS.isCDEDualRegInstr(Mnemonic)) {
7141       bool GotError = CDEConvertDualRegOperand(Mnemonic, Operands);
7142       if (GotError)
7143         return GotError;
7144     }
7145   }
7146 
7147   // Some instructions, mostly Thumb, have forms for the same mnemonic that
7148   // do and don't have a cc_out optional-def operand. With some spot-checks
7149   // of the operand list, we can figure out which variant we're trying to
7150   // parse and adjust accordingly before actually matching. We shouldn't ever
7151   // try to remove a cc_out operand that was explicitly set on the
7152   // mnemonic, of course (CarrySetting == true). Reason number #317 the
7153   // table driven matcher doesn't fit well with the ARM instruction set.
7154   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
7155     Operands.erase(Operands.begin() + 1);
7156 
7157   // Some instructions have the same mnemonic, but don't always
7158   // have a predicate. Distinguish them here and delete the
7159   // appropriate predicate if needed.  This could be either the scalar
7160   // predication code or the vector predication code.
7161   if (PredicationCode == ARMCC::AL &&
7162       shouldOmitPredicateOperand(Mnemonic, Operands))
7163     Operands.erase(Operands.begin() + 1);
7164 
7165 
7166   if (hasMVE()) {
7167     if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands) &&
7168         Mnemonic == "vmov" && PredicationCode == ARMCC::LT) {
7169       // Very nasty hack to deal with the vector predicated variant of vmovlt
7170       // the scalar predicated vmov with condition 'lt'.  We can not tell them
7171       // apart until we have parsed their operands.
7172       Operands.erase(Operands.begin() + 1);
7173       Operands.erase(Operands.begin());
7174       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7175       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7176                                          Mnemonic.size() - 1 + CarrySetting);
7177       Operands.insert(Operands.begin(),
7178                       ARMOperand::CreateVPTPred(ARMVCC::None, PLoc));
7179       Operands.insert(Operands.begin(),
7180                       ARMOperand::CreateToken(StringRef("vmovlt"), MLoc));
7181     } else if (Mnemonic == "vcvt" && PredicationCode == ARMCC::NE &&
7182                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7183       // Another nasty hack to deal with the ambiguity between vcvt with scalar
7184       // predication 'ne' and vcvtn with vector predication 'e'.  As above we
7185       // can only distinguish between the two after we have parsed their
7186       // operands.
7187       Operands.erase(Operands.begin() + 1);
7188       Operands.erase(Operands.begin());
7189       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7190       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7191                                          Mnemonic.size() - 1 + CarrySetting);
7192       Operands.insert(Operands.begin(),
7193                       ARMOperand::CreateVPTPred(ARMVCC::Else, PLoc));
7194       Operands.insert(Operands.begin(),
7195                       ARMOperand::CreateToken(StringRef("vcvtn"), MLoc));
7196     } else if (Mnemonic == "vmul" && PredicationCode == ARMCC::LT &&
7197                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7198       // Another hack, this time to distinguish between scalar predicated vmul
7199       // with 'lt' predication code and the vector instruction vmullt with
7200       // vector predication code "none"
7201       Operands.erase(Operands.begin() + 1);
7202       Operands.erase(Operands.begin());
7203       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7204       Operands.insert(Operands.begin(),
7205                       ARMOperand::CreateToken(StringRef("vmullt"), MLoc));
7206     }
7207     // For vmov and vcmp, as mentioned earlier, we did not add the vector
7208     // predication code, since these may contain operands that require
7209     // special parsing.  So now we have to see if they require vector
7210     // predication and replace the scalar one with the vector predication
7211     // operand if that is the case.
7212     else if (Mnemonic == "vmov" || Mnemonic.startswith("vcmp") ||
7213              (Mnemonic.startswith("vcvt") && !Mnemonic.startswith("vcvta") &&
7214               !Mnemonic.startswith("vcvtn") && !Mnemonic.startswith("vcvtp") &&
7215               !Mnemonic.startswith("vcvtm"))) {
7216       if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7217         // We could not split the vector predicate off vcvt because it might
7218         // have been the scalar vcvtt instruction.  Now we know its a vector
7219         // instruction, we still need to check whether its the vector
7220         // predicated vcvt with 'Then' predication or the vector vcvtt.  We can
7221         // distinguish the two based on the suffixes, if it is any of
7222         // ".f16.f32", ".f32.f16", ".f16.f64" or ".f64.f16" then it is the vcvtt.
7223         if (Mnemonic.startswith("vcvtt") && Operands.size() >= 4) {
7224           auto Sz1 = static_cast<ARMOperand &>(*Operands[2]);
7225           auto Sz2 = static_cast<ARMOperand &>(*Operands[3]);
7226           if (!(Sz1.isToken() && Sz1.getToken().startswith(".f") &&
7227               Sz2.isToken() && Sz2.getToken().startswith(".f"))) {
7228             Operands.erase(Operands.begin());
7229             SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7230             VPTPredicationCode = ARMVCC::Then;
7231 
7232             Mnemonic = Mnemonic.substr(0, 4);
7233             Operands.insert(Operands.begin(),
7234                             ARMOperand::CreateToken(Mnemonic, MLoc));
7235           }
7236         }
7237         Operands.erase(Operands.begin() + 1);
7238         SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7239                                           Mnemonic.size() + CarrySetting);
7240         Operands.insert(Operands.begin() + 1,
7241                         ARMOperand::CreateVPTPred(
7242                             ARMVCC::VPTCodes(VPTPredicationCode), PLoc));
7243       }
7244     } else if (CanAcceptVPTPredicationCode) {
7245       // For all other instructions, make sure only one of the two
7246       // predication operands is left behind, depending on whether we should
7247       // use the vector predication.
7248       if (shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7249         if (CanAcceptPredicationCode)
7250           Operands.erase(Operands.begin() + 2);
7251         else
7252           Operands.erase(Operands.begin() + 1);
7253       } else if (CanAcceptPredicationCode && PredicationCode == ARMCC::AL) {
7254         Operands.erase(Operands.begin() + 1);
7255       }
7256     }
7257   }
7258 
7259   if (VPTPredicationCode != ARMVCC::None) {
7260     bool usedVPTPredicationCode = false;
7261     for (unsigned I = 1; I < Operands.size(); ++I)
7262       if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7263         usedVPTPredicationCode = true;
7264     if (!usedVPTPredicationCode) {
7265       // If we have a VPT predication code and we haven't just turned it
7266       // into an operand, then it was a mistake for splitMnemonic to
7267       // separate it from the rest of the mnemonic in the first place,
7268       // and this may lead to wrong disassembly (e.g. scalar floating
7269       // point VCMPE is actually a different instruction from VCMP, so
7270       // we mustn't treat them the same). In that situation, glue it
7271       // back on.
7272       Mnemonic = Name.slice(0, Mnemonic.size() + 1);
7273       Operands.erase(Operands.begin());
7274       Operands.insert(Operands.begin(),
7275                       ARMOperand::CreateToken(Mnemonic, NameLoc));
7276     }
7277   }
7278 
7279     // ARM mode 'blx' need special handling, as the register operand version
7280     // is predicable, but the label operand version is not. So, we can't rely
7281     // on the Mnemonic based checking to correctly figure out when to put
7282     // a k_CondCode operand in the list. If we're trying to match the label
7283     // version, remove the k_CondCode operand here.
7284     if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
7285         static_cast<ARMOperand &>(*Operands[2]).isImm())
7286       Operands.erase(Operands.begin() + 1);
7287 
7288     // Adjust operands of ldrexd/strexd to MCK_GPRPair.
7289     // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
7290     // a single GPRPair reg operand is used in the .td file to replace the two
7291     // GPRs. However, when parsing from asm, the two GRPs cannot be
7292     // automatically
7293     // expressed as a GPRPair, so we have to manually merge them.
7294     // FIXME: We would really like to be able to tablegen'erate this.
7295     if (!isThumb() && Operands.size() > 4 &&
7296         (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
7297          Mnemonic == "stlexd")) {
7298       bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
7299       unsigned Idx = isLoad ? 2 : 3;
7300       ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
7301       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
7302 
7303       const MCRegisterClass &MRC = MRI->getRegClass(ARM::GPRRegClassID);
7304       // Adjust only if Op1 and Op2 are GPRs.
7305       if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
7306           MRC.contains(Op2.getReg())) {
7307         unsigned Reg1 = Op1.getReg();
7308         unsigned Reg2 = Op2.getReg();
7309         unsigned Rt = MRI->getEncodingValue(Reg1);
7310         unsigned Rt2 = MRI->getEncodingValue(Reg2);
7311 
7312         // Rt2 must be Rt + 1 and Rt must be even.
7313         if (Rt + 1 != Rt2 || (Rt & 1)) {
7314           return Error(Op2.getStartLoc(),
7315                        isLoad ? "destination operands must be sequential"
7316                               : "source operands must be sequential");
7317         }
7318         unsigned NewReg = MRI->getMatchingSuperReg(
7319             Reg1, ARM::gsub_0, &(MRI->getRegClass(ARM::GPRPairRegClassID)));
7320         Operands[Idx] =
7321             ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
7322         Operands.erase(Operands.begin() + Idx + 1);
7323       }
7324   }
7325 
7326   // GNU Assembler extension (compatibility).
7327   fixupGNULDRDAlias(Mnemonic, Operands);
7328 
7329   // FIXME: As said above, this is all a pretty gross hack.  This instruction
7330   // does not fit with other "subs" and tblgen.
7331   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
7332   // so the Mnemonic is the original name "subs" and delete the predicate
7333   // operand so it will match the table entry.
7334   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
7335       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
7336       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
7337       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
7338       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
7339       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
7340     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
7341     Operands.erase(Operands.begin() + 1);
7342   }
7343   return false;
7344 }
7345 
7346 // Validate context-sensitive operand constraints.
7347 
7348 // return 'true' if register list contains non-low GPR registers,
7349 // 'false' otherwise. If Reg is in the register list or is HiReg, set
7350 // 'containsReg' to true.
7351 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
7352                                  unsigned Reg, unsigned HiReg,
7353                                  bool &containsReg) {
7354   containsReg = false;
7355   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
7356     unsigned OpReg = Inst.getOperand(i).getReg();
7357     if (OpReg == Reg)
7358       containsReg = true;
7359     // Anything other than a low register isn't legal here.
7360     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
7361       return true;
7362   }
7363   return false;
7364 }
7365 
7366 // Check if the specified regisgter is in the register list of the inst,
7367 // starting at the indicated operand number.
7368 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
7369   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
7370     unsigned OpReg = Inst.getOperand(i).getReg();
7371     if (OpReg == Reg)
7372       return true;
7373   }
7374   return false;
7375 }
7376 
7377 // Return true if instruction has the interesting property of being
7378 // allowed in IT blocks, but not being predicable.
7379 static bool instIsBreakpoint(const MCInst &Inst) {
7380     return Inst.getOpcode() == ARM::tBKPT ||
7381            Inst.getOpcode() == ARM::BKPT ||
7382            Inst.getOpcode() == ARM::tHLT ||
7383            Inst.getOpcode() == ARM::HLT;
7384 }
7385 
7386 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
7387                                        const OperandVector &Operands,
7388                                        unsigned ListNo, bool IsARPop) {
7389   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7390   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7391 
7392   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7393   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
7394   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7395 
7396   if (!IsARPop && ListContainsSP)
7397     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7398                  "SP may not be in the register list");
7399   else if (ListContainsPC && ListContainsLR)
7400     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7401                  "PC and LR may not be in the register list simultaneously");
7402   return false;
7403 }
7404 
7405 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
7406                                        const OperandVector &Operands,
7407                                        unsigned ListNo) {
7408   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7409   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7410 
7411   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7412   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7413 
7414   if (ListContainsSP && ListContainsPC)
7415     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7416                  "SP and PC may not be in the register list");
7417   else if (ListContainsSP)
7418     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7419                  "SP may not be in the register list");
7420   else if (ListContainsPC)
7421     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7422                  "PC may not be in the register list");
7423   return false;
7424 }
7425 
7426 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
7427                                     const OperandVector &Operands,
7428                                     bool Load, bool ARMMode, bool Writeback) {
7429   unsigned RtIndex = Load || !Writeback ? 0 : 1;
7430   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
7431   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
7432 
7433   if (ARMMode) {
7434     // Rt can't be R14.
7435     if (Rt == 14)
7436       return Error(Operands[3]->getStartLoc(),
7437                   "Rt can't be R14");
7438 
7439     // Rt must be even-numbered.
7440     if ((Rt & 1) == 1)
7441       return Error(Operands[3]->getStartLoc(),
7442                    "Rt must be even-numbered");
7443 
7444     // Rt2 must be Rt + 1.
7445     if (Rt2 != Rt + 1) {
7446       if (Load)
7447         return Error(Operands[3]->getStartLoc(),
7448                      "destination operands must be sequential");
7449       else
7450         return Error(Operands[3]->getStartLoc(),
7451                      "source operands must be sequential");
7452     }
7453 
7454     // FIXME: Diagnose m == 15
7455     // FIXME: Diagnose ldrd with m == t || m == t2.
7456   }
7457 
7458   if (!ARMMode && Load) {
7459     if (Rt2 == Rt)
7460       return Error(Operands[3]->getStartLoc(),
7461                    "destination operands can't be identical");
7462   }
7463 
7464   if (Writeback) {
7465     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7466 
7467     if (Rn == Rt || Rn == Rt2) {
7468       if (Load)
7469         return Error(Operands[3]->getStartLoc(),
7470                      "base register needs to be different from destination "
7471                      "registers");
7472       else
7473         return Error(Operands[3]->getStartLoc(),
7474                      "source register and base register can't be identical");
7475     }
7476 
7477     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
7478     // (Except the immediate form of ldrd?)
7479   }
7480 
7481   return false;
7482 }
7483 
7484 static int findFirstVectorPredOperandIdx(const MCInstrDesc &MCID) {
7485   for (unsigned i = 0; i < MCID.NumOperands; ++i) {
7486     if (ARM::isVpred(MCID.OpInfo[i].OperandType))
7487       return i;
7488   }
7489   return -1;
7490 }
7491 
7492 static bool isVectorPredicable(const MCInstrDesc &MCID) {
7493   return findFirstVectorPredOperandIdx(MCID) != -1;
7494 }
7495 
7496 // FIXME: We would really like to be able to tablegen'erate this.
7497 bool ARMAsmParser::validateInstruction(MCInst &Inst,
7498                                        const OperandVector &Operands) {
7499   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
7500   SMLoc Loc = Operands[0]->getStartLoc();
7501 
7502   // Check the IT block state first.
7503   // NOTE: BKPT and HLT instructions have the interesting property of being
7504   // allowed in IT blocks, but not being predicable. They just always execute.
7505   if (inITBlock() && !instIsBreakpoint(Inst)) {
7506     // The instruction must be predicable.
7507     if (!MCID.isPredicable())
7508       return Error(Loc, "instructions in IT block must be predicable");
7509     ARMCC::CondCodes Cond = ARMCC::CondCodes(
7510         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
7511     if (Cond != currentITCond()) {
7512       // Find the condition code Operand to get its SMLoc information.
7513       SMLoc CondLoc;
7514       for (unsigned I = 1; I < Operands.size(); ++I)
7515         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
7516           CondLoc = Operands[I]->getStartLoc();
7517       return Error(CondLoc, "incorrect condition in IT block; got '" +
7518                                 StringRef(ARMCondCodeToString(Cond)) +
7519                                 "', but expected '" +
7520                                 ARMCondCodeToString(currentITCond()) + "'");
7521     }
7522   // Check for non-'al' condition codes outside of the IT block.
7523   } else if (isThumbTwo() && MCID.isPredicable() &&
7524              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7525              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
7526              Inst.getOpcode() != ARM::t2Bcc &&
7527              Inst.getOpcode() != ARM::t2BFic) {
7528     return Error(Loc, "predicated instructions must be in IT block");
7529   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
7530              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7531                  ARMCC::AL) {
7532     return Warning(Loc, "predicated instructions should be in IT block");
7533   } else if (!MCID.isPredicable()) {
7534     // Check the instruction doesn't have a predicate operand anyway
7535     // that it's not allowed to use. Sometimes this happens in order
7536     // to keep instructions the same shape even though one cannot
7537     // legally be predicated, e.g. vmul.f16 vs vmul.f32.
7538     for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
7539       if (MCID.OpInfo[i].isPredicate()) {
7540         if (Inst.getOperand(i).getImm() != ARMCC::AL)
7541           return Error(Loc, "instruction is not predicable");
7542         break;
7543       }
7544     }
7545   }
7546 
7547   // PC-setting instructions in an IT block, but not the last instruction of
7548   // the block, are UNPREDICTABLE.
7549   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
7550     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
7551   }
7552 
7553   if (inVPTBlock() && !instIsBreakpoint(Inst)) {
7554     unsigned Bit = extractITMaskBit(VPTState.Mask, VPTState.CurPosition);
7555     if (!isVectorPredicable(MCID))
7556       return Error(Loc, "instruction in VPT block must be predicable");
7557     unsigned Pred = Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm();
7558     unsigned VPTPred = Bit ? ARMVCC::Else : ARMVCC::Then;
7559     if (Pred != VPTPred) {
7560       SMLoc PredLoc;
7561       for (unsigned I = 1; I < Operands.size(); ++I)
7562         if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7563           PredLoc = Operands[I]->getStartLoc();
7564       return Error(PredLoc, "incorrect predication in VPT block; got '" +
7565                    StringRef(ARMVPTPredToString(ARMVCC::VPTCodes(Pred))) +
7566                    "', but expected '" +
7567                    ARMVPTPredToString(ARMVCC::VPTCodes(VPTPred)) + "'");
7568     }
7569   }
7570   else if (isVectorPredicable(MCID) &&
7571            Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm() !=
7572            ARMVCC::None)
7573     return Error(Loc, "VPT predicated instructions must be in VPT block");
7574 
7575   const unsigned Opcode = Inst.getOpcode();
7576   switch (Opcode) {
7577   case ARM::t2IT: {
7578     // Encoding is unpredictable if it ever results in a notional 'NV'
7579     // predicate. Since we don't parse 'NV' directly this means an 'AL'
7580     // predicate with an "else" mask bit.
7581     unsigned Cond = Inst.getOperand(0).getImm();
7582     unsigned Mask = Inst.getOperand(1).getImm();
7583 
7584     // Conditions only allowing a 't' are those with no set bit except
7585     // the lowest-order one that indicates the end of the sequence. In
7586     // other words, powers of 2.
7587     if (Cond == ARMCC::AL && countPopulation(Mask) != 1)
7588       return Error(Loc, "unpredictable IT predicate sequence");
7589     break;
7590   }
7591   case ARM::LDRD:
7592     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7593                          /*Writeback*/false))
7594       return true;
7595     break;
7596   case ARM::LDRD_PRE:
7597   case ARM::LDRD_POST:
7598     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7599                          /*Writeback*/true))
7600       return true;
7601     break;
7602   case ARM::t2LDRDi8:
7603     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7604                          /*Writeback*/false))
7605       return true;
7606     break;
7607   case ARM::t2LDRD_PRE:
7608   case ARM::t2LDRD_POST:
7609     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7610                          /*Writeback*/true))
7611       return true;
7612     break;
7613   case ARM::t2BXJ: {
7614     const unsigned RmReg = Inst.getOperand(0).getReg();
7615     // Rm = SP is no longer unpredictable in v8-A
7616     if (RmReg == ARM::SP && !hasV8Ops())
7617       return Error(Operands[2]->getStartLoc(),
7618                    "r13 (SP) is an unpredictable operand to BXJ");
7619     return false;
7620   }
7621   case ARM::STRD:
7622     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7623                          /*Writeback*/false))
7624       return true;
7625     break;
7626   case ARM::STRD_PRE:
7627   case ARM::STRD_POST:
7628     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7629                          /*Writeback*/true))
7630       return true;
7631     break;
7632   case ARM::t2STRD_PRE:
7633   case ARM::t2STRD_POST:
7634     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
7635                          /*Writeback*/true))
7636       return true;
7637     break;
7638   case ARM::STR_PRE_IMM:
7639   case ARM::STR_PRE_REG:
7640   case ARM::t2STR_PRE:
7641   case ARM::STR_POST_IMM:
7642   case ARM::STR_POST_REG:
7643   case ARM::t2STR_POST:
7644   case ARM::STRH_PRE:
7645   case ARM::t2STRH_PRE:
7646   case ARM::STRH_POST:
7647   case ARM::t2STRH_POST:
7648   case ARM::STRB_PRE_IMM:
7649   case ARM::STRB_PRE_REG:
7650   case ARM::t2STRB_PRE:
7651   case ARM::STRB_POST_IMM:
7652   case ARM::STRB_POST_REG:
7653   case ARM::t2STRB_POST: {
7654     // Rt must be different from Rn.
7655     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7656     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7657 
7658     if (Rt == Rn)
7659       return Error(Operands[3]->getStartLoc(),
7660                    "source register and base register can't be identical");
7661     return false;
7662   }
7663   case ARM::LDR_PRE_IMM:
7664   case ARM::LDR_PRE_REG:
7665   case ARM::t2LDR_PRE:
7666   case ARM::LDR_POST_IMM:
7667   case ARM::LDR_POST_REG:
7668   case ARM::t2LDR_POST:
7669   case ARM::LDRH_PRE:
7670   case ARM::t2LDRH_PRE:
7671   case ARM::LDRH_POST:
7672   case ARM::t2LDRH_POST:
7673   case ARM::LDRSH_PRE:
7674   case ARM::t2LDRSH_PRE:
7675   case ARM::LDRSH_POST:
7676   case ARM::t2LDRSH_POST:
7677   case ARM::LDRB_PRE_IMM:
7678   case ARM::LDRB_PRE_REG:
7679   case ARM::t2LDRB_PRE:
7680   case ARM::LDRB_POST_IMM:
7681   case ARM::LDRB_POST_REG:
7682   case ARM::t2LDRB_POST:
7683   case ARM::LDRSB_PRE:
7684   case ARM::t2LDRSB_PRE:
7685   case ARM::LDRSB_POST:
7686   case ARM::t2LDRSB_POST: {
7687     // Rt must be different from Rn.
7688     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7689     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7690 
7691     if (Rt == Rn)
7692       return Error(Operands[3]->getStartLoc(),
7693                    "destination register and base register can't be identical");
7694     return false;
7695   }
7696 
7697   case ARM::MVE_VLDRBU8_rq:
7698   case ARM::MVE_VLDRBU16_rq:
7699   case ARM::MVE_VLDRBS16_rq:
7700   case ARM::MVE_VLDRBU32_rq:
7701   case ARM::MVE_VLDRBS32_rq:
7702   case ARM::MVE_VLDRHU16_rq:
7703   case ARM::MVE_VLDRHU16_rq_u:
7704   case ARM::MVE_VLDRHU32_rq:
7705   case ARM::MVE_VLDRHU32_rq_u:
7706   case ARM::MVE_VLDRHS32_rq:
7707   case ARM::MVE_VLDRHS32_rq_u:
7708   case ARM::MVE_VLDRWU32_rq:
7709   case ARM::MVE_VLDRWU32_rq_u:
7710   case ARM::MVE_VLDRDU64_rq:
7711   case ARM::MVE_VLDRDU64_rq_u:
7712   case ARM::MVE_VLDRWU32_qi:
7713   case ARM::MVE_VLDRWU32_qi_pre:
7714   case ARM::MVE_VLDRDU64_qi:
7715   case ARM::MVE_VLDRDU64_qi_pre: {
7716     // Qd must be different from Qm.
7717     unsigned QdIdx = 0, QmIdx = 2;
7718     bool QmIsPointer = false;
7719     switch (Opcode) {
7720     case ARM::MVE_VLDRWU32_qi:
7721     case ARM::MVE_VLDRDU64_qi:
7722       QmIdx = 1;
7723       QmIsPointer = true;
7724       break;
7725     case ARM::MVE_VLDRWU32_qi_pre:
7726     case ARM::MVE_VLDRDU64_qi_pre:
7727       QdIdx = 1;
7728       QmIsPointer = true;
7729       break;
7730     }
7731 
7732     const unsigned Qd = MRI->getEncodingValue(Inst.getOperand(QdIdx).getReg());
7733     const unsigned Qm = MRI->getEncodingValue(Inst.getOperand(QmIdx).getReg());
7734 
7735     if (Qd == Qm) {
7736       return Error(Operands[3]->getStartLoc(),
7737                    Twine("destination vector register and vector ") +
7738                    (QmIsPointer ? "pointer" : "offset") +
7739                    " register can't be identical");
7740     }
7741     return false;
7742   }
7743 
7744   case ARM::SBFX:
7745   case ARM::t2SBFX:
7746   case ARM::UBFX:
7747   case ARM::t2UBFX: {
7748     // Width must be in range [1, 32-lsb].
7749     unsigned LSB = Inst.getOperand(2).getImm();
7750     unsigned Widthm1 = Inst.getOperand(3).getImm();
7751     if (Widthm1 >= 32 - LSB)
7752       return Error(Operands[5]->getStartLoc(),
7753                    "bitfield width must be in range [1,32-lsb]");
7754     return false;
7755   }
7756   // Notionally handles ARM::tLDMIA_UPD too.
7757   case ARM::tLDMIA: {
7758     // If we're parsing Thumb2, the .w variant is available and handles
7759     // most cases that are normally illegal for a Thumb1 LDM instruction.
7760     // We'll make the transformation in processInstruction() if necessary.
7761     //
7762     // Thumb LDM instructions are writeback iff the base register is not
7763     // in the register list.
7764     unsigned Rn = Inst.getOperand(0).getReg();
7765     bool HasWritebackToken =
7766         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7767          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
7768     bool ListContainsBase;
7769     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
7770       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
7771                    "registers must be in range r0-r7");
7772     // If we should have writeback, then there should be a '!' token.
7773     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
7774       return Error(Operands[2]->getStartLoc(),
7775                    "writeback operator '!' expected");
7776     // If we should not have writeback, there must not be a '!'. This is
7777     // true even for the 32-bit wide encodings.
7778     if (ListContainsBase && HasWritebackToken)
7779       return Error(Operands[3]->getStartLoc(),
7780                    "writeback operator '!' not allowed when base register "
7781                    "in register list");
7782 
7783     if (validatetLDMRegList(Inst, Operands, 3))
7784       return true;
7785     break;
7786   }
7787   case ARM::LDMIA_UPD:
7788   case ARM::LDMDB_UPD:
7789   case ARM::LDMIB_UPD:
7790   case ARM::LDMDA_UPD:
7791     // ARM variants loading and updating the same register are only officially
7792     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
7793     if (!hasV7Ops())
7794       break;
7795     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7796       return Error(Operands.back()->getStartLoc(),
7797                    "writeback register not allowed in register list");
7798     break;
7799   case ARM::t2LDMIA:
7800   case ARM::t2LDMDB:
7801     if (validatetLDMRegList(Inst, Operands, 3))
7802       return true;
7803     break;
7804   case ARM::t2STMIA:
7805   case ARM::t2STMDB:
7806     if (validatetSTMRegList(Inst, Operands, 3))
7807       return true;
7808     break;
7809   case ARM::t2LDMIA_UPD:
7810   case ARM::t2LDMDB_UPD:
7811   case ARM::t2STMIA_UPD:
7812   case ARM::t2STMDB_UPD:
7813     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7814       return Error(Operands.back()->getStartLoc(),
7815                    "writeback register not allowed in register list");
7816 
7817     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
7818       if (validatetLDMRegList(Inst, Operands, 3))
7819         return true;
7820     } else {
7821       if (validatetSTMRegList(Inst, Operands, 3))
7822         return true;
7823     }
7824     break;
7825 
7826   case ARM::sysLDMIA_UPD:
7827   case ARM::sysLDMDA_UPD:
7828   case ARM::sysLDMDB_UPD:
7829   case ARM::sysLDMIB_UPD:
7830     if (!listContainsReg(Inst, 3, ARM::PC))
7831       return Error(Operands[4]->getStartLoc(),
7832                    "writeback register only allowed on system LDM "
7833                    "if PC in register-list");
7834     break;
7835   case ARM::sysSTMIA_UPD:
7836   case ARM::sysSTMDA_UPD:
7837   case ARM::sysSTMDB_UPD:
7838   case ARM::sysSTMIB_UPD:
7839     return Error(Operands[2]->getStartLoc(),
7840                  "system STM cannot have writeback register");
7841   case ARM::tMUL:
7842     // The second source operand must be the same register as the destination
7843     // operand.
7844     //
7845     // In this case, we must directly check the parsed operands because the
7846     // cvtThumbMultiply() function is written in such a way that it guarantees
7847     // this first statement is always true for the new Inst.  Essentially, the
7848     // destination is unconditionally copied into the second source operand
7849     // without checking to see if it matches what we actually parsed.
7850     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
7851                                  ((ARMOperand &)*Operands[5]).getReg()) &&
7852         (((ARMOperand &)*Operands[3]).getReg() !=
7853          ((ARMOperand &)*Operands[4]).getReg())) {
7854       return Error(Operands[3]->getStartLoc(),
7855                    "destination register must match source register");
7856     }
7857     break;
7858 
7859   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
7860   // so only issue a diagnostic for thumb1. The instructions will be
7861   // switched to the t2 encodings in processInstruction() if necessary.
7862   case ARM::tPOP: {
7863     bool ListContainsBase;
7864     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
7865         !isThumbTwo())
7866       return Error(Operands[2]->getStartLoc(),
7867                    "registers must be in range r0-r7 or pc");
7868     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
7869       return true;
7870     break;
7871   }
7872   case ARM::tPUSH: {
7873     bool ListContainsBase;
7874     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
7875         !isThumbTwo())
7876       return Error(Operands[2]->getStartLoc(),
7877                    "registers must be in range r0-r7 or lr");
7878     if (validatetSTMRegList(Inst, Operands, 2))
7879       return true;
7880     break;
7881   }
7882   case ARM::tSTMIA_UPD: {
7883     bool ListContainsBase, InvalidLowList;
7884     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
7885                                           0, ListContainsBase);
7886     if (InvalidLowList && !isThumbTwo())
7887       return Error(Operands[4]->getStartLoc(),
7888                    "registers must be in range r0-r7");
7889 
7890     // This would be converted to a 32-bit stm, but that's not valid if the
7891     // writeback register is in the list.
7892     if (InvalidLowList && ListContainsBase)
7893       return Error(Operands[4]->getStartLoc(),
7894                    "writeback operator '!' not allowed when base register "
7895                    "in register list");
7896 
7897     if (validatetSTMRegList(Inst, Operands, 4))
7898       return true;
7899     break;
7900   }
7901   case ARM::tADDrSP:
7902     // If the non-SP source operand and the destination operand are not the
7903     // same, we need thumb2 (for the wide encoding), or we have an error.
7904     if (!isThumbTwo() &&
7905         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
7906       return Error(Operands[4]->getStartLoc(),
7907                    "source register must be the same as destination");
7908     }
7909     break;
7910 
7911   case ARM::t2ADDrr:
7912   case ARM::t2ADDrs:
7913   case ARM::t2SUBrr:
7914   case ARM::t2SUBrs:
7915     if (Inst.getOperand(0).getReg() == ARM::SP &&
7916         Inst.getOperand(1).getReg() != ARM::SP)
7917       return Error(Operands[4]->getStartLoc(),
7918                    "source register must be sp if destination is sp");
7919     break;
7920 
7921   // Final range checking for Thumb unconditional branch instructions.
7922   case ARM::tB:
7923     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
7924       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7925     break;
7926   case ARM::t2B: {
7927     int op = (Operands[2]->isImm()) ? 2 : 3;
7928     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
7929       return Error(Operands[op]->getStartLoc(), "branch target out of range");
7930     break;
7931   }
7932   // Final range checking for Thumb conditional branch instructions.
7933   case ARM::tBcc:
7934     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
7935       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7936     break;
7937   case ARM::t2Bcc: {
7938     int Op = (Operands[2]->isImm()) ? 2 : 3;
7939     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
7940       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
7941     break;
7942   }
7943   case ARM::tCBZ:
7944   case ARM::tCBNZ: {
7945     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
7946       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7947     break;
7948   }
7949   case ARM::MOVi16:
7950   case ARM::MOVTi16:
7951   case ARM::t2MOVi16:
7952   case ARM::t2MOVTi16:
7953     {
7954     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
7955     // especially when we turn it into a movw and the expression <symbol> does
7956     // not have a :lower16: or :upper16 as part of the expression.  We don't
7957     // want the behavior of silently truncating, which can be unexpected and
7958     // lead to bugs that are difficult to find since this is an easy mistake
7959     // to make.
7960     int i = (Operands[3]->isImm()) ? 3 : 4;
7961     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
7962     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
7963     if (CE) break;
7964     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
7965     if (!E) break;
7966     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
7967     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
7968                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
7969       return Error(
7970           Op.getStartLoc(),
7971           "immediate expression for mov requires :lower16: or :upper16");
7972     break;
7973   }
7974   case ARM::HINT:
7975   case ARM::t2HINT: {
7976     unsigned Imm8 = Inst.getOperand(0).getImm();
7977     unsigned Pred = Inst.getOperand(1).getImm();
7978     // ESB is not predicable (pred must be AL). Without the RAS extension, this
7979     // behaves as any other unallocated hint.
7980     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
7981       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
7982                                                "predicable, but condition "
7983                                                "code specified");
7984     if (Imm8 == 0x14 && Pred != ARMCC::AL)
7985       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
7986                                                "predicable, but condition "
7987                                                "code specified");
7988     break;
7989   }
7990   case ARM::t2BFi:
7991   case ARM::t2BFr:
7992   case ARM::t2BFLi:
7993   case ARM::t2BFLr: {
7994     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<4, 1>() ||
7995         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
7996       return Error(Operands[2]->getStartLoc(),
7997                    "branch location out of range or not a multiple of 2");
7998 
7999     if (Opcode == ARM::t2BFi) {
8000       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<16, 1>())
8001         return Error(Operands[3]->getStartLoc(),
8002                      "branch target out of range or not a multiple of 2");
8003     } else if (Opcode == ARM::t2BFLi) {
8004       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<18, 1>())
8005         return Error(Operands[3]->getStartLoc(),
8006                      "branch target out of range or not a multiple of 2");
8007     }
8008     break;
8009   }
8010   case ARM::t2BFic: {
8011     if (!static_cast<ARMOperand &>(*Operands[1]).isUnsignedOffset<4, 1>() ||
8012         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
8013       return Error(Operands[1]->getStartLoc(),
8014                    "branch location out of range or not a multiple of 2");
8015 
8016     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<16, 1>())
8017       return Error(Operands[2]->getStartLoc(),
8018                    "branch target out of range or not a multiple of 2");
8019 
8020     assert(Inst.getOperand(0).isImm() == Inst.getOperand(2).isImm() &&
8021            "branch location and else branch target should either both be "
8022            "immediates or both labels");
8023 
8024     if (Inst.getOperand(0).isImm() && Inst.getOperand(2).isImm()) {
8025       int Diff = Inst.getOperand(2).getImm() - Inst.getOperand(0).getImm();
8026       if (Diff != 4 && Diff != 2)
8027         return Error(
8028             Operands[3]->getStartLoc(),
8029             "else branch target must be 2 or 4 greater than the branch location");
8030     }
8031     break;
8032   }
8033   case ARM::t2CLRM: {
8034     for (unsigned i = 2; i < Inst.getNumOperands(); i++) {
8035       if (Inst.getOperand(i).isReg() &&
8036           !ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(
8037               Inst.getOperand(i).getReg())) {
8038         return Error(Operands[2]->getStartLoc(),
8039                      "invalid register in register list. Valid registers are "
8040                      "r0-r12, lr/r14 and APSR.");
8041       }
8042     }
8043     break;
8044   }
8045   case ARM::DSB:
8046   case ARM::t2DSB: {
8047 
8048     if (Inst.getNumOperands() < 2)
8049       break;
8050 
8051     unsigned Option = Inst.getOperand(0).getImm();
8052     unsigned Pred = Inst.getOperand(1).getImm();
8053 
8054     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
8055     if (Option == 0 && Pred != ARMCC::AL)
8056       return Error(Operands[1]->getStartLoc(),
8057                    "instruction 'ssbb' is not predicable, but condition code "
8058                    "specified");
8059     if (Option == 4 && Pred != ARMCC::AL)
8060       return Error(Operands[1]->getStartLoc(),
8061                    "instruction 'pssbb' is not predicable, but condition code "
8062                    "specified");
8063     break;
8064   }
8065   case ARM::VMOVRRS: {
8066     // Source registers must be sequential.
8067     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
8068     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
8069     if (Sm1 != Sm + 1)
8070       return Error(Operands[5]->getStartLoc(),
8071                    "source operands must be sequential");
8072     break;
8073   }
8074   case ARM::VMOVSRR: {
8075     // Destination registers must be sequential.
8076     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
8077     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
8078     if (Sm1 != Sm + 1)
8079       return Error(Operands[3]->getStartLoc(),
8080                    "destination operands must be sequential");
8081     break;
8082   }
8083   case ARM::VLDMDIA:
8084   case ARM::VSTMDIA: {
8085     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
8086     auto &RegList = Op.getRegList();
8087     if (RegList.size() < 1 || RegList.size() > 16)
8088       return Error(Operands[3]->getStartLoc(),
8089                    "list of registers must be at least 1 and at most 16");
8090     break;
8091   }
8092   case ARM::MVE_VQDMULLs32bh:
8093   case ARM::MVE_VQDMULLs32th:
8094   case ARM::MVE_VCMULf32:
8095   case ARM::MVE_VMULLBs32:
8096   case ARM::MVE_VMULLTs32:
8097   case ARM::MVE_VMULLBu32:
8098   case ARM::MVE_VMULLTu32: {
8099     if (Operands[3]->getReg() == Operands[4]->getReg()) {
8100       return Error (Operands[3]->getStartLoc(),
8101                     "Qd register and Qn register can't be identical");
8102     }
8103     if (Operands[3]->getReg() == Operands[5]->getReg()) {
8104       return Error (Operands[3]->getStartLoc(),
8105                     "Qd register and Qm register can't be identical");
8106     }
8107     break;
8108   }
8109   case ARM::MVE_VMOV_rr_q: {
8110     if (Operands[4]->getReg() != Operands[6]->getReg())
8111       return Error (Operands[4]->getStartLoc(), "Q-registers must be the same");
8112     if (static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() !=
8113         static_cast<ARMOperand &>(*Operands[7]).getVectorIndex() + 2)
8114       return Error (Operands[5]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8115     break;
8116   }
8117   case ARM::MVE_VMOV_q_rr: {
8118     if (Operands[2]->getReg() != Operands[4]->getReg())
8119       return Error (Operands[2]->getStartLoc(), "Q-registers must be the same");
8120     if (static_cast<ARMOperand &>(*Operands[3]).getVectorIndex() !=
8121         static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() + 2)
8122       return Error (Operands[3]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8123     break;
8124   }
8125   case ARM::UMAAL:
8126   case ARM::UMLAL:
8127   case ARM::UMULL:
8128   case ARM::t2UMAAL:
8129   case ARM::t2UMLAL:
8130   case ARM::t2UMULL:
8131   case ARM::SMLAL:
8132   case ARM::SMLALBB:
8133   case ARM::SMLALBT:
8134   case ARM::SMLALD:
8135   case ARM::SMLALDX:
8136   case ARM::SMLALTB:
8137   case ARM::SMLALTT:
8138   case ARM::SMLSLD:
8139   case ARM::SMLSLDX:
8140   case ARM::SMULL:
8141   case ARM::t2SMLAL:
8142   case ARM::t2SMLALBB:
8143   case ARM::t2SMLALBT:
8144   case ARM::t2SMLALD:
8145   case ARM::t2SMLALDX:
8146   case ARM::t2SMLALTB:
8147   case ARM::t2SMLALTT:
8148   case ARM::t2SMLSLD:
8149   case ARM::t2SMLSLDX:
8150   case ARM::t2SMULL: {
8151     unsigned RdHi = Inst.getOperand(0).getReg();
8152     unsigned RdLo = Inst.getOperand(1).getReg();
8153     if(RdHi == RdLo) {
8154       return Error(Loc,
8155                    "unpredictable instruction, RdHi and RdLo must be different");
8156     }
8157     break;
8158   }
8159 
8160   case ARM::CDE_CX1:
8161   case ARM::CDE_CX1A:
8162   case ARM::CDE_CX1D:
8163   case ARM::CDE_CX1DA:
8164   case ARM::CDE_CX2:
8165   case ARM::CDE_CX2A:
8166   case ARM::CDE_CX2D:
8167   case ARM::CDE_CX2DA:
8168   case ARM::CDE_CX3:
8169   case ARM::CDE_CX3A:
8170   case ARM::CDE_CX3D:
8171   case ARM::CDE_CX3DA:
8172   case ARM::CDE_VCX1_vec:
8173   case ARM::CDE_VCX1_fpsp:
8174   case ARM::CDE_VCX1_fpdp:
8175   case ARM::CDE_VCX1A_vec:
8176   case ARM::CDE_VCX1A_fpsp:
8177   case ARM::CDE_VCX1A_fpdp:
8178   case ARM::CDE_VCX2_vec:
8179   case ARM::CDE_VCX2_fpsp:
8180   case ARM::CDE_VCX2_fpdp:
8181   case ARM::CDE_VCX2A_vec:
8182   case ARM::CDE_VCX2A_fpsp:
8183   case ARM::CDE_VCX2A_fpdp:
8184   case ARM::CDE_VCX3_vec:
8185   case ARM::CDE_VCX3_fpsp:
8186   case ARM::CDE_VCX3_fpdp:
8187   case ARM::CDE_VCX3A_vec:
8188   case ARM::CDE_VCX3A_fpsp:
8189   case ARM::CDE_VCX3A_fpdp: {
8190     assert(Inst.getOperand(1).isImm() &&
8191            "CDE operand 1 must be a coprocessor ID");
8192     int64_t Coproc = Inst.getOperand(1).getImm();
8193     if (Coproc < 8 && !ARM::isCDECoproc(Coproc, *STI))
8194       return Error(Operands[1]->getStartLoc(),
8195                    "coprocessor must be configured as CDE");
8196     else if (Coproc >= 8)
8197       return Error(Operands[1]->getStartLoc(),
8198                    "coprocessor must be in the range [p0, p7]");
8199     break;
8200   }
8201 
8202   case ARM::t2CDP:
8203   case ARM::t2CDP2:
8204   case ARM::t2LDC2L_OFFSET:
8205   case ARM::t2LDC2L_OPTION:
8206   case ARM::t2LDC2L_POST:
8207   case ARM::t2LDC2L_PRE:
8208   case ARM::t2LDC2_OFFSET:
8209   case ARM::t2LDC2_OPTION:
8210   case ARM::t2LDC2_POST:
8211   case ARM::t2LDC2_PRE:
8212   case ARM::t2LDCL_OFFSET:
8213   case ARM::t2LDCL_OPTION:
8214   case ARM::t2LDCL_POST:
8215   case ARM::t2LDCL_PRE:
8216   case ARM::t2LDC_OFFSET:
8217   case ARM::t2LDC_OPTION:
8218   case ARM::t2LDC_POST:
8219   case ARM::t2LDC_PRE:
8220   case ARM::t2MCR:
8221   case ARM::t2MCR2:
8222   case ARM::t2MCRR:
8223   case ARM::t2MCRR2:
8224   case ARM::t2MRC:
8225   case ARM::t2MRC2:
8226   case ARM::t2MRRC:
8227   case ARM::t2MRRC2:
8228   case ARM::t2STC2L_OFFSET:
8229   case ARM::t2STC2L_OPTION:
8230   case ARM::t2STC2L_POST:
8231   case ARM::t2STC2L_PRE:
8232   case ARM::t2STC2_OFFSET:
8233   case ARM::t2STC2_OPTION:
8234   case ARM::t2STC2_POST:
8235   case ARM::t2STC2_PRE:
8236   case ARM::t2STCL_OFFSET:
8237   case ARM::t2STCL_OPTION:
8238   case ARM::t2STCL_POST:
8239   case ARM::t2STCL_PRE:
8240   case ARM::t2STC_OFFSET:
8241   case ARM::t2STC_OPTION:
8242   case ARM::t2STC_POST:
8243   case ARM::t2STC_PRE: {
8244     unsigned Opcode = Inst.getOpcode();
8245     // Inst.getOperand indexes operands in the (oops ...) and (iops ...) dags,
8246     // CopInd is the index of the coprocessor operand.
8247     size_t CopInd = 0;
8248     if (Opcode == ARM::t2MRRC || Opcode == ARM::t2MRRC2)
8249       CopInd = 2;
8250     else if (Opcode == ARM::t2MRC || Opcode == ARM::t2MRC2)
8251       CopInd = 1;
8252     assert(Inst.getOperand(CopInd).isImm() &&
8253            "Operand must be a coprocessor ID");
8254     int64_t Coproc = Inst.getOperand(CopInd).getImm();
8255     // Operands[2] is the coprocessor operand at syntactic level
8256     if (ARM::isCDECoproc(Coproc, *STI))
8257       return Error(Operands[2]->getStartLoc(),
8258                    "coprocessor must be configured as GCP");
8259     break;
8260   }
8261   }
8262 
8263   return false;
8264 }
8265 
8266 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
8267   switch(Opc) {
8268   default: llvm_unreachable("unexpected opcode!");
8269   // VST1LN
8270   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8271   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8272   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8273   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8274   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8275   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8276   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
8277   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
8278   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
8279 
8280   // VST2LN
8281   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8282   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8283   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8284   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8285   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8286 
8287   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8288   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8289   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8290   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8291   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8292 
8293   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
8294   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
8295   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
8296   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
8297   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
8298 
8299   // VST3LN
8300   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8301   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8302   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8303   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
8304   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8305   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8306   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8307   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8308   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
8309   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8310   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
8311   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
8312   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
8313   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
8314   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
8315 
8316   // VST3
8317   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8318   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8319   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8320   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8321   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8322   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8323   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8324   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8325   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8326   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8327   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8328   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8329   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
8330   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
8331   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
8332   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
8333   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
8334   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
8335 
8336   // VST4LN
8337   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8338   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8339   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8340   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
8341   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8342   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8343   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8344   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8345   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
8346   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8347   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
8348   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
8349   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
8350   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
8351   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
8352 
8353   // VST4
8354   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8355   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8356   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8357   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8358   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8359   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8360   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8361   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8362   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8363   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8364   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8365   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8366   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
8367   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
8368   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
8369   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
8370   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
8371   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
8372   }
8373 }
8374 
8375 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
8376   switch(Opc) {
8377   default: llvm_unreachable("unexpected opcode!");
8378   // VLD1LN
8379   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8380   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8381   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8382   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8383   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8384   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8385   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
8386   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
8387   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
8388 
8389   // VLD2LN
8390   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8391   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8392   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8393   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
8394   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8395   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8396   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8397   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8398   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
8399   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8400   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
8401   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
8402   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
8403   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
8404   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
8405 
8406   // VLD3DUP
8407   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8408   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8409   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8410   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
8411   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8412   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8413   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8414   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8415   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8416   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
8417   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8418   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8419   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
8420   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
8421   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
8422   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
8423   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
8424   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
8425 
8426   // VLD3LN
8427   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8428   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8429   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8430   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
8431   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8432   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8433   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8434   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8435   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
8436   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8437   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
8438   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
8439   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
8440   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
8441   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
8442 
8443   // VLD3
8444   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8445   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8446   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8447   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8448   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8449   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8450   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8451   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8452   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8453   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8454   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8455   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8456   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
8457   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
8458   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
8459   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
8460   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
8461   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
8462 
8463   // VLD4LN
8464   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8465   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8466   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8467   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8468   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8469   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8470   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8471   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8472   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8473   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8474   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
8475   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
8476   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
8477   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
8478   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
8479 
8480   // VLD4DUP
8481   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8482   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8483   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8484   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
8485   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
8486   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8487   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8488   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8489   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8490   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
8491   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
8492   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8493   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
8494   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
8495   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
8496   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
8497   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
8498   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
8499 
8500   // VLD4
8501   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8502   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8503   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8504   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8505   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8506   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8507   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8508   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8509   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8510   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8511   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8512   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8513   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
8514   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
8515   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
8516   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
8517   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
8518   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
8519   }
8520 }
8521 
8522 bool ARMAsmParser::processInstruction(MCInst &Inst,
8523                                       const OperandVector &Operands,
8524                                       MCStreamer &Out) {
8525   // Check if we have the wide qualifier, because if it's present we
8526   // must avoid selecting a 16-bit thumb instruction.
8527   bool HasWideQualifier = false;
8528   for (auto &Op : Operands) {
8529     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
8530     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
8531       HasWideQualifier = true;
8532       break;
8533     }
8534   }
8535 
8536   switch (Inst.getOpcode()) {
8537   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
8538   case ARM::LDRT_POST:
8539   case ARM::LDRBT_POST: {
8540     const unsigned Opcode =
8541       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
8542                                            : ARM::LDRBT_POST_IMM;
8543     MCInst TmpInst;
8544     TmpInst.setOpcode(Opcode);
8545     TmpInst.addOperand(Inst.getOperand(0));
8546     TmpInst.addOperand(Inst.getOperand(1));
8547     TmpInst.addOperand(Inst.getOperand(1));
8548     TmpInst.addOperand(MCOperand::createReg(0));
8549     TmpInst.addOperand(MCOperand::createImm(0));
8550     TmpInst.addOperand(Inst.getOperand(2));
8551     TmpInst.addOperand(Inst.getOperand(3));
8552     Inst = TmpInst;
8553     return true;
8554   }
8555   // Alias for 'ldr{sb,h,sh}t Rt, [Rn] {, #imm}' for ommitted immediate.
8556   case ARM::LDRSBTii:
8557   case ARM::LDRHTii:
8558   case ARM::LDRSHTii: {
8559     MCInst TmpInst;
8560 
8561     if (Inst.getOpcode() == ARM::LDRSBTii)
8562       TmpInst.setOpcode(ARM::LDRSBTi);
8563     else if (Inst.getOpcode() == ARM::LDRHTii)
8564       TmpInst.setOpcode(ARM::LDRHTi);
8565     else if (Inst.getOpcode() == ARM::LDRSHTii)
8566       TmpInst.setOpcode(ARM::LDRSHTi);
8567     TmpInst.addOperand(Inst.getOperand(0));
8568     TmpInst.addOperand(Inst.getOperand(1));
8569     TmpInst.addOperand(Inst.getOperand(1));
8570     TmpInst.addOperand(MCOperand::createImm(256));
8571     TmpInst.addOperand(Inst.getOperand(2));
8572     Inst = TmpInst;
8573     return true;
8574   }
8575   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
8576   case ARM::STRT_POST:
8577   case ARM::STRBT_POST: {
8578     const unsigned Opcode =
8579       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
8580                                            : ARM::STRBT_POST_IMM;
8581     MCInst TmpInst;
8582     TmpInst.setOpcode(Opcode);
8583     TmpInst.addOperand(Inst.getOperand(1));
8584     TmpInst.addOperand(Inst.getOperand(0));
8585     TmpInst.addOperand(Inst.getOperand(1));
8586     TmpInst.addOperand(MCOperand::createReg(0));
8587     TmpInst.addOperand(MCOperand::createImm(0));
8588     TmpInst.addOperand(Inst.getOperand(2));
8589     TmpInst.addOperand(Inst.getOperand(3));
8590     Inst = TmpInst;
8591     return true;
8592   }
8593   // Alias for alternate form of 'ADR Rd, #imm' instruction.
8594   case ARM::ADDri: {
8595     if (Inst.getOperand(1).getReg() != ARM::PC ||
8596         Inst.getOperand(5).getReg() != 0 ||
8597         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
8598       return false;
8599     MCInst TmpInst;
8600     TmpInst.setOpcode(ARM::ADR);
8601     TmpInst.addOperand(Inst.getOperand(0));
8602     if (Inst.getOperand(2).isImm()) {
8603       // Immediate (mod_imm) will be in its encoded form, we must unencode it
8604       // before passing it to the ADR instruction.
8605       unsigned Enc = Inst.getOperand(2).getImm();
8606       TmpInst.addOperand(MCOperand::createImm(
8607         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
8608     } else {
8609       // Turn PC-relative expression into absolute expression.
8610       // Reading PC provides the start of the current instruction + 8 and
8611       // the transform to adr is biased by that.
8612       MCSymbol *Dot = getContext().createTempSymbol();
8613       Out.emitLabel(Dot);
8614       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
8615       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
8616                                                      MCSymbolRefExpr::VK_None,
8617                                                      getContext());
8618       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
8619       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
8620                                                      getContext());
8621       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
8622                                                         getContext());
8623       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
8624     }
8625     TmpInst.addOperand(Inst.getOperand(3));
8626     TmpInst.addOperand(Inst.getOperand(4));
8627     Inst = TmpInst;
8628     return true;
8629   }
8630   // Aliases for alternate PC+imm syntax of LDR instructions.
8631   case ARM::t2LDRpcrel:
8632     // Select the narrow version if the immediate will fit.
8633     if (Inst.getOperand(1).getImm() > 0 &&
8634         Inst.getOperand(1).getImm() <= 0xff &&
8635         !HasWideQualifier)
8636       Inst.setOpcode(ARM::tLDRpci);
8637     else
8638       Inst.setOpcode(ARM::t2LDRpci);
8639     return true;
8640   case ARM::t2LDRBpcrel:
8641     Inst.setOpcode(ARM::t2LDRBpci);
8642     return true;
8643   case ARM::t2LDRHpcrel:
8644     Inst.setOpcode(ARM::t2LDRHpci);
8645     return true;
8646   case ARM::t2LDRSBpcrel:
8647     Inst.setOpcode(ARM::t2LDRSBpci);
8648     return true;
8649   case ARM::t2LDRSHpcrel:
8650     Inst.setOpcode(ARM::t2LDRSHpci);
8651     return true;
8652   case ARM::LDRConstPool:
8653   case ARM::tLDRConstPool:
8654   case ARM::t2LDRConstPool: {
8655     // Pseudo instruction ldr rt, =immediate is converted to a
8656     // MOV rt, immediate if immediate is known and representable
8657     // otherwise we create a constant pool entry that we load from.
8658     MCInst TmpInst;
8659     if (Inst.getOpcode() == ARM::LDRConstPool)
8660       TmpInst.setOpcode(ARM::LDRi12);
8661     else if (Inst.getOpcode() == ARM::tLDRConstPool)
8662       TmpInst.setOpcode(ARM::tLDRpci);
8663     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
8664       TmpInst.setOpcode(ARM::t2LDRpci);
8665     const ARMOperand &PoolOperand =
8666       (HasWideQualifier ?
8667        static_cast<ARMOperand &>(*Operands[4]) :
8668        static_cast<ARMOperand &>(*Operands[3]));
8669     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
8670     // If SubExprVal is a constant we may be able to use a MOV
8671     if (isa<MCConstantExpr>(SubExprVal) &&
8672         Inst.getOperand(0).getReg() != ARM::PC &&
8673         Inst.getOperand(0).getReg() != ARM::SP) {
8674       int64_t Value =
8675         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
8676       bool UseMov  = true;
8677       bool MovHasS = true;
8678       if (Inst.getOpcode() == ARM::LDRConstPool) {
8679         // ARM Constant
8680         if (ARM_AM::getSOImmVal(Value) != -1) {
8681           Value = ARM_AM::getSOImmVal(Value);
8682           TmpInst.setOpcode(ARM::MOVi);
8683         }
8684         else if (ARM_AM::getSOImmVal(~Value) != -1) {
8685           Value = ARM_AM::getSOImmVal(~Value);
8686           TmpInst.setOpcode(ARM::MVNi);
8687         }
8688         else if (hasV6T2Ops() &&
8689                  Value >=0 && Value < 65536) {
8690           TmpInst.setOpcode(ARM::MOVi16);
8691           MovHasS = false;
8692         }
8693         else
8694           UseMov = false;
8695       }
8696       else {
8697         // Thumb/Thumb2 Constant
8698         if (hasThumb2() &&
8699             ARM_AM::getT2SOImmVal(Value) != -1)
8700           TmpInst.setOpcode(ARM::t2MOVi);
8701         else if (hasThumb2() &&
8702                  ARM_AM::getT2SOImmVal(~Value) != -1) {
8703           TmpInst.setOpcode(ARM::t2MVNi);
8704           Value = ~Value;
8705         }
8706         else if (hasV8MBaseline() &&
8707                  Value >=0 && Value < 65536) {
8708           TmpInst.setOpcode(ARM::t2MOVi16);
8709           MovHasS = false;
8710         }
8711         else
8712           UseMov = false;
8713       }
8714       if (UseMov) {
8715         TmpInst.addOperand(Inst.getOperand(0));           // Rt
8716         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
8717         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8718         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8719         if (MovHasS)
8720           TmpInst.addOperand(MCOperand::createReg(0));    // S
8721         Inst = TmpInst;
8722         return true;
8723       }
8724     }
8725     // No opportunity to use MOV/MVN create constant pool
8726     const MCExpr *CPLoc =
8727       getTargetStreamer().addConstantPoolEntry(SubExprVal,
8728                                                PoolOperand.getStartLoc());
8729     TmpInst.addOperand(Inst.getOperand(0));           // Rt
8730     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
8731     if (TmpInst.getOpcode() == ARM::LDRi12)
8732       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
8733     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8734     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8735     Inst = TmpInst;
8736     return true;
8737   }
8738   // Handle NEON VST complex aliases.
8739   case ARM::VST1LNdWB_register_Asm_8:
8740   case ARM::VST1LNdWB_register_Asm_16:
8741   case ARM::VST1LNdWB_register_Asm_32: {
8742     MCInst TmpInst;
8743     // Shuffle the operands around so the lane index operand is in the
8744     // right place.
8745     unsigned Spacing;
8746     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8747     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8748     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8749     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8750     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8751     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8752     TmpInst.addOperand(Inst.getOperand(1)); // lane
8753     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8754     TmpInst.addOperand(Inst.getOperand(6));
8755     Inst = TmpInst;
8756     return true;
8757   }
8758 
8759   case ARM::VST2LNdWB_register_Asm_8:
8760   case ARM::VST2LNdWB_register_Asm_16:
8761   case ARM::VST2LNdWB_register_Asm_32:
8762   case ARM::VST2LNqWB_register_Asm_16:
8763   case ARM::VST2LNqWB_register_Asm_32: {
8764     MCInst TmpInst;
8765     // Shuffle the operands around so the lane index operand is in the
8766     // right place.
8767     unsigned Spacing;
8768     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8769     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8770     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8771     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8772     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8773     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8774     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8775                                             Spacing));
8776     TmpInst.addOperand(Inst.getOperand(1)); // lane
8777     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8778     TmpInst.addOperand(Inst.getOperand(6));
8779     Inst = TmpInst;
8780     return true;
8781   }
8782 
8783   case ARM::VST3LNdWB_register_Asm_8:
8784   case ARM::VST3LNdWB_register_Asm_16:
8785   case ARM::VST3LNdWB_register_Asm_32:
8786   case ARM::VST3LNqWB_register_Asm_16:
8787   case ARM::VST3LNqWB_register_Asm_32: {
8788     MCInst TmpInst;
8789     // Shuffle the operands around so the lane index operand is in the
8790     // right place.
8791     unsigned Spacing;
8792     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8793     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8794     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8795     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8796     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8797     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8798     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8799                                             Spacing));
8800     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8801                                             Spacing * 2));
8802     TmpInst.addOperand(Inst.getOperand(1)); // lane
8803     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8804     TmpInst.addOperand(Inst.getOperand(6));
8805     Inst = TmpInst;
8806     return true;
8807   }
8808 
8809   case ARM::VST4LNdWB_register_Asm_8:
8810   case ARM::VST4LNdWB_register_Asm_16:
8811   case ARM::VST4LNdWB_register_Asm_32:
8812   case ARM::VST4LNqWB_register_Asm_16:
8813   case ARM::VST4LNqWB_register_Asm_32: {
8814     MCInst TmpInst;
8815     // Shuffle the operands around so the lane index operand is in the
8816     // right place.
8817     unsigned Spacing;
8818     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8819     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8820     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8821     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8822     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8823     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8824     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8825                                             Spacing));
8826     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8827                                             Spacing * 2));
8828     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8829                                             Spacing * 3));
8830     TmpInst.addOperand(Inst.getOperand(1)); // lane
8831     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8832     TmpInst.addOperand(Inst.getOperand(6));
8833     Inst = TmpInst;
8834     return true;
8835   }
8836 
8837   case ARM::VST1LNdWB_fixed_Asm_8:
8838   case ARM::VST1LNdWB_fixed_Asm_16:
8839   case ARM::VST1LNdWB_fixed_Asm_32: {
8840     MCInst TmpInst;
8841     // Shuffle the operands around so the lane index operand is in the
8842     // right place.
8843     unsigned Spacing;
8844     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8845     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8846     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8847     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8848     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8849     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8850     TmpInst.addOperand(Inst.getOperand(1)); // lane
8851     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8852     TmpInst.addOperand(Inst.getOperand(5));
8853     Inst = TmpInst;
8854     return true;
8855   }
8856 
8857   case ARM::VST2LNdWB_fixed_Asm_8:
8858   case ARM::VST2LNdWB_fixed_Asm_16:
8859   case ARM::VST2LNdWB_fixed_Asm_32:
8860   case ARM::VST2LNqWB_fixed_Asm_16:
8861   case ARM::VST2LNqWB_fixed_Asm_32: {
8862     MCInst TmpInst;
8863     // Shuffle the operands around so the lane index operand is in the
8864     // right place.
8865     unsigned Spacing;
8866     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8867     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8868     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8869     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8870     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8871     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8872     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8873                                             Spacing));
8874     TmpInst.addOperand(Inst.getOperand(1)); // lane
8875     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8876     TmpInst.addOperand(Inst.getOperand(5));
8877     Inst = TmpInst;
8878     return true;
8879   }
8880 
8881   case ARM::VST3LNdWB_fixed_Asm_8:
8882   case ARM::VST3LNdWB_fixed_Asm_16:
8883   case ARM::VST3LNdWB_fixed_Asm_32:
8884   case ARM::VST3LNqWB_fixed_Asm_16:
8885   case ARM::VST3LNqWB_fixed_Asm_32: {
8886     MCInst TmpInst;
8887     // Shuffle the operands around so the lane index operand is in the
8888     // right place.
8889     unsigned Spacing;
8890     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8891     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8892     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8893     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8894     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8895     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8896     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8897                                             Spacing));
8898     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8899                                             Spacing * 2));
8900     TmpInst.addOperand(Inst.getOperand(1)); // lane
8901     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8902     TmpInst.addOperand(Inst.getOperand(5));
8903     Inst = TmpInst;
8904     return true;
8905   }
8906 
8907   case ARM::VST4LNdWB_fixed_Asm_8:
8908   case ARM::VST4LNdWB_fixed_Asm_16:
8909   case ARM::VST4LNdWB_fixed_Asm_32:
8910   case ARM::VST4LNqWB_fixed_Asm_16:
8911   case ARM::VST4LNqWB_fixed_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(MCOperand::createReg(0)); // Rm
8921     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8922     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8923                                             Spacing));
8924     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8925                                             Spacing * 2));
8926     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8927                                             Spacing * 3));
8928     TmpInst.addOperand(Inst.getOperand(1)); // lane
8929     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8930     TmpInst.addOperand(Inst.getOperand(5));
8931     Inst = TmpInst;
8932     return true;
8933   }
8934 
8935   case ARM::VST1LNdAsm_8:
8936   case ARM::VST1LNdAsm_16:
8937   case ARM::VST1LNdAsm_32: {
8938     MCInst TmpInst;
8939     // Shuffle the operands around so the lane index operand is in the
8940     // right place.
8941     unsigned Spacing;
8942     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8943     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8944     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8945     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8946     TmpInst.addOperand(Inst.getOperand(1)); // lane
8947     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8948     TmpInst.addOperand(Inst.getOperand(5));
8949     Inst = TmpInst;
8950     return true;
8951   }
8952 
8953   case ARM::VST2LNdAsm_8:
8954   case ARM::VST2LNdAsm_16:
8955   case ARM::VST2LNdAsm_32:
8956   case ARM::VST2LNqAsm_16:
8957   case ARM::VST2LNqAsm_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
8964     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8965     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8966     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8967                                             Spacing));
8968     TmpInst.addOperand(Inst.getOperand(1)); // lane
8969     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8970     TmpInst.addOperand(Inst.getOperand(5));
8971     Inst = TmpInst;
8972     return true;
8973   }
8974 
8975   case ARM::VST3LNdAsm_8:
8976   case ARM::VST3LNdAsm_16:
8977   case ARM::VST3LNdAsm_32:
8978   case ARM::VST3LNqAsm_16:
8979   case ARM::VST3LNqAsm_32: {
8980     MCInst TmpInst;
8981     // Shuffle the operands around so the lane index operand is in the
8982     // right place.
8983     unsigned Spacing;
8984     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8985     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8986     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8987     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8988     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8989                                             Spacing));
8990     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8991                                             Spacing * 2));
8992     TmpInst.addOperand(Inst.getOperand(1)); // lane
8993     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8994     TmpInst.addOperand(Inst.getOperand(5));
8995     Inst = TmpInst;
8996     return true;
8997   }
8998 
8999   case ARM::VST4LNdAsm_8:
9000   case ARM::VST4LNdAsm_16:
9001   case ARM::VST4LNdAsm_32:
9002   case ARM::VST4LNqAsm_16:
9003   case ARM::VST4LNqAsm_32: {
9004     MCInst TmpInst;
9005     // Shuffle the operands around so the lane index operand is in the
9006     // right place.
9007     unsigned Spacing;
9008     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9009     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9010     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9011     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9012     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9013                                             Spacing));
9014     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9015                                             Spacing * 2));
9016     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9017                                             Spacing * 3));
9018     TmpInst.addOperand(Inst.getOperand(1)); // lane
9019     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9020     TmpInst.addOperand(Inst.getOperand(5));
9021     Inst = TmpInst;
9022     return true;
9023   }
9024 
9025   // Handle NEON VLD complex aliases.
9026   case ARM::VLD1LNdWB_register_Asm_8:
9027   case ARM::VLD1LNdWB_register_Asm_16:
9028   case ARM::VLD1LNdWB_register_Asm_32: {
9029     MCInst TmpInst;
9030     // Shuffle the operands around so the lane index operand is in the
9031     // right place.
9032     unsigned Spacing;
9033     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9034     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9035     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9036     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9037     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9038     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9039     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9040     TmpInst.addOperand(Inst.getOperand(1)); // lane
9041     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9042     TmpInst.addOperand(Inst.getOperand(6));
9043     Inst = TmpInst;
9044     return true;
9045   }
9046 
9047   case ARM::VLD2LNdWB_register_Asm_8:
9048   case ARM::VLD2LNdWB_register_Asm_16:
9049   case ARM::VLD2LNdWB_register_Asm_32:
9050   case ARM::VLD2LNqWB_register_Asm_16:
9051   case ARM::VLD2LNqWB_register_Asm_32: {
9052     MCInst TmpInst;
9053     // Shuffle the operands around so the lane index operand is in the
9054     // right place.
9055     unsigned Spacing;
9056     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9057     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9058     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9059                                             Spacing));
9060     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9061     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9062     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9063     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9064     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9065     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9066                                             Spacing));
9067     TmpInst.addOperand(Inst.getOperand(1)); // lane
9068     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9069     TmpInst.addOperand(Inst.getOperand(6));
9070     Inst = TmpInst;
9071     return true;
9072   }
9073 
9074   case ARM::VLD3LNdWB_register_Asm_8:
9075   case ARM::VLD3LNdWB_register_Asm_16:
9076   case ARM::VLD3LNdWB_register_Asm_32:
9077   case ARM::VLD3LNqWB_register_Asm_16:
9078   case ARM::VLD3LNqWB_register_Asm_32: {
9079     MCInst TmpInst;
9080     // Shuffle the operands around so the lane index operand is in the
9081     // right place.
9082     unsigned Spacing;
9083     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9084     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9085     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9086                                             Spacing));
9087     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9088                                             Spacing * 2));
9089     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9090     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9091     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9092     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9093     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9094     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9095                                             Spacing));
9096     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9097                                             Spacing * 2));
9098     TmpInst.addOperand(Inst.getOperand(1)); // lane
9099     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9100     TmpInst.addOperand(Inst.getOperand(6));
9101     Inst = TmpInst;
9102     return true;
9103   }
9104 
9105   case ARM::VLD4LNdWB_register_Asm_8:
9106   case ARM::VLD4LNdWB_register_Asm_16:
9107   case ARM::VLD4LNdWB_register_Asm_32:
9108   case ARM::VLD4LNqWB_register_Asm_16:
9109   case ARM::VLD4LNqWB_register_Asm_32: {
9110     MCInst TmpInst;
9111     // Shuffle the operands around so the lane index operand is in the
9112     // right place.
9113     unsigned Spacing;
9114     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9115     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9116     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9117                                             Spacing));
9118     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9119                                             Spacing * 2));
9120     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9121                                             Spacing * 3));
9122     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9123     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9124     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9125     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9126     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9127     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9128                                             Spacing));
9129     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9130                                             Spacing * 2));
9131     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9132                                             Spacing * 3));
9133     TmpInst.addOperand(Inst.getOperand(1)); // lane
9134     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9135     TmpInst.addOperand(Inst.getOperand(6));
9136     Inst = TmpInst;
9137     return true;
9138   }
9139 
9140   case ARM::VLD1LNdWB_fixed_Asm_8:
9141   case ARM::VLD1LNdWB_fixed_Asm_16:
9142   case ARM::VLD1LNdWB_fixed_Asm_32: {
9143     MCInst TmpInst;
9144     // Shuffle the operands around so the lane index operand is in the
9145     // right place.
9146     unsigned Spacing;
9147     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9148     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9149     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9150     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9151     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9152     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9153     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9154     TmpInst.addOperand(Inst.getOperand(1)); // lane
9155     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9156     TmpInst.addOperand(Inst.getOperand(5));
9157     Inst = TmpInst;
9158     return true;
9159   }
9160 
9161   case ARM::VLD2LNdWB_fixed_Asm_8:
9162   case ARM::VLD2LNdWB_fixed_Asm_16:
9163   case ARM::VLD2LNdWB_fixed_Asm_32:
9164   case ARM::VLD2LNqWB_fixed_Asm_16:
9165   case ARM::VLD2LNqWB_fixed_Asm_32: {
9166     MCInst TmpInst;
9167     // Shuffle the operands around so the lane index operand is in the
9168     // right place.
9169     unsigned Spacing;
9170     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9171     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9172     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9173                                             Spacing));
9174     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9175     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9176     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9177     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9178     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9179     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9180                                             Spacing));
9181     TmpInst.addOperand(Inst.getOperand(1)); // lane
9182     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9183     TmpInst.addOperand(Inst.getOperand(5));
9184     Inst = TmpInst;
9185     return true;
9186   }
9187 
9188   case ARM::VLD3LNdWB_fixed_Asm_8:
9189   case ARM::VLD3LNdWB_fixed_Asm_16:
9190   case ARM::VLD3LNdWB_fixed_Asm_32:
9191   case ARM::VLD3LNqWB_fixed_Asm_16:
9192   case ARM::VLD3LNqWB_fixed_Asm_32: {
9193     MCInst TmpInst;
9194     // Shuffle the operands around so the lane index operand is in the
9195     // right place.
9196     unsigned Spacing;
9197     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9198     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9199     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9200                                             Spacing));
9201     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9202                                             Spacing * 2));
9203     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9204     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9205     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9206     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9207     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9208     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9209                                             Spacing));
9210     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9211                                             Spacing * 2));
9212     TmpInst.addOperand(Inst.getOperand(1)); // lane
9213     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9214     TmpInst.addOperand(Inst.getOperand(5));
9215     Inst = TmpInst;
9216     return true;
9217   }
9218 
9219   case ARM::VLD4LNdWB_fixed_Asm_8:
9220   case ARM::VLD4LNdWB_fixed_Asm_16:
9221   case ARM::VLD4LNdWB_fixed_Asm_32:
9222   case ARM::VLD4LNqWB_fixed_Asm_16:
9223   case ARM::VLD4LNqWB_fixed_Asm_32: {
9224     MCInst TmpInst;
9225     // Shuffle the operands around so the lane index operand is in the
9226     // right place.
9227     unsigned Spacing;
9228     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9229     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9230     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9231                                             Spacing));
9232     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9233                                             Spacing * 2));
9234     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9235                                             Spacing * 3));
9236     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9237     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9238     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9239     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9240     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9241     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9242                                             Spacing));
9243     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9244                                             Spacing * 2));
9245     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9246                                             Spacing * 3));
9247     TmpInst.addOperand(Inst.getOperand(1)); // lane
9248     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9249     TmpInst.addOperand(Inst.getOperand(5));
9250     Inst = TmpInst;
9251     return true;
9252   }
9253 
9254   case ARM::VLD1LNdAsm_8:
9255   case ARM::VLD1LNdAsm_16:
9256   case ARM::VLD1LNdAsm_32: {
9257     MCInst TmpInst;
9258     // Shuffle the operands around so the lane index operand is in the
9259     // right place.
9260     unsigned Spacing;
9261     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9262     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9263     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9264     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9265     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9266     TmpInst.addOperand(Inst.getOperand(1)); // lane
9267     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9268     TmpInst.addOperand(Inst.getOperand(5));
9269     Inst = TmpInst;
9270     return true;
9271   }
9272 
9273   case ARM::VLD2LNdAsm_8:
9274   case ARM::VLD2LNdAsm_16:
9275   case ARM::VLD2LNdAsm_32:
9276   case ARM::VLD2LNqAsm_16:
9277   case ARM::VLD2LNqAsm_32: {
9278     MCInst TmpInst;
9279     // Shuffle the operands around so the lane index operand is in the
9280     // right place.
9281     unsigned Spacing;
9282     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9283     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9284     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9285                                             Spacing));
9286     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9287     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9288     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9289     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9290                                             Spacing));
9291     TmpInst.addOperand(Inst.getOperand(1)); // lane
9292     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9293     TmpInst.addOperand(Inst.getOperand(5));
9294     Inst = TmpInst;
9295     return true;
9296   }
9297 
9298   case ARM::VLD3LNdAsm_8:
9299   case ARM::VLD3LNdAsm_16:
9300   case ARM::VLD3LNdAsm_32:
9301   case ARM::VLD3LNqAsm_16:
9302   case ARM::VLD3LNqAsm_32: {
9303     MCInst TmpInst;
9304     // Shuffle the operands around so the lane index operand is in the
9305     // right place.
9306     unsigned Spacing;
9307     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9308     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9309     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9310                                             Spacing));
9311     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9312                                             Spacing * 2));
9313     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9314     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9315     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9316     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9317                                             Spacing));
9318     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9319                                             Spacing * 2));
9320     TmpInst.addOperand(Inst.getOperand(1)); // lane
9321     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9322     TmpInst.addOperand(Inst.getOperand(5));
9323     Inst = TmpInst;
9324     return true;
9325   }
9326 
9327   case ARM::VLD4LNdAsm_8:
9328   case ARM::VLD4LNdAsm_16:
9329   case ARM::VLD4LNdAsm_32:
9330   case ARM::VLD4LNqAsm_16:
9331   case ARM::VLD4LNqAsm_32: {
9332     MCInst TmpInst;
9333     // Shuffle the operands around so the lane index operand is in the
9334     // right place.
9335     unsigned Spacing;
9336     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9337     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9338     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9339                                             Spacing));
9340     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9341                                             Spacing * 2));
9342     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9343                                             Spacing * 3));
9344     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9345     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9346     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9347     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9348                                             Spacing));
9349     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9350                                             Spacing * 2));
9351     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9352                                             Spacing * 3));
9353     TmpInst.addOperand(Inst.getOperand(1)); // lane
9354     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9355     TmpInst.addOperand(Inst.getOperand(5));
9356     Inst = TmpInst;
9357     return true;
9358   }
9359 
9360   // VLD3DUP single 3-element structure to all lanes instructions.
9361   case ARM::VLD3DUPdAsm_8:
9362   case ARM::VLD3DUPdAsm_16:
9363   case ARM::VLD3DUPdAsm_32:
9364   case ARM::VLD3DUPqAsm_8:
9365   case ARM::VLD3DUPqAsm_16:
9366   case ARM::VLD3DUPqAsm_32: {
9367     MCInst TmpInst;
9368     unsigned Spacing;
9369     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9370     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9371     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9372                                             Spacing));
9373     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9374                                             Spacing * 2));
9375     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9376     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9377     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9378     TmpInst.addOperand(Inst.getOperand(4));
9379     Inst = TmpInst;
9380     return true;
9381   }
9382 
9383   case ARM::VLD3DUPdWB_fixed_Asm_8:
9384   case ARM::VLD3DUPdWB_fixed_Asm_16:
9385   case ARM::VLD3DUPdWB_fixed_Asm_32:
9386   case ARM::VLD3DUPqWB_fixed_Asm_8:
9387   case ARM::VLD3DUPqWB_fixed_Asm_16:
9388   case ARM::VLD3DUPqWB_fixed_Asm_32: {
9389     MCInst TmpInst;
9390     unsigned Spacing;
9391     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9392     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9393     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9394                                             Spacing));
9395     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9396                                             Spacing * 2));
9397     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9398     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9399     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9400     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9401     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9402     TmpInst.addOperand(Inst.getOperand(4));
9403     Inst = TmpInst;
9404     return true;
9405   }
9406 
9407   case ARM::VLD3DUPdWB_register_Asm_8:
9408   case ARM::VLD3DUPdWB_register_Asm_16:
9409   case ARM::VLD3DUPdWB_register_Asm_32:
9410   case ARM::VLD3DUPqWB_register_Asm_8:
9411   case ARM::VLD3DUPqWB_register_Asm_16:
9412   case ARM::VLD3DUPqWB_register_Asm_32: {
9413     MCInst TmpInst;
9414     unsigned Spacing;
9415     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9416     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9417     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9418                                             Spacing));
9419     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9420                                             Spacing * 2));
9421     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9422     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9423     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9424     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9425     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9426     TmpInst.addOperand(Inst.getOperand(5));
9427     Inst = TmpInst;
9428     return true;
9429   }
9430 
9431   // VLD3 multiple 3-element structure instructions.
9432   case ARM::VLD3dAsm_8:
9433   case ARM::VLD3dAsm_16:
9434   case ARM::VLD3dAsm_32:
9435   case ARM::VLD3qAsm_8:
9436   case ARM::VLD3qAsm_16:
9437   case ARM::VLD3qAsm_32: {
9438     MCInst TmpInst;
9439     unsigned Spacing;
9440     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9441     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9442     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9443                                             Spacing));
9444     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9445                                             Spacing * 2));
9446     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9447     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9448     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9449     TmpInst.addOperand(Inst.getOperand(4));
9450     Inst = TmpInst;
9451     return true;
9452   }
9453 
9454   case ARM::VLD3dWB_fixed_Asm_8:
9455   case ARM::VLD3dWB_fixed_Asm_16:
9456   case ARM::VLD3dWB_fixed_Asm_32:
9457   case ARM::VLD3qWB_fixed_Asm_8:
9458   case ARM::VLD3qWB_fixed_Asm_16:
9459   case ARM::VLD3qWB_fixed_Asm_32: {
9460     MCInst TmpInst;
9461     unsigned Spacing;
9462     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9463     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9464     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9465                                             Spacing));
9466     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9467                                             Spacing * 2));
9468     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9469     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9470     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9471     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9472     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9473     TmpInst.addOperand(Inst.getOperand(4));
9474     Inst = TmpInst;
9475     return true;
9476   }
9477 
9478   case ARM::VLD3dWB_register_Asm_8:
9479   case ARM::VLD3dWB_register_Asm_16:
9480   case ARM::VLD3dWB_register_Asm_32:
9481   case ARM::VLD3qWB_register_Asm_8:
9482   case ARM::VLD3qWB_register_Asm_16:
9483   case ARM::VLD3qWB_register_Asm_32: {
9484     MCInst TmpInst;
9485     unsigned Spacing;
9486     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9487     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9488     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9489                                             Spacing));
9490     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9491                                             Spacing * 2));
9492     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9493     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9494     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9495     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9496     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9497     TmpInst.addOperand(Inst.getOperand(5));
9498     Inst = TmpInst;
9499     return true;
9500   }
9501 
9502   // VLD4DUP single 3-element structure to all lanes instructions.
9503   case ARM::VLD4DUPdAsm_8:
9504   case ARM::VLD4DUPdAsm_16:
9505   case ARM::VLD4DUPdAsm_32:
9506   case ARM::VLD4DUPqAsm_8:
9507   case ARM::VLD4DUPqAsm_16:
9508   case ARM::VLD4DUPqAsm_32: {
9509     MCInst TmpInst;
9510     unsigned Spacing;
9511     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9512     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9513     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9514                                             Spacing));
9515     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9516                                             Spacing * 2));
9517     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9518                                             Spacing * 3));
9519     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9520     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9521     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9522     TmpInst.addOperand(Inst.getOperand(4));
9523     Inst = TmpInst;
9524     return true;
9525   }
9526 
9527   case ARM::VLD4DUPdWB_fixed_Asm_8:
9528   case ARM::VLD4DUPdWB_fixed_Asm_16:
9529   case ARM::VLD4DUPdWB_fixed_Asm_32:
9530   case ARM::VLD4DUPqWB_fixed_Asm_8:
9531   case ARM::VLD4DUPqWB_fixed_Asm_16:
9532   case ARM::VLD4DUPqWB_fixed_Asm_32: {
9533     MCInst TmpInst;
9534     unsigned Spacing;
9535     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9536     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9537     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9538                                             Spacing));
9539     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9540                                             Spacing * 2));
9541     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9542                                             Spacing * 3));
9543     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9544     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9545     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9546     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9547     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9548     TmpInst.addOperand(Inst.getOperand(4));
9549     Inst = TmpInst;
9550     return true;
9551   }
9552 
9553   case ARM::VLD4DUPdWB_register_Asm_8:
9554   case ARM::VLD4DUPdWB_register_Asm_16:
9555   case ARM::VLD4DUPdWB_register_Asm_32:
9556   case ARM::VLD4DUPqWB_register_Asm_8:
9557   case ARM::VLD4DUPqWB_register_Asm_16:
9558   case ARM::VLD4DUPqWB_register_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(MCOperand::createReg(Inst.getOperand(0).getReg() +
9568                                             Spacing * 3));
9569     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9570     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9571     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9572     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9573     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9574     TmpInst.addOperand(Inst.getOperand(5));
9575     Inst = TmpInst;
9576     return true;
9577   }
9578 
9579   // VLD4 multiple 4-element structure instructions.
9580   case ARM::VLD4dAsm_8:
9581   case ARM::VLD4dAsm_16:
9582   case ARM::VLD4dAsm_32:
9583   case ARM::VLD4qAsm_8:
9584   case ARM::VLD4qAsm_16:
9585   case ARM::VLD4qAsm_32: {
9586     MCInst TmpInst;
9587     unsigned Spacing;
9588     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9589     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9590     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9591                                             Spacing));
9592     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9593                                             Spacing * 2));
9594     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9595                                             Spacing * 3));
9596     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9597     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9598     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9599     TmpInst.addOperand(Inst.getOperand(4));
9600     Inst = TmpInst;
9601     return true;
9602   }
9603 
9604   case ARM::VLD4dWB_fixed_Asm_8:
9605   case ARM::VLD4dWB_fixed_Asm_16:
9606   case ARM::VLD4dWB_fixed_Asm_32:
9607   case ARM::VLD4qWB_fixed_Asm_8:
9608   case ARM::VLD4qWB_fixed_Asm_16:
9609   case ARM::VLD4qWB_fixed_Asm_32: {
9610     MCInst TmpInst;
9611     unsigned Spacing;
9612     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9613     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9614     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9615                                             Spacing));
9616     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9617                                             Spacing * 2));
9618     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9619                                             Spacing * 3));
9620     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9621     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9622     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9623     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9624     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9625     TmpInst.addOperand(Inst.getOperand(4));
9626     Inst = TmpInst;
9627     return true;
9628   }
9629 
9630   case ARM::VLD4dWB_register_Asm_8:
9631   case ARM::VLD4dWB_register_Asm_16:
9632   case ARM::VLD4dWB_register_Asm_32:
9633   case ARM::VLD4qWB_register_Asm_8:
9634   case ARM::VLD4qWB_register_Asm_16:
9635   case ARM::VLD4qWB_register_Asm_32: {
9636     MCInst TmpInst;
9637     unsigned Spacing;
9638     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9639     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9640     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9641                                             Spacing));
9642     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9643                                             Spacing * 2));
9644     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9645                                             Spacing * 3));
9646     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9647     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9648     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9649     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9650     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9651     TmpInst.addOperand(Inst.getOperand(5));
9652     Inst = TmpInst;
9653     return true;
9654   }
9655 
9656   // VST3 multiple 3-element structure instructions.
9657   case ARM::VST3dAsm_8:
9658   case ARM::VST3dAsm_16:
9659   case ARM::VST3dAsm_32:
9660   case ARM::VST3qAsm_8:
9661   case ARM::VST3qAsm_16:
9662   case ARM::VST3qAsm_32: {
9663     MCInst TmpInst;
9664     unsigned Spacing;
9665     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9666     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9667     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9668     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9669     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9670                                             Spacing));
9671     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9672                                             Spacing * 2));
9673     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9674     TmpInst.addOperand(Inst.getOperand(4));
9675     Inst = TmpInst;
9676     return true;
9677   }
9678 
9679   case ARM::VST3dWB_fixed_Asm_8:
9680   case ARM::VST3dWB_fixed_Asm_16:
9681   case ARM::VST3dWB_fixed_Asm_32:
9682   case ARM::VST3qWB_fixed_Asm_8:
9683   case ARM::VST3qWB_fixed_Asm_16:
9684   case ARM::VST3qWB_fixed_Asm_32: {
9685     MCInst TmpInst;
9686     unsigned Spacing;
9687     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9688     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9689     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9690     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9691     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9692     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9693     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9694                                             Spacing));
9695     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9696                                             Spacing * 2));
9697     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9698     TmpInst.addOperand(Inst.getOperand(4));
9699     Inst = TmpInst;
9700     return true;
9701   }
9702 
9703   case ARM::VST3dWB_register_Asm_8:
9704   case ARM::VST3dWB_register_Asm_16:
9705   case ARM::VST3dWB_register_Asm_32:
9706   case ARM::VST3qWB_register_Asm_8:
9707   case ARM::VST3qWB_register_Asm_16:
9708   case ARM::VST3qWB_register_Asm_32: {
9709     MCInst TmpInst;
9710     unsigned Spacing;
9711     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9712     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9713     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9714     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9715     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9716     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9717     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9718                                             Spacing));
9719     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9720                                             Spacing * 2));
9721     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9722     TmpInst.addOperand(Inst.getOperand(5));
9723     Inst = TmpInst;
9724     return true;
9725   }
9726 
9727   // VST4 multiple 3-element structure instructions.
9728   case ARM::VST4dAsm_8:
9729   case ARM::VST4dAsm_16:
9730   case ARM::VST4dAsm_32:
9731   case ARM::VST4qAsm_8:
9732   case ARM::VST4qAsm_16:
9733   case ARM::VST4qAsm_32: {
9734     MCInst TmpInst;
9735     unsigned Spacing;
9736     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9737     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9738     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9739     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9740     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9741                                             Spacing));
9742     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9743                                             Spacing * 2));
9744     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9745                                             Spacing * 3));
9746     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9747     TmpInst.addOperand(Inst.getOperand(4));
9748     Inst = TmpInst;
9749     return true;
9750   }
9751 
9752   case ARM::VST4dWB_fixed_Asm_8:
9753   case ARM::VST4dWB_fixed_Asm_16:
9754   case ARM::VST4dWB_fixed_Asm_32:
9755   case ARM::VST4qWB_fixed_Asm_8:
9756   case ARM::VST4qWB_fixed_Asm_16:
9757   case ARM::VST4qWB_fixed_Asm_32: {
9758     MCInst TmpInst;
9759     unsigned Spacing;
9760     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9761     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9762     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9763     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9764     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9765     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9766     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9767                                             Spacing));
9768     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9769                                             Spacing * 2));
9770     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9771                                             Spacing * 3));
9772     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9773     TmpInst.addOperand(Inst.getOperand(4));
9774     Inst = TmpInst;
9775     return true;
9776   }
9777 
9778   case ARM::VST4dWB_register_Asm_8:
9779   case ARM::VST4dWB_register_Asm_16:
9780   case ARM::VST4dWB_register_Asm_32:
9781   case ARM::VST4qWB_register_Asm_8:
9782   case ARM::VST4qWB_register_Asm_16:
9783   case ARM::VST4qWB_register_Asm_32: {
9784     MCInst TmpInst;
9785     unsigned Spacing;
9786     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9787     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9788     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9789     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9790     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9791     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9792     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9793                                             Spacing));
9794     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9795                                             Spacing * 2));
9796     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9797                                             Spacing * 3));
9798     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9799     TmpInst.addOperand(Inst.getOperand(5));
9800     Inst = TmpInst;
9801     return true;
9802   }
9803 
9804   // Handle encoding choice for the shift-immediate instructions.
9805   case ARM::t2LSLri:
9806   case ARM::t2LSRri:
9807   case ARM::t2ASRri:
9808     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9809         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9810         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9811         !HasWideQualifier) {
9812       unsigned NewOpc;
9813       switch (Inst.getOpcode()) {
9814       default: llvm_unreachable("unexpected opcode");
9815       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
9816       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
9817       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
9818       }
9819       // The Thumb1 operands aren't in the same order. Awesome, eh?
9820       MCInst TmpInst;
9821       TmpInst.setOpcode(NewOpc);
9822       TmpInst.addOperand(Inst.getOperand(0));
9823       TmpInst.addOperand(Inst.getOperand(5));
9824       TmpInst.addOperand(Inst.getOperand(1));
9825       TmpInst.addOperand(Inst.getOperand(2));
9826       TmpInst.addOperand(Inst.getOperand(3));
9827       TmpInst.addOperand(Inst.getOperand(4));
9828       Inst = TmpInst;
9829       return true;
9830     }
9831     return false;
9832 
9833   // Handle the Thumb2 mode MOV complex aliases.
9834   case ARM::t2MOVsr:
9835   case ARM::t2MOVSsr: {
9836     // Which instruction to expand to depends on the CCOut operand and
9837     // whether we're in an IT block if the register operands are low
9838     // registers.
9839     bool isNarrow = false;
9840     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9841         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9842         isARMLowRegister(Inst.getOperand(2).getReg()) &&
9843         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
9844         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
9845         !HasWideQualifier)
9846       isNarrow = true;
9847     MCInst TmpInst;
9848     unsigned newOpc;
9849     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
9850     default: llvm_unreachable("unexpected opcode!");
9851     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
9852     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
9853     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
9854     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
9855     }
9856     TmpInst.setOpcode(newOpc);
9857     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9858     if (isNarrow)
9859       TmpInst.addOperand(MCOperand::createReg(
9860           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9861     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9862     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9863     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9864     TmpInst.addOperand(Inst.getOperand(5));
9865     if (!isNarrow)
9866       TmpInst.addOperand(MCOperand::createReg(
9867           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9868     Inst = TmpInst;
9869     return true;
9870   }
9871   case ARM::t2MOVsi:
9872   case ARM::t2MOVSsi: {
9873     // Which instruction to expand to depends on the CCOut operand and
9874     // whether we're in an IT block if the register operands are low
9875     // registers.
9876     bool isNarrow = false;
9877     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9878         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9879         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
9880         !HasWideQualifier)
9881       isNarrow = true;
9882     MCInst TmpInst;
9883     unsigned newOpc;
9884     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
9885     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
9886     bool isMov = false;
9887     // MOV rd, rm, LSL #0 is actually a MOV instruction
9888     if (Shift == ARM_AM::lsl && Amount == 0) {
9889       isMov = true;
9890       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
9891       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
9892       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
9893       // instead.
9894       if (inITBlock()) {
9895         isNarrow = false;
9896       }
9897       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
9898     } else {
9899       switch(Shift) {
9900       default: llvm_unreachable("unexpected opcode!");
9901       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
9902       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
9903       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
9904       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
9905       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
9906       }
9907     }
9908     if (Amount == 32) Amount = 0;
9909     TmpInst.setOpcode(newOpc);
9910     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9911     if (isNarrow && !isMov)
9912       TmpInst.addOperand(MCOperand::createReg(
9913           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9914     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9915     if (newOpc != ARM::t2RRX && !isMov)
9916       TmpInst.addOperand(MCOperand::createImm(Amount));
9917     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9918     TmpInst.addOperand(Inst.getOperand(4));
9919     if (!isNarrow)
9920       TmpInst.addOperand(MCOperand::createReg(
9921           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9922     Inst = TmpInst;
9923     return true;
9924   }
9925   // Handle the ARM mode MOV complex aliases.
9926   case ARM::ASRr:
9927   case ARM::LSRr:
9928   case ARM::LSLr:
9929   case ARM::RORr: {
9930     ARM_AM::ShiftOpc ShiftTy;
9931     switch(Inst.getOpcode()) {
9932     default: llvm_unreachable("unexpected opcode!");
9933     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
9934     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
9935     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
9936     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
9937     }
9938     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
9939     MCInst TmpInst;
9940     TmpInst.setOpcode(ARM::MOVsr);
9941     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9942     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9943     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9944     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9945     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9946     TmpInst.addOperand(Inst.getOperand(4));
9947     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9948     Inst = TmpInst;
9949     return true;
9950   }
9951   case ARM::ASRi:
9952   case ARM::LSRi:
9953   case ARM::LSLi:
9954   case ARM::RORi: {
9955     ARM_AM::ShiftOpc ShiftTy;
9956     switch(Inst.getOpcode()) {
9957     default: llvm_unreachable("unexpected opcode!");
9958     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
9959     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
9960     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
9961     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
9962     }
9963     // A shift by zero is a plain MOVr, not a MOVsi.
9964     unsigned Amt = Inst.getOperand(2).getImm();
9965     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
9966     // A shift by 32 should be encoded as 0 when permitted
9967     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
9968       Amt = 0;
9969     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
9970     MCInst TmpInst;
9971     TmpInst.setOpcode(Opc);
9972     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9973     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9974     if (Opc == ARM::MOVsi)
9975       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9976     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9977     TmpInst.addOperand(Inst.getOperand(4));
9978     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9979     Inst = TmpInst;
9980     return true;
9981   }
9982   case ARM::RRXi: {
9983     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
9984     MCInst TmpInst;
9985     TmpInst.setOpcode(ARM::MOVsi);
9986     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9987     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9988     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9989     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9990     TmpInst.addOperand(Inst.getOperand(3));
9991     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
9992     Inst = TmpInst;
9993     return true;
9994   }
9995   case ARM::t2LDMIA_UPD: {
9996     // If this is a load of a single register, then we should use
9997     // a post-indexed LDR instruction instead, per the ARM ARM.
9998     if (Inst.getNumOperands() != 5)
9999       return false;
10000     MCInst TmpInst;
10001     TmpInst.setOpcode(ARM::t2LDR_POST);
10002     TmpInst.addOperand(Inst.getOperand(4)); // Rt
10003     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10004     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10005     TmpInst.addOperand(MCOperand::createImm(4));
10006     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10007     TmpInst.addOperand(Inst.getOperand(3));
10008     Inst = TmpInst;
10009     return true;
10010   }
10011   case ARM::t2STMDB_UPD: {
10012     // If this is a store of a single register, then we should use
10013     // a pre-indexed STR instruction instead, per the ARM ARM.
10014     if (Inst.getNumOperands() != 5)
10015       return false;
10016     MCInst TmpInst;
10017     TmpInst.setOpcode(ARM::t2STR_PRE);
10018     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10019     TmpInst.addOperand(Inst.getOperand(4)); // Rt
10020     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10021     TmpInst.addOperand(MCOperand::createImm(-4));
10022     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10023     TmpInst.addOperand(Inst.getOperand(3));
10024     Inst = TmpInst;
10025     return true;
10026   }
10027   case ARM::LDMIA_UPD:
10028     // If this is a load of a single register via a 'pop', then we should use
10029     // a post-indexed LDR instruction instead, per the ARM ARM.
10030     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
10031         Inst.getNumOperands() == 5) {
10032       MCInst TmpInst;
10033       TmpInst.setOpcode(ARM::LDR_POST_IMM);
10034       TmpInst.addOperand(Inst.getOperand(4)); // Rt
10035       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10036       TmpInst.addOperand(Inst.getOperand(1)); // Rn
10037       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
10038       TmpInst.addOperand(MCOperand::createImm(4));
10039       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10040       TmpInst.addOperand(Inst.getOperand(3));
10041       Inst = TmpInst;
10042       return true;
10043     }
10044     break;
10045   case ARM::STMDB_UPD:
10046     // If this is a store of a single register via a 'push', then we should use
10047     // a pre-indexed STR instruction instead, per the ARM ARM.
10048     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
10049         Inst.getNumOperands() == 5) {
10050       MCInst TmpInst;
10051       TmpInst.setOpcode(ARM::STR_PRE_IMM);
10052       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10053       TmpInst.addOperand(Inst.getOperand(4)); // Rt
10054       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
10055       TmpInst.addOperand(MCOperand::createImm(-4));
10056       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10057       TmpInst.addOperand(Inst.getOperand(3));
10058       Inst = TmpInst;
10059     }
10060     break;
10061   case ARM::t2ADDri12:
10062   case ARM::t2SUBri12:
10063   case ARM::t2ADDspImm12:
10064   case ARM::t2SUBspImm12: {
10065     // If the immediate fits for encoding T3 and the generic
10066     // mnemonic was used, encoding T3 is preferred.
10067     const StringRef Token = static_cast<ARMOperand &>(*Operands[0]).getToken();
10068     if ((Token != "add" && Token != "sub") ||
10069         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
10070       break;
10071     switch (Inst.getOpcode()) {
10072     case ARM::t2ADDri12:
10073       Inst.setOpcode(ARM::t2ADDri);
10074       break;
10075     case ARM::t2SUBri12:
10076       Inst.setOpcode(ARM::t2SUBri);
10077       break;
10078     case ARM::t2ADDspImm12:
10079       Inst.setOpcode(ARM::t2ADDspImm);
10080       break;
10081     case ARM::t2SUBspImm12:
10082       Inst.setOpcode(ARM::t2SUBspImm);
10083       break;
10084     }
10085 
10086     Inst.addOperand(MCOperand::createReg(0)); // cc_out
10087     return true;
10088   }
10089   case ARM::tADDi8:
10090     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10091     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10092     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10093     // to encoding T1 if <Rd> is omitted."
10094     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10095       Inst.setOpcode(ARM::tADDi3);
10096       return true;
10097     }
10098     break;
10099   case ARM::tSUBi8:
10100     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10101     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10102     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10103     // to encoding T1 if <Rd> is omitted."
10104     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10105       Inst.setOpcode(ARM::tSUBi3);
10106       return true;
10107     }
10108     break;
10109   case ARM::t2ADDri:
10110   case ARM::t2SUBri: {
10111     // If the destination and first source operand are the same, and
10112     // the flags are compatible with the current IT status, use encoding T2
10113     // instead of T3. For compatibility with the system 'as'. Make sure the
10114     // wide encoding wasn't explicit.
10115     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
10116         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
10117         (Inst.getOperand(2).isImm() &&
10118          (unsigned)Inst.getOperand(2).getImm() > 255) ||
10119         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
10120         HasWideQualifier)
10121       break;
10122     MCInst TmpInst;
10123     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
10124                       ARM::tADDi8 : ARM::tSUBi8);
10125     TmpInst.addOperand(Inst.getOperand(0));
10126     TmpInst.addOperand(Inst.getOperand(5));
10127     TmpInst.addOperand(Inst.getOperand(0));
10128     TmpInst.addOperand(Inst.getOperand(2));
10129     TmpInst.addOperand(Inst.getOperand(3));
10130     TmpInst.addOperand(Inst.getOperand(4));
10131     Inst = TmpInst;
10132     return true;
10133   }
10134   case ARM::t2ADDspImm:
10135   case ARM::t2SUBspImm: {
10136     // Prefer T1 encoding if possible
10137     if (Inst.getOperand(5).getReg() != 0 || HasWideQualifier)
10138       break;
10139     unsigned V = Inst.getOperand(2).getImm();
10140     if (V & 3 || V > ((1 << 7) - 1) << 2)
10141       break;
10142     MCInst TmpInst;
10143     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDspImm ? ARM::tADDspi
10144                                                           : ARM::tSUBspi);
10145     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // destination reg
10146     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // source reg
10147     TmpInst.addOperand(MCOperand::createImm(V / 4));   // immediate
10148     TmpInst.addOperand(Inst.getOperand(3));            // pred
10149     TmpInst.addOperand(Inst.getOperand(4));
10150     Inst = TmpInst;
10151     return true;
10152   }
10153   case ARM::t2ADDrr: {
10154     // If the destination and first source operand are the same, and
10155     // there's no setting of the flags, use encoding T2 instead of T3.
10156     // Note that this is only for ADD, not SUB. This mirrors the system
10157     // 'as' behaviour.  Also take advantage of ADD being commutative.
10158     // Make sure the wide encoding wasn't explicit.
10159     bool Swap = false;
10160     auto DestReg = Inst.getOperand(0).getReg();
10161     bool Transform = DestReg == Inst.getOperand(1).getReg();
10162     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
10163       Transform = true;
10164       Swap = true;
10165     }
10166     if (!Transform ||
10167         Inst.getOperand(5).getReg() != 0 ||
10168         HasWideQualifier)
10169       break;
10170     MCInst TmpInst;
10171     TmpInst.setOpcode(ARM::tADDhirr);
10172     TmpInst.addOperand(Inst.getOperand(0));
10173     TmpInst.addOperand(Inst.getOperand(0));
10174     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
10175     TmpInst.addOperand(Inst.getOperand(3));
10176     TmpInst.addOperand(Inst.getOperand(4));
10177     Inst = TmpInst;
10178     return true;
10179   }
10180   case ARM::tADDrSP:
10181     // If the non-SP source operand and the destination operand are not the
10182     // same, we need to use the 32-bit encoding if it's available.
10183     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
10184       Inst.setOpcode(ARM::t2ADDrr);
10185       Inst.addOperand(MCOperand::createReg(0)); // cc_out
10186       return true;
10187     }
10188     break;
10189   case ARM::tB:
10190     // A Thumb conditional branch outside of an IT block is a tBcc.
10191     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
10192       Inst.setOpcode(ARM::tBcc);
10193       return true;
10194     }
10195     break;
10196   case ARM::t2B:
10197     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
10198     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
10199       Inst.setOpcode(ARM::t2Bcc);
10200       return true;
10201     }
10202     break;
10203   case ARM::t2Bcc:
10204     // If the conditional is AL or we're in an IT block, we really want t2B.
10205     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
10206       Inst.setOpcode(ARM::t2B);
10207       return true;
10208     }
10209     break;
10210   case ARM::tBcc:
10211     // If the conditional is AL, we really want tB.
10212     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
10213       Inst.setOpcode(ARM::tB);
10214       return true;
10215     }
10216     break;
10217   case ARM::tLDMIA: {
10218     // If the register list contains any high registers, or if the writeback
10219     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
10220     // instead if we're in Thumb2. Otherwise, this should have generated
10221     // an error in validateInstruction().
10222     unsigned Rn = Inst.getOperand(0).getReg();
10223     bool hasWritebackToken =
10224         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
10225          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
10226     bool listContainsBase;
10227     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
10228         (!listContainsBase && !hasWritebackToken) ||
10229         (listContainsBase && hasWritebackToken)) {
10230       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10231       assert(isThumbTwo());
10232       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
10233       // If we're switching to the updating version, we need to insert
10234       // the writeback tied operand.
10235       if (hasWritebackToken)
10236         Inst.insert(Inst.begin(),
10237                     MCOperand::createReg(Inst.getOperand(0).getReg()));
10238       return true;
10239     }
10240     break;
10241   }
10242   case ARM::tSTMIA_UPD: {
10243     // If the register list contains any high registers, we need to use
10244     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10245     // should have generated an error in validateInstruction().
10246     unsigned Rn = Inst.getOperand(0).getReg();
10247     bool listContainsBase;
10248     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
10249       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10250       assert(isThumbTwo());
10251       Inst.setOpcode(ARM::t2STMIA_UPD);
10252       return true;
10253     }
10254     break;
10255   }
10256   case ARM::tPOP: {
10257     bool listContainsBase;
10258     // If the register list contains any high registers, we need to use
10259     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10260     // should have generated an error in validateInstruction().
10261     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
10262       return false;
10263     assert(isThumbTwo());
10264     Inst.setOpcode(ARM::t2LDMIA_UPD);
10265     // Add the base register and writeback operands.
10266     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10267     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10268     return true;
10269   }
10270   case ARM::tPUSH: {
10271     bool listContainsBase;
10272     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
10273       return false;
10274     assert(isThumbTwo());
10275     Inst.setOpcode(ARM::t2STMDB_UPD);
10276     // Add the base register and writeback operands.
10277     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10278     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10279     return true;
10280   }
10281   case ARM::t2MOVi:
10282     // If we can use the 16-bit encoding and the user didn't explicitly
10283     // request the 32-bit variant, transform it here.
10284     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10285         (Inst.getOperand(1).isImm() &&
10286          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
10287         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10288         !HasWideQualifier) {
10289       // The operands aren't in the same order for tMOVi8...
10290       MCInst TmpInst;
10291       TmpInst.setOpcode(ARM::tMOVi8);
10292       TmpInst.addOperand(Inst.getOperand(0));
10293       TmpInst.addOperand(Inst.getOperand(4));
10294       TmpInst.addOperand(Inst.getOperand(1));
10295       TmpInst.addOperand(Inst.getOperand(2));
10296       TmpInst.addOperand(Inst.getOperand(3));
10297       Inst = TmpInst;
10298       return true;
10299     }
10300     break;
10301 
10302   case ARM::t2MOVr:
10303     // If we can use the 16-bit encoding and the user didn't explicitly
10304     // request the 32-bit variant, transform it here.
10305     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10306         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10307         Inst.getOperand(2).getImm() == ARMCC::AL &&
10308         Inst.getOperand(4).getReg() == ARM::CPSR &&
10309         !HasWideQualifier) {
10310       // The operands aren't the same for tMOV[S]r... (no cc_out)
10311       MCInst TmpInst;
10312       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
10313       TmpInst.addOperand(Inst.getOperand(0));
10314       TmpInst.addOperand(Inst.getOperand(1));
10315       TmpInst.addOperand(Inst.getOperand(2));
10316       TmpInst.addOperand(Inst.getOperand(3));
10317       Inst = TmpInst;
10318       return true;
10319     }
10320     break;
10321 
10322   case ARM::t2SXTH:
10323   case ARM::t2SXTB:
10324   case ARM::t2UXTH:
10325   case ARM::t2UXTB:
10326     // If we can use the 16-bit encoding and the user didn't explicitly
10327     // request the 32-bit variant, transform it here.
10328     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10329         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10330         Inst.getOperand(2).getImm() == 0 &&
10331         !HasWideQualifier) {
10332       unsigned NewOpc;
10333       switch (Inst.getOpcode()) {
10334       default: llvm_unreachable("Illegal opcode!");
10335       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
10336       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
10337       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
10338       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
10339       }
10340       // The operands aren't the same for thumb1 (no rotate operand).
10341       MCInst TmpInst;
10342       TmpInst.setOpcode(NewOpc);
10343       TmpInst.addOperand(Inst.getOperand(0));
10344       TmpInst.addOperand(Inst.getOperand(1));
10345       TmpInst.addOperand(Inst.getOperand(3));
10346       TmpInst.addOperand(Inst.getOperand(4));
10347       Inst = TmpInst;
10348       return true;
10349     }
10350     break;
10351 
10352   case ARM::MOVsi: {
10353     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
10354     // rrx shifts and asr/lsr of #32 is encoded as 0
10355     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
10356       return false;
10357     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
10358       // Shifting by zero is accepted as a vanilla 'MOVr'
10359       MCInst TmpInst;
10360       TmpInst.setOpcode(ARM::MOVr);
10361       TmpInst.addOperand(Inst.getOperand(0));
10362       TmpInst.addOperand(Inst.getOperand(1));
10363       TmpInst.addOperand(Inst.getOperand(3));
10364       TmpInst.addOperand(Inst.getOperand(4));
10365       TmpInst.addOperand(Inst.getOperand(5));
10366       Inst = TmpInst;
10367       return true;
10368     }
10369     return false;
10370   }
10371   case ARM::ANDrsi:
10372   case ARM::ORRrsi:
10373   case ARM::EORrsi:
10374   case ARM::BICrsi:
10375   case ARM::SUBrsi:
10376   case ARM::ADDrsi: {
10377     unsigned newOpc;
10378     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
10379     if (SOpc == ARM_AM::rrx) return false;
10380     switch (Inst.getOpcode()) {
10381     default: llvm_unreachable("unexpected opcode!");
10382     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
10383     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
10384     case ARM::EORrsi: newOpc = ARM::EORrr; break;
10385     case ARM::BICrsi: newOpc = ARM::BICrr; break;
10386     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
10387     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
10388     }
10389     // If the shift is by zero, use the non-shifted instruction definition.
10390     // The exception is for right shifts, where 0 == 32
10391     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
10392         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
10393       MCInst TmpInst;
10394       TmpInst.setOpcode(newOpc);
10395       TmpInst.addOperand(Inst.getOperand(0));
10396       TmpInst.addOperand(Inst.getOperand(1));
10397       TmpInst.addOperand(Inst.getOperand(2));
10398       TmpInst.addOperand(Inst.getOperand(4));
10399       TmpInst.addOperand(Inst.getOperand(5));
10400       TmpInst.addOperand(Inst.getOperand(6));
10401       Inst = TmpInst;
10402       return true;
10403     }
10404     return false;
10405   }
10406   case ARM::ITasm:
10407   case ARM::t2IT: {
10408     // Set up the IT block state according to the IT instruction we just
10409     // matched.
10410     assert(!inITBlock() && "nested IT blocks?!");
10411     startExplicitITBlock(ARMCC::CondCodes(Inst.getOperand(0).getImm()),
10412                          Inst.getOperand(1).getImm());
10413     break;
10414   }
10415   case ARM::t2LSLrr:
10416   case ARM::t2LSRrr:
10417   case ARM::t2ASRrr:
10418   case ARM::t2SBCrr:
10419   case ARM::t2RORrr:
10420   case ARM::t2BICrr:
10421     // Assemblers should use the narrow encodings of these instructions when permissible.
10422     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10423          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10424         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10425         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10426         !HasWideQualifier) {
10427       unsigned NewOpc;
10428       switch (Inst.getOpcode()) {
10429         default: llvm_unreachable("unexpected opcode");
10430         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
10431         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
10432         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
10433         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
10434         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
10435         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
10436       }
10437       MCInst TmpInst;
10438       TmpInst.setOpcode(NewOpc);
10439       TmpInst.addOperand(Inst.getOperand(0));
10440       TmpInst.addOperand(Inst.getOperand(5));
10441       TmpInst.addOperand(Inst.getOperand(1));
10442       TmpInst.addOperand(Inst.getOperand(2));
10443       TmpInst.addOperand(Inst.getOperand(3));
10444       TmpInst.addOperand(Inst.getOperand(4));
10445       Inst = TmpInst;
10446       return true;
10447     }
10448     return false;
10449 
10450   case ARM::t2ANDrr:
10451   case ARM::t2EORrr:
10452   case ARM::t2ADCrr:
10453   case ARM::t2ORRrr:
10454     // Assemblers should use the narrow encodings of these instructions when permissible.
10455     // These instructions are special in that they are commutable, so shorter encodings
10456     // are available more often.
10457     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10458          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10459         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
10460          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
10461         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10462         !HasWideQualifier) {
10463       unsigned NewOpc;
10464       switch (Inst.getOpcode()) {
10465         default: llvm_unreachable("unexpected opcode");
10466         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
10467         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
10468         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
10469         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
10470       }
10471       MCInst TmpInst;
10472       TmpInst.setOpcode(NewOpc);
10473       TmpInst.addOperand(Inst.getOperand(0));
10474       TmpInst.addOperand(Inst.getOperand(5));
10475       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
10476         TmpInst.addOperand(Inst.getOperand(1));
10477         TmpInst.addOperand(Inst.getOperand(2));
10478       } else {
10479         TmpInst.addOperand(Inst.getOperand(2));
10480         TmpInst.addOperand(Inst.getOperand(1));
10481       }
10482       TmpInst.addOperand(Inst.getOperand(3));
10483       TmpInst.addOperand(Inst.getOperand(4));
10484       Inst = TmpInst;
10485       return true;
10486     }
10487     return false;
10488   case ARM::MVE_VPST:
10489   case ARM::MVE_VPTv16i8:
10490   case ARM::MVE_VPTv8i16:
10491   case ARM::MVE_VPTv4i32:
10492   case ARM::MVE_VPTv16u8:
10493   case ARM::MVE_VPTv8u16:
10494   case ARM::MVE_VPTv4u32:
10495   case ARM::MVE_VPTv16s8:
10496   case ARM::MVE_VPTv8s16:
10497   case ARM::MVE_VPTv4s32:
10498   case ARM::MVE_VPTv4f32:
10499   case ARM::MVE_VPTv8f16:
10500   case ARM::MVE_VPTv16i8r:
10501   case ARM::MVE_VPTv8i16r:
10502   case ARM::MVE_VPTv4i32r:
10503   case ARM::MVE_VPTv16u8r:
10504   case ARM::MVE_VPTv8u16r:
10505   case ARM::MVE_VPTv4u32r:
10506   case ARM::MVE_VPTv16s8r:
10507   case ARM::MVE_VPTv8s16r:
10508   case ARM::MVE_VPTv4s32r:
10509   case ARM::MVE_VPTv4f32r:
10510   case ARM::MVE_VPTv8f16r: {
10511     assert(!inVPTBlock() && "Nested VPT blocks are not allowed");
10512     MCOperand &MO = Inst.getOperand(0);
10513     VPTState.Mask = MO.getImm();
10514     VPTState.CurPosition = 0;
10515     break;
10516   }
10517   }
10518   return false;
10519 }
10520 
10521 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
10522   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
10523   // suffix depending on whether they're in an IT block or not.
10524   unsigned Opc = Inst.getOpcode();
10525   const MCInstrDesc &MCID = MII.get(Opc);
10526   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
10527     assert(MCID.hasOptionalDef() &&
10528            "optionally flag setting instruction missing optional def operand");
10529     assert(MCID.NumOperands == Inst.getNumOperands() &&
10530            "operand count mismatch!");
10531     // Find the optional-def operand (cc_out).
10532     unsigned OpNo;
10533     for (OpNo = 0;
10534          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
10535          ++OpNo)
10536       ;
10537     // If we're parsing Thumb1, reject it completely.
10538     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
10539       return Match_RequiresFlagSetting;
10540     // If we're parsing Thumb2, which form is legal depends on whether we're
10541     // in an IT block.
10542     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
10543         !inITBlock())
10544       return Match_RequiresITBlock;
10545     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
10546         inITBlock())
10547       return Match_RequiresNotITBlock;
10548     // LSL with zero immediate is not allowed in an IT block
10549     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
10550       return Match_RequiresNotITBlock;
10551   } else if (isThumbOne()) {
10552     // Some high-register supporting Thumb1 encodings only allow both registers
10553     // to be from r0-r7 when in Thumb2.
10554     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
10555         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10556         isARMLowRegister(Inst.getOperand(2).getReg()))
10557       return Match_RequiresThumb2;
10558     // Others only require ARMv6 or later.
10559     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
10560              isARMLowRegister(Inst.getOperand(0).getReg()) &&
10561              isARMLowRegister(Inst.getOperand(1).getReg()))
10562       return Match_RequiresV6;
10563   }
10564 
10565   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
10566   // than the loop below can handle, so it uses the GPRnopc register class and
10567   // we do SP handling here.
10568   if (Opc == ARM::t2MOVr && !hasV8Ops())
10569   {
10570     // SP as both source and destination is not allowed
10571     if (Inst.getOperand(0).getReg() == ARM::SP &&
10572         Inst.getOperand(1).getReg() == ARM::SP)
10573       return Match_RequiresV8;
10574     // When flags-setting SP as either source or destination is not allowed
10575     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
10576         (Inst.getOperand(0).getReg() == ARM::SP ||
10577          Inst.getOperand(1).getReg() == ARM::SP))
10578       return Match_RequiresV8;
10579   }
10580 
10581   switch (Inst.getOpcode()) {
10582   case ARM::VMRS:
10583   case ARM::VMSR:
10584   case ARM::VMRS_FPCXTS:
10585   case ARM::VMRS_FPCXTNS:
10586   case ARM::VMSR_FPCXTS:
10587   case ARM::VMSR_FPCXTNS:
10588   case ARM::VMRS_FPSCR_NZCVQC:
10589   case ARM::VMSR_FPSCR_NZCVQC:
10590   case ARM::FMSTAT:
10591   case ARM::VMRS_VPR:
10592   case ARM::VMRS_P0:
10593   case ARM::VMSR_VPR:
10594   case ARM::VMSR_P0:
10595     // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
10596     // ARMv8-A.
10597     if (Inst.getOperand(0).isReg() && Inst.getOperand(0).getReg() == ARM::SP &&
10598         (isThumb() && !hasV8Ops()))
10599       return Match_InvalidOperand;
10600     break;
10601   default:
10602     break;
10603   }
10604 
10605   for (unsigned I = 0; I < MCID.NumOperands; ++I)
10606     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
10607       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
10608       const auto &Op = Inst.getOperand(I);
10609       if (!Op.isReg()) {
10610         // This can happen in awkward cases with tied operands, e.g. a
10611         // writeback load/store with a complex addressing mode in
10612         // which there's an output operand corresponding to the
10613         // updated written-back base register: the Tablegen-generated
10614         // AsmMatcher will have written a placeholder operand to that
10615         // slot in the form of an immediate 0, because it can't
10616         // generate the register part of the complex addressing-mode
10617         // operand ahead of time.
10618         continue;
10619       }
10620 
10621       unsigned Reg = Op.getReg();
10622       if ((Reg == ARM::SP) && !hasV8Ops())
10623         return Match_RequiresV8;
10624       else if (Reg == ARM::PC)
10625         return Match_InvalidOperand;
10626     }
10627 
10628   return Match_Success;
10629 }
10630 
10631 namespace llvm {
10632 
10633 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
10634   return true; // In an assembly source, no need to second-guess
10635 }
10636 
10637 } // end namespace llvm
10638 
10639 // Returns true if Inst is unpredictable if it is in and IT block, but is not
10640 // the last instruction in the block.
10641 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
10642   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10643 
10644   // All branch & call instructions terminate IT blocks with the exception of
10645   // SVC.
10646   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
10647       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
10648     return true;
10649 
10650   // Any arithmetic instruction which writes to the PC also terminates the IT
10651   // block.
10652   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
10653     return true;
10654 
10655   return false;
10656 }
10657 
10658 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
10659                                           SmallVectorImpl<NearMissInfo> &NearMisses,
10660                                           bool MatchingInlineAsm,
10661                                           bool &EmitInITBlock,
10662                                           MCStreamer &Out) {
10663   // If we can't use an implicit IT block here, just match as normal.
10664   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
10665     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10666 
10667   // Try to match the instruction in an extension of the current IT block (if
10668   // there is one).
10669   if (inImplicitITBlock()) {
10670     extendImplicitITBlock(ITState.Cond);
10671     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10672             Match_Success) {
10673       // The match succeded, but we still have to check that the instruction is
10674       // valid in this implicit IT block.
10675       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10676       if (MCID.isPredicable()) {
10677         ARMCC::CondCodes InstCond =
10678             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10679                 .getImm();
10680         ARMCC::CondCodes ITCond = currentITCond();
10681         if (InstCond == ITCond) {
10682           EmitInITBlock = true;
10683           return Match_Success;
10684         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
10685           invertCurrentITCondition();
10686           EmitInITBlock = true;
10687           return Match_Success;
10688         }
10689       }
10690     }
10691     rewindImplicitITPosition();
10692   }
10693 
10694   // Finish the current IT block, and try to match outside any IT block.
10695   flushPendingInstructions(Out);
10696   unsigned PlainMatchResult =
10697       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10698   if (PlainMatchResult == Match_Success) {
10699     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10700     if (MCID.isPredicable()) {
10701       ARMCC::CondCodes InstCond =
10702           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10703               .getImm();
10704       // Some forms of the branch instruction have their own condition code
10705       // fields, so can be conditionally executed without an IT block.
10706       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
10707         EmitInITBlock = false;
10708         return Match_Success;
10709       }
10710       if (InstCond == ARMCC::AL) {
10711         EmitInITBlock = false;
10712         return Match_Success;
10713       }
10714     } else {
10715       EmitInITBlock = false;
10716       return Match_Success;
10717     }
10718   }
10719 
10720   // Try to match in a new IT block. The matcher doesn't check the actual
10721   // condition, so we create an IT block with a dummy condition, and fix it up
10722   // once we know the actual condition.
10723   startImplicitITBlock();
10724   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10725       Match_Success) {
10726     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10727     if (MCID.isPredicable()) {
10728       ITState.Cond =
10729           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10730               .getImm();
10731       EmitInITBlock = true;
10732       return Match_Success;
10733     }
10734   }
10735   discardImplicitITBlock();
10736 
10737   // If none of these succeed, return the error we got when trying to match
10738   // outside any IT blocks.
10739   EmitInITBlock = false;
10740   return PlainMatchResult;
10741 }
10742 
10743 static std::string ARMMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
10744                                          unsigned VariantID = 0);
10745 
10746 static const char *getSubtargetFeatureName(uint64_t Val);
10747 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
10748                                            OperandVector &Operands,
10749                                            MCStreamer &Out, uint64_t &ErrorInfo,
10750                                            bool MatchingInlineAsm) {
10751   MCInst Inst;
10752   unsigned MatchResult;
10753   bool PendConditionalInstruction = false;
10754 
10755   SmallVector<NearMissInfo, 4> NearMisses;
10756   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
10757                                  PendConditionalInstruction, Out);
10758 
10759   switch (MatchResult) {
10760   case Match_Success:
10761     LLVM_DEBUG(dbgs() << "Parsed as: ";
10762                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10763                dbgs() << "\n");
10764 
10765     // Context sensitive operand constraints aren't handled by the matcher,
10766     // so check them here.
10767     if (validateInstruction(Inst, Operands)) {
10768       // Still progress the IT block, otherwise one wrong condition causes
10769       // nasty cascading errors.
10770       forwardITPosition();
10771       forwardVPTPosition();
10772       return true;
10773     }
10774 
10775     { // processInstruction() updates inITBlock state, we need to save it away
10776       bool wasInITBlock = inITBlock();
10777 
10778       // Some instructions need post-processing to, for example, tweak which
10779       // encoding is selected. Loop on it while changes happen so the
10780       // individual transformations can chain off each other. E.g.,
10781       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
10782       while (processInstruction(Inst, Operands, Out))
10783         LLVM_DEBUG(dbgs() << "Changed to: ";
10784                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10785                    dbgs() << "\n");
10786 
10787       // Only after the instruction is fully processed, we can validate it
10788       if (wasInITBlock && hasV8Ops() && isThumb() &&
10789           !isV8EligibleForIT(&Inst)) {
10790         Warning(IDLoc, "deprecated instruction in IT block");
10791       }
10792     }
10793 
10794     // Only move forward at the very end so that everything in validate
10795     // and process gets a consistent answer about whether we're in an IT
10796     // block.
10797     forwardITPosition();
10798     forwardVPTPosition();
10799 
10800     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
10801     // doesn't actually encode.
10802     if (Inst.getOpcode() == ARM::ITasm)
10803       return false;
10804 
10805     Inst.setLoc(IDLoc);
10806     if (PendConditionalInstruction) {
10807       PendingConditionalInsts.push_back(Inst);
10808       if (isITBlockFull() || isITBlockTerminator(Inst))
10809         flushPendingInstructions(Out);
10810     } else {
10811       Out.emitInstruction(Inst, getSTI());
10812     }
10813     return false;
10814   case Match_NearMisses:
10815     ReportNearMisses(NearMisses, IDLoc, Operands);
10816     return true;
10817   case Match_MnemonicFail: {
10818     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
10819     std::string Suggestion = ARMMnemonicSpellCheck(
10820       ((ARMOperand &)*Operands[0]).getToken(), FBS);
10821     return Error(IDLoc, "invalid instruction" + Suggestion,
10822                  ((ARMOperand &)*Operands[0]).getLocRange());
10823   }
10824   }
10825 
10826   llvm_unreachable("Implement any new match types added!");
10827 }
10828 
10829 /// parseDirective parses the arm specific directives
10830 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
10831   const MCObjectFileInfo::Environment Format =
10832     getContext().getObjectFileInfo()->getObjectFileType();
10833   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10834   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
10835 
10836   std::string IDVal = DirectiveID.getIdentifier().lower();
10837   if (IDVal == ".word")
10838     parseLiteralValues(4, DirectiveID.getLoc());
10839   else if (IDVal == ".short" || IDVal == ".hword")
10840     parseLiteralValues(2, DirectiveID.getLoc());
10841   else if (IDVal == ".thumb")
10842     parseDirectiveThumb(DirectiveID.getLoc());
10843   else if (IDVal == ".arm")
10844     parseDirectiveARM(DirectiveID.getLoc());
10845   else if (IDVal == ".thumb_func")
10846     parseDirectiveThumbFunc(DirectiveID.getLoc());
10847   else if (IDVal == ".code")
10848     parseDirectiveCode(DirectiveID.getLoc());
10849   else if (IDVal == ".syntax")
10850     parseDirectiveSyntax(DirectiveID.getLoc());
10851   else if (IDVal == ".unreq")
10852     parseDirectiveUnreq(DirectiveID.getLoc());
10853   else if (IDVal == ".fnend")
10854     parseDirectiveFnEnd(DirectiveID.getLoc());
10855   else if (IDVal == ".cantunwind")
10856     parseDirectiveCantUnwind(DirectiveID.getLoc());
10857   else if (IDVal == ".personality")
10858     parseDirectivePersonality(DirectiveID.getLoc());
10859   else if (IDVal == ".handlerdata")
10860     parseDirectiveHandlerData(DirectiveID.getLoc());
10861   else if (IDVal == ".setfp")
10862     parseDirectiveSetFP(DirectiveID.getLoc());
10863   else if (IDVal == ".pad")
10864     parseDirectivePad(DirectiveID.getLoc());
10865   else if (IDVal == ".save")
10866     parseDirectiveRegSave(DirectiveID.getLoc(), false);
10867   else if (IDVal == ".vsave")
10868     parseDirectiveRegSave(DirectiveID.getLoc(), true);
10869   else if (IDVal == ".ltorg" || IDVal == ".pool")
10870     parseDirectiveLtorg(DirectiveID.getLoc());
10871   else if (IDVal == ".even")
10872     parseDirectiveEven(DirectiveID.getLoc());
10873   else if (IDVal == ".personalityindex")
10874     parseDirectivePersonalityIndex(DirectiveID.getLoc());
10875   else if (IDVal == ".unwind_raw")
10876     parseDirectiveUnwindRaw(DirectiveID.getLoc());
10877   else if (IDVal == ".movsp")
10878     parseDirectiveMovSP(DirectiveID.getLoc());
10879   else if (IDVal == ".arch_extension")
10880     parseDirectiveArchExtension(DirectiveID.getLoc());
10881   else if (IDVal == ".align")
10882     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
10883   else if (IDVal == ".thumb_set")
10884     parseDirectiveThumbSet(DirectiveID.getLoc());
10885   else if (IDVal == ".inst")
10886     parseDirectiveInst(DirectiveID.getLoc());
10887   else if (IDVal == ".inst.n")
10888     parseDirectiveInst(DirectiveID.getLoc(), 'n');
10889   else if (IDVal == ".inst.w")
10890     parseDirectiveInst(DirectiveID.getLoc(), 'w');
10891   else if (!IsMachO && !IsCOFF) {
10892     if (IDVal == ".arch")
10893       parseDirectiveArch(DirectiveID.getLoc());
10894     else if (IDVal == ".cpu")
10895       parseDirectiveCPU(DirectiveID.getLoc());
10896     else if (IDVal == ".eabi_attribute")
10897       parseDirectiveEabiAttr(DirectiveID.getLoc());
10898     else if (IDVal == ".fpu")
10899       parseDirectiveFPU(DirectiveID.getLoc());
10900     else if (IDVal == ".fnstart")
10901       parseDirectiveFnStart(DirectiveID.getLoc());
10902     else if (IDVal == ".object_arch")
10903       parseDirectiveObjectArch(DirectiveID.getLoc());
10904     else if (IDVal == ".tlsdescseq")
10905       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
10906     else
10907       return true;
10908   } else
10909     return true;
10910   return false;
10911 }
10912 
10913 /// parseLiteralValues
10914 ///  ::= .hword expression [, expression]*
10915 ///  ::= .short expression [, expression]*
10916 ///  ::= .word expression [, expression]*
10917 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
10918   auto parseOne = [&]() -> bool {
10919     const MCExpr *Value;
10920     if (getParser().parseExpression(Value))
10921       return true;
10922     getParser().getStreamer().emitValue(Value, Size, L);
10923     return false;
10924   };
10925   return (parseMany(parseOne));
10926 }
10927 
10928 /// parseDirectiveThumb
10929 ///  ::= .thumb
10930 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
10931   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10932       check(!hasThumb(), L, "target does not support Thumb mode"))
10933     return true;
10934 
10935   if (!isThumb())
10936     SwitchMode();
10937 
10938   getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
10939   return false;
10940 }
10941 
10942 /// parseDirectiveARM
10943 ///  ::= .arm
10944 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
10945   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10946       check(!hasARM(), L, "target does not support ARM mode"))
10947     return true;
10948 
10949   if (isThumb())
10950     SwitchMode();
10951   getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
10952   return false;
10953 }
10954 
10955 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
10956   // We need to flush the current implicit IT block on a label, because it is
10957   // not legal to branch into an IT block.
10958   flushPendingInstructions(getStreamer());
10959 }
10960 
10961 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
10962   if (NextSymbolIsThumb) {
10963     getParser().getStreamer().emitThumbFunc(Symbol);
10964     NextSymbolIsThumb = false;
10965   }
10966 }
10967 
10968 /// parseDirectiveThumbFunc
10969 ///  ::= .thumbfunc symbol_name
10970 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
10971   MCAsmParser &Parser = getParser();
10972   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
10973   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10974 
10975   // Darwin asm has (optionally) function name after .thumb_func direction
10976   // ELF doesn't
10977 
10978   if (IsMachO) {
10979     if (Parser.getTok().is(AsmToken::Identifier) ||
10980         Parser.getTok().is(AsmToken::String)) {
10981       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
10982           Parser.getTok().getIdentifier());
10983       getParser().getStreamer().emitThumbFunc(Func);
10984       Parser.Lex();
10985       if (parseToken(AsmToken::EndOfStatement,
10986                      "unexpected token in '.thumb_func' directive"))
10987         return true;
10988       return false;
10989     }
10990   }
10991 
10992   if (parseToken(AsmToken::EndOfStatement,
10993                  "unexpected token in '.thumb_func' directive"))
10994     return true;
10995 
10996   NextSymbolIsThumb = true;
10997   return false;
10998 }
10999 
11000 /// parseDirectiveSyntax
11001 ///  ::= .syntax unified | divided
11002 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
11003   MCAsmParser &Parser = getParser();
11004   const AsmToken &Tok = Parser.getTok();
11005   if (Tok.isNot(AsmToken::Identifier)) {
11006     Error(L, "unexpected token in .syntax directive");
11007     return false;
11008   }
11009 
11010   StringRef Mode = Tok.getString();
11011   Parser.Lex();
11012   if (check(Mode == "divided" || Mode == "DIVIDED", L,
11013             "'.syntax divided' arm assembly not supported") ||
11014       check(Mode != "unified" && Mode != "UNIFIED", L,
11015             "unrecognized syntax mode in .syntax directive") ||
11016       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11017     return true;
11018 
11019   // TODO tell the MC streamer the mode
11020   // getParser().getStreamer().Emit???();
11021   return false;
11022 }
11023 
11024 /// parseDirectiveCode
11025 ///  ::= .code 16 | 32
11026 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
11027   MCAsmParser &Parser = getParser();
11028   const AsmToken &Tok = Parser.getTok();
11029   if (Tok.isNot(AsmToken::Integer))
11030     return Error(L, "unexpected token in .code directive");
11031   int64_t Val = Parser.getTok().getIntVal();
11032   if (Val != 16 && Val != 32) {
11033     Error(L, "invalid operand to .code directive");
11034     return false;
11035   }
11036   Parser.Lex();
11037 
11038   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11039     return true;
11040 
11041   if (Val == 16) {
11042     if (!hasThumb())
11043       return Error(L, "target does not support Thumb mode");
11044 
11045     if (!isThumb())
11046       SwitchMode();
11047     getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11048   } else {
11049     if (!hasARM())
11050       return Error(L, "target does not support ARM mode");
11051 
11052     if (isThumb())
11053       SwitchMode();
11054     getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
11055   }
11056 
11057   return false;
11058 }
11059 
11060 /// parseDirectiveReq
11061 ///  ::= name .req registername
11062 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
11063   MCAsmParser &Parser = getParser();
11064   Parser.Lex(); // Eat the '.req' token.
11065   unsigned Reg;
11066   SMLoc SRegLoc, ERegLoc;
11067   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
11068             "register name expected") ||
11069       parseToken(AsmToken::EndOfStatement,
11070                  "unexpected input in .req directive."))
11071     return true;
11072 
11073   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
11074     return Error(SRegLoc,
11075                  "redefinition of '" + Name + "' does not match original.");
11076 
11077   return false;
11078 }
11079 
11080 /// parseDirectiveUneq
11081 ///  ::= .unreq registername
11082 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
11083   MCAsmParser &Parser = getParser();
11084   if (Parser.getTok().isNot(AsmToken::Identifier))
11085     return Error(L, "unexpected input in .unreq directive.");
11086   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
11087   Parser.Lex(); // Eat the identifier.
11088   if (parseToken(AsmToken::EndOfStatement,
11089                  "unexpected input in '.unreq' directive"))
11090     return true;
11091   return false;
11092 }
11093 
11094 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
11095 // before, if supported by the new target, or emit mapping symbols for the mode
11096 // switch.
11097 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
11098   if (WasThumb != isThumb()) {
11099     if (WasThumb && hasThumb()) {
11100       // Stay in Thumb mode
11101       SwitchMode();
11102     } else if (!WasThumb && hasARM()) {
11103       // Stay in ARM mode
11104       SwitchMode();
11105     } else {
11106       // Mode switch forced, because the new arch doesn't support the old mode.
11107       getParser().getStreamer().emitAssemblerFlag(isThumb() ? MCAF_Code16
11108                                                             : MCAF_Code32);
11109       // Warn about the implcit mode switch. GAS does not switch modes here,
11110       // but instead stays in the old mode, reporting an error on any following
11111       // instructions as the mode does not exist on the target.
11112       Warning(Loc, Twine("new target does not support ") +
11113                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
11114                        (!WasThumb ? "thumb" : "arm") + " mode");
11115     }
11116   }
11117 }
11118 
11119 /// parseDirectiveArch
11120 ///  ::= .arch token
11121 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
11122   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
11123   ARM::ArchKind ID = ARM::parseArch(Arch);
11124 
11125   if (ID == ARM::ArchKind::INVALID)
11126     return Error(L, "Unknown arch name");
11127 
11128   bool WasThumb = isThumb();
11129   Triple T;
11130   MCSubtargetInfo &STI = copySTI();
11131   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
11132   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11133   FixModeAfterArchChange(WasThumb, L);
11134 
11135   getTargetStreamer().emitArch(ID);
11136   return false;
11137 }
11138 
11139 /// parseDirectiveEabiAttr
11140 ///  ::= .eabi_attribute int, int [, "str"]
11141 ///  ::= .eabi_attribute Tag_name, int [, "str"]
11142 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
11143   MCAsmParser &Parser = getParser();
11144   int64_t Tag;
11145   SMLoc TagLoc;
11146   TagLoc = Parser.getTok().getLoc();
11147   if (Parser.getTok().is(AsmToken::Identifier)) {
11148     StringRef Name = Parser.getTok().getIdentifier();
11149     Optional<unsigned> Ret =
11150         ELFAttrs::attrTypeFromString(Name, ARMBuildAttrs::ARMAttributeTags);
11151     if (!Ret.hasValue()) {
11152       Error(TagLoc, "attribute name not recognised: " + Name);
11153       return false;
11154     }
11155     Tag = Ret.getValue();
11156     Parser.Lex();
11157   } else {
11158     const MCExpr *AttrExpr;
11159 
11160     TagLoc = Parser.getTok().getLoc();
11161     if (Parser.parseExpression(AttrExpr))
11162       return true;
11163 
11164     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
11165     if (check(!CE, TagLoc, "expected numeric constant"))
11166       return true;
11167 
11168     Tag = CE->getValue();
11169   }
11170 
11171   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11172     return true;
11173 
11174   StringRef StringValue = "";
11175   bool IsStringValue = false;
11176 
11177   int64_t IntegerValue = 0;
11178   bool IsIntegerValue = false;
11179 
11180   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
11181     IsStringValue = true;
11182   else if (Tag == ARMBuildAttrs::compatibility) {
11183     IsStringValue = true;
11184     IsIntegerValue = true;
11185   } else if (Tag < 32 || Tag % 2 == 0)
11186     IsIntegerValue = true;
11187   else if (Tag % 2 == 1)
11188     IsStringValue = true;
11189   else
11190     llvm_unreachable("invalid tag type");
11191 
11192   if (IsIntegerValue) {
11193     const MCExpr *ValueExpr;
11194     SMLoc ValueExprLoc = Parser.getTok().getLoc();
11195     if (Parser.parseExpression(ValueExpr))
11196       return true;
11197 
11198     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
11199     if (!CE)
11200       return Error(ValueExprLoc, "expected numeric constant");
11201     IntegerValue = CE->getValue();
11202   }
11203 
11204   if (Tag == ARMBuildAttrs::compatibility) {
11205     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11206       return true;
11207   }
11208 
11209   if (IsStringValue) {
11210     if (Parser.getTok().isNot(AsmToken::String))
11211       return Error(Parser.getTok().getLoc(), "bad string constant");
11212 
11213     StringValue = Parser.getTok().getStringContents();
11214     Parser.Lex();
11215   }
11216 
11217   if (Parser.parseToken(AsmToken::EndOfStatement,
11218                         "unexpected token in '.eabi_attribute' directive"))
11219     return true;
11220 
11221   if (IsIntegerValue && IsStringValue) {
11222     assert(Tag == ARMBuildAttrs::compatibility);
11223     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
11224   } else if (IsIntegerValue)
11225     getTargetStreamer().emitAttribute(Tag, IntegerValue);
11226   else if (IsStringValue)
11227     getTargetStreamer().emitTextAttribute(Tag, StringValue);
11228   return false;
11229 }
11230 
11231 /// parseDirectiveCPU
11232 ///  ::= .cpu str
11233 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
11234   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
11235   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
11236 
11237   // FIXME: This is using table-gen data, but should be moved to
11238   // ARMTargetParser once that is table-gen'd.
11239   if (!getSTI().isCPUStringValid(CPU))
11240     return Error(L, "Unknown CPU name");
11241 
11242   bool WasThumb = isThumb();
11243   MCSubtargetInfo &STI = copySTI();
11244   STI.setDefaultFeatures(CPU, "");
11245   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11246   FixModeAfterArchChange(WasThumb, L);
11247 
11248   return false;
11249 }
11250 
11251 /// parseDirectiveFPU
11252 ///  ::= .fpu str
11253 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
11254   SMLoc FPUNameLoc = getTok().getLoc();
11255   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
11256 
11257   unsigned ID = ARM::parseFPU(FPU);
11258   std::vector<StringRef> Features;
11259   if (!ARM::getFPUFeatures(ID, Features))
11260     return Error(FPUNameLoc, "Unknown FPU name");
11261 
11262   MCSubtargetInfo &STI = copySTI();
11263   for (auto Feature : Features)
11264     STI.ApplyFeatureFlag(Feature);
11265   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11266 
11267   getTargetStreamer().emitFPU(ID);
11268   return false;
11269 }
11270 
11271 /// parseDirectiveFnStart
11272 ///  ::= .fnstart
11273 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
11274   if (parseToken(AsmToken::EndOfStatement,
11275                  "unexpected token in '.fnstart' directive"))
11276     return true;
11277 
11278   if (UC.hasFnStart()) {
11279     Error(L, ".fnstart starts before the end of previous one");
11280     UC.emitFnStartLocNotes();
11281     return true;
11282   }
11283 
11284   // Reset the unwind directives parser state
11285   UC.reset();
11286 
11287   getTargetStreamer().emitFnStart();
11288 
11289   UC.recordFnStart(L);
11290   return false;
11291 }
11292 
11293 /// parseDirectiveFnEnd
11294 ///  ::= .fnend
11295 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
11296   if (parseToken(AsmToken::EndOfStatement,
11297                  "unexpected token in '.fnend' directive"))
11298     return true;
11299   // Check the ordering of unwind directives
11300   if (!UC.hasFnStart())
11301     return Error(L, ".fnstart must precede .fnend directive");
11302 
11303   // Reset the unwind directives parser state
11304   getTargetStreamer().emitFnEnd();
11305 
11306   UC.reset();
11307   return false;
11308 }
11309 
11310 /// parseDirectiveCantUnwind
11311 ///  ::= .cantunwind
11312 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
11313   if (parseToken(AsmToken::EndOfStatement,
11314                  "unexpected token in '.cantunwind' directive"))
11315     return true;
11316 
11317   UC.recordCantUnwind(L);
11318   // Check the ordering of unwind directives
11319   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
11320     return true;
11321 
11322   if (UC.hasHandlerData()) {
11323     Error(L, ".cantunwind can't be used with .handlerdata directive");
11324     UC.emitHandlerDataLocNotes();
11325     return true;
11326   }
11327   if (UC.hasPersonality()) {
11328     Error(L, ".cantunwind can't be used with .personality directive");
11329     UC.emitPersonalityLocNotes();
11330     return true;
11331   }
11332 
11333   getTargetStreamer().emitCantUnwind();
11334   return false;
11335 }
11336 
11337 /// parseDirectivePersonality
11338 ///  ::= .personality name
11339 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
11340   MCAsmParser &Parser = getParser();
11341   bool HasExistingPersonality = UC.hasPersonality();
11342 
11343   // Parse the name of the personality routine
11344   if (Parser.getTok().isNot(AsmToken::Identifier))
11345     return Error(L, "unexpected input in .personality directive.");
11346   StringRef Name(Parser.getTok().getIdentifier());
11347   Parser.Lex();
11348 
11349   if (parseToken(AsmToken::EndOfStatement,
11350                  "unexpected token in '.personality' directive"))
11351     return true;
11352 
11353   UC.recordPersonality(L);
11354 
11355   // Check the ordering of unwind directives
11356   if (!UC.hasFnStart())
11357     return Error(L, ".fnstart must precede .personality directive");
11358   if (UC.cantUnwind()) {
11359     Error(L, ".personality can't be used with .cantunwind directive");
11360     UC.emitCantUnwindLocNotes();
11361     return true;
11362   }
11363   if (UC.hasHandlerData()) {
11364     Error(L, ".personality must precede .handlerdata directive");
11365     UC.emitHandlerDataLocNotes();
11366     return true;
11367   }
11368   if (HasExistingPersonality) {
11369     Error(L, "multiple personality directives");
11370     UC.emitPersonalityLocNotes();
11371     return true;
11372   }
11373 
11374   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
11375   getTargetStreamer().emitPersonality(PR);
11376   return false;
11377 }
11378 
11379 /// parseDirectiveHandlerData
11380 ///  ::= .handlerdata
11381 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
11382   if (parseToken(AsmToken::EndOfStatement,
11383                  "unexpected token in '.handlerdata' directive"))
11384     return true;
11385 
11386   UC.recordHandlerData(L);
11387   // Check the ordering of unwind directives
11388   if (!UC.hasFnStart())
11389     return Error(L, ".fnstart must precede .personality directive");
11390   if (UC.cantUnwind()) {
11391     Error(L, ".handlerdata can't be used with .cantunwind directive");
11392     UC.emitCantUnwindLocNotes();
11393     return true;
11394   }
11395 
11396   getTargetStreamer().emitHandlerData();
11397   return false;
11398 }
11399 
11400 /// parseDirectiveSetFP
11401 ///  ::= .setfp fpreg, spreg [, offset]
11402 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
11403   MCAsmParser &Parser = getParser();
11404   // Check the ordering of unwind directives
11405   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
11406       check(UC.hasHandlerData(), L,
11407             ".setfp must precede .handlerdata directive"))
11408     return true;
11409 
11410   // Parse fpreg
11411   SMLoc FPRegLoc = Parser.getTok().getLoc();
11412   int FPReg = tryParseRegister();
11413 
11414   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
11415       Parser.parseToken(AsmToken::Comma, "comma expected"))
11416     return true;
11417 
11418   // Parse spreg
11419   SMLoc SPRegLoc = Parser.getTok().getLoc();
11420   int SPReg = tryParseRegister();
11421   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
11422       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
11423             "register should be either $sp or the latest fp register"))
11424     return true;
11425 
11426   // Update the frame pointer register
11427   UC.saveFPReg(FPReg);
11428 
11429   // Parse offset
11430   int64_t Offset = 0;
11431   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11432     if (Parser.getTok().isNot(AsmToken::Hash) &&
11433         Parser.getTok().isNot(AsmToken::Dollar))
11434       return Error(Parser.getTok().getLoc(), "'#' expected");
11435     Parser.Lex(); // skip hash token.
11436 
11437     const MCExpr *OffsetExpr;
11438     SMLoc ExLoc = Parser.getTok().getLoc();
11439     SMLoc EndLoc;
11440     if (getParser().parseExpression(OffsetExpr, EndLoc))
11441       return Error(ExLoc, "malformed setfp offset");
11442     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11443     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
11444       return true;
11445     Offset = CE->getValue();
11446   }
11447 
11448   if (Parser.parseToken(AsmToken::EndOfStatement))
11449     return true;
11450 
11451   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
11452                                 static_cast<unsigned>(SPReg), Offset);
11453   return false;
11454 }
11455 
11456 /// parseDirective
11457 ///  ::= .pad offset
11458 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
11459   MCAsmParser &Parser = getParser();
11460   // Check the ordering of unwind directives
11461   if (!UC.hasFnStart())
11462     return Error(L, ".fnstart must precede .pad directive");
11463   if (UC.hasHandlerData())
11464     return Error(L, ".pad must precede .handlerdata directive");
11465 
11466   // Parse the offset
11467   if (Parser.getTok().isNot(AsmToken::Hash) &&
11468       Parser.getTok().isNot(AsmToken::Dollar))
11469     return Error(Parser.getTok().getLoc(), "'#' expected");
11470   Parser.Lex(); // skip hash token.
11471 
11472   const MCExpr *OffsetExpr;
11473   SMLoc ExLoc = Parser.getTok().getLoc();
11474   SMLoc EndLoc;
11475   if (getParser().parseExpression(OffsetExpr, EndLoc))
11476     return Error(ExLoc, "malformed pad offset");
11477   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11478   if (!CE)
11479     return Error(ExLoc, "pad offset must be an immediate");
11480 
11481   if (parseToken(AsmToken::EndOfStatement,
11482                  "unexpected token in '.pad' directive"))
11483     return true;
11484 
11485   getTargetStreamer().emitPad(CE->getValue());
11486   return false;
11487 }
11488 
11489 /// parseDirectiveRegSave
11490 ///  ::= .save  { registers }
11491 ///  ::= .vsave { registers }
11492 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
11493   // Check the ordering of unwind directives
11494   if (!UC.hasFnStart())
11495     return Error(L, ".fnstart must precede .save or .vsave directives");
11496   if (UC.hasHandlerData())
11497     return Error(L, ".save or .vsave must precede .handlerdata directive");
11498 
11499   // RAII object to make sure parsed operands are deleted.
11500   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
11501 
11502   // Parse the register list
11503   if (parseRegisterList(Operands) ||
11504       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11505     return true;
11506   ARMOperand &Op = (ARMOperand &)*Operands[0];
11507   if (!IsVector && !Op.isRegList())
11508     return Error(L, ".save expects GPR registers");
11509   if (IsVector && !Op.isDPRRegList())
11510     return Error(L, ".vsave expects DPR registers");
11511 
11512   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
11513   return false;
11514 }
11515 
11516 /// parseDirectiveInst
11517 ///  ::= .inst opcode [, ...]
11518 ///  ::= .inst.n opcode [, ...]
11519 ///  ::= .inst.w opcode [, ...]
11520 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
11521   int Width = 4;
11522 
11523   if (isThumb()) {
11524     switch (Suffix) {
11525     case 'n':
11526       Width = 2;
11527       break;
11528     case 'w':
11529       break;
11530     default:
11531       Width = 0;
11532       break;
11533     }
11534   } else {
11535     if (Suffix)
11536       return Error(Loc, "width suffixes are invalid in ARM mode");
11537   }
11538 
11539   auto parseOne = [&]() -> bool {
11540     const MCExpr *Expr;
11541     if (getParser().parseExpression(Expr))
11542       return true;
11543     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
11544     if (!Value) {
11545       return Error(Loc, "expected constant expression");
11546     }
11547 
11548     char CurSuffix = Suffix;
11549     switch (Width) {
11550     case 2:
11551       if (Value->getValue() > 0xffff)
11552         return Error(Loc, "inst.n operand is too big, use inst.w instead");
11553       break;
11554     case 4:
11555       if (Value->getValue() > 0xffffffff)
11556         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
11557                               " operand is too big");
11558       break;
11559     case 0:
11560       // Thumb mode, no width indicated. Guess from the opcode, if possible.
11561       if (Value->getValue() < 0xe800)
11562         CurSuffix = 'n';
11563       else if (Value->getValue() >= 0xe8000000)
11564         CurSuffix = 'w';
11565       else
11566         return Error(Loc, "cannot determine Thumb instruction size, "
11567                           "use inst.n/inst.w instead");
11568       break;
11569     default:
11570       llvm_unreachable("only supported widths are 2 and 4");
11571     }
11572 
11573     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
11574     return false;
11575   };
11576 
11577   if (parseOptionalToken(AsmToken::EndOfStatement))
11578     return Error(Loc, "expected expression following directive");
11579   if (parseMany(parseOne))
11580     return true;
11581   return false;
11582 }
11583 
11584 /// parseDirectiveLtorg
11585 ///  ::= .ltorg | .pool
11586 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
11587   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11588     return true;
11589   getTargetStreamer().emitCurrentConstantPool();
11590   return false;
11591 }
11592 
11593 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
11594   const MCSection *Section = getStreamer().getCurrentSectionOnly();
11595 
11596   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11597     return true;
11598 
11599   if (!Section) {
11600     getStreamer().InitSections(false);
11601     Section = getStreamer().getCurrentSectionOnly();
11602   }
11603 
11604   assert(Section && "must have section to emit alignment");
11605   if (Section->UseCodeAlign())
11606     getStreamer().emitCodeAlignment(2);
11607   else
11608     getStreamer().emitValueToAlignment(2);
11609 
11610   return false;
11611 }
11612 
11613 /// parseDirectivePersonalityIndex
11614 ///   ::= .personalityindex index
11615 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
11616   MCAsmParser &Parser = getParser();
11617   bool HasExistingPersonality = UC.hasPersonality();
11618 
11619   const MCExpr *IndexExpression;
11620   SMLoc IndexLoc = Parser.getTok().getLoc();
11621   if (Parser.parseExpression(IndexExpression) ||
11622       parseToken(AsmToken::EndOfStatement,
11623                  "unexpected token in '.personalityindex' directive")) {
11624     return true;
11625   }
11626 
11627   UC.recordPersonalityIndex(L);
11628 
11629   if (!UC.hasFnStart()) {
11630     return Error(L, ".fnstart must precede .personalityindex directive");
11631   }
11632   if (UC.cantUnwind()) {
11633     Error(L, ".personalityindex cannot be used with .cantunwind");
11634     UC.emitCantUnwindLocNotes();
11635     return true;
11636   }
11637   if (UC.hasHandlerData()) {
11638     Error(L, ".personalityindex must precede .handlerdata directive");
11639     UC.emitHandlerDataLocNotes();
11640     return true;
11641   }
11642   if (HasExistingPersonality) {
11643     Error(L, "multiple personality directives");
11644     UC.emitPersonalityLocNotes();
11645     return true;
11646   }
11647 
11648   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
11649   if (!CE)
11650     return Error(IndexLoc, "index must be a constant number");
11651   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
11652     return Error(IndexLoc,
11653                  "personality routine index should be in range [0-3]");
11654 
11655   getTargetStreamer().emitPersonalityIndex(CE->getValue());
11656   return false;
11657 }
11658 
11659 /// parseDirectiveUnwindRaw
11660 ///   ::= .unwind_raw offset, opcode [, opcode...]
11661 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
11662   MCAsmParser &Parser = getParser();
11663   int64_t StackOffset;
11664   const MCExpr *OffsetExpr;
11665   SMLoc OffsetLoc = getLexer().getLoc();
11666 
11667   if (!UC.hasFnStart())
11668     return Error(L, ".fnstart must precede .unwind_raw directives");
11669   if (getParser().parseExpression(OffsetExpr))
11670     return Error(OffsetLoc, "expected expression");
11671 
11672   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11673   if (!CE)
11674     return Error(OffsetLoc, "offset must be a constant");
11675 
11676   StackOffset = CE->getValue();
11677 
11678   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
11679     return true;
11680 
11681   SmallVector<uint8_t, 16> Opcodes;
11682 
11683   auto parseOne = [&]() -> bool {
11684     const MCExpr *OE = nullptr;
11685     SMLoc OpcodeLoc = getLexer().getLoc();
11686     if (check(getLexer().is(AsmToken::EndOfStatement) ||
11687                   Parser.parseExpression(OE),
11688               OpcodeLoc, "expected opcode expression"))
11689       return true;
11690     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
11691     if (!OC)
11692       return Error(OpcodeLoc, "opcode value must be a constant");
11693     const int64_t Opcode = OC->getValue();
11694     if (Opcode & ~0xff)
11695       return Error(OpcodeLoc, "invalid opcode");
11696     Opcodes.push_back(uint8_t(Opcode));
11697     return false;
11698   };
11699 
11700   // Must have at least 1 element
11701   SMLoc OpcodeLoc = getLexer().getLoc();
11702   if (parseOptionalToken(AsmToken::EndOfStatement))
11703     return Error(OpcodeLoc, "expected opcode expression");
11704   if (parseMany(parseOne))
11705     return true;
11706 
11707   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
11708   return false;
11709 }
11710 
11711 /// parseDirectiveTLSDescSeq
11712 ///   ::= .tlsdescseq tls-variable
11713 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
11714   MCAsmParser &Parser = getParser();
11715 
11716   if (getLexer().isNot(AsmToken::Identifier))
11717     return TokError("expected variable after '.tlsdescseq' directive");
11718 
11719   const MCSymbolRefExpr *SRE =
11720     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
11721                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
11722   Lex();
11723 
11724   if (parseToken(AsmToken::EndOfStatement,
11725                  "unexpected token in '.tlsdescseq' directive"))
11726     return true;
11727 
11728   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
11729   return false;
11730 }
11731 
11732 /// parseDirectiveMovSP
11733 ///  ::= .movsp reg [, #offset]
11734 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
11735   MCAsmParser &Parser = getParser();
11736   if (!UC.hasFnStart())
11737     return Error(L, ".fnstart must precede .movsp directives");
11738   if (UC.getFPReg() != ARM::SP)
11739     return Error(L, "unexpected .movsp directive");
11740 
11741   SMLoc SPRegLoc = Parser.getTok().getLoc();
11742   int SPReg = tryParseRegister();
11743   if (SPReg == -1)
11744     return Error(SPRegLoc, "register expected");
11745   if (SPReg == ARM::SP || SPReg == ARM::PC)
11746     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
11747 
11748   int64_t Offset = 0;
11749   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11750     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
11751       return true;
11752 
11753     const MCExpr *OffsetExpr;
11754     SMLoc OffsetLoc = Parser.getTok().getLoc();
11755 
11756     if (Parser.parseExpression(OffsetExpr))
11757       return Error(OffsetLoc, "malformed offset expression");
11758 
11759     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11760     if (!CE)
11761       return Error(OffsetLoc, "offset must be an immediate constant");
11762 
11763     Offset = CE->getValue();
11764   }
11765 
11766   if (parseToken(AsmToken::EndOfStatement,
11767                  "unexpected token in '.movsp' directive"))
11768     return true;
11769 
11770   getTargetStreamer().emitMovSP(SPReg, Offset);
11771   UC.saveFPReg(SPReg);
11772 
11773   return false;
11774 }
11775 
11776 /// parseDirectiveObjectArch
11777 ///   ::= .object_arch name
11778 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
11779   MCAsmParser &Parser = getParser();
11780   if (getLexer().isNot(AsmToken::Identifier))
11781     return Error(getLexer().getLoc(), "unexpected token");
11782 
11783   StringRef Arch = Parser.getTok().getString();
11784   SMLoc ArchLoc = Parser.getTok().getLoc();
11785   Lex();
11786 
11787   ARM::ArchKind ID = ARM::parseArch(Arch);
11788 
11789   if (ID == ARM::ArchKind::INVALID)
11790     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
11791   if (parseToken(AsmToken::EndOfStatement))
11792     return true;
11793 
11794   getTargetStreamer().emitObjectArch(ID);
11795   return false;
11796 }
11797 
11798 /// parseDirectiveAlign
11799 ///   ::= .align
11800 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
11801   // NOTE: if this is not the end of the statement, fall back to the target
11802   // agnostic handling for this directive which will correctly handle this.
11803   if (parseOptionalToken(AsmToken::EndOfStatement)) {
11804     // '.align' is target specifically handled to mean 2**2 byte alignment.
11805     const MCSection *Section = getStreamer().getCurrentSectionOnly();
11806     assert(Section && "must have section to emit alignment");
11807     if (Section->UseCodeAlign())
11808       getStreamer().emitCodeAlignment(4, 0);
11809     else
11810       getStreamer().emitValueToAlignment(4, 0, 1, 0);
11811     return false;
11812   }
11813   return true;
11814 }
11815 
11816 /// parseDirectiveThumbSet
11817 ///  ::= .thumb_set name, value
11818 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
11819   MCAsmParser &Parser = getParser();
11820 
11821   StringRef Name;
11822   if (check(Parser.parseIdentifier(Name),
11823             "expected identifier after '.thumb_set'") ||
11824       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
11825     return true;
11826 
11827   MCSymbol *Sym;
11828   const MCExpr *Value;
11829   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
11830                                                Parser, Sym, Value))
11831     return true;
11832 
11833   getTargetStreamer().emitThumbSet(Sym, Value);
11834   return false;
11835 }
11836 
11837 /// Force static initialization.
11838 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmParser() {
11839   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
11840   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
11841   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
11842   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
11843 }
11844 
11845 #define GET_REGISTER_MATCHER
11846 #define GET_SUBTARGET_FEATURE_NAME
11847 #define GET_MATCHER_IMPLEMENTATION
11848 #define GET_MNEMONIC_SPELL_CHECKER
11849 #include "ARMGenAsmMatcher.inc"
11850 
11851 // Some diagnostics need to vary with subtarget features, so they are handled
11852 // here. For example, the DPR class has either 16 or 32 registers, depending
11853 // on the FPU available.
11854 const char *
11855 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
11856   switch (MatchError) {
11857   // rGPR contains sp starting with ARMv8.
11858   case Match_rGPR:
11859     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
11860                       : "operand must be a register in range [r0, r12] or r14";
11861   // DPR contains 16 registers for some FPUs, and 32 for others.
11862   case Match_DPR:
11863     return hasD32() ? "operand must be a register in range [d0, d31]"
11864                     : "operand must be a register in range [d0, d15]";
11865   case Match_DPR_RegList:
11866     return hasD32() ? "operand must be a list of registers in range [d0, d31]"
11867                     : "operand must be a list of registers in range [d0, d15]";
11868 
11869   // For all other diags, use the static string from tablegen.
11870   default:
11871     return getMatchKindDiag(MatchError);
11872   }
11873 }
11874 
11875 // Process the list of near-misses, throwing away ones we don't want to report
11876 // to the user, and converting the rest to a source location and string that
11877 // should be reported.
11878 void
11879 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
11880                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
11881                                SMLoc IDLoc, OperandVector &Operands) {
11882   // TODO: If operand didn't match, sub in a dummy one and run target
11883   // predicate, so that we can avoid reporting near-misses that are invalid?
11884   // TODO: Many operand types dont have SuperClasses set, so we report
11885   // redundant ones.
11886   // TODO: Some operands are superclasses of registers (e.g.
11887   // MCK_RegShiftedImm), we don't have any way to represent that currently.
11888   // TODO: This is not all ARM-specific, can some of it be factored out?
11889 
11890   // Record some information about near-misses that we have already seen, so
11891   // that we can avoid reporting redundant ones. For example, if there are
11892   // variants of an instruction that take 8- and 16-bit immediates, we want
11893   // to only report the widest one.
11894   std::multimap<unsigned, unsigned> OperandMissesSeen;
11895   SmallSet<FeatureBitset, 4> FeatureMissesSeen;
11896   bool ReportedTooFewOperands = false;
11897 
11898   // Process the near-misses in reverse order, so that we see more general ones
11899   // first, and so can avoid emitting more specific ones.
11900   for (NearMissInfo &I : reverse(NearMissesIn)) {
11901     switch (I.getKind()) {
11902     case NearMissInfo::NearMissOperand: {
11903       SMLoc OperandLoc =
11904           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
11905       const char *OperandDiag =
11906           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
11907 
11908       // If we have already emitted a message for a superclass, don't also report
11909       // the sub-class. We consider all operand classes that we don't have a
11910       // specialised diagnostic for to be equal for the propose of this check,
11911       // so that we don't report the generic error multiple times on the same
11912       // operand.
11913       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
11914       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
11915       if (std::any_of(PrevReports.first, PrevReports.second,
11916                       [DupCheckMatchClass](
11917                           const std::pair<unsigned, unsigned> Pair) {
11918             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
11919               return Pair.second == DupCheckMatchClass;
11920             else
11921               return isSubclass((MatchClassKind)DupCheckMatchClass,
11922                                 (MatchClassKind)Pair.second);
11923           }))
11924         break;
11925       OperandMissesSeen.insert(
11926           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
11927 
11928       NearMissMessage Message;
11929       Message.Loc = OperandLoc;
11930       if (OperandDiag) {
11931         Message.Message = OperandDiag;
11932       } else if (I.getOperandClass() == InvalidMatchClass) {
11933         Message.Message = "too many operands for instruction";
11934       } else {
11935         Message.Message = "invalid operand for instruction";
11936         LLVM_DEBUG(
11937             dbgs() << "Missing diagnostic string for operand class "
11938                    << getMatchClassName((MatchClassKind)I.getOperandClass())
11939                    << I.getOperandClass() << ", error " << I.getOperandError()
11940                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
11941       }
11942       NearMissesOut.emplace_back(Message);
11943       break;
11944     }
11945     case NearMissInfo::NearMissFeature: {
11946       const FeatureBitset &MissingFeatures = I.getFeatures();
11947       // Don't report the same set of features twice.
11948       if (FeatureMissesSeen.count(MissingFeatures))
11949         break;
11950       FeatureMissesSeen.insert(MissingFeatures);
11951 
11952       // Special case: don't report a feature set which includes arm-mode for
11953       // targets that don't have ARM mode.
11954       if (MissingFeatures.test(Feature_IsARMBit) && !hasARM())
11955         break;
11956       // Don't report any near-misses that both require switching instruction
11957       // set, and adding other subtarget features.
11958       if (isThumb() && MissingFeatures.test(Feature_IsARMBit) &&
11959           MissingFeatures.count() > 1)
11960         break;
11961       if (!isThumb() && MissingFeatures.test(Feature_IsThumbBit) &&
11962           MissingFeatures.count() > 1)
11963         break;
11964       if (!isThumb() && MissingFeatures.test(Feature_IsThumb2Bit) &&
11965           (MissingFeatures & ~FeatureBitset({Feature_IsThumb2Bit,
11966                                              Feature_IsThumbBit})).any())
11967         break;
11968       if (isMClass() && MissingFeatures.test(Feature_HasNEONBit))
11969         break;
11970 
11971       NearMissMessage Message;
11972       Message.Loc = IDLoc;
11973       raw_svector_ostream OS(Message.Message);
11974 
11975       OS << "instruction requires:";
11976       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
11977         if (MissingFeatures.test(i))
11978           OS << ' ' << getSubtargetFeatureName(i);
11979 
11980       NearMissesOut.emplace_back(Message);
11981 
11982       break;
11983     }
11984     case NearMissInfo::NearMissPredicate: {
11985       NearMissMessage Message;
11986       Message.Loc = IDLoc;
11987       switch (I.getPredicateError()) {
11988       case Match_RequiresNotITBlock:
11989         Message.Message = "flag setting instruction only valid outside IT block";
11990         break;
11991       case Match_RequiresITBlock:
11992         Message.Message = "instruction only valid inside IT block";
11993         break;
11994       case Match_RequiresV6:
11995         Message.Message = "instruction variant requires ARMv6 or later";
11996         break;
11997       case Match_RequiresThumb2:
11998         Message.Message = "instruction variant requires Thumb2";
11999         break;
12000       case Match_RequiresV8:
12001         Message.Message = "instruction variant requires ARMv8 or later";
12002         break;
12003       case Match_RequiresFlagSetting:
12004         Message.Message = "no flag-preserving variant of this instruction available";
12005         break;
12006       case Match_InvalidOperand:
12007         Message.Message = "invalid operand for instruction";
12008         break;
12009       default:
12010         llvm_unreachable("Unhandled target predicate error");
12011         break;
12012       }
12013       NearMissesOut.emplace_back(Message);
12014       break;
12015     }
12016     case NearMissInfo::NearMissTooFewOperands: {
12017       if (!ReportedTooFewOperands) {
12018         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
12019         NearMissesOut.emplace_back(NearMissMessage{
12020             EndLoc, StringRef("too few operands for instruction")});
12021         ReportedTooFewOperands = true;
12022       }
12023       break;
12024     }
12025     case NearMissInfo::NoNearMiss:
12026       // This should never leave the matcher.
12027       llvm_unreachable("not a near-miss");
12028       break;
12029     }
12030   }
12031 }
12032 
12033 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
12034                                     SMLoc IDLoc, OperandVector &Operands) {
12035   SmallVector<NearMissMessage, 4> Messages;
12036   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
12037 
12038   if (Messages.size() == 0) {
12039     // No near-misses were found, so the best we can do is "invalid
12040     // instruction".
12041     Error(IDLoc, "invalid instruction");
12042   } else if (Messages.size() == 1) {
12043     // One near miss was found, report it as the sole error.
12044     Error(Messages[0].Loc, Messages[0].Message);
12045   } else {
12046     // More than one near miss, so report a generic "invalid instruction"
12047     // error, followed by notes for each of the near-misses.
12048     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
12049     for (auto &M : Messages) {
12050       Note(M.Loc, M.Message);
12051     }
12052   }
12053 }
12054 
12055 /// parseDirectiveArchExtension
12056 ///   ::= .arch_extension [no]feature
12057 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
12058   // FIXME: This structure should be moved inside ARMTargetParser
12059   // when we start to table-generate them, and we can use the ARM
12060   // flags below, that were generated by table-gen.
12061   static const struct {
12062     const uint64_t Kind;
12063     const FeatureBitset ArchCheck;
12064     const FeatureBitset Features;
12065   } Extensions[] = {
12066     { ARM::AEK_CRC, {Feature_HasV8Bit}, {ARM::FeatureCRC} },
12067     { ARM::AEK_CRYPTO,  {Feature_HasV8Bit},
12068       {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
12069     { ARM::AEK_FP, {Feature_HasV8Bit},
12070       {ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8} },
12071     { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM),
12072       {Feature_HasV7Bit, Feature_IsNotMClassBit},
12073       {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
12074     { ARM::AEK_MP, {Feature_HasV7Bit, Feature_IsNotMClassBit},
12075       {ARM::FeatureMP} },
12076     { ARM::AEK_SIMD, {Feature_HasV8Bit},
12077       {ARM::FeatureNEON, ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8} },
12078     { ARM::AEK_SEC, {Feature_HasV6KBit}, {ARM::FeatureTrustZone} },
12079     // FIXME: Only available in A-class, isel not predicated
12080     { ARM::AEK_VIRT, {Feature_HasV7Bit}, {ARM::FeatureVirtualization} },
12081     { ARM::AEK_FP16, {Feature_HasV8_2aBit},
12082       {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
12083     { ARM::AEK_RAS, {Feature_HasV8Bit}, {ARM::FeatureRAS} },
12084     { ARM::AEK_LOB, {Feature_HasV8_1MMainlineBit}, {ARM::FeatureLOB} },
12085     // FIXME: Unsupported extensions.
12086     { ARM::AEK_OS, {}, {} },
12087     { ARM::AEK_IWMMXT, {}, {} },
12088     { ARM::AEK_IWMMXT2, {}, {} },
12089     { ARM::AEK_MAVERICK, {}, {} },
12090     { ARM::AEK_XSCALE, {}, {} },
12091   };
12092 
12093   MCAsmParser &Parser = getParser();
12094 
12095   if (getLexer().isNot(AsmToken::Identifier))
12096     return Error(getLexer().getLoc(), "expected architecture extension name");
12097 
12098   StringRef Name = Parser.getTok().getString();
12099   SMLoc ExtLoc = Parser.getTok().getLoc();
12100   Lex();
12101 
12102   if (parseToken(AsmToken::EndOfStatement,
12103                  "unexpected token in '.arch_extension' directive"))
12104     return true;
12105 
12106   bool EnableFeature = true;
12107   if (Name.startswith_lower("no")) {
12108     EnableFeature = false;
12109     Name = Name.substr(2);
12110   }
12111   uint64_t FeatureKind = ARM::parseArchExt(Name);
12112   if (FeatureKind == ARM::AEK_INVALID)
12113     return Error(ExtLoc, "unknown architectural extension: " + Name);
12114 
12115   for (const auto &Extension : Extensions) {
12116     if (Extension.Kind != FeatureKind)
12117       continue;
12118 
12119     if (Extension.Features.none())
12120       return Error(ExtLoc, "unsupported architectural extension: " + Name);
12121 
12122     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
12123       return Error(ExtLoc, "architectural extension '" + Name +
12124                                "' is not "
12125                                "allowed for the current base architecture");
12126 
12127     MCSubtargetInfo &STI = copySTI();
12128     if (EnableFeature) {
12129       STI.SetFeatureBitsTransitively(Extension.Features);
12130     } else {
12131       STI.ClearFeatureBitsTransitively(Extension.Features);
12132     }
12133     FeatureBitset Features = ComputeAvailableFeatures(STI.getFeatureBits());
12134     setAvailableFeatures(Features);
12135     return false;
12136   }
12137 
12138   return Error(ExtLoc, "unknown architectural extension: " + Name);
12139 }
12140 
12141 // Define this matcher function after the auto-generated include so we
12142 // have the match class enum definitions.
12143 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
12144                                                   unsigned Kind) {
12145   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
12146   // If the kind is a token for a literal immediate, check if our asm
12147   // operand matches. This is for InstAliases which have a fixed-value
12148   // immediate in the syntax.
12149   switch (Kind) {
12150   default: break;
12151   case MCK__HASH_0:
12152     if (Op.isImm())
12153       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12154         if (CE->getValue() == 0)
12155           return Match_Success;
12156     break;
12157   case MCK__HASH_8:
12158     if (Op.isImm())
12159       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12160         if (CE->getValue() == 8)
12161           return Match_Success;
12162     break;
12163   case MCK__HASH_16:
12164     if (Op.isImm())
12165       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12166         if (CE->getValue() == 16)
12167           return Match_Success;
12168     break;
12169   case MCK_ModImm:
12170     if (Op.isImm()) {
12171       const MCExpr *SOExpr = Op.getImm();
12172       int64_t Value;
12173       if (!SOExpr->evaluateAsAbsolute(Value))
12174         return Match_Success;
12175       assert((Value >= std::numeric_limits<int32_t>::min() &&
12176               Value <= std::numeric_limits<uint32_t>::max()) &&
12177              "expression value must be representable in 32 bits");
12178     }
12179     break;
12180   case MCK_rGPR:
12181     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
12182       return Match_Success;
12183     return Match_rGPR;
12184   case MCK_GPRPair:
12185     if (Op.isReg() &&
12186         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
12187       return Match_Success;
12188     break;
12189   }
12190   return Match_InvalidOperand;
12191 }
12192 
12193 bool ARMAsmParser::isMnemonicVPTPredicable(StringRef Mnemonic,
12194                                            StringRef ExtraToken) {
12195   if (!hasMVE())
12196     return false;
12197 
12198   return Mnemonic.startswith("vabav") || Mnemonic.startswith("vaddv") ||
12199          Mnemonic.startswith("vaddlv") || Mnemonic.startswith("vminnmv") ||
12200          Mnemonic.startswith("vminnmav") || Mnemonic.startswith("vminv") ||
12201          Mnemonic.startswith("vminav") || Mnemonic.startswith("vmaxnmv") ||
12202          Mnemonic.startswith("vmaxnmav") || Mnemonic.startswith("vmaxv") ||
12203          Mnemonic.startswith("vmaxav") || Mnemonic.startswith("vmladav") ||
12204          Mnemonic.startswith("vrmlaldavh") || Mnemonic.startswith("vrmlalvh") ||
12205          Mnemonic.startswith("vmlsdav") || Mnemonic.startswith("vmlav") ||
12206          Mnemonic.startswith("vmlaldav") || Mnemonic.startswith("vmlalv") ||
12207          Mnemonic.startswith("vmaxnm") || Mnemonic.startswith("vminnm") ||
12208          Mnemonic.startswith("vmax") || Mnemonic.startswith("vmin") ||
12209          Mnemonic.startswith("vshlc") || Mnemonic.startswith("vmovlt") ||
12210          Mnemonic.startswith("vmovlb") || Mnemonic.startswith("vshll") ||
12211          Mnemonic.startswith("vrshrn") || Mnemonic.startswith("vshrn") ||
12212          Mnemonic.startswith("vqrshrun") || Mnemonic.startswith("vqshrun") ||
12213          Mnemonic.startswith("vqrshrn") || Mnemonic.startswith("vqshrn") ||
12214          Mnemonic.startswith("vbic") || Mnemonic.startswith("vrev64") ||
12215          Mnemonic.startswith("vrev32") || Mnemonic.startswith("vrev16") ||
12216          Mnemonic.startswith("vmvn") || Mnemonic.startswith("veor") ||
12217          Mnemonic.startswith("vorn") || Mnemonic.startswith("vorr") ||
12218          Mnemonic.startswith("vand") || Mnemonic.startswith("vmul") ||
12219          Mnemonic.startswith("vqrdmulh") || Mnemonic.startswith("vqdmulh") ||
12220          Mnemonic.startswith("vsub") || Mnemonic.startswith("vadd") ||
12221          Mnemonic.startswith("vqsub") || Mnemonic.startswith("vqadd") ||
12222          Mnemonic.startswith("vabd") || Mnemonic.startswith("vrhadd") ||
12223          Mnemonic.startswith("vhsub") || Mnemonic.startswith("vhadd") ||
12224          Mnemonic.startswith("vdup") || Mnemonic.startswith("vcls") ||
12225          Mnemonic.startswith("vclz") || Mnemonic.startswith("vneg") ||
12226          Mnemonic.startswith("vabs") || Mnemonic.startswith("vqneg") ||
12227          Mnemonic.startswith("vqabs") ||
12228          (Mnemonic.startswith("vrint") && Mnemonic != "vrintr") ||
12229          Mnemonic.startswith("vcmla") || Mnemonic.startswith("vfma") ||
12230          Mnemonic.startswith("vfms") || Mnemonic.startswith("vcadd") ||
12231          Mnemonic.startswith("vadd") || Mnemonic.startswith("vsub") ||
12232          Mnemonic.startswith("vshl") || Mnemonic.startswith("vqshl") ||
12233          Mnemonic.startswith("vqrshl") || Mnemonic.startswith("vrshl") ||
12234          Mnemonic.startswith("vsri") || Mnemonic.startswith("vsli") ||
12235          Mnemonic.startswith("vrshr") || Mnemonic.startswith("vshr") ||
12236          Mnemonic.startswith("vpsel") || Mnemonic.startswith("vcmp") ||
12237          Mnemonic.startswith("vqdmladh") || Mnemonic.startswith("vqrdmladh") ||
12238          Mnemonic.startswith("vqdmlsdh") || Mnemonic.startswith("vqrdmlsdh") ||
12239          Mnemonic.startswith("vcmul") || Mnemonic.startswith("vrmulh") ||
12240          Mnemonic.startswith("vqmovn") || Mnemonic.startswith("vqmovun") ||
12241          Mnemonic.startswith("vmovnt") || Mnemonic.startswith("vmovnb") ||
12242          Mnemonic.startswith("vmaxa") || Mnemonic.startswith("vmaxnma") ||
12243          Mnemonic.startswith("vhcadd") || Mnemonic.startswith("vadc") ||
12244          Mnemonic.startswith("vsbc") || Mnemonic.startswith("vrshr") ||
12245          Mnemonic.startswith("vshr") || Mnemonic.startswith("vstrb") ||
12246          Mnemonic.startswith("vldrb") ||
12247          (Mnemonic.startswith("vstrh") && Mnemonic != "vstrhi") ||
12248          (Mnemonic.startswith("vldrh") && Mnemonic != "vldrhi") ||
12249          Mnemonic.startswith("vstrw") || Mnemonic.startswith("vldrw") ||
12250          Mnemonic.startswith("vldrd") || Mnemonic.startswith("vstrd") ||
12251          Mnemonic.startswith("vqdmull") || Mnemonic.startswith("vbrsr") ||
12252          Mnemonic.startswith("vfmas") || Mnemonic.startswith("vmlas") ||
12253          Mnemonic.startswith("vmla") || Mnemonic.startswith("vqdmlash") ||
12254          Mnemonic.startswith("vqdmlah") || Mnemonic.startswith("vqrdmlash") ||
12255          Mnemonic.startswith("vqrdmlah") || Mnemonic.startswith("viwdup") ||
12256          Mnemonic.startswith("vdwdup") || Mnemonic.startswith("vidup") ||
12257          Mnemonic.startswith("vddup") || Mnemonic.startswith("vctp") ||
12258          Mnemonic.startswith("vpnot") || Mnemonic.startswith("vbic") ||
12259          Mnemonic.startswith("vrmlsldavh") || Mnemonic.startswith("vmlsldav") ||
12260          Mnemonic.startswith("vcvt") ||
12261          MS.isVPTPredicableCDEInstr(Mnemonic) ||
12262          (Mnemonic.startswith("vmov") &&
12263           !(ExtraToken == ".f16" || ExtraToken == ".32" ||
12264             ExtraToken == ".16" || ExtraToken == ".8"));
12265 }
12266