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 "Utils/ARMBaseInfo.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMInstPrinter.h"
14 #include "MCTargetDesc/ARMMCExpr.h"
15 #include "MCTargetDesc/ARMMCTargetDesc.h"
16 #include "TargetInfo/ARMTargetInfo.h"
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCObjectFileInfo.h"
34 #include "llvm/MC/MCParser/MCAsmLexer.h"
35 #include "llvm/MC/MCParser/MCAsmParser.h"
36 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
37 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
38 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
39 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/MC/MCSection.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSubtargetInfo.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/MC/SubtargetFeature.h"
46 #include "llvm/Support/ARMBuildAttributes.h"
47 #include "llvm/Support/ARMEHABI.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/SMLoc.h"
54 #include "llvm/Support/TargetParser.h"
55 #include "llvm/Support/TargetRegistry.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <algorithm>
58 #include <cassert>
59 #include <cstddef>
60 #include <cstdint>
61 #include <iterator>
62 #include <limits>
63 #include <memory>
64 #include <string>
65 #include <utility>
66 #include <vector>
67 
68 #define DEBUG_TYPE "asm-parser"
69 
70 using namespace llvm;
71 
72 namespace llvm {
73 extern const MCInstrDesc ARMInsts[];
74 } // end namespace llvm
75 
76 namespace {
77 
78 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
79 
80 static cl::opt<ImplicitItModeTy> ImplicitItMode(
81     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
82     cl::desc("Allow conditional instructions outdside of an IT block"),
83     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
84                           "Accept in both ISAs, emit implicit ITs in Thumb"),
85                clEnumValN(ImplicitItModeTy::Never, "never",
86                           "Warn in ARM, reject in Thumb"),
87                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
88                           "Accept in ARM, reject in Thumb"),
89                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
90                           "Warn in ARM, emit implicit ITs in Thumb")));
91 
92 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
93                                         cl::init(false));
94 
95 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
96 
97 static inline unsigned extractITMaskBit(unsigned Mask, unsigned Position) {
98   // Position==0 means we're not in an IT block at all. Position==1
99   // means we want the first state bit, which is always 0 (Then).
100   // Position==2 means we want the second state bit, stored at bit 3
101   // of Mask, and so on downwards. So (5 - Position) will shift the
102   // right bit down to bit 0, including the always-0 bit at bit 4 for
103   // the mandatory initial Then.
104   return (Mask >> (5 - Position) & 1);
105 }
106 
107 class UnwindContext {
108   using Locs = SmallVector<SMLoc, 4>;
109 
110   MCAsmParser &Parser;
111   Locs FnStartLocs;
112   Locs CantUnwindLocs;
113   Locs PersonalityLocs;
114   Locs PersonalityIndexLocs;
115   Locs HandlerDataLocs;
116   int FPReg;
117 
118 public:
119   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
120 
121   bool hasFnStart() const { return !FnStartLocs.empty(); }
122   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
123   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
124 
125   bool hasPersonality() const {
126     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
127   }
128 
129   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
130   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
131   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
132   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
133   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
134 
135   void saveFPReg(int Reg) { FPReg = Reg; }
136   int getFPReg() const { return FPReg; }
137 
138   void emitFnStartLocNotes() const {
139     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
140          FI != FE; ++FI)
141       Parser.Note(*FI, ".fnstart was specified here");
142   }
143 
144   void emitCantUnwindLocNotes() const {
145     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
146                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
147       Parser.Note(*UI, ".cantunwind was specified here");
148   }
149 
150   void emitHandlerDataLocNotes() const {
151     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
152                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
153       Parser.Note(*HI, ".handlerdata was specified here");
154   }
155 
156   void emitPersonalityLocNotes() const {
157     for (Locs::const_iterator PI = PersonalityLocs.begin(),
158                               PE = PersonalityLocs.end(),
159                               PII = PersonalityIndexLocs.begin(),
160                               PIE = PersonalityIndexLocs.end();
161          PI != PE || PII != PIE;) {
162       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
163         Parser.Note(*PI++, ".personality was specified here");
164       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
165         Parser.Note(*PII++, ".personalityindex was specified here");
166       else
167         llvm_unreachable(".personality and .personalityindex cannot be "
168                          "at the same location");
169     }
170   }
171 
172   void reset() {
173     FnStartLocs = Locs();
174     CantUnwindLocs = Locs();
175     PersonalityLocs = Locs();
176     HandlerDataLocs = Locs();
177     PersonalityIndexLocs = Locs();
178     FPReg = ARM::SP;
179   }
180 };
181 
182 
183 class ARMAsmParser : public MCTargetAsmParser {
184   const MCRegisterInfo *MRI;
185   UnwindContext UC;
186 
187   ARMTargetStreamer &getTargetStreamer() {
188     assert(getParser().getStreamer().getTargetStreamer() &&
189            "do not have a target streamer");
190     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
191     return static_cast<ARMTargetStreamer &>(TS);
192   }
193 
194   // Map of register aliases registers via the .req directive.
195   StringMap<unsigned> RegisterReqs;
196 
197   bool NextSymbolIsThumb;
198 
199   bool useImplicitITThumb() const {
200     return ImplicitItMode == ImplicitItModeTy::Always ||
201            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
202   }
203 
204   bool useImplicitITARM() const {
205     return ImplicitItMode == ImplicitItModeTy::Always ||
206            ImplicitItMode == ImplicitItModeTy::ARMOnly;
207   }
208 
209   struct {
210     ARMCC::CondCodes Cond;    // Condition for IT block.
211     unsigned Mask:4;          // Condition mask for instructions.
212                               // Starting at first 1 (from lsb).
213                               //   '1'  condition as indicated in IT.
214                               //   '0'  inverse of condition (else).
215                               // Count of instructions in IT block is
216                               // 4 - trailingzeroes(mask)
217                               // Note that this does not have the same encoding
218                               // as in the IT instruction, which also depends
219                               // on the low bit of the condition code.
220 
221     unsigned CurPosition;     // Current position in parsing of IT
222                               // block. In range [0,4], with 0 being the IT
223                               // instruction itself. Initialized according to
224                               // count of instructions in block.  ~0U if no
225                               // active IT block.
226 
227     bool IsExplicit;          // true  - The IT instruction was present in the
228                               //         input, we should not modify it.
229                               // false - The IT instruction was added
230                               //         implicitly, we can extend it if that
231                               //         would be legal.
232   } ITState;
233 
234   SmallVector<MCInst, 4> PendingConditionalInsts;
235 
236   void flushPendingInstructions(MCStreamer &Out) override {
237     if (!inImplicitITBlock()) {
238       assert(PendingConditionalInsts.size() == 0);
239       return;
240     }
241 
242     // Emit the IT instruction
243     MCInst ITInst;
244     ITInst.setOpcode(ARM::t2IT);
245     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
246     ITInst.addOperand(MCOperand::createImm(ITState.Mask));
247     Out.EmitInstruction(ITInst, getSTI());
248 
249     // Emit the conditonal instructions
250     assert(PendingConditionalInsts.size() <= 4);
251     for (const MCInst &Inst : PendingConditionalInsts) {
252       Out.EmitInstruction(Inst, getSTI());
253     }
254     PendingConditionalInsts.clear();
255 
256     // Clear the IT state
257     ITState.Mask = 0;
258     ITState.CurPosition = ~0U;
259   }
260 
261   bool inITBlock() { return ITState.CurPosition != ~0U; }
262   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
263   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
264 
265   bool lastInITBlock() {
266     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
267   }
268 
269   void forwardITPosition() {
270     if (!inITBlock()) return;
271     // Move to the next instruction in the IT block, if there is one. If not,
272     // mark the block as done, except for implicit IT blocks, which we leave
273     // open until we find an instruction that can't be added to it.
274     unsigned TZ = countTrailingZeros(ITState.Mask);
275     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
276       ITState.CurPosition = ~0U; // Done with the IT block after this.
277   }
278 
279   // Rewind the state of the current IT block, removing the last slot from it.
280   void rewindImplicitITPosition() {
281     assert(inImplicitITBlock());
282     assert(ITState.CurPosition > 1);
283     ITState.CurPosition--;
284     unsigned TZ = countTrailingZeros(ITState.Mask);
285     unsigned NewMask = 0;
286     NewMask |= ITState.Mask & (0xC << TZ);
287     NewMask |= 0x2 << TZ;
288     ITState.Mask = NewMask;
289   }
290 
291   // Rewind the state of the current IT block, removing the last slot from it.
292   // If we were at the first slot, this closes the IT block.
293   void discardImplicitITBlock() {
294     assert(inImplicitITBlock());
295     assert(ITState.CurPosition == 1);
296     ITState.CurPosition = ~0U;
297   }
298 
299   // Return the low-subreg of a given Q register.
300   unsigned getDRegFromQReg(unsigned QReg) const {
301     return MRI->getSubReg(QReg, ARM::dsub_0);
302   }
303 
304   // Get the condition code corresponding to the current IT block slot.
305   ARMCC::CondCodes currentITCond() {
306     unsigned MaskBit = extractITMaskBit(ITState.Mask, ITState.CurPosition);
307     return MaskBit ? ARMCC::getOppositeCondition(ITState.Cond) : ITState.Cond;
308   }
309 
310   // Invert the condition of the current IT block slot without changing any
311   // other slots in the same block.
312   void invertCurrentITCondition() {
313     if (ITState.CurPosition == 1) {
314       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
315     } else {
316       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
317     }
318   }
319 
320   // Returns true if the current IT block is full (all 4 slots used).
321   bool isITBlockFull() {
322     return inITBlock() && (ITState.Mask & 1);
323   }
324 
325   // Extend the current implicit IT block to have one more slot with the given
326   // condition code.
327   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
328     assert(inImplicitITBlock());
329     assert(!isITBlockFull());
330     assert(Cond == ITState.Cond ||
331            Cond == ARMCC::getOppositeCondition(ITState.Cond));
332     unsigned TZ = countTrailingZeros(ITState.Mask);
333     unsigned NewMask = 0;
334     // Keep any existing condition bits.
335     NewMask |= ITState.Mask & (0xE << TZ);
336     // Insert the new condition bit.
337     NewMask |= (Cond != ITState.Cond) << TZ;
338     // Move the trailing 1 down one bit.
339     NewMask |= 1 << (TZ - 1);
340     ITState.Mask = NewMask;
341   }
342 
343   // Create a new implicit IT block with a dummy condition code.
344   void startImplicitITBlock() {
345     assert(!inITBlock());
346     ITState.Cond = ARMCC::AL;
347     ITState.Mask = 8;
348     ITState.CurPosition = 1;
349     ITState.IsExplicit = false;
350   }
351 
352   // Create a new explicit IT block with the given condition and mask.
353   // The mask should be in the format used in ARMOperand and
354   // MCOperand, with a 1 implying 'e', regardless of the low bit of
355   // the condition.
356   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
357     assert(!inITBlock());
358     ITState.Cond = Cond;
359     ITState.Mask = Mask;
360     ITState.CurPosition = 0;
361     ITState.IsExplicit = true;
362   }
363 
364   struct {
365     unsigned Mask : 4;
366     unsigned CurPosition;
367   } VPTState;
368   bool inVPTBlock() { return VPTState.CurPosition != ~0U; }
369   void forwardVPTPosition() {
370     if (!inVPTBlock()) return;
371     unsigned TZ = countTrailingZeros(VPTState.Mask);
372     if (++VPTState.CurPosition == 5 - TZ)
373       VPTState.CurPosition = ~0U;
374   }
375 
376   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
377     return getParser().Note(L, Msg, Range);
378   }
379 
380   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
381     return getParser().Warning(L, Msg, Range);
382   }
383 
384   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
385     return getParser().Error(L, Msg, Range);
386   }
387 
388   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
389                            unsigned ListNo, bool IsARPop = false);
390   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
391                            unsigned ListNo);
392 
393   int tryParseRegister();
394   bool tryParseRegisterWithWriteBack(OperandVector &);
395   int tryParseShiftRegister(OperandVector &);
396   bool parseRegisterList(OperandVector &, bool EnforceOrder = true);
397   bool parseMemory(OperandVector &);
398   bool parseOperand(OperandVector &, StringRef Mnemonic);
399   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
400   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
401                               unsigned &ShiftAmount);
402   bool parseLiteralValues(unsigned Size, SMLoc L);
403   bool parseDirectiveThumb(SMLoc L);
404   bool parseDirectiveARM(SMLoc L);
405   bool parseDirectiveThumbFunc(SMLoc L);
406   bool parseDirectiveCode(SMLoc L);
407   bool parseDirectiveSyntax(SMLoc L);
408   bool parseDirectiveReq(StringRef Name, SMLoc L);
409   bool parseDirectiveUnreq(SMLoc L);
410   bool parseDirectiveArch(SMLoc L);
411   bool parseDirectiveEabiAttr(SMLoc L);
412   bool parseDirectiveCPU(SMLoc L);
413   bool parseDirectiveFPU(SMLoc L);
414   bool parseDirectiveFnStart(SMLoc L);
415   bool parseDirectiveFnEnd(SMLoc L);
416   bool parseDirectiveCantUnwind(SMLoc L);
417   bool parseDirectivePersonality(SMLoc L);
418   bool parseDirectiveHandlerData(SMLoc L);
419   bool parseDirectiveSetFP(SMLoc L);
420   bool parseDirectivePad(SMLoc L);
421   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
422   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
423   bool parseDirectiveLtorg(SMLoc L);
424   bool parseDirectiveEven(SMLoc L);
425   bool parseDirectivePersonalityIndex(SMLoc L);
426   bool parseDirectiveUnwindRaw(SMLoc L);
427   bool parseDirectiveTLSDescSeq(SMLoc L);
428   bool parseDirectiveMovSP(SMLoc L);
429   bool parseDirectiveObjectArch(SMLoc L);
430   bool parseDirectiveArchExtension(SMLoc L);
431   bool parseDirectiveAlign(SMLoc L);
432   bool parseDirectiveThumbSet(SMLoc L);
433 
434   bool isMnemonicVPTPredicable(StringRef Mnemonic, StringRef ExtraToken);
435   StringRef splitMnemonic(StringRef Mnemonic, StringRef ExtraToken,
436                           unsigned &PredicationCode,
437                           unsigned &VPTPredicationCode, bool &CarrySetting,
438                           unsigned &ProcessorIMod, StringRef &ITMask);
439   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef ExtraToken,
440                              StringRef FullInst, bool &CanAcceptCarrySet,
441                              bool &CanAcceptPredicationCode,
442                              bool &CanAcceptVPTPredicationCode);
443 
444   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
445                                      OperandVector &Operands);
446   bool isThumb() const {
447     // FIXME: Can tablegen auto-generate this?
448     return getSTI().getFeatureBits()[ARM::ModeThumb];
449   }
450 
451   bool isThumbOne() const {
452     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
453   }
454 
455   bool isThumbTwo() const {
456     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
457   }
458 
459   bool hasThumb() const {
460     return getSTI().getFeatureBits()[ARM::HasV4TOps];
461   }
462 
463   bool hasThumb2() const {
464     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
465   }
466 
467   bool hasV6Ops() const {
468     return getSTI().getFeatureBits()[ARM::HasV6Ops];
469   }
470 
471   bool hasV6T2Ops() const {
472     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
473   }
474 
475   bool hasV6MOps() const {
476     return getSTI().getFeatureBits()[ARM::HasV6MOps];
477   }
478 
479   bool hasV7Ops() const {
480     return getSTI().getFeatureBits()[ARM::HasV7Ops];
481   }
482 
483   bool hasV8Ops() const {
484     return getSTI().getFeatureBits()[ARM::HasV8Ops];
485   }
486 
487   bool hasV8MBaseline() const {
488     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
489   }
490 
491   bool hasV8MMainline() const {
492     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
493   }
494   bool hasV8_1MMainline() const {
495     return getSTI().getFeatureBits()[ARM::HasV8_1MMainlineOps];
496   }
497   bool hasMVE() const {
498     return getSTI().getFeatureBits()[ARM::HasMVEIntegerOps];
499   }
500   bool hasMVEFloat() const {
501     return getSTI().getFeatureBits()[ARM::HasMVEFloatOps];
502   }
503   bool has8MSecExt() const {
504     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
505   }
506 
507   bool hasARM() const {
508     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
509   }
510 
511   bool hasDSP() const {
512     return getSTI().getFeatureBits()[ARM::FeatureDSP];
513   }
514 
515   bool hasD32() const {
516     return getSTI().getFeatureBits()[ARM::FeatureD32];
517   }
518 
519   bool hasV8_1aOps() const {
520     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
521   }
522 
523   bool hasRAS() const {
524     return getSTI().getFeatureBits()[ARM::FeatureRAS];
525   }
526 
527   void SwitchMode() {
528     MCSubtargetInfo &STI = copySTI();
529     auto FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
530     setAvailableFeatures(FB);
531   }
532 
533   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
534 
535   bool isMClass() const {
536     return getSTI().getFeatureBits()[ARM::FeatureMClass];
537   }
538 
539   /// @name Auto-generated Match Functions
540   /// {
541 
542 #define GET_ASSEMBLER_HEADER
543 #include "ARMGenAsmMatcher.inc"
544 
545   /// }
546 
547   OperandMatchResultTy parseITCondCode(OperandVector &);
548   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
549   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
550   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
551   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
552   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
553   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
554   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
555   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
556   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
557   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
558                                    int High);
559   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
560     return parsePKHImm(O, "lsl", 0, 31);
561   }
562   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
563     return parsePKHImm(O, "asr", 1, 32);
564   }
565   OperandMatchResultTy parseSetEndImm(OperandVector &);
566   OperandMatchResultTy parseShifterImm(OperandVector &);
567   OperandMatchResultTy parseRotImm(OperandVector &);
568   OperandMatchResultTy parseModImm(OperandVector &);
569   OperandMatchResultTy parseBitfield(OperandVector &);
570   OperandMatchResultTy parsePostIdxReg(OperandVector &);
571   OperandMatchResultTy parseAM3Offset(OperandVector &);
572   OperandMatchResultTy parseFPImm(OperandVector &);
573   OperandMatchResultTy parseVectorList(OperandVector &);
574   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
575                                        SMLoc &EndLoc);
576 
577   // Asm Match Converter Methods
578   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
579   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
580   void cvtMVEVMOVQtoDReg(MCInst &Inst, const OperandVector &);
581 
582   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
583   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
584   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
585   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
586   bool shouldOmitVectorPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
587   bool isITBlockTerminator(MCInst &Inst) const;
588   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
589   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
590                         bool Load, bool ARMMode, bool Writeback);
591 
592 public:
593   enum ARMMatchResultTy {
594     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
595     Match_RequiresNotITBlock,
596     Match_RequiresV6,
597     Match_RequiresThumb2,
598     Match_RequiresV8,
599     Match_RequiresFlagSetting,
600 #define GET_OPERAND_DIAGNOSTIC_TYPES
601 #include "ARMGenAsmMatcher.inc"
602 
603   };
604 
605   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
606                const MCInstrInfo &MII, const MCTargetOptions &Options)
607     : MCTargetAsmParser(Options, STI, MII), UC(Parser) {
608     MCAsmParserExtension::Initialize(Parser);
609 
610     // Cache the MCRegisterInfo.
611     MRI = getContext().getRegisterInfo();
612 
613     // Initialize the set of available features.
614     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
615 
616     // Add build attributes based on the selected target.
617     if (AddBuildAttributes)
618       getTargetStreamer().emitTargetAttributes(STI);
619 
620     // Not in an ITBlock to start with.
621     ITState.CurPosition = ~0U;
622 
623     VPTState.CurPosition = ~0U;
624 
625     NextSymbolIsThumb = false;
626   }
627 
628   // Implementation of the MCTargetAsmParser interface:
629   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
630   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
631                         SMLoc NameLoc, OperandVector &Operands) override;
632   bool ParseDirective(AsmToken DirectiveID) override;
633 
634   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
635                                       unsigned Kind) override;
636   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
637 
638   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
639                                OperandVector &Operands, MCStreamer &Out,
640                                uint64_t &ErrorInfo,
641                                bool MatchingInlineAsm) override;
642   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
643                             SmallVectorImpl<NearMissInfo> &NearMisses,
644                             bool MatchingInlineAsm, bool &EmitInITBlock,
645                             MCStreamer &Out);
646 
647   struct NearMissMessage {
648     SMLoc Loc;
649     SmallString<128> Message;
650   };
651 
652   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
653 
654   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
655                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
656                         SMLoc IDLoc, OperandVector &Operands);
657   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
658                         OperandVector &Operands);
659 
660   void doBeforeLabelEmit(MCSymbol *Symbol) override;
661 
662   void onLabelParsed(MCSymbol *Symbol) override;
663 };
664 
665 /// ARMOperand - Instances of this class represent a parsed ARM machine
666 /// operand.
667 class ARMOperand : public MCParsedAsmOperand {
668   enum KindTy {
669     k_CondCode,
670     k_VPTPred,
671     k_CCOut,
672     k_ITCondMask,
673     k_CoprocNum,
674     k_CoprocReg,
675     k_CoprocOption,
676     k_Immediate,
677     k_MemBarrierOpt,
678     k_InstSyncBarrierOpt,
679     k_TraceSyncBarrierOpt,
680     k_Memory,
681     k_PostIndexRegister,
682     k_MSRMask,
683     k_BankedReg,
684     k_ProcIFlags,
685     k_VectorIndex,
686     k_Register,
687     k_RegisterList,
688     k_RegisterListWithAPSR,
689     k_DPRRegisterList,
690     k_SPRRegisterList,
691     k_FPSRegisterListWithVPR,
692     k_FPDRegisterListWithVPR,
693     k_VectorList,
694     k_VectorListAllLanes,
695     k_VectorListIndexed,
696     k_ShiftedRegister,
697     k_ShiftedImmediate,
698     k_ShifterImmediate,
699     k_RotateImmediate,
700     k_ModifiedImmediate,
701     k_ConstantPoolImmediate,
702     k_BitfieldDescriptor,
703     k_Token,
704   } Kind;
705 
706   SMLoc StartLoc, EndLoc, AlignmentLoc;
707   SmallVector<unsigned, 8> Registers;
708 
709   struct CCOp {
710     ARMCC::CondCodes Val;
711   };
712 
713   struct VCCOp {
714     ARMVCC::VPTCodes Val;
715   };
716 
717   struct CopOp {
718     unsigned Val;
719   };
720 
721   struct CoprocOptionOp {
722     unsigned Val;
723   };
724 
725   struct ITMaskOp {
726     unsigned Mask:4;
727   };
728 
729   struct MBOptOp {
730     ARM_MB::MemBOpt Val;
731   };
732 
733   struct ISBOptOp {
734     ARM_ISB::InstSyncBOpt Val;
735   };
736 
737   struct TSBOptOp {
738     ARM_TSB::TraceSyncBOpt Val;
739   };
740 
741   struct IFlagsOp {
742     ARM_PROC::IFlags Val;
743   };
744 
745   struct MMaskOp {
746     unsigned Val;
747   };
748 
749   struct BankedRegOp {
750     unsigned Val;
751   };
752 
753   struct TokOp {
754     const char *Data;
755     unsigned Length;
756   };
757 
758   struct RegOp {
759     unsigned RegNum;
760   };
761 
762   // A vector register list is a sequential list of 1 to 4 registers.
763   struct VectorListOp {
764     unsigned RegNum;
765     unsigned Count;
766     unsigned LaneIndex;
767     bool isDoubleSpaced;
768   };
769 
770   struct VectorIndexOp {
771     unsigned Val;
772   };
773 
774   struct ImmOp {
775     const MCExpr *Val;
776   };
777 
778   /// Combined record for all forms of ARM address expressions.
779   struct MemoryOp {
780     unsigned BaseRegNum;
781     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
782     // was specified.
783     const MCConstantExpr *OffsetImm;  // Offset immediate value
784     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
785     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
786     unsigned ShiftImm;        // shift for OffsetReg.
787     unsigned Alignment;       // 0 = no alignment specified
788     // n = alignment in bytes (2, 4, 8, 16, or 32)
789     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
790   };
791 
792   struct PostIdxRegOp {
793     unsigned RegNum;
794     bool isAdd;
795     ARM_AM::ShiftOpc ShiftTy;
796     unsigned ShiftImm;
797   };
798 
799   struct ShifterImmOp {
800     bool isASR;
801     unsigned Imm;
802   };
803 
804   struct RegShiftedRegOp {
805     ARM_AM::ShiftOpc ShiftTy;
806     unsigned SrcReg;
807     unsigned ShiftReg;
808     unsigned ShiftImm;
809   };
810 
811   struct RegShiftedImmOp {
812     ARM_AM::ShiftOpc ShiftTy;
813     unsigned SrcReg;
814     unsigned ShiftImm;
815   };
816 
817   struct RotImmOp {
818     unsigned Imm;
819   };
820 
821   struct ModImmOp {
822     unsigned Bits;
823     unsigned Rot;
824   };
825 
826   struct BitfieldOp {
827     unsigned LSB;
828     unsigned Width;
829   };
830 
831   union {
832     struct CCOp CC;
833     struct VCCOp VCC;
834     struct CopOp Cop;
835     struct CoprocOptionOp CoprocOption;
836     struct MBOptOp MBOpt;
837     struct ISBOptOp ISBOpt;
838     struct TSBOptOp TSBOpt;
839     struct ITMaskOp ITMask;
840     struct IFlagsOp IFlags;
841     struct MMaskOp MMask;
842     struct BankedRegOp BankedReg;
843     struct TokOp Tok;
844     struct RegOp Reg;
845     struct VectorListOp VectorList;
846     struct VectorIndexOp VectorIndex;
847     struct ImmOp Imm;
848     struct MemoryOp Memory;
849     struct PostIdxRegOp PostIdxReg;
850     struct ShifterImmOp ShifterImm;
851     struct RegShiftedRegOp RegShiftedReg;
852     struct RegShiftedImmOp RegShiftedImm;
853     struct RotImmOp RotImm;
854     struct ModImmOp ModImm;
855     struct BitfieldOp Bitfield;
856   };
857 
858 public:
859   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
860 
861   /// getStartLoc - Get the location of the first token of this operand.
862   SMLoc getStartLoc() const override { return StartLoc; }
863 
864   /// getEndLoc - Get the location of the last token of this operand.
865   SMLoc getEndLoc() const override { return EndLoc; }
866 
867   /// getLocRange - Get the range between the first and last token of this
868   /// operand.
869   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
870 
871   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
872   SMLoc getAlignmentLoc() const {
873     assert(Kind == k_Memory && "Invalid access!");
874     return AlignmentLoc;
875   }
876 
877   ARMCC::CondCodes getCondCode() const {
878     assert(Kind == k_CondCode && "Invalid access!");
879     return CC.Val;
880   }
881 
882   ARMVCC::VPTCodes getVPTPred() const {
883     assert(isVPTPred() && "Invalid access!");
884     return VCC.Val;
885   }
886 
887   unsigned getCoproc() const {
888     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
889     return Cop.Val;
890   }
891 
892   StringRef getToken() const {
893     assert(Kind == k_Token && "Invalid access!");
894     return StringRef(Tok.Data, Tok.Length);
895   }
896 
897   unsigned getReg() const override {
898     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
899     return Reg.RegNum;
900   }
901 
902   const SmallVectorImpl<unsigned> &getRegList() const {
903     assert((Kind == k_RegisterList || Kind == k_RegisterListWithAPSR ||
904             Kind == k_DPRRegisterList || Kind == k_SPRRegisterList ||
905             Kind == k_FPSRegisterListWithVPR ||
906             Kind == k_FPDRegisterListWithVPR) &&
907            "Invalid access!");
908     return Registers;
909   }
910 
911   const MCExpr *getImm() const {
912     assert(isImm() && "Invalid access!");
913     return Imm.Val;
914   }
915 
916   const MCExpr *getConstantPoolImm() const {
917     assert(isConstantPoolImm() && "Invalid access!");
918     return Imm.Val;
919   }
920 
921   unsigned getVectorIndex() const {
922     assert(Kind == k_VectorIndex && "Invalid access!");
923     return VectorIndex.Val;
924   }
925 
926   ARM_MB::MemBOpt getMemBarrierOpt() const {
927     assert(Kind == k_MemBarrierOpt && "Invalid access!");
928     return MBOpt.Val;
929   }
930 
931   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
932     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
933     return ISBOpt.Val;
934   }
935 
936   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
937     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
938     return TSBOpt.Val;
939   }
940 
941   ARM_PROC::IFlags getProcIFlags() const {
942     assert(Kind == k_ProcIFlags && "Invalid access!");
943     return IFlags.Val;
944   }
945 
946   unsigned getMSRMask() const {
947     assert(Kind == k_MSRMask && "Invalid access!");
948     return MMask.Val;
949   }
950 
951   unsigned getBankedReg() const {
952     assert(Kind == k_BankedReg && "Invalid access!");
953     return BankedReg.Val;
954   }
955 
956   bool isCoprocNum() const { return Kind == k_CoprocNum; }
957   bool isCoprocReg() const { return Kind == k_CoprocReg; }
958   bool isCoprocOption() const { return Kind == k_CoprocOption; }
959   bool isCondCode() const { return Kind == k_CondCode; }
960   bool isVPTPred() const { return Kind == k_VPTPred; }
961   bool isCCOut() const { return Kind == k_CCOut; }
962   bool isITMask() const { return Kind == k_ITCondMask; }
963   bool isITCondCode() const { return Kind == k_CondCode; }
964   bool isImm() const override {
965     return Kind == k_Immediate;
966   }
967 
968   bool isARMBranchTarget() const {
969     if (!isImm()) return false;
970 
971     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
972       return CE->getValue() % 4 == 0;
973     return true;
974   }
975 
976 
977   bool isThumbBranchTarget() const {
978     if (!isImm()) return false;
979 
980     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
981       return CE->getValue() % 2 == 0;
982     return true;
983   }
984 
985   // checks whether this operand is an unsigned offset which fits is a field
986   // of specified width and scaled by a specific number of bits
987   template<unsigned width, unsigned scale>
988   bool isUnsignedOffset() const {
989     if (!isImm()) return false;
990     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
991     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
992       int64_t Val = CE->getValue();
993       int64_t Align = 1LL << scale;
994       int64_t Max = Align * ((1LL << width) - 1);
995       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
996     }
997     return false;
998   }
999 
1000   // checks whether this operand is an signed offset which fits is a field
1001   // of specified width and scaled by a specific number of bits
1002   template<unsigned width, unsigned scale>
1003   bool isSignedOffset() const {
1004     if (!isImm()) return false;
1005     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1006     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1007       int64_t Val = CE->getValue();
1008       int64_t Align = 1LL << scale;
1009       int64_t Max = Align * ((1LL << (width-1)) - 1);
1010       int64_t Min = -Align * (1LL << (width-1));
1011       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
1012     }
1013     return false;
1014   }
1015 
1016   // checks whether this operand is a memory operand computed as an offset
1017   // applied to PC. the offset may have 8 bits of magnitude and is represented
1018   // with two bits of shift. textually it may be either [pc, #imm], #imm or
1019   // relocable expression...
1020   bool isThumbMemPC() const {
1021     int64_t Val = 0;
1022     if (isImm()) {
1023       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1024       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
1025       if (!CE) return false;
1026       Val = CE->getValue();
1027     }
1028     else if (isMem()) {
1029       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
1030       if(Memory.BaseRegNum != ARM::PC) return false;
1031       Val = Memory.OffsetImm->getValue();
1032     }
1033     else return false;
1034     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
1035   }
1036 
1037   bool isFPImm() const {
1038     if (!isImm()) return false;
1039     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1040     if (!CE) return false;
1041     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1042     return Val != -1;
1043   }
1044 
1045   template<int64_t N, int64_t M>
1046   bool isImmediate() const {
1047     if (!isImm()) return false;
1048     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1049     if (!CE) return false;
1050     int64_t Value = CE->getValue();
1051     return Value >= N && Value <= M;
1052   }
1053 
1054   template<int64_t N, int64_t M>
1055   bool isImmediateS4() const {
1056     if (!isImm()) return false;
1057     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1058     if (!CE) return false;
1059     int64_t Value = CE->getValue();
1060     return ((Value & 3) == 0) && Value >= N && Value <= M;
1061   }
1062 
1063   bool isFBits16() const {
1064     return isImmediate<0, 17>();
1065   }
1066   bool isFBits32() const {
1067     return isImmediate<1, 33>();
1068   }
1069   bool isImm8s4() const {
1070     return isImmediateS4<-1020, 1020>();
1071   }
1072   bool isImm7s4() const {
1073     return isImmediateS4<-508, 508>();
1074   }
1075   bool isImm0_1020s4() const {
1076     return isImmediateS4<0, 1020>();
1077   }
1078   bool isImm0_508s4() const {
1079     return isImmediateS4<0, 508>();
1080   }
1081   bool isImm0_508s4Neg() const {
1082     if (!isImm()) return false;
1083     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1084     if (!CE) return false;
1085     int64_t Value = -CE->getValue();
1086     // explicitly exclude zero. we want that to use the normal 0_508 version.
1087     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1088   }
1089 
1090   bool isImm0_4095Neg() const {
1091     if (!isImm()) return false;
1092     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1093     if (!CE) return false;
1094     // isImm0_4095Neg is used with 32-bit immediates only.
1095     // 32-bit immediates are zero extended to 64-bit when parsed,
1096     // thus simple -CE->getValue() results in a big negative number,
1097     // not a small positive number as intended
1098     if ((CE->getValue() >> 32) > 0) return false;
1099     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1100     return Value > 0 && Value < 4096;
1101   }
1102 
1103   bool isImm0_7() const {
1104     return isImmediate<0, 7>();
1105   }
1106 
1107   bool isImm1_16() const {
1108     return isImmediate<1, 16>();
1109   }
1110 
1111   bool isImm1_32() const {
1112     return isImmediate<1, 32>();
1113   }
1114 
1115   bool isImm8_255() const {
1116     return isImmediate<8, 255>();
1117   }
1118 
1119   bool isImm256_65535Expr() const {
1120     if (!isImm()) return false;
1121     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1122     // If it's not a constant expression, it'll generate a fixup and be
1123     // handled later.
1124     if (!CE) return true;
1125     int64_t Value = CE->getValue();
1126     return Value >= 256 && Value < 65536;
1127   }
1128 
1129   bool isImm0_65535Expr() const {
1130     if (!isImm()) return false;
1131     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1132     // If it's not a constant expression, it'll generate a fixup and be
1133     // handled later.
1134     if (!CE) return true;
1135     int64_t Value = CE->getValue();
1136     return Value >= 0 && Value < 65536;
1137   }
1138 
1139   bool isImm24bit() const {
1140     return isImmediate<0, 0xffffff + 1>();
1141   }
1142 
1143   bool isImmThumbSR() const {
1144     return isImmediate<1, 33>();
1145   }
1146 
1147   template<int shift>
1148   bool isExpImmValue(uint64_t Value) const {
1149     uint64_t mask = (1 << shift) - 1;
1150     if ((Value & mask) != 0 || (Value >> shift) > 0xff)
1151       return false;
1152     return true;
1153   }
1154 
1155   template<int shift>
1156   bool isExpImm() const {
1157     if (!isImm()) return false;
1158     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1159     if (!CE) return false;
1160 
1161     return isExpImmValue<shift>(CE->getValue());
1162   }
1163 
1164   template<int shift, int size>
1165   bool isInvertedExpImm() const {
1166     if (!isImm()) return false;
1167     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1168     if (!CE) return false;
1169 
1170     uint64_t OriginalValue = CE->getValue();
1171     uint64_t InvertedValue = OriginalValue ^ (((uint64_t)1 << size) - 1);
1172     return isExpImmValue<shift>(InvertedValue);
1173   }
1174 
1175   bool isPKHLSLImm() const {
1176     return isImmediate<0, 32>();
1177   }
1178 
1179   bool isPKHASRImm() const {
1180     return isImmediate<0, 33>();
1181   }
1182 
1183   bool isAdrLabel() const {
1184     // If we have an immediate that's not a constant, treat it as a label
1185     // reference needing a fixup.
1186     if (isImm() && !isa<MCConstantExpr>(getImm()))
1187       return true;
1188 
1189     // If it is a constant, it must fit into a modified immediate encoding.
1190     if (!isImm()) return false;
1191     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1192     if (!CE) return false;
1193     int64_t Value = CE->getValue();
1194     return (ARM_AM::getSOImmVal(Value) != -1 ||
1195             ARM_AM::getSOImmVal(-Value) != -1);
1196   }
1197 
1198   bool isT2SOImm() const {
1199     // If we have an immediate that's not a constant, treat it as an expression
1200     // needing a fixup.
1201     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1202       // We want to avoid matching :upper16: and :lower16: as we want these
1203       // expressions to match in isImm0_65535Expr()
1204       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1205       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1206                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1207     }
1208     if (!isImm()) return false;
1209     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1210     if (!CE) return false;
1211     int64_t Value = CE->getValue();
1212     return ARM_AM::getT2SOImmVal(Value) != -1;
1213   }
1214 
1215   bool isT2SOImmNot() const {
1216     if (!isImm()) return false;
1217     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1218     if (!CE) return false;
1219     int64_t Value = CE->getValue();
1220     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1221       ARM_AM::getT2SOImmVal(~Value) != -1;
1222   }
1223 
1224   bool isT2SOImmNeg() const {
1225     if (!isImm()) return false;
1226     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1227     if (!CE) return false;
1228     int64_t Value = CE->getValue();
1229     // Only use this when not representable as a plain so_imm.
1230     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1231       ARM_AM::getT2SOImmVal(-Value) != -1;
1232   }
1233 
1234   bool isSetEndImm() const {
1235     if (!isImm()) return false;
1236     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1237     if (!CE) return false;
1238     int64_t Value = CE->getValue();
1239     return Value == 1 || Value == 0;
1240   }
1241 
1242   bool isReg() const override { return Kind == k_Register; }
1243   bool isRegList() const { return Kind == k_RegisterList; }
1244   bool isRegListWithAPSR() const {
1245     return Kind == k_RegisterListWithAPSR || Kind == k_RegisterList;
1246   }
1247   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1248   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1249   bool isFPSRegListWithVPR() const { return Kind == k_FPSRegisterListWithVPR; }
1250   bool isFPDRegListWithVPR() const { return Kind == k_FPDRegisterListWithVPR; }
1251   bool isToken() const override { return Kind == k_Token; }
1252   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1253   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1254   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
1255   bool isMem() const override {
1256     if (Kind != k_Memory)
1257       return false;
1258     if (Memory.BaseRegNum &&
1259         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1260       return false;
1261     if (Memory.OffsetRegNum &&
1262         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1263       return false;
1264     return true;
1265   }
1266   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1267   bool isRegShiftedReg() const {
1268     return Kind == k_ShiftedRegister &&
1269            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1270                RegShiftedReg.SrcReg) &&
1271            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1272                RegShiftedReg.ShiftReg);
1273   }
1274   bool isRegShiftedImm() const {
1275     return Kind == k_ShiftedImmediate &&
1276            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1277                RegShiftedImm.SrcReg);
1278   }
1279   bool isRotImm() const { return Kind == k_RotateImmediate; }
1280 
1281   template<unsigned Min, unsigned Max>
1282   bool isPowerTwoInRange() const {
1283     if (!isImm()) return false;
1284     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1285     if (!CE) return false;
1286     int64_t Value = CE->getValue();
1287     return Value > 0 && countPopulation((uint64_t)Value) == 1 &&
1288            Value >= Min && Value <= Max;
1289   }
1290   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1291 
1292   bool isModImmNot() const {
1293     if (!isImm()) return false;
1294     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1295     if (!CE) return false;
1296     int64_t Value = CE->getValue();
1297     return ARM_AM::getSOImmVal(~Value) != -1;
1298   }
1299 
1300   bool isModImmNeg() const {
1301     if (!isImm()) return false;
1302     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1303     if (!CE) return false;
1304     int64_t Value = CE->getValue();
1305     return ARM_AM::getSOImmVal(Value) == -1 &&
1306       ARM_AM::getSOImmVal(-Value) != -1;
1307   }
1308 
1309   bool isThumbModImmNeg1_7() const {
1310     if (!isImm()) return false;
1311     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1312     if (!CE) return false;
1313     int32_t Value = -(int32_t)CE->getValue();
1314     return 0 < Value && Value < 8;
1315   }
1316 
1317   bool isThumbModImmNeg8_255() const {
1318     if (!isImm()) return false;
1319     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1320     if (!CE) return false;
1321     int32_t Value = -(int32_t)CE->getValue();
1322     return 7 < Value && Value < 256;
1323   }
1324 
1325   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1326   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1327   bool isPostIdxRegShifted() const {
1328     return Kind == k_PostIndexRegister &&
1329            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1330   }
1331   bool isPostIdxReg() const {
1332     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1333   }
1334   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1335     if (!isMem())
1336       return false;
1337     // No offset of any kind.
1338     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1339      (alignOK || Memory.Alignment == Alignment);
1340   }
1341   bool isMemNoOffsetT2(bool alignOK = false, unsigned Alignment = 0) const {
1342     if (!isMem())
1343       return false;
1344 
1345     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1346             Memory.BaseRegNum))
1347       return false;
1348 
1349     // No offset of any kind.
1350     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1351      (alignOK || Memory.Alignment == Alignment);
1352   }
1353   bool isMemNoOffsetT2NoSp(bool alignOK = false, unsigned Alignment = 0) const {
1354     if (!isMem())
1355       return false;
1356 
1357     if (!ARMMCRegisterClasses[ARM::rGPRRegClassID].contains(
1358             Memory.BaseRegNum))
1359       return false;
1360 
1361     // No offset of any kind.
1362     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1363      (alignOK || Memory.Alignment == Alignment);
1364   }
1365   bool isMemPCRelImm12() const {
1366     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1367       return false;
1368     // Base register must be PC.
1369     if (Memory.BaseRegNum != ARM::PC)
1370       return false;
1371     // Immediate offset in range [-4095, 4095].
1372     if (!Memory.OffsetImm) return true;
1373     int64_t Val = Memory.OffsetImm->getValue();
1374     return (Val > -4096 && Val < 4096) ||
1375            (Val == std::numeric_limits<int32_t>::min());
1376   }
1377 
1378   bool isAlignedMemory() const {
1379     return isMemNoOffset(true);
1380   }
1381 
1382   bool isAlignedMemoryNone() const {
1383     return isMemNoOffset(false, 0);
1384   }
1385 
1386   bool isDupAlignedMemoryNone() const {
1387     return isMemNoOffset(false, 0);
1388   }
1389 
1390   bool isAlignedMemory16() const {
1391     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1392       return true;
1393     return isMemNoOffset(false, 0);
1394   }
1395 
1396   bool isDupAlignedMemory16() const {
1397     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1398       return true;
1399     return isMemNoOffset(false, 0);
1400   }
1401 
1402   bool isAlignedMemory32() const {
1403     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1404       return true;
1405     return isMemNoOffset(false, 0);
1406   }
1407 
1408   bool isDupAlignedMemory32() const {
1409     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1410       return true;
1411     return isMemNoOffset(false, 0);
1412   }
1413 
1414   bool isAlignedMemory64() const {
1415     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1416       return true;
1417     return isMemNoOffset(false, 0);
1418   }
1419 
1420   bool isDupAlignedMemory64() const {
1421     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1422       return true;
1423     return isMemNoOffset(false, 0);
1424   }
1425 
1426   bool isAlignedMemory64or128() const {
1427     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1428       return true;
1429     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1430       return true;
1431     return isMemNoOffset(false, 0);
1432   }
1433 
1434   bool isDupAlignedMemory64or128() const {
1435     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1436       return true;
1437     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1438       return true;
1439     return isMemNoOffset(false, 0);
1440   }
1441 
1442   bool isAlignedMemory64or128or256() const {
1443     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1444       return true;
1445     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1446       return true;
1447     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1448       return true;
1449     return isMemNoOffset(false, 0);
1450   }
1451 
1452   bool isAddrMode2() const {
1453     if (!isMem() || Memory.Alignment != 0) return false;
1454     // Check for register offset.
1455     if (Memory.OffsetRegNum) return true;
1456     // Immediate offset in range [-4095, 4095].
1457     if (!Memory.OffsetImm) return true;
1458     int64_t Val = Memory.OffsetImm->getValue();
1459     return Val > -4096 && Val < 4096;
1460   }
1461 
1462   bool isAM2OffsetImm() const {
1463     if (!isImm()) return false;
1464     // Immediate offset in range [-4095, 4095].
1465     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1466     if (!CE) return false;
1467     int64_t Val = CE->getValue();
1468     return (Val == std::numeric_limits<int32_t>::min()) ||
1469            (Val > -4096 && Val < 4096);
1470   }
1471 
1472   bool isAddrMode3() const {
1473     // If we have an immediate that's not a constant, treat it as a label
1474     // reference needing a fixup. If it is a constant, it's something else
1475     // and we reject it.
1476     if (isImm() && !isa<MCConstantExpr>(getImm()))
1477       return true;
1478     if (!isMem() || Memory.Alignment != 0) return false;
1479     // No shifts are legal for AM3.
1480     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1481     // Check for register offset.
1482     if (Memory.OffsetRegNum) return true;
1483     // Immediate offset in range [-255, 255].
1484     if (!Memory.OffsetImm) return true;
1485     int64_t Val = Memory.OffsetImm->getValue();
1486     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1487     // have to check for this too.
1488     return (Val > -256 && Val < 256) ||
1489            Val == std::numeric_limits<int32_t>::min();
1490   }
1491 
1492   bool isAM3Offset() const {
1493     if (isPostIdxReg())
1494       return true;
1495     if (!isImm())
1496       return false;
1497     // Immediate offset in range [-255, 255].
1498     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1499     if (!CE) return false;
1500     int64_t Val = CE->getValue();
1501     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1502     return (Val > -256 && Val < 256) ||
1503            Val == std::numeric_limits<int32_t>::min();
1504   }
1505 
1506   bool isAddrMode5() const {
1507     // If we have an immediate that's not a constant, treat it as a label
1508     // reference needing a fixup. If it is a constant, it's something else
1509     // and we reject it.
1510     if (isImm() && !isa<MCConstantExpr>(getImm()))
1511       return true;
1512     if (!isMem() || Memory.Alignment != 0) return false;
1513     // Check for register offset.
1514     if (Memory.OffsetRegNum) return false;
1515     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1516     if (!Memory.OffsetImm) return true;
1517     int64_t Val = Memory.OffsetImm->getValue();
1518     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1519       Val == std::numeric_limits<int32_t>::min();
1520   }
1521 
1522   bool isAddrMode5FP16() const {
1523     // If we have an immediate that's not a constant, treat it as a label
1524     // reference needing a fixup. If it is a constant, it's something else
1525     // and we reject it.
1526     if (isImm() && !isa<MCConstantExpr>(getImm()))
1527       return true;
1528     if (!isMem() || Memory.Alignment != 0) return false;
1529     // Check for register offset.
1530     if (Memory.OffsetRegNum) return false;
1531     // Immediate offset in range [-510, 510] and a multiple of 2.
1532     if (!Memory.OffsetImm) return true;
1533     int64_t Val = Memory.OffsetImm->getValue();
1534     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1535            Val == std::numeric_limits<int32_t>::min();
1536   }
1537 
1538   bool isMemTBB() const {
1539     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1540         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1541       return false;
1542     return true;
1543   }
1544 
1545   bool isMemTBH() const {
1546     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1547         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1548         Memory.Alignment != 0 )
1549       return false;
1550     return true;
1551   }
1552 
1553   bool isMemRegOffset() const {
1554     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1555       return false;
1556     return true;
1557   }
1558 
1559   bool isT2MemRegOffset() const {
1560     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1561         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1562       return false;
1563     // Only lsl #{0, 1, 2, 3} allowed.
1564     if (Memory.ShiftType == ARM_AM::no_shift)
1565       return true;
1566     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1567       return false;
1568     return true;
1569   }
1570 
1571   bool isMemThumbRR() const {
1572     // Thumb reg+reg addressing is simple. Just two registers, a base and
1573     // an offset. No shifts, negations or any other complicating factors.
1574     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1575         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1576       return false;
1577     return isARMLowRegister(Memory.BaseRegNum) &&
1578       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1579   }
1580 
1581   bool isMemThumbRIs4() const {
1582     if (!isMem() || Memory.OffsetRegNum != 0 ||
1583         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1584       return false;
1585     // Immediate offset, multiple of 4 in range [0, 124].
1586     if (!Memory.OffsetImm) return true;
1587     int64_t Val = Memory.OffsetImm->getValue();
1588     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1589   }
1590 
1591   bool isMemThumbRIs2() const {
1592     if (!isMem() || Memory.OffsetRegNum != 0 ||
1593         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1594       return false;
1595     // Immediate offset, multiple of 4 in range [0, 62].
1596     if (!Memory.OffsetImm) return true;
1597     int64_t Val = Memory.OffsetImm->getValue();
1598     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1599   }
1600 
1601   bool isMemThumbRIs1() const {
1602     if (!isMem() || Memory.OffsetRegNum != 0 ||
1603         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1604       return false;
1605     // Immediate offset in range [0, 31].
1606     if (!Memory.OffsetImm) return true;
1607     int64_t Val = Memory.OffsetImm->getValue();
1608     return Val >= 0 && Val <= 31;
1609   }
1610 
1611   bool isMemThumbSPI() const {
1612     if (!isMem() || Memory.OffsetRegNum != 0 ||
1613         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1614       return false;
1615     // Immediate offset, multiple of 4 in range [0, 1020].
1616     if (!Memory.OffsetImm) return true;
1617     int64_t Val = Memory.OffsetImm->getValue();
1618     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1619   }
1620 
1621   bool isMemImm8s4Offset() const {
1622     // If we have an immediate that's not a constant, treat it as a label
1623     // reference needing a fixup. If it is a constant, it's something else
1624     // and we reject it.
1625     if (isImm() && !isa<MCConstantExpr>(getImm()))
1626       return true;
1627     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1628       return false;
1629     // Immediate offset a multiple of 4 in range [-1020, 1020].
1630     if (!Memory.OffsetImm) return true;
1631     int64_t Val = Memory.OffsetImm->getValue();
1632     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1633     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1634            Val == std::numeric_limits<int32_t>::min();
1635   }
1636   bool isMemImm7s4Offset() const {
1637     // If we have an immediate that's not a constant, treat it as a label
1638     // reference needing a fixup. If it is a constant, it's something else
1639     // and we reject it.
1640     if (isImm() && !isa<MCConstantExpr>(getImm()))
1641       return true;
1642     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1643         !ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1644             Memory.BaseRegNum))
1645       return false;
1646     // Immediate offset a multiple of 4 in range [-508, 508].
1647     if (!Memory.OffsetImm) return true;
1648     int64_t Val = Memory.OffsetImm->getValue();
1649     // Special case, #-0 is INT32_MIN.
1650     return (Val >= -508 && Val <= 508 && (Val & 3) == 0) || Val == INT32_MIN;
1651   }
1652   bool isMemImm0_1020s4Offset() const {
1653     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1654       return false;
1655     // Immediate offset a multiple of 4 in range [0, 1020].
1656     if (!Memory.OffsetImm) return true;
1657     int64_t Val = Memory.OffsetImm->getValue();
1658     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1659   }
1660 
1661   bool isMemImm8Offset() const {
1662     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1663       return false;
1664     // Base reg of PC isn't allowed for these encodings.
1665     if (Memory.BaseRegNum == ARM::PC) return false;
1666     // Immediate offset in range [-255, 255].
1667     if (!Memory.OffsetImm) return true;
1668     int64_t Val = Memory.OffsetImm->getValue();
1669     return (Val == std::numeric_limits<int32_t>::min()) ||
1670            (Val > -256 && Val < 256);
1671   }
1672 
1673   bool isMemPosImm8Offset() const {
1674     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1675       return false;
1676     // Immediate offset in range [0, 255].
1677     if (!Memory.OffsetImm) return true;
1678     int64_t Val = Memory.OffsetImm->getValue();
1679     return Val >= 0 && Val < 256;
1680   }
1681 
1682   bool isMemNegImm8Offset() const {
1683     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1684       return false;
1685     // Base reg of PC isn't allowed for these encodings.
1686     if (Memory.BaseRegNum == ARM::PC) return false;
1687     // Immediate offset in range [-255, -1].
1688     if (!Memory.OffsetImm) return false;
1689     int64_t Val = Memory.OffsetImm->getValue();
1690     return (Val == std::numeric_limits<int32_t>::min()) ||
1691            (Val > -256 && Val < 0);
1692   }
1693 
1694   bool isMemUImm12Offset() const {
1695     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1696       return false;
1697     // Immediate offset in range [0, 4095].
1698     if (!Memory.OffsetImm) return true;
1699     int64_t Val = Memory.OffsetImm->getValue();
1700     return (Val >= 0 && Val < 4096);
1701   }
1702 
1703   bool isMemImm12Offset() const {
1704     // If we have an immediate that's not a constant, treat it as a label
1705     // reference needing a fixup. If it is a constant, it's something else
1706     // and we reject it.
1707 
1708     if (isImm() && !isa<MCConstantExpr>(getImm()))
1709       return true;
1710 
1711     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1712       return false;
1713     // Immediate offset in range [-4095, 4095].
1714     if (!Memory.OffsetImm) return true;
1715     int64_t Val = Memory.OffsetImm->getValue();
1716     return (Val > -4096 && Val < 4096) ||
1717            (Val == std::numeric_limits<int32_t>::min());
1718   }
1719 
1720   bool isConstPoolAsmImm() const {
1721     // Delay processing of Constant Pool Immediate, this will turn into
1722     // a constant. Match no other operand
1723     return (isConstantPoolImm());
1724   }
1725 
1726   bool isPostIdxImm8() const {
1727     if (!isImm()) return false;
1728     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1729     if (!CE) return false;
1730     int64_t Val = CE->getValue();
1731     return (Val > -256 && Val < 256) ||
1732            (Val == std::numeric_limits<int32_t>::min());
1733   }
1734 
1735   bool isPostIdxImm8s4() const {
1736     if (!isImm()) return false;
1737     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1738     if (!CE) return false;
1739     int64_t Val = CE->getValue();
1740     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1741            (Val == std::numeric_limits<int32_t>::min());
1742   }
1743 
1744   bool isMSRMask() const { return Kind == k_MSRMask; }
1745   bool isBankedReg() const { return Kind == k_BankedReg; }
1746   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1747 
1748   // NEON operands.
1749   bool isSingleSpacedVectorList() const {
1750     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1751   }
1752 
1753   bool isDoubleSpacedVectorList() const {
1754     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1755   }
1756 
1757   bool isVecListOneD() const {
1758     if (!isSingleSpacedVectorList()) return false;
1759     return VectorList.Count == 1;
1760   }
1761 
1762   bool isVecListTwoMQ() const {
1763     return isSingleSpacedVectorList() && VectorList.Count == 2 &&
1764            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1765                VectorList.RegNum);
1766   }
1767 
1768   bool isVecListDPair() const {
1769     if (!isSingleSpacedVectorList()) return false;
1770     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1771               .contains(VectorList.RegNum));
1772   }
1773 
1774   bool isVecListThreeD() const {
1775     if (!isSingleSpacedVectorList()) return false;
1776     return VectorList.Count == 3;
1777   }
1778 
1779   bool isVecListFourD() const {
1780     if (!isSingleSpacedVectorList()) return false;
1781     return VectorList.Count == 4;
1782   }
1783 
1784   bool isVecListDPairSpaced() const {
1785     if (Kind != k_VectorList) return false;
1786     if (isSingleSpacedVectorList()) return false;
1787     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1788               .contains(VectorList.RegNum));
1789   }
1790 
1791   bool isVecListThreeQ() const {
1792     if (!isDoubleSpacedVectorList()) return false;
1793     return VectorList.Count == 3;
1794   }
1795 
1796   bool isVecListFourQ() const {
1797     if (!isDoubleSpacedVectorList()) return false;
1798     return VectorList.Count == 4;
1799   }
1800 
1801   bool isVecListFourMQ() const {
1802     return isSingleSpacedVectorList() && VectorList.Count == 4 &&
1803            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1804                VectorList.RegNum);
1805   }
1806 
1807   bool isSingleSpacedVectorAllLanes() const {
1808     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1809   }
1810 
1811   bool isDoubleSpacedVectorAllLanes() const {
1812     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1813   }
1814 
1815   bool isVecListOneDAllLanes() const {
1816     if (!isSingleSpacedVectorAllLanes()) return false;
1817     return VectorList.Count == 1;
1818   }
1819 
1820   bool isVecListDPairAllLanes() const {
1821     if (!isSingleSpacedVectorAllLanes()) return false;
1822     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1823               .contains(VectorList.RegNum));
1824   }
1825 
1826   bool isVecListDPairSpacedAllLanes() const {
1827     if (!isDoubleSpacedVectorAllLanes()) return false;
1828     return VectorList.Count == 2;
1829   }
1830 
1831   bool isVecListThreeDAllLanes() const {
1832     if (!isSingleSpacedVectorAllLanes()) return false;
1833     return VectorList.Count == 3;
1834   }
1835 
1836   bool isVecListThreeQAllLanes() const {
1837     if (!isDoubleSpacedVectorAllLanes()) return false;
1838     return VectorList.Count == 3;
1839   }
1840 
1841   bool isVecListFourDAllLanes() const {
1842     if (!isSingleSpacedVectorAllLanes()) return false;
1843     return VectorList.Count == 4;
1844   }
1845 
1846   bool isVecListFourQAllLanes() const {
1847     if (!isDoubleSpacedVectorAllLanes()) return false;
1848     return VectorList.Count == 4;
1849   }
1850 
1851   bool isSingleSpacedVectorIndexed() const {
1852     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1853   }
1854 
1855   bool isDoubleSpacedVectorIndexed() const {
1856     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1857   }
1858 
1859   bool isVecListOneDByteIndexed() const {
1860     if (!isSingleSpacedVectorIndexed()) return false;
1861     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1862   }
1863 
1864   bool isVecListOneDHWordIndexed() const {
1865     if (!isSingleSpacedVectorIndexed()) return false;
1866     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1867   }
1868 
1869   bool isVecListOneDWordIndexed() const {
1870     if (!isSingleSpacedVectorIndexed()) return false;
1871     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1872   }
1873 
1874   bool isVecListTwoDByteIndexed() const {
1875     if (!isSingleSpacedVectorIndexed()) return false;
1876     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1877   }
1878 
1879   bool isVecListTwoDHWordIndexed() const {
1880     if (!isSingleSpacedVectorIndexed()) return false;
1881     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1882   }
1883 
1884   bool isVecListTwoQWordIndexed() const {
1885     if (!isDoubleSpacedVectorIndexed()) return false;
1886     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1887   }
1888 
1889   bool isVecListTwoQHWordIndexed() const {
1890     if (!isDoubleSpacedVectorIndexed()) return false;
1891     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1892   }
1893 
1894   bool isVecListTwoDWordIndexed() const {
1895     if (!isSingleSpacedVectorIndexed()) return false;
1896     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1897   }
1898 
1899   bool isVecListThreeDByteIndexed() const {
1900     if (!isSingleSpacedVectorIndexed()) return false;
1901     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1902   }
1903 
1904   bool isVecListThreeDHWordIndexed() const {
1905     if (!isSingleSpacedVectorIndexed()) return false;
1906     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1907   }
1908 
1909   bool isVecListThreeQWordIndexed() const {
1910     if (!isDoubleSpacedVectorIndexed()) return false;
1911     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1912   }
1913 
1914   bool isVecListThreeQHWordIndexed() const {
1915     if (!isDoubleSpacedVectorIndexed()) return false;
1916     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1917   }
1918 
1919   bool isVecListThreeDWordIndexed() const {
1920     if (!isSingleSpacedVectorIndexed()) return false;
1921     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1922   }
1923 
1924   bool isVecListFourDByteIndexed() const {
1925     if (!isSingleSpacedVectorIndexed()) return false;
1926     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1927   }
1928 
1929   bool isVecListFourDHWordIndexed() const {
1930     if (!isSingleSpacedVectorIndexed()) return false;
1931     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1932   }
1933 
1934   bool isVecListFourQWordIndexed() const {
1935     if (!isDoubleSpacedVectorIndexed()) return false;
1936     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1937   }
1938 
1939   bool isVecListFourQHWordIndexed() const {
1940     if (!isDoubleSpacedVectorIndexed()) return false;
1941     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1942   }
1943 
1944   bool isVecListFourDWordIndexed() const {
1945     if (!isSingleSpacedVectorIndexed()) return false;
1946     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1947   }
1948 
1949   bool isVectorIndex() const { return Kind == k_VectorIndex; }
1950 
1951   template <unsigned NumLanes>
1952   bool isVectorIndexInRange() const {
1953     if (Kind != k_VectorIndex) return false;
1954     return VectorIndex.Val < NumLanes;
1955   }
1956 
1957   bool isVectorIndex8()  const { return isVectorIndexInRange<8>(); }
1958   bool isVectorIndex16() const { return isVectorIndexInRange<4>(); }
1959   bool isVectorIndex32() const { return isVectorIndexInRange<2>(); }
1960   bool isVectorIndex64() const { return isVectorIndexInRange<1>(); }
1961 
1962   template<int PermittedValue, int OtherPermittedValue>
1963   bool isMVEPairVectorIndex() const {
1964     if (Kind != k_VectorIndex) return false;
1965     return VectorIndex.Val == PermittedValue ||
1966            VectorIndex.Val == OtherPermittedValue;
1967   }
1968 
1969   bool isNEONi8splat() const {
1970     if (!isImm()) return false;
1971     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1972     // Must be a constant.
1973     if (!CE) return false;
1974     int64_t Value = CE->getValue();
1975     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1976     // value.
1977     return Value >= 0 && Value < 256;
1978   }
1979 
1980   bool isNEONi16splat() const {
1981     if (isNEONByteReplicate(2))
1982       return false; // Leave that for bytes replication and forbid by default.
1983     if (!isImm())
1984       return false;
1985     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1986     // Must be a constant.
1987     if (!CE) return false;
1988     unsigned Value = CE->getValue();
1989     return ARM_AM::isNEONi16splat(Value);
1990   }
1991 
1992   bool isNEONi16splatNot() const {
1993     if (!isImm())
1994       return false;
1995     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1996     // Must be a constant.
1997     if (!CE) return false;
1998     unsigned Value = CE->getValue();
1999     return ARM_AM::isNEONi16splat(~Value & 0xffff);
2000   }
2001 
2002   bool isNEONi32splat() const {
2003     if (isNEONByteReplicate(4))
2004       return false; // Leave that for bytes replication and forbid by default.
2005     if (!isImm())
2006       return false;
2007     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2008     // Must be a constant.
2009     if (!CE) return false;
2010     unsigned Value = CE->getValue();
2011     return ARM_AM::isNEONi32splat(Value);
2012   }
2013 
2014   bool isNEONi32splatNot() const {
2015     if (!isImm())
2016       return false;
2017     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2018     // Must be a constant.
2019     if (!CE) return false;
2020     unsigned Value = CE->getValue();
2021     return ARM_AM::isNEONi32splat(~Value);
2022   }
2023 
2024   static bool isValidNEONi32vmovImm(int64_t Value) {
2025     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
2026     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
2027     return ((Value & 0xffffffffffffff00) == 0) ||
2028            ((Value & 0xffffffffffff00ff) == 0) ||
2029            ((Value & 0xffffffffff00ffff) == 0) ||
2030            ((Value & 0xffffffff00ffffff) == 0) ||
2031            ((Value & 0xffffffffffff00ff) == 0xff) ||
2032            ((Value & 0xffffffffff00ffff) == 0xffff);
2033   }
2034 
2035   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
2036     assert((Width == 8 || Width == 16 || Width == 32) &&
2037            "Invalid element width");
2038     assert(NumElems * Width <= 64 && "Invalid result width");
2039 
2040     if (!isImm())
2041       return false;
2042     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2043     // Must be a constant.
2044     if (!CE)
2045       return false;
2046     int64_t Value = CE->getValue();
2047     if (!Value)
2048       return false; // Don't bother with zero.
2049     if (Inv)
2050       Value = ~Value;
2051 
2052     uint64_t Mask = (1ull << Width) - 1;
2053     uint64_t Elem = Value & Mask;
2054     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
2055       return false;
2056     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
2057       return false;
2058 
2059     for (unsigned i = 1; i < NumElems; ++i) {
2060       Value >>= Width;
2061       if ((Value & Mask) != Elem)
2062         return false;
2063     }
2064     return true;
2065   }
2066 
2067   bool isNEONByteReplicate(unsigned NumBytes) const {
2068     return isNEONReplicate(8, NumBytes, false);
2069   }
2070 
2071   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
2072     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
2073            "Invalid source width");
2074     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
2075            "Invalid destination width");
2076     assert(FromW < ToW && "ToW is not less than FromW");
2077   }
2078 
2079   template<unsigned FromW, unsigned ToW>
2080   bool isNEONmovReplicate() const {
2081     checkNeonReplicateArgs(FromW, ToW);
2082     if (ToW == 64 && isNEONi64splat())
2083       return false;
2084     return isNEONReplicate(FromW, ToW / FromW, false);
2085   }
2086 
2087   template<unsigned FromW, unsigned ToW>
2088   bool isNEONinvReplicate() const {
2089     checkNeonReplicateArgs(FromW, ToW);
2090     return isNEONReplicate(FromW, ToW / FromW, true);
2091   }
2092 
2093   bool isNEONi32vmov() const {
2094     if (isNEONByteReplicate(4))
2095       return false; // Let it to be classified as byte-replicate case.
2096     if (!isImm())
2097       return false;
2098     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2099     // Must be a constant.
2100     if (!CE)
2101       return false;
2102     return isValidNEONi32vmovImm(CE->getValue());
2103   }
2104 
2105   bool isNEONi32vmovNeg() const {
2106     if (!isImm()) return false;
2107     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2108     // Must be a constant.
2109     if (!CE) return false;
2110     return isValidNEONi32vmovImm(~CE->getValue());
2111   }
2112 
2113   bool isNEONi64splat() const {
2114     if (!isImm()) return false;
2115     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2116     // Must be a constant.
2117     if (!CE) return false;
2118     uint64_t Value = CE->getValue();
2119     // i64 value with each byte being either 0 or 0xff.
2120     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
2121       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
2122     return true;
2123   }
2124 
2125   template<int64_t Angle, int64_t Remainder>
2126   bool isComplexRotation() const {
2127     if (!isImm()) return false;
2128 
2129     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2130     if (!CE) return false;
2131     uint64_t Value = CE->getValue();
2132 
2133     return (Value % Angle == Remainder && Value <= 270);
2134   }
2135 
2136   bool isMVELongShift() const {
2137     if (!isImm()) return false;
2138     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2139     // Must be a constant.
2140     if (!CE) return false;
2141     uint64_t Value = CE->getValue();
2142     return Value >= 1 && Value <= 32;
2143   }
2144 
2145   bool isITCondCodeNoAL() const {
2146     if (!isITCondCode()) return false;
2147     ARMCC::CondCodes CC = getCondCode();
2148     return CC != ARMCC::AL;
2149   }
2150 
2151   bool isITCondCodeRestrictedI() const {
2152     if (!isITCondCode())
2153       return false;
2154     ARMCC::CondCodes CC = getCondCode();
2155     return CC == ARMCC::EQ || CC == ARMCC::NE;
2156   }
2157 
2158   bool isITCondCodeRestrictedS() const {
2159     if (!isITCondCode())
2160       return false;
2161     ARMCC::CondCodes CC = getCondCode();
2162     return CC == ARMCC::LT || CC == ARMCC::GT || CC == ARMCC::LE ||
2163            CC == ARMCC::GE;
2164   }
2165 
2166   bool isITCondCodeRestrictedU() const {
2167     if (!isITCondCode())
2168       return false;
2169     ARMCC::CondCodes CC = getCondCode();
2170     return CC == ARMCC::HS || CC == ARMCC::HI;
2171   }
2172 
2173   bool isITCondCodeRestrictedFP() const {
2174     if (!isITCondCode())
2175       return false;
2176     ARMCC::CondCodes CC = getCondCode();
2177     return CC == ARMCC::EQ || CC == ARMCC::NE || CC == ARMCC::LT ||
2178            CC == ARMCC::GT || CC == ARMCC::LE || CC == ARMCC::GE;
2179   }
2180 
2181   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
2182     // Add as immediates when possible.  Null MCExpr = 0.
2183     if (!Expr)
2184       Inst.addOperand(MCOperand::createImm(0));
2185     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2186       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2187     else
2188       Inst.addOperand(MCOperand::createExpr(Expr));
2189   }
2190 
2191   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2192     assert(N == 1 && "Invalid number of operands!");
2193     addExpr(Inst, getImm());
2194   }
2195 
2196   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2197     assert(N == 1 && "Invalid number of operands!");
2198     addExpr(Inst, getImm());
2199   }
2200 
2201   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2202     assert(N == 2 && "Invalid number of operands!");
2203     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2204     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2205     Inst.addOperand(MCOperand::createReg(RegNum));
2206   }
2207 
2208   void addVPTPredNOperands(MCInst &Inst, unsigned N) const {
2209     assert(N == 2 && "Invalid number of operands!");
2210     Inst.addOperand(MCOperand::createImm(unsigned(getVPTPred())));
2211     unsigned RegNum = getVPTPred() == ARMVCC::None ? 0: ARM::P0;
2212     Inst.addOperand(MCOperand::createReg(RegNum));
2213   }
2214 
2215   void addVPTPredROperands(MCInst &Inst, unsigned N) const {
2216     assert(N == 3 && "Invalid number of operands!");
2217     addVPTPredNOperands(Inst, N-1);
2218     unsigned RegNum;
2219     if (getVPTPred() == ARMVCC::None) {
2220       RegNum = 0;
2221     } else {
2222       unsigned NextOpIndex = Inst.getNumOperands();
2223       const MCInstrDesc &MCID = ARMInsts[Inst.getOpcode()];
2224       int TiedOp = MCID.getOperandConstraint(NextOpIndex, MCOI::TIED_TO);
2225       assert(TiedOp >= 0 &&
2226              "Inactive register in vpred_r is not tied to an output!");
2227       RegNum = Inst.getOperand(TiedOp).getReg();
2228     }
2229     Inst.addOperand(MCOperand::createReg(RegNum));
2230   }
2231 
2232   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2233     assert(N == 1 && "Invalid number of operands!");
2234     Inst.addOperand(MCOperand::createImm(getCoproc()));
2235   }
2236 
2237   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2238     assert(N == 1 && "Invalid number of operands!");
2239     Inst.addOperand(MCOperand::createImm(getCoproc()));
2240   }
2241 
2242   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2243     assert(N == 1 && "Invalid number of operands!");
2244     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2245   }
2246 
2247   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2248     assert(N == 1 && "Invalid number of operands!");
2249     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2250   }
2251 
2252   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2253     assert(N == 1 && "Invalid number of operands!");
2254     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2255   }
2256 
2257   void addITCondCodeInvOperands(MCInst &Inst, unsigned N) const {
2258     assert(N == 1 && "Invalid number of operands!");
2259     Inst.addOperand(MCOperand::createImm(unsigned(ARMCC::getOppositeCondition(getCondCode()))));
2260   }
2261 
2262   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2263     assert(N == 1 && "Invalid number of operands!");
2264     Inst.addOperand(MCOperand::createReg(getReg()));
2265   }
2266 
2267   void addRegOperands(MCInst &Inst, unsigned N) const {
2268     assert(N == 1 && "Invalid number of operands!");
2269     Inst.addOperand(MCOperand::createReg(getReg()));
2270   }
2271 
2272   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2273     assert(N == 3 && "Invalid number of operands!");
2274     assert(isRegShiftedReg() &&
2275            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2276     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2277     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2278     Inst.addOperand(MCOperand::createImm(
2279       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2280   }
2281 
2282   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2283     assert(N == 2 && "Invalid number of operands!");
2284     assert(isRegShiftedImm() &&
2285            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2286     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2287     // Shift of #32 is encoded as 0 where permitted
2288     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2289     Inst.addOperand(MCOperand::createImm(
2290       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2291   }
2292 
2293   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2294     assert(N == 1 && "Invalid number of operands!");
2295     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2296                                          ShifterImm.Imm));
2297   }
2298 
2299   void addRegListOperands(MCInst &Inst, unsigned N) const {
2300     assert(N == 1 && "Invalid number of operands!");
2301     const SmallVectorImpl<unsigned> &RegList = getRegList();
2302     for (SmallVectorImpl<unsigned>::const_iterator
2303            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2304       Inst.addOperand(MCOperand::createReg(*I));
2305   }
2306 
2307   void addRegListWithAPSROperands(MCInst &Inst, unsigned N) const {
2308     assert(N == 1 && "Invalid number of operands!");
2309     const SmallVectorImpl<unsigned> &RegList = getRegList();
2310     for (SmallVectorImpl<unsigned>::const_iterator
2311            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2312       Inst.addOperand(MCOperand::createReg(*I));
2313   }
2314 
2315   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2316     addRegListOperands(Inst, N);
2317   }
2318 
2319   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2320     addRegListOperands(Inst, N);
2321   }
2322 
2323   void addFPSRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2324     addRegListOperands(Inst, N);
2325   }
2326 
2327   void addFPDRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2328     addRegListOperands(Inst, N);
2329   }
2330 
2331   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2332     assert(N == 1 && "Invalid number of operands!");
2333     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2334     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2335   }
2336 
2337   void addModImmOperands(MCInst &Inst, unsigned N) const {
2338     assert(N == 1 && "Invalid number of operands!");
2339 
2340     // Support for fixups (MCFixup)
2341     if (isImm())
2342       return addImmOperands(Inst, N);
2343 
2344     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2345   }
2346 
2347   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2348     assert(N == 1 && "Invalid number of operands!");
2349     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2350     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2351     Inst.addOperand(MCOperand::createImm(Enc));
2352   }
2353 
2354   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2355     assert(N == 1 && "Invalid number of operands!");
2356     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2357     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2358     Inst.addOperand(MCOperand::createImm(Enc));
2359   }
2360 
2361   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2362     assert(N == 1 && "Invalid number of operands!");
2363     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2364     uint32_t Val = -CE->getValue();
2365     Inst.addOperand(MCOperand::createImm(Val));
2366   }
2367 
2368   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2369     assert(N == 1 && "Invalid number of operands!");
2370     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2371     uint32_t Val = -CE->getValue();
2372     Inst.addOperand(MCOperand::createImm(Val));
2373   }
2374 
2375   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2376     assert(N == 1 && "Invalid number of operands!");
2377     // Munge the lsb/width into a bitfield mask.
2378     unsigned lsb = Bitfield.LSB;
2379     unsigned width = Bitfield.Width;
2380     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2381     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2382                       (32 - (lsb + width)));
2383     Inst.addOperand(MCOperand::createImm(Mask));
2384   }
2385 
2386   void addImmOperands(MCInst &Inst, unsigned N) const {
2387     assert(N == 1 && "Invalid number of operands!");
2388     addExpr(Inst, getImm());
2389   }
2390 
2391   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2392     assert(N == 1 && "Invalid number of operands!");
2393     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2394     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2395   }
2396 
2397   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2398     assert(N == 1 && "Invalid number of operands!");
2399     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2400     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2401   }
2402 
2403   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2404     assert(N == 1 && "Invalid number of operands!");
2405     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2406     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2407     Inst.addOperand(MCOperand::createImm(Val));
2408   }
2409 
2410   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2411     assert(N == 1 && "Invalid number of operands!");
2412     // FIXME: We really want to scale the value here, but the LDRD/STRD
2413     // instruction don't encode operands that way yet.
2414     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2415     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2416   }
2417 
2418   void addImm7s4Operands(MCInst &Inst, unsigned N) const {
2419     assert(N == 1 && "Invalid number of operands!");
2420     // FIXME: We really want to scale the value here, but the VSTR/VLDR_VSYSR
2421     // instruction don't encode operands that way yet.
2422     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2423     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2424   }
2425 
2426   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2427     assert(N == 1 && "Invalid number of operands!");
2428     // The immediate is scaled by four in the encoding and is stored
2429     // in the MCInst as such. Lop off the low two bits here.
2430     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2431     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2432   }
2433 
2434   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2435     assert(N == 1 && "Invalid number of operands!");
2436     // The immediate is scaled by four in the encoding and is stored
2437     // in the MCInst as such. Lop off the low two bits here.
2438     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2439     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2440   }
2441 
2442   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2443     assert(N == 1 && "Invalid number of operands!");
2444     // The immediate is scaled by four in the encoding and is stored
2445     // in the MCInst as such. Lop off the low two bits here.
2446     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2447     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2448   }
2449 
2450   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2451     assert(N == 1 && "Invalid number of operands!");
2452     // The constant encodes as the immediate-1, and we store in the instruction
2453     // the bits as encoded, so subtract off one here.
2454     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2455     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2456   }
2457 
2458   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2459     assert(N == 1 && "Invalid number of operands!");
2460     // The constant encodes as the immediate-1, and we store in the instruction
2461     // the bits as encoded, so subtract off one here.
2462     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2463     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2464   }
2465 
2466   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2467     assert(N == 1 && "Invalid number of operands!");
2468     // The constant encodes as the immediate, except for 32, which encodes as
2469     // zero.
2470     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2471     unsigned Imm = CE->getValue();
2472     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2473   }
2474 
2475   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2476     assert(N == 1 && "Invalid number of operands!");
2477     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2478     // the instruction as well.
2479     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2480     int Val = CE->getValue();
2481     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2482   }
2483 
2484   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2485     assert(N == 1 && "Invalid number of operands!");
2486     // The operand is actually a t2_so_imm, but we have its bitwise
2487     // negation in the assembly source, so twiddle it here.
2488     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2489     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2490   }
2491 
2492   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2493     assert(N == 1 && "Invalid number of operands!");
2494     // The operand is actually a t2_so_imm, but we have its
2495     // negation in the assembly source, so twiddle it here.
2496     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2497     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2498   }
2499 
2500   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2501     assert(N == 1 && "Invalid number of operands!");
2502     // The operand is actually an imm0_4095, but we have its
2503     // negation in the assembly source, so twiddle it here.
2504     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2505     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2506   }
2507 
2508   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2509     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2510       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2511       return;
2512     }
2513 
2514     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2515     assert(SR && "Unknown value type!");
2516     Inst.addOperand(MCOperand::createExpr(SR));
2517   }
2518 
2519   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2520     assert(N == 1 && "Invalid number of operands!");
2521     if (isImm()) {
2522       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2523       if (CE) {
2524         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2525         return;
2526       }
2527 
2528       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2529 
2530       assert(SR && "Unknown value type!");
2531       Inst.addOperand(MCOperand::createExpr(SR));
2532       return;
2533     }
2534 
2535     assert(isMem()  && "Unknown value type!");
2536     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2537     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2538   }
2539 
2540   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2541     assert(N == 1 && "Invalid number of operands!");
2542     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2543   }
2544 
2545   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2546     assert(N == 1 && "Invalid number of operands!");
2547     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2548   }
2549 
2550   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2551     assert(N == 1 && "Invalid number of operands!");
2552     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2553   }
2554 
2555   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2556     assert(N == 1 && "Invalid number of operands!");
2557     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2558   }
2559 
2560   void addMemNoOffsetT2Operands(MCInst &Inst, unsigned N) const {
2561     assert(N == 1 && "Invalid number of operands!");
2562     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2563   }
2564 
2565   void addMemNoOffsetT2NoSpOperands(MCInst &Inst, unsigned N) const {
2566     assert(N == 1 && "Invalid number of operands!");
2567     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2568   }
2569 
2570   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2571     assert(N == 1 && "Invalid number of operands!");
2572     int32_t Imm = Memory.OffsetImm->getValue();
2573     Inst.addOperand(MCOperand::createImm(Imm));
2574   }
2575 
2576   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2577     assert(N == 1 && "Invalid number of operands!");
2578     assert(isImm() && "Not an immediate!");
2579 
2580     // If we have an immediate that's not a constant, treat it as a label
2581     // reference needing a fixup.
2582     if (!isa<MCConstantExpr>(getImm())) {
2583       Inst.addOperand(MCOperand::createExpr(getImm()));
2584       return;
2585     }
2586 
2587     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2588     int Val = CE->getValue();
2589     Inst.addOperand(MCOperand::createImm(Val));
2590   }
2591 
2592   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2593     assert(N == 2 && "Invalid number of operands!");
2594     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2595     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2596   }
2597 
2598   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2599     addAlignedMemoryOperands(Inst, N);
2600   }
2601 
2602   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2603     addAlignedMemoryOperands(Inst, N);
2604   }
2605 
2606   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2607     addAlignedMemoryOperands(Inst, N);
2608   }
2609 
2610   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2611     addAlignedMemoryOperands(Inst, N);
2612   }
2613 
2614   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2615     addAlignedMemoryOperands(Inst, N);
2616   }
2617 
2618   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2619     addAlignedMemoryOperands(Inst, N);
2620   }
2621 
2622   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2623     addAlignedMemoryOperands(Inst, N);
2624   }
2625 
2626   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2627     addAlignedMemoryOperands(Inst, N);
2628   }
2629 
2630   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2631     addAlignedMemoryOperands(Inst, N);
2632   }
2633 
2634   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2635     addAlignedMemoryOperands(Inst, N);
2636   }
2637 
2638   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2639     addAlignedMemoryOperands(Inst, N);
2640   }
2641 
2642   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2643     assert(N == 3 && "Invalid number of operands!");
2644     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2645     if (!Memory.OffsetRegNum) {
2646       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2647       // Special case for #-0
2648       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2649       if (Val < 0) Val = -Val;
2650       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2651     } else {
2652       // For register offset, we encode the shift type and negation flag
2653       // here.
2654       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2655                               Memory.ShiftImm, Memory.ShiftType);
2656     }
2657     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2658     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2659     Inst.addOperand(MCOperand::createImm(Val));
2660   }
2661 
2662   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2663     assert(N == 2 && "Invalid number of operands!");
2664     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2665     assert(CE && "non-constant AM2OffsetImm operand!");
2666     int32_t Val = CE->getValue();
2667     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2668     // Special case for #-0
2669     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2670     if (Val < 0) Val = -Val;
2671     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2672     Inst.addOperand(MCOperand::createReg(0));
2673     Inst.addOperand(MCOperand::createImm(Val));
2674   }
2675 
2676   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2677     assert(N == 3 && "Invalid number of operands!");
2678     // If we have an immediate that's not a constant, treat it as a label
2679     // reference needing a fixup. If it is a constant, it's something else
2680     // and we reject it.
2681     if (isImm()) {
2682       Inst.addOperand(MCOperand::createExpr(getImm()));
2683       Inst.addOperand(MCOperand::createReg(0));
2684       Inst.addOperand(MCOperand::createImm(0));
2685       return;
2686     }
2687 
2688     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2689     if (!Memory.OffsetRegNum) {
2690       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2691       // Special case for #-0
2692       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2693       if (Val < 0) Val = -Val;
2694       Val = ARM_AM::getAM3Opc(AddSub, Val);
2695     } else {
2696       // For register offset, we encode the shift type and negation flag
2697       // here.
2698       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2699     }
2700     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2701     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2702     Inst.addOperand(MCOperand::createImm(Val));
2703   }
2704 
2705   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2706     assert(N == 2 && "Invalid number of operands!");
2707     if (Kind == k_PostIndexRegister) {
2708       int32_t Val =
2709         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2710       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2711       Inst.addOperand(MCOperand::createImm(Val));
2712       return;
2713     }
2714 
2715     // Constant offset.
2716     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2717     int32_t Val = CE->getValue();
2718     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2719     // Special case for #-0
2720     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2721     if (Val < 0) Val = -Val;
2722     Val = ARM_AM::getAM3Opc(AddSub, Val);
2723     Inst.addOperand(MCOperand::createReg(0));
2724     Inst.addOperand(MCOperand::createImm(Val));
2725   }
2726 
2727   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2728     assert(N == 2 && "Invalid number of operands!");
2729     // If we have an immediate that's not a constant, treat it as a label
2730     // reference needing a fixup. If it is a constant, it's something else
2731     // and we reject it.
2732     if (isImm()) {
2733       Inst.addOperand(MCOperand::createExpr(getImm()));
2734       Inst.addOperand(MCOperand::createImm(0));
2735       return;
2736     }
2737 
2738     // The lower two bits are always zero and as such are not encoded.
2739     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2740     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2741     // Special case for #-0
2742     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2743     if (Val < 0) Val = -Val;
2744     Val = ARM_AM::getAM5Opc(AddSub, Val);
2745     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2746     Inst.addOperand(MCOperand::createImm(Val));
2747   }
2748 
2749   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2750     assert(N == 2 && "Invalid number of operands!");
2751     // If we have an immediate that's not a constant, treat it as a label
2752     // reference needing a fixup. If it is a constant, it's something else
2753     // and we reject it.
2754     if (isImm()) {
2755       Inst.addOperand(MCOperand::createExpr(getImm()));
2756       Inst.addOperand(MCOperand::createImm(0));
2757       return;
2758     }
2759 
2760     // The lower bit is always zero and as such is not encoded.
2761     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2762     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2763     // Special case for #-0
2764     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2765     if (Val < 0) Val = -Val;
2766     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2767     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2768     Inst.addOperand(MCOperand::createImm(Val));
2769   }
2770 
2771   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2772     assert(N == 2 && "Invalid number of operands!");
2773     // If we have an immediate that's not a constant, treat it as a label
2774     // reference needing a fixup. If it is a constant, it's something else
2775     // and we reject it.
2776     if (isImm()) {
2777       Inst.addOperand(MCOperand::createExpr(getImm()));
2778       Inst.addOperand(MCOperand::createImm(0));
2779       return;
2780     }
2781 
2782     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2783     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2784     Inst.addOperand(MCOperand::createImm(Val));
2785   }
2786 
2787   void addMemImm7s4OffsetOperands(MCInst &Inst, unsigned N) const {
2788     assert(N == 2 && "Invalid number of operands!");
2789     // If we have an immediate that's not a constant, treat it as a label
2790     // reference needing a fixup. If it is a constant, it's something else
2791     // and we reject it.
2792     if (isImm()) {
2793       Inst.addOperand(MCOperand::createExpr(getImm()));
2794       Inst.addOperand(MCOperand::createImm(0));
2795       return;
2796     }
2797 
2798     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2799     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2800     Inst.addOperand(MCOperand::createImm(Val));
2801   }
2802 
2803   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2804     assert(N == 2 && "Invalid number of operands!");
2805     // The lower two bits are always zero and as such are not encoded.
2806     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2807     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2808     Inst.addOperand(MCOperand::createImm(Val));
2809   }
2810 
2811   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2812     assert(N == 2 && "Invalid number of operands!");
2813     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2814     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2815     Inst.addOperand(MCOperand::createImm(Val));
2816   }
2817 
2818   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2819     addMemImm8OffsetOperands(Inst, N);
2820   }
2821 
2822   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2823     addMemImm8OffsetOperands(Inst, N);
2824   }
2825 
2826   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2827     assert(N == 2 && "Invalid number of operands!");
2828     // If this is an immediate, it's a label reference.
2829     if (isImm()) {
2830       addExpr(Inst, getImm());
2831       Inst.addOperand(MCOperand::createImm(0));
2832       return;
2833     }
2834 
2835     // Otherwise, it's a normal memory reg+offset.
2836     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2837     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2838     Inst.addOperand(MCOperand::createImm(Val));
2839   }
2840 
2841   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2842     assert(N == 2 && "Invalid number of operands!");
2843     // If this is an immediate, it's a label reference.
2844     if (isImm()) {
2845       addExpr(Inst, getImm());
2846       Inst.addOperand(MCOperand::createImm(0));
2847       return;
2848     }
2849 
2850     // Otherwise, it's a normal memory reg+offset.
2851     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2852     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2853     Inst.addOperand(MCOperand::createImm(Val));
2854   }
2855 
2856   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2857     assert(N == 1 && "Invalid number of operands!");
2858     // This is container for the immediate that we will create the constant
2859     // pool from
2860     addExpr(Inst, getConstantPoolImm());
2861     return;
2862   }
2863 
2864   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2865     assert(N == 2 && "Invalid number of operands!");
2866     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2867     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2868   }
2869 
2870   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2871     assert(N == 2 && "Invalid number of operands!");
2872     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2873     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2874   }
2875 
2876   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2877     assert(N == 3 && "Invalid number of operands!");
2878     unsigned Val =
2879       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2880                         Memory.ShiftImm, Memory.ShiftType);
2881     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2882     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2883     Inst.addOperand(MCOperand::createImm(Val));
2884   }
2885 
2886   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2887     assert(N == 3 && "Invalid number of operands!");
2888     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2889     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2890     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2891   }
2892 
2893   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2894     assert(N == 2 && "Invalid number of operands!");
2895     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2896     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2897   }
2898 
2899   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2900     assert(N == 2 && "Invalid number of operands!");
2901     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2902     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2903     Inst.addOperand(MCOperand::createImm(Val));
2904   }
2905 
2906   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2907     assert(N == 2 && "Invalid number of operands!");
2908     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2909     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2910     Inst.addOperand(MCOperand::createImm(Val));
2911   }
2912 
2913   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2914     assert(N == 2 && "Invalid number of operands!");
2915     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2916     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2917     Inst.addOperand(MCOperand::createImm(Val));
2918   }
2919 
2920   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2921     assert(N == 2 && "Invalid number of operands!");
2922     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2923     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2924     Inst.addOperand(MCOperand::createImm(Val));
2925   }
2926 
2927   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2928     assert(N == 1 && "Invalid number of operands!");
2929     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2930     assert(CE && "non-constant post-idx-imm8 operand!");
2931     int Imm = CE->getValue();
2932     bool isAdd = Imm >= 0;
2933     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2934     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2935     Inst.addOperand(MCOperand::createImm(Imm));
2936   }
2937 
2938   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2939     assert(N == 1 && "Invalid number of operands!");
2940     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2941     assert(CE && "non-constant post-idx-imm8s4 operand!");
2942     int Imm = CE->getValue();
2943     bool isAdd = Imm >= 0;
2944     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2945     // Immediate is scaled by 4.
2946     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2947     Inst.addOperand(MCOperand::createImm(Imm));
2948   }
2949 
2950   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2951     assert(N == 2 && "Invalid number of operands!");
2952     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2953     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2954   }
2955 
2956   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2957     assert(N == 2 && "Invalid number of operands!");
2958     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2959     // The sign, shift type, and shift amount are encoded in a single operand
2960     // using the AM2 encoding helpers.
2961     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2962     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2963                                      PostIdxReg.ShiftTy);
2964     Inst.addOperand(MCOperand::createImm(Imm));
2965   }
2966 
2967   void addPowerTwoOperands(MCInst &Inst, unsigned N) const {
2968     assert(N == 1 && "Invalid number of operands!");
2969     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2970     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2971   }
2972 
2973   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2974     assert(N == 1 && "Invalid number of operands!");
2975     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2976   }
2977 
2978   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2979     assert(N == 1 && "Invalid number of operands!");
2980     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2981   }
2982 
2983   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2984     assert(N == 1 && "Invalid number of operands!");
2985     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2986   }
2987 
2988   void addVecListOperands(MCInst &Inst, unsigned N) const {
2989     assert(N == 1 && "Invalid number of operands!");
2990     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2991   }
2992 
2993   void addMVEVecListOperands(MCInst &Inst, unsigned N) const {
2994     assert(N == 1 && "Invalid number of operands!");
2995 
2996     // When we come here, the VectorList field will identify a range
2997     // of q-registers by its base register and length, and it will
2998     // have already been error-checked to be the expected length of
2999     // range and contain only q-regs in the range q0-q7. So we can
3000     // count on the base register being in the range q0-q6 (for 2
3001     // regs) or q0-q4 (for 4)
3002     //
3003     // The MVE instructions taking a register range of this kind will
3004     // need an operand in the QQPR or QQQQPR class, representing the
3005     // entire range as a unit. So we must translate into that class,
3006     // by finding the index of the base register in the MQPR reg
3007     // class, and returning the super-register at the corresponding
3008     // index in the target class.
3009 
3010     const MCRegisterClass *RC_in = &ARMMCRegisterClasses[ARM::MQPRRegClassID];
3011     const MCRegisterClass *RC_out = (VectorList.Count == 2) ?
3012       &ARMMCRegisterClasses[ARM::QQPRRegClassID] :
3013       &ARMMCRegisterClasses[ARM::QQQQPRRegClassID];
3014 
3015     unsigned I, E = RC_out->getNumRegs();
3016     for (I = 0; I < E; I++)
3017       if (RC_in->getRegister(I) == VectorList.RegNum)
3018         break;
3019     assert(I < E && "Invalid vector list start register!");
3020 
3021     Inst.addOperand(MCOperand::createReg(RC_out->getRegister(I)));
3022   }
3023 
3024   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
3025     assert(N == 2 && "Invalid number of operands!");
3026     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3027     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
3028   }
3029 
3030   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
3031     assert(N == 1 && "Invalid number of operands!");
3032     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3033   }
3034 
3035   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
3036     assert(N == 1 && "Invalid number of operands!");
3037     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3038   }
3039 
3040   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
3041     assert(N == 1 && "Invalid number of operands!");
3042     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3043   }
3044 
3045   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
3046     assert(N == 1 && "Invalid number of operands!");
3047     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3048   }
3049 
3050   void addMVEVectorIndexOperands(MCInst &Inst, unsigned N) const {
3051     assert(N == 1 && "Invalid number of operands!");
3052     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3053   }
3054 
3055   void addMVEPairVectorIndexOperands(MCInst &Inst, unsigned N) const {
3056     assert(N == 1 && "Invalid number of operands!");
3057     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3058   }
3059 
3060   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
3061     assert(N == 1 && "Invalid number of operands!");
3062     // The immediate encodes the type of constant as well as the value.
3063     // Mask in that this is an i8 splat.
3064     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3065     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
3066   }
3067 
3068   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
3069     assert(N == 1 && "Invalid number of operands!");
3070     // The immediate encodes the type of constant as well as the value.
3071     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3072     unsigned Value = CE->getValue();
3073     Value = ARM_AM::encodeNEONi16splat(Value);
3074     Inst.addOperand(MCOperand::createImm(Value));
3075   }
3076 
3077   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
3078     assert(N == 1 && "Invalid number of operands!");
3079     // The immediate encodes the type of constant as well as the value.
3080     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3081     unsigned Value = CE->getValue();
3082     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
3083     Inst.addOperand(MCOperand::createImm(Value));
3084   }
3085 
3086   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
3087     assert(N == 1 && "Invalid number of operands!");
3088     // The immediate encodes the type of constant as well as the value.
3089     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3090     unsigned Value = CE->getValue();
3091     Value = ARM_AM::encodeNEONi32splat(Value);
3092     Inst.addOperand(MCOperand::createImm(Value));
3093   }
3094 
3095   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
3096     assert(N == 1 && "Invalid number of operands!");
3097     // The immediate encodes the type of constant as well as the value.
3098     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3099     unsigned Value = CE->getValue();
3100     Value = ARM_AM::encodeNEONi32splat(~Value);
3101     Inst.addOperand(MCOperand::createImm(Value));
3102   }
3103 
3104   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
3105     // The immediate encodes the type of constant as well as the value.
3106     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3107     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
3108             Inst.getOpcode() == ARM::VMOVv16i8) &&
3109           "All instructions that wants to replicate non-zero byte "
3110           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
3111     unsigned Value = CE->getValue();
3112     if (Inv)
3113       Value = ~Value;
3114     unsigned B = Value & 0xff;
3115     B |= 0xe00; // cmode = 0b1110
3116     Inst.addOperand(MCOperand::createImm(B));
3117   }
3118 
3119   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3120     assert(N == 1 && "Invalid number of operands!");
3121     addNEONi8ReplicateOperands(Inst, true);
3122   }
3123 
3124   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
3125     if (Value >= 256 && Value <= 0xffff)
3126       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
3127     else if (Value > 0xffff && Value <= 0xffffff)
3128       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
3129     else if (Value > 0xffffff)
3130       Value = (Value >> 24) | 0x600;
3131     return Value;
3132   }
3133 
3134   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
3135     assert(N == 1 && "Invalid number of operands!");
3136     // The immediate encodes the type of constant as well as the value.
3137     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3138     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
3139     Inst.addOperand(MCOperand::createImm(Value));
3140   }
3141 
3142   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3143     assert(N == 1 && "Invalid number of operands!");
3144     addNEONi8ReplicateOperands(Inst, false);
3145   }
3146 
3147   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
3148     assert(N == 1 && "Invalid number of operands!");
3149     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3150     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
3151             Inst.getOpcode() == ARM::VMOVv8i16 ||
3152             Inst.getOpcode() == ARM::VMVNv4i16 ||
3153             Inst.getOpcode() == ARM::VMVNv8i16) &&
3154           "All instructions that want to replicate non-zero half-word "
3155           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
3156     uint64_t Value = CE->getValue();
3157     unsigned Elem = Value & 0xffff;
3158     if (Elem >= 256)
3159       Elem = (Elem >> 8) | 0x200;
3160     Inst.addOperand(MCOperand::createImm(Elem));
3161   }
3162 
3163   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
3164     assert(N == 1 && "Invalid number of operands!");
3165     // The immediate encodes the type of constant as well as the value.
3166     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3167     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
3168     Inst.addOperand(MCOperand::createImm(Value));
3169   }
3170 
3171   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
3172     assert(N == 1 && "Invalid number of operands!");
3173     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3174     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
3175             Inst.getOpcode() == ARM::VMOVv4i32 ||
3176             Inst.getOpcode() == ARM::VMVNv2i32 ||
3177             Inst.getOpcode() == ARM::VMVNv4i32) &&
3178           "All instructions that want to replicate non-zero word "
3179           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
3180     uint64_t Value = CE->getValue();
3181     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
3182     Inst.addOperand(MCOperand::createImm(Elem));
3183   }
3184 
3185   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
3186     assert(N == 1 && "Invalid number of operands!");
3187     // The immediate encodes the type of constant as well as the value.
3188     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3189     uint64_t Value = CE->getValue();
3190     unsigned Imm = 0;
3191     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
3192       Imm |= (Value & 1) << i;
3193     }
3194     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
3195   }
3196 
3197   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
3198     assert(N == 1 && "Invalid number of operands!");
3199     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3200     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
3201   }
3202 
3203   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
3204     assert(N == 1 && "Invalid number of operands!");
3205     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3206     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
3207   }
3208 
3209   void print(raw_ostream &OS) const override;
3210 
3211   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
3212     auto Op = make_unique<ARMOperand>(k_ITCondMask);
3213     Op->ITMask.Mask = Mask;
3214     Op->StartLoc = S;
3215     Op->EndLoc = S;
3216     return Op;
3217   }
3218 
3219   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
3220                                                     SMLoc S) {
3221     auto Op = make_unique<ARMOperand>(k_CondCode);
3222     Op->CC.Val = CC;
3223     Op->StartLoc = S;
3224     Op->EndLoc = S;
3225     return Op;
3226   }
3227 
3228   static std::unique_ptr<ARMOperand> CreateVPTPred(ARMVCC::VPTCodes CC,
3229                                                    SMLoc S) {
3230     auto Op = make_unique<ARMOperand>(k_VPTPred);
3231     Op->VCC.Val = CC;
3232     Op->StartLoc = S;
3233     Op->EndLoc = S;
3234     return Op;
3235   }
3236 
3237   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
3238     auto Op = make_unique<ARMOperand>(k_CoprocNum);
3239     Op->Cop.Val = CopVal;
3240     Op->StartLoc = S;
3241     Op->EndLoc = S;
3242     return Op;
3243   }
3244 
3245   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
3246     auto Op = make_unique<ARMOperand>(k_CoprocReg);
3247     Op->Cop.Val = CopVal;
3248     Op->StartLoc = S;
3249     Op->EndLoc = S;
3250     return Op;
3251   }
3252 
3253   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
3254                                                         SMLoc E) {
3255     auto Op = make_unique<ARMOperand>(k_CoprocOption);
3256     Op->Cop.Val = Val;
3257     Op->StartLoc = S;
3258     Op->EndLoc = E;
3259     return Op;
3260   }
3261 
3262   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
3263     auto Op = make_unique<ARMOperand>(k_CCOut);
3264     Op->Reg.RegNum = RegNum;
3265     Op->StartLoc = S;
3266     Op->EndLoc = S;
3267     return Op;
3268   }
3269 
3270   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
3271     auto Op = make_unique<ARMOperand>(k_Token);
3272     Op->Tok.Data = Str.data();
3273     Op->Tok.Length = Str.size();
3274     Op->StartLoc = S;
3275     Op->EndLoc = S;
3276     return Op;
3277   }
3278 
3279   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
3280                                                SMLoc E) {
3281     auto Op = make_unique<ARMOperand>(k_Register);
3282     Op->Reg.RegNum = RegNum;
3283     Op->StartLoc = S;
3284     Op->EndLoc = E;
3285     return Op;
3286   }
3287 
3288   static std::unique_ptr<ARMOperand>
3289   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3290                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
3291                         SMLoc E) {
3292     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
3293     Op->RegShiftedReg.ShiftTy = ShTy;
3294     Op->RegShiftedReg.SrcReg = SrcReg;
3295     Op->RegShiftedReg.ShiftReg = ShiftReg;
3296     Op->RegShiftedReg.ShiftImm = ShiftImm;
3297     Op->StartLoc = S;
3298     Op->EndLoc = E;
3299     return Op;
3300   }
3301 
3302   static std::unique_ptr<ARMOperand>
3303   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3304                          unsigned ShiftImm, SMLoc S, SMLoc E) {
3305     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
3306     Op->RegShiftedImm.ShiftTy = ShTy;
3307     Op->RegShiftedImm.SrcReg = SrcReg;
3308     Op->RegShiftedImm.ShiftImm = ShiftImm;
3309     Op->StartLoc = S;
3310     Op->EndLoc = E;
3311     return Op;
3312   }
3313 
3314   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
3315                                                       SMLoc S, SMLoc E) {
3316     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
3317     Op->ShifterImm.isASR = isASR;
3318     Op->ShifterImm.Imm = Imm;
3319     Op->StartLoc = S;
3320     Op->EndLoc = E;
3321     return Op;
3322   }
3323 
3324   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3325                                                   SMLoc E) {
3326     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
3327     Op->RotImm.Imm = Imm;
3328     Op->StartLoc = S;
3329     Op->EndLoc = E;
3330     return Op;
3331   }
3332 
3333   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3334                                                   SMLoc S, SMLoc E) {
3335     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
3336     Op->ModImm.Bits = Bits;
3337     Op->ModImm.Rot = Rot;
3338     Op->StartLoc = S;
3339     Op->EndLoc = E;
3340     return Op;
3341   }
3342 
3343   static std::unique_ptr<ARMOperand>
3344   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3345     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
3346     Op->Imm.Val = Val;
3347     Op->StartLoc = S;
3348     Op->EndLoc = E;
3349     return Op;
3350   }
3351 
3352   static std::unique_ptr<ARMOperand>
3353   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3354     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
3355     Op->Bitfield.LSB = LSB;
3356     Op->Bitfield.Width = Width;
3357     Op->StartLoc = S;
3358     Op->EndLoc = E;
3359     return Op;
3360   }
3361 
3362   static std::unique_ptr<ARMOperand>
3363   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3364                 SMLoc StartLoc, SMLoc EndLoc) {
3365     assert(Regs.size() > 0 && "RegList contains no registers?");
3366     KindTy Kind = k_RegisterList;
3367 
3368     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
3369             Regs.front().second)) {
3370       if (Regs.back().second == ARM::VPR)
3371         Kind = k_FPDRegisterListWithVPR;
3372       else
3373         Kind = k_DPRRegisterList;
3374     } else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
3375                    Regs.front().second)) {
3376       if (Regs.back().second == ARM::VPR)
3377         Kind = k_FPSRegisterListWithVPR;
3378       else
3379         Kind = k_SPRRegisterList;
3380     }
3381 
3382     // Sort based on the register encoding values.
3383     array_pod_sort(Regs.begin(), Regs.end());
3384 
3385     if (Kind == k_RegisterList && Regs.back().second == ARM::APSR)
3386       Kind = k_RegisterListWithAPSR;
3387 
3388     auto Op = make_unique<ARMOperand>(Kind);
3389     for (SmallVectorImpl<std::pair<unsigned, unsigned>>::const_iterator
3390            I = Regs.begin(), E = Regs.end(); I != E; ++I)
3391       Op->Registers.push_back(I->second);
3392 
3393     Op->StartLoc = StartLoc;
3394     Op->EndLoc = EndLoc;
3395     return Op;
3396   }
3397 
3398   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3399                                                       unsigned Count,
3400                                                       bool isDoubleSpaced,
3401                                                       SMLoc S, SMLoc E) {
3402     auto Op = make_unique<ARMOperand>(k_VectorList);
3403     Op->VectorList.RegNum = RegNum;
3404     Op->VectorList.Count = Count;
3405     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3406     Op->StartLoc = S;
3407     Op->EndLoc = E;
3408     return Op;
3409   }
3410 
3411   static std::unique_ptr<ARMOperand>
3412   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3413                            SMLoc S, SMLoc E) {
3414     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
3415     Op->VectorList.RegNum = RegNum;
3416     Op->VectorList.Count = Count;
3417     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3418     Op->StartLoc = S;
3419     Op->EndLoc = E;
3420     return Op;
3421   }
3422 
3423   static std::unique_ptr<ARMOperand>
3424   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3425                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3426     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
3427     Op->VectorList.RegNum = RegNum;
3428     Op->VectorList.Count = Count;
3429     Op->VectorList.LaneIndex = Index;
3430     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3431     Op->StartLoc = S;
3432     Op->EndLoc = E;
3433     return Op;
3434   }
3435 
3436   static std::unique_ptr<ARMOperand>
3437   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3438     auto Op = make_unique<ARMOperand>(k_VectorIndex);
3439     Op->VectorIndex.Val = Idx;
3440     Op->StartLoc = S;
3441     Op->EndLoc = E;
3442     return Op;
3443   }
3444 
3445   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3446                                                SMLoc E) {
3447     auto Op = make_unique<ARMOperand>(k_Immediate);
3448     Op->Imm.Val = Val;
3449     Op->StartLoc = S;
3450     Op->EndLoc = E;
3451     return Op;
3452   }
3453 
3454   static std::unique_ptr<ARMOperand>
3455   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3456             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3457             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3458             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3459     auto Op = make_unique<ARMOperand>(k_Memory);
3460     Op->Memory.BaseRegNum = BaseRegNum;
3461     Op->Memory.OffsetImm = OffsetImm;
3462     Op->Memory.OffsetRegNum = OffsetRegNum;
3463     Op->Memory.ShiftType = ShiftType;
3464     Op->Memory.ShiftImm = ShiftImm;
3465     Op->Memory.Alignment = Alignment;
3466     Op->Memory.isNegative = isNegative;
3467     Op->StartLoc = S;
3468     Op->EndLoc = E;
3469     Op->AlignmentLoc = AlignmentLoc;
3470     return Op;
3471   }
3472 
3473   static std::unique_ptr<ARMOperand>
3474   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3475                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3476     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
3477     Op->PostIdxReg.RegNum = RegNum;
3478     Op->PostIdxReg.isAdd = isAdd;
3479     Op->PostIdxReg.ShiftTy = ShiftTy;
3480     Op->PostIdxReg.ShiftImm = ShiftImm;
3481     Op->StartLoc = S;
3482     Op->EndLoc = E;
3483     return Op;
3484   }
3485 
3486   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3487                                                          SMLoc S) {
3488     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3489     Op->MBOpt.Val = Opt;
3490     Op->StartLoc = S;
3491     Op->EndLoc = S;
3492     return Op;
3493   }
3494 
3495   static std::unique_ptr<ARMOperand>
3496   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3497     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3498     Op->ISBOpt.Val = Opt;
3499     Op->StartLoc = S;
3500     Op->EndLoc = S;
3501     return Op;
3502   }
3503 
3504   static std::unique_ptr<ARMOperand>
3505   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3506     auto Op = make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3507     Op->TSBOpt.Val = Opt;
3508     Op->StartLoc = S;
3509     Op->EndLoc = S;
3510     return Op;
3511   }
3512 
3513   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3514                                                       SMLoc S) {
3515     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3516     Op->IFlags.Val = IFlags;
3517     Op->StartLoc = S;
3518     Op->EndLoc = S;
3519     return Op;
3520   }
3521 
3522   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3523     auto Op = make_unique<ARMOperand>(k_MSRMask);
3524     Op->MMask.Val = MMask;
3525     Op->StartLoc = S;
3526     Op->EndLoc = S;
3527     return Op;
3528   }
3529 
3530   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3531     auto Op = make_unique<ARMOperand>(k_BankedReg);
3532     Op->BankedReg.Val = Reg;
3533     Op->StartLoc = S;
3534     Op->EndLoc = S;
3535     return Op;
3536   }
3537 };
3538 
3539 } // end anonymous namespace.
3540 
3541 void ARMOperand::print(raw_ostream &OS) const {
3542   auto RegName = [](unsigned Reg) {
3543     if (Reg)
3544       return ARMInstPrinter::getRegisterName(Reg);
3545     else
3546       return "noreg";
3547   };
3548 
3549   switch (Kind) {
3550   case k_CondCode:
3551     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3552     break;
3553   case k_VPTPred:
3554     OS << "<ARMVCC::" << ARMVPTPredToString(getVPTPred()) << ">";
3555     break;
3556   case k_CCOut:
3557     OS << "<ccout " << RegName(getReg()) << ">";
3558     break;
3559   case k_ITCondMask: {
3560     static const char *const MaskStr[] = {
3561       "(invalid)", "(tttt)", "(ttt)", "(ttte)",
3562       "(tt)",      "(ttet)", "(tte)", "(ttee)",
3563       "(t)",       "(tett)", "(tet)", "(tete)",
3564       "(te)",      "(teet)", "(tee)", "(teee)",
3565     };
3566     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3567     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3568     break;
3569   }
3570   case k_CoprocNum:
3571     OS << "<coprocessor number: " << getCoproc() << ">";
3572     break;
3573   case k_CoprocReg:
3574     OS << "<coprocessor register: " << getCoproc() << ">";
3575     break;
3576   case k_CoprocOption:
3577     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3578     break;
3579   case k_MSRMask:
3580     OS << "<mask: " << getMSRMask() << ">";
3581     break;
3582   case k_BankedReg:
3583     OS << "<banked reg: " << getBankedReg() << ">";
3584     break;
3585   case k_Immediate:
3586     OS << *getImm();
3587     break;
3588   case k_MemBarrierOpt:
3589     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3590     break;
3591   case k_InstSyncBarrierOpt:
3592     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3593     break;
3594   case k_TraceSyncBarrierOpt:
3595     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3596     break;
3597   case k_Memory:
3598     OS << "<memory";
3599     if (Memory.BaseRegNum)
3600       OS << " base:" << RegName(Memory.BaseRegNum);
3601     if (Memory.OffsetImm)
3602       OS << " offset-imm:" << *Memory.OffsetImm;
3603     if (Memory.OffsetRegNum)
3604       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3605          << RegName(Memory.OffsetRegNum);
3606     if (Memory.ShiftType != ARM_AM::no_shift) {
3607       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3608       OS << " shift-imm:" << Memory.ShiftImm;
3609     }
3610     if (Memory.Alignment)
3611       OS << " alignment:" << Memory.Alignment;
3612     OS << ">";
3613     break;
3614   case k_PostIndexRegister:
3615     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3616        << RegName(PostIdxReg.RegNum);
3617     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3618       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3619          << PostIdxReg.ShiftImm;
3620     OS << ">";
3621     break;
3622   case k_ProcIFlags: {
3623     OS << "<ARM_PROC::";
3624     unsigned IFlags = getProcIFlags();
3625     for (int i=2; i >= 0; --i)
3626       if (IFlags & (1 << i))
3627         OS << ARM_PROC::IFlagsToString(1 << i);
3628     OS << ">";
3629     break;
3630   }
3631   case k_Register:
3632     OS << "<register " << RegName(getReg()) << ">";
3633     break;
3634   case k_ShifterImmediate:
3635     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3636        << " #" << ShifterImm.Imm << ">";
3637     break;
3638   case k_ShiftedRegister:
3639     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3640        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3641        << RegName(RegShiftedReg.ShiftReg) << ">";
3642     break;
3643   case k_ShiftedImmediate:
3644     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3645        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3646        << RegShiftedImm.ShiftImm << ">";
3647     break;
3648   case k_RotateImmediate:
3649     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3650     break;
3651   case k_ModifiedImmediate:
3652     OS << "<mod_imm #" << ModImm.Bits << ", #"
3653        <<  ModImm.Rot << ")>";
3654     break;
3655   case k_ConstantPoolImmediate:
3656     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3657     break;
3658   case k_BitfieldDescriptor:
3659     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3660        << ", width: " << Bitfield.Width << ">";
3661     break;
3662   case k_RegisterList:
3663   case k_RegisterListWithAPSR:
3664   case k_DPRRegisterList:
3665   case k_SPRRegisterList:
3666   case k_FPSRegisterListWithVPR:
3667   case k_FPDRegisterListWithVPR: {
3668     OS << "<register_list ";
3669 
3670     const SmallVectorImpl<unsigned> &RegList = getRegList();
3671     for (SmallVectorImpl<unsigned>::const_iterator
3672            I = RegList.begin(), E = RegList.end(); I != E; ) {
3673       OS << RegName(*I);
3674       if (++I < E) OS << ", ";
3675     }
3676 
3677     OS << ">";
3678     break;
3679   }
3680   case k_VectorList:
3681     OS << "<vector_list " << VectorList.Count << " * "
3682        << RegName(VectorList.RegNum) << ">";
3683     break;
3684   case k_VectorListAllLanes:
3685     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3686        << RegName(VectorList.RegNum) << ">";
3687     break;
3688   case k_VectorListIndexed:
3689     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3690        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
3691     break;
3692   case k_Token:
3693     OS << "'" << getToken() << "'";
3694     break;
3695   case k_VectorIndex:
3696     OS << "<vectorindex " << getVectorIndex() << ">";
3697     break;
3698   }
3699 }
3700 
3701 /// @name Auto-generated Match Functions
3702 /// {
3703 
3704 static unsigned MatchRegisterName(StringRef Name);
3705 
3706 /// }
3707 
3708 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3709                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3710   const AsmToken &Tok = getParser().getTok();
3711   StartLoc = Tok.getLoc();
3712   EndLoc = Tok.getEndLoc();
3713   RegNo = tryParseRegister();
3714 
3715   return (RegNo == (unsigned)-1);
3716 }
3717 
3718 /// Try to parse a register name.  The token must be an Identifier when called,
3719 /// and if it is a register name the token is eaten and the register number is
3720 /// returned.  Otherwise return -1.
3721 int ARMAsmParser::tryParseRegister() {
3722   MCAsmParser &Parser = getParser();
3723   const AsmToken &Tok = Parser.getTok();
3724   if (Tok.isNot(AsmToken::Identifier)) return -1;
3725 
3726   std::string lowerCase = Tok.getString().lower();
3727   unsigned RegNum = MatchRegisterName(lowerCase);
3728   if (!RegNum) {
3729     RegNum = StringSwitch<unsigned>(lowerCase)
3730       .Case("r13", ARM::SP)
3731       .Case("r14", ARM::LR)
3732       .Case("r15", ARM::PC)
3733       .Case("ip", ARM::R12)
3734       // Additional register name aliases for 'gas' compatibility.
3735       .Case("a1", ARM::R0)
3736       .Case("a2", ARM::R1)
3737       .Case("a3", ARM::R2)
3738       .Case("a4", ARM::R3)
3739       .Case("v1", ARM::R4)
3740       .Case("v2", ARM::R5)
3741       .Case("v3", ARM::R6)
3742       .Case("v4", ARM::R7)
3743       .Case("v5", ARM::R8)
3744       .Case("v6", ARM::R9)
3745       .Case("v7", ARM::R10)
3746       .Case("v8", ARM::R11)
3747       .Case("sb", ARM::R9)
3748       .Case("sl", ARM::R10)
3749       .Case("fp", ARM::R11)
3750       .Default(0);
3751   }
3752   if (!RegNum) {
3753     // Check for aliases registered via .req. Canonicalize to lower case.
3754     // That's more consistent since register names are case insensitive, and
3755     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3756     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3757     // If no match, return failure.
3758     if (Entry == RegisterReqs.end())
3759       return -1;
3760     Parser.Lex(); // Eat identifier token.
3761     return Entry->getValue();
3762   }
3763 
3764   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3765   if (!hasD32() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3766     return -1;
3767 
3768   Parser.Lex(); // Eat identifier token.
3769 
3770   return RegNum;
3771 }
3772 
3773 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3774 // If a recoverable error occurs, return 1. If an irrecoverable error
3775 // occurs, return -1. An irrecoverable error is one where tokens have been
3776 // consumed in the process of trying to parse the shifter (i.e., when it is
3777 // indeed a shifter operand, but malformed).
3778 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3779   MCAsmParser &Parser = getParser();
3780   SMLoc S = Parser.getTok().getLoc();
3781   const AsmToken &Tok = Parser.getTok();
3782   if (Tok.isNot(AsmToken::Identifier))
3783     return -1;
3784 
3785   std::string lowerCase = Tok.getString().lower();
3786   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3787       .Case("asl", ARM_AM::lsl)
3788       .Case("lsl", ARM_AM::lsl)
3789       .Case("lsr", ARM_AM::lsr)
3790       .Case("asr", ARM_AM::asr)
3791       .Case("ror", ARM_AM::ror)
3792       .Case("rrx", ARM_AM::rrx)
3793       .Default(ARM_AM::no_shift);
3794 
3795   if (ShiftTy == ARM_AM::no_shift)
3796     return 1;
3797 
3798   Parser.Lex(); // Eat the operator.
3799 
3800   // The source register for the shift has already been added to the
3801   // operand list, so we need to pop it off and combine it into the shifted
3802   // register operand instead.
3803   std::unique_ptr<ARMOperand> PrevOp(
3804       (ARMOperand *)Operands.pop_back_val().release());
3805   if (!PrevOp->isReg())
3806     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3807   int SrcReg = PrevOp->getReg();
3808 
3809   SMLoc EndLoc;
3810   int64_t Imm = 0;
3811   int ShiftReg = 0;
3812   if (ShiftTy == ARM_AM::rrx) {
3813     // RRX Doesn't have an explicit shift amount. The encoder expects
3814     // the shift register to be the same as the source register. Seems odd,
3815     // but OK.
3816     ShiftReg = SrcReg;
3817   } else {
3818     // Figure out if this is shifted by a constant or a register (for non-RRX).
3819     if (Parser.getTok().is(AsmToken::Hash) ||
3820         Parser.getTok().is(AsmToken::Dollar)) {
3821       Parser.Lex(); // Eat hash.
3822       SMLoc ImmLoc = Parser.getTok().getLoc();
3823       const MCExpr *ShiftExpr = nullptr;
3824       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3825         Error(ImmLoc, "invalid immediate shift value");
3826         return -1;
3827       }
3828       // The expression must be evaluatable as an immediate.
3829       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3830       if (!CE) {
3831         Error(ImmLoc, "invalid immediate shift value");
3832         return -1;
3833       }
3834       // Range check the immediate.
3835       // lsl, ror: 0 <= imm <= 31
3836       // lsr, asr: 0 <= imm <= 32
3837       Imm = CE->getValue();
3838       if (Imm < 0 ||
3839           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3840           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3841         Error(ImmLoc, "immediate shift value out of range");
3842         return -1;
3843       }
3844       // shift by zero is a nop. Always send it through as lsl.
3845       // ('as' compatibility)
3846       if (Imm == 0)
3847         ShiftTy = ARM_AM::lsl;
3848     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3849       SMLoc L = Parser.getTok().getLoc();
3850       EndLoc = Parser.getTok().getEndLoc();
3851       ShiftReg = tryParseRegister();
3852       if (ShiftReg == -1) {
3853         Error(L, "expected immediate or register in shift operand");
3854         return -1;
3855       }
3856     } else {
3857       Error(Parser.getTok().getLoc(),
3858             "expected immediate or register in shift operand");
3859       return -1;
3860     }
3861   }
3862 
3863   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3864     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3865                                                          ShiftReg, Imm,
3866                                                          S, EndLoc));
3867   else
3868     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3869                                                           S, EndLoc));
3870 
3871   return 0;
3872 }
3873 
3874 /// Try to parse a register name.  The token must be an Identifier when called.
3875 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3876 /// if there is a "writeback". 'true' if it's not a register.
3877 ///
3878 /// TODO this is likely to change to allow different register types and or to
3879 /// parse for a specific register type.
3880 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3881   MCAsmParser &Parser = getParser();
3882   SMLoc RegStartLoc = Parser.getTok().getLoc();
3883   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
3884   int RegNo = tryParseRegister();
3885   if (RegNo == -1)
3886     return true;
3887 
3888   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
3889 
3890   const AsmToken &ExclaimTok = Parser.getTok();
3891   if (ExclaimTok.is(AsmToken::Exclaim)) {
3892     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3893                                                ExclaimTok.getLoc()));
3894     Parser.Lex(); // Eat exclaim token
3895     return false;
3896   }
3897 
3898   // Also check for an index operand. This is only legal for vector registers,
3899   // but that'll get caught OK in operand matching, so we don't need to
3900   // explicitly filter everything else out here.
3901   if (Parser.getTok().is(AsmToken::LBrac)) {
3902     SMLoc SIdx = Parser.getTok().getLoc();
3903     Parser.Lex(); // Eat left bracket token.
3904 
3905     const MCExpr *ImmVal;
3906     if (getParser().parseExpression(ImmVal))
3907       return true;
3908     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3909     if (!MCE)
3910       return TokError("immediate value expected for vector index");
3911 
3912     if (Parser.getTok().isNot(AsmToken::RBrac))
3913       return Error(Parser.getTok().getLoc(), "']' expected");
3914 
3915     SMLoc E = Parser.getTok().getEndLoc();
3916     Parser.Lex(); // Eat right bracket token.
3917 
3918     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3919                                                      SIdx, E,
3920                                                      getContext()));
3921   }
3922 
3923   return false;
3924 }
3925 
3926 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3927 /// instruction with a symbolic operand name.
3928 /// We accept "crN" syntax for GAS compatibility.
3929 /// <operand-name> ::= <prefix><number>
3930 /// If CoprocOp is 'c', then:
3931 ///   <prefix> ::= c | cr
3932 /// If CoprocOp is 'p', then :
3933 ///   <prefix> ::= p
3934 /// <number> ::= integer in range [0, 15]
3935 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3936   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3937   // but efficient.
3938   if (Name.size() < 2 || Name[0] != CoprocOp)
3939     return -1;
3940   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3941 
3942   switch (Name.size()) {
3943   default: return -1;
3944   case 1:
3945     switch (Name[0]) {
3946     default:  return -1;
3947     case '0': return 0;
3948     case '1': return 1;
3949     case '2': return 2;
3950     case '3': return 3;
3951     case '4': return 4;
3952     case '5': return 5;
3953     case '6': return 6;
3954     case '7': return 7;
3955     case '8': return 8;
3956     case '9': return 9;
3957     }
3958   case 2:
3959     if (Name[0] != '1')
3960       return -1;
3961     switch (Name[1]) {
3962     default:  return -1;
3963     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3964     // However, old cores (v5/v6) did use them in that way.
3965     case '0': return 10;
3966     case '1': return 11;
3967     case '2': return 12;
3968     case '3': return 13;
3969     case '4': return 14;
3970     case '5': return 15;
3971     }
3972   }
3973 }
3974 
3975 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3976 OperandMatchResultTy
3977 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3978   MCAsmParser &Parser = getParser();
3979   SMLoc S = Parser.getTok().getLoc();
3980   const AsmToken &Tok = Parser.getTok();
3981   if (!Tok.is(AsmToken::Identifier))
3982     return MatchOperand_NoMatch;
3983   unsigned CC = ARMCondCodeFromString(Tok.getString());
3984   if (CC == ~0U)
3985     return MatchOperand_NoMatch;
3986   Parser.Lex(); // Eat the token.
3987 
3988   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3989 
3990   return MatchOperand_Success;
3991 }
3992 
3993 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3994 /// token must be an Identifier when called, and if it is a coprocessor
3995 /// number, the token is eaten and the operand is added to the operand list.
3996 OperandMatchResultTy
3997 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3998   MCAsmParser &Parser = getParser();
3999   SMLoc S = Parser.getTok().getLoc();
4000   const AsmToken &Tok = Parser.getTok();
4001   if (Tok.isNot(AsmToken::Identifier))
4002     return MatchOperand_NoMatch;
4003 
4004   int Num = MatchCoprocessorOperandName(Tok.getString().lower(), 'p');
4005   if (Num == -1)
4006     return MatchOperand_NoMatch;
4007   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
4008   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
4009     return MatchOperand_NoMatch;
4010 
4011   Parser.Lex(); // Eat identifier token.
4012   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
4013   return MatchOperand_Success;
4014 }
4015 
4016 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
4017 /// token must be an Identifier when called, and if it is a coprocessor
4018 /// number, the token is eaten and the operand is added to the operand list.
4019 OperandMatchResultTy
4020 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
4021   MCAsmParser &Parser = getParser();
4022   SMLoc S = Parser.getTok().getLoc();
4023   const AsmToken &Tok = Parser.getTok();
4024   if (Tok.isNot(AsmToken::Identifier))
4025     return MatchOperand_NoMatch;
4026 
4027   int Reg = MatchCoprocessorOperandName(Tok.getString().lower(), 'c');
4028   if (Reg == -1)
4029     return MatchOperand_NoMatch;
4030 
4031   Parser.Lex(); // Eat identifier token.
4032   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
4033   return MatchOperand_Success;
4034 }
4035 
4036 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
4037 /// coproc_option : '{' imm0_255 '}'
4038 OperandMatchResultTy
4039 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
4040   MCAsmParser &Parser = getParser();
4041   SMLoc S = Parser.getTok().getLoc();
4042 
4043   // If this isn't a '{', this isn't a coprocessor immediate operand.
4044   if (Parser.getTok().isNot(AsmToken::LCurly))
4045     return MatchOperand_NoMatch;
4046   Parser.Lex(); // Eat the '{'
4047 
4048   const MCExpr *Expr;
4049   SMLoc Loc = Parser.getTok().getLoc();
4050   if (getParser().parseExpression(Expr)) {
4051     Error(Loc, "illegal expression");
4052     return MatchOperand_ParseFail;
4053   }
4054   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4055   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
4056     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
4057     return MatchOperand_ParseFail;
4058   }
4059   int Val = CE->getValue();
4060 
4061   // Check for and consume the closing '}'
4062   if (Parser.getTok().isNot(AsmToken::RCurly))
4063     return MatchOperand_ParseFail;
4064   SMLoc E = Parser.getTok().getEndLoc();
4065   Parser.Lex(); // Eat the '}'
4066 
4067   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
4068   return MatchOperand_Success;
4069 }
4070 
4071 // For register list parsing, we need to map from raw GPR register numbering
4072 // to the enumeration values. The enumeration values aren't sorted by
4073 // register number due to our using "sp", "lr" and "pc" as canonical names.
4074 static unsigned getNextRegister(unsigned Reg) {
4075   // If this is a GPR, we need to do it manually, otherwise we can rely
4076   // on the sort ordering of the enumeration since the other reg-classes
4077   // are sane.
4078   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4079     return Reg + 1;
4080   switch(Reg) {
4081   default: llvm_unreachable("Invalid GPR number!");
4082   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
4083   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
4084   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
4085   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
4086   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
4087   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
4088   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
4089   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
4090   }
4091 }
4092 
4093 /// Parse a register list.
4094 bool ARMAsmParser::parseRegisterList(OperandVector &Operands,
4095                                      bool EnforceOrder) {
4096   MCAsmParser &Parser = getParser();
4097   if (Parser.getTok().isNot(AsmToken::LCurly))
4098     return TokError("Token is not a Left Curly Brace");
4099   SMLoc S = Parser.getTok().getLoc();
4100   Parser.Lex(); // Eat '{' token.
4101   SMLoc RegLoc = Parser.getTok().getLoc();
4102 
4103   // Check the first register in the list to see what register class
4104   // this is a list of.
4105   int Reg = tryParseRegister();
4106   if (Reg == -1)
4107     return Error(RegLoc, "register expected");
4108 
4109   // The reglist instructions have at most 16 registers, so reserve
4110   // space for that many.
4111   int EReg = 0;
4112   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
4113 
4114   // Allow Q regs and just interpret them as the two D sub-registers.
4115   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4116     Reg = getDRegFromQReg(Reg);
4117     EReg = MRI->getEncodingValue(Reg);
4118     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4119     ++Reg;
4120   }
4121   const MCRegisterClass *RC;
4122   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4123     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
4124   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
4125     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
4126   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
4127     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
4128   else if (ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4129     RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4130   else
4131     return Error(RegLoc, "invalid register in register list");
4132 
4133   // Store the register.
4134   EReg = MRI->getEncodingValue(Reg);
4135   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4136 
4137   // This starts immediately after the first register token in the list,
4138   // so we can see either a comma or a minus (range separator) as a legal
4139   // next token.
4140   while (Parser.getTok().is(AsmToken::Comma) ||
4141          Parser.getTok().is(AsmToken::Minus)) {
4142     if (Parser.getTok().is(AsmToken::Minus)) {
4143       Parser.Lex(); // Eat the minus.
4144       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4145       int EndReg = tryParseRegister();
4146       if (EndReg == -1)
4147         return Error(AfterMinusLoc, "register expected");
4148       // Allow Q regs and just interpret them as the two D sub-registers.
4149       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4150         EndReg = getDRegFromQReg(EndReg) + 1;
4151       // If the register is the same as the start reg, there's nothing
4152       // more to do.
4153       if (Reg == EndReg)
4154         continue;
4155       // The register must be in the same register class as the first.
4156       if (!RC->contains(EndReg))
4157         return Error(AfterMinusLoc, "invalid register in register list");
4158       // Ranges must go from low to high.
4159       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
4160         return Error(AfterMinusLoc, "bad range in register list");
4161 
4162       // Add all the registers in the range to the register list.
4163       while (Reg != EndReg) {
4164         Reg = getNextRegister(Reg);
4165         EReg = MRI->getEncodingValue(Reg);
4166         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4167       }
4168       continue;
4169     }
4170     Parser.Lex(); // Eat the comma.
4171     RegLoc = Parser.getTok().getLoc();
4172     int OldReg = Reg;
4173     const AsmToken RegTok = Parser.getTok();
4174     Reg = tryParseRegister();
4175     if (Reg == -1)
4176       return Error(RegLoc, "register expected");
4177     // Allow Q regs and just interpret them as the two D sub-registers.
4178     bool isQReg = false;
4179     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4180       Reg = getDRegFromQReg(Reg);
4181       isQReg = true;
4182     }
4183     if (!RC->contains(Reg) &&
4184         RC->getID() == ARMMCRegisterClasses[ARM::GPRRegClassID].getID() &&
4185         ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg)) {
4186       // switch the register classes, as GPRwithAPSRnospRegClassID is a partial
4187       // subset of GPRRegClassId except it contains APSR as well.
4188       RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4189     }
4190     if (Reg == ARM::VPR && (RC == &ARMMCRegisterClasses[ARM::SPRRegClassID] ||
4191                             RC == &ARMMCRegisterClasses[ARM::DPRRegClassID])) {
4192       RC = &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID];
4193       EReg = MRI->getEncodingValue(Reg);
4194       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4195       continue;
4196     }
4197     // The register must be in the same register class as the first.
4198     if (!RC->contains(Reg))
4199       return Error(RegLoc, "invalid register in register list");
4200     // In most cases, the list must be monotonically increasing. An
4201     // exception is CLRM, which is order-independent anyway, so
4202     // there's no potential for confusion if you write clrm {r2,r1}
4203     // instead of clrm {r1,r2}.
4204     if (EnforceOrder &&
4205         MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
4206       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4207         Warning(RegLoc, "register list not in ascending order");
4208       else if (!ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4209         return Error(RegLoc, "register list not in ascending order");
4210     }
4211     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
4212       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4213               ") in register list");
4214       continue;
4215     }
4216     // VFP register lists must also be contiguous.
4217     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
4218         RC != &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID] &&
4219         Reg != OldReg + 1)
4220       return Error(RegLoc, "non-contiguous register range");
4221     EReg = MRI->getEncodingValue(Reg);
4222     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4223     if (isQReg) {
4224       EReg = MRI->getEncodingValue(++Reg);
4225       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4226     }
4227   }
4228 
4229   if (Parser.getTok().isNot(AsmToken::RCurly))
4230     return Error(Parser.getTok().getLoc(), "'}' expected");
4231   SMLoc E = Parser.getTok().getEndLoc();
4232   Parser.Lex(); // Eat '}' token.
4233 
4234   // Push the register list operand.
4235   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
4236 
4237   // The ARM system instruction variants for LDM/STM have a '^' token here.
4238   if (Parser.getTok().is(AsmToken::Caret)) {
4239     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
4240     Parser.Lex(); // Eat '^' token.
4241   }
4242 
4243   return false;
4244 }
4245 
4246 // Helper function to parse the lane index for vector lists.
4247 OperandMatchResultTy ARMAsmParser::
4248 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
4249   MCAsmParser &Parser = getParser();
4250   Index = 0; // Always return a defined index value.
4251   if (Parser.getTok().is(AsmToken::LBrac)) {
4252     Parser.Lex(); // Eat the '['.
4253     if (Parser.getTok().is(AsmToken::RBrac)) {
4254       // "Dn[]" is the 'all lanes' syntax.
4255       LaneKind = AllLanes;
4256       EndLoc = Parser.getTok().getEndLoc();
4257       Parser.Lex(); // Eat the ']'.
4258       return MatchOperand_Success;
4259     }
4260 
4261     // There's an optional '#' token here. Normally there wouldn't be, but
4262     // inline assemble puts one in, and it's friendly to accept that.
4263     if (Parser.getTok().is(AsmToken::Hash))
4264       Parser.Lex(); // Eat '#' or '$'.
4265 
4266     const MCExpr *LaneIndex;
4267     SMLoc Loc = Parser.getTok().getLoc();
4268     if (getParser().parseExpression(LaneIndex)) {
4269       Error(Loc, "illegal expression");
4270       return MatchOperand_ParseFail;
4271     }
4272     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
4273     if (!CE) {
4274       Error(Loc, "lane index must be empty or an integer");
4275       return MatchOperand_ParseFail;
4276     }
4277     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4278       Error(Parser.getTok().getLoc(), "']' expected");
4279       return MatchOperand_ParseFail;
4280     }
4281     EndLoc = Parser.getTok().getEndLoc();
4282     Parser.Lex(); // Eat the ']'.
4283     int64_t Val = CE->getValue();
4284 
4285     // FIXME: Make this range check context sensitive for .8, .16, .32.
4286     if (Val < 0 || Val > 7) {
4287       Error(Parser.getTok().getLoc(), "lane index out of range");
4288       return MatchOperand_ParseFail;
4289     }
4290     Index = Val;
4291     LaneKind = IndexedLane;
4292     return MatchOperand_Success;
4293   }
4294   LaneKind = NoLanes;
4295   return MatchOperand_Success;
4296 }
4297 
4298 // parse a vector register list
4299 OperandMatchResultTy
4300 ARMAsmParser::parseVectorList(OperandVector &Operands) {
4301   MCAsmParser &Parser = getParser();
4302   VectorLaneTy LaneKind;
4303   unsigned LaneIndex;
4304   SMLoc S = Parser.getTok().getLoc();
4305   // As an extension (to match gas), support a plain D register or Q register
4306   // (without encosing curly braces) as a single or double entry list,
4307   // respectively.
4308   if (!hasMVE() && Parser.getTok().is(AsmToken::Identifier)) {
4309     SMLoc E = Parser.getTok().getEndLoc();
4310     int Reg = tryParseRegister();
4311     if (Reg == -1)
4312       return MatchOperand_NoMatch;
4313     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
4314       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4315       if (Res != MatchOperand_Success)
4316         return Res;
4317       switch (LaneKind) {
4318       case NoLanes:
4319         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
4320         break;
4321       case AllLanes:
4322         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
4323                                                                 S, E));
4324         break;
4325       case IndexedLane:
4326         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
4327                                                                LaneIndex,
4328                                                                false, S, E));
4329         break;
4330       }
4331       return MatchOperand_Success;
4332     }
4333     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4334       Reg = getDRegFromQReg(Reg);
4335       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4336       if (Res != MatchOperand_Success)
4337         return Res;
4338       switch (LaneKind) {
4339       case NoLanes:
4340         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4341                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4342         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
4343         break;
4344       case AllLanes:
4345         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4346                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4347         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
4348                                                                 S, E));
4349         break;
4350       case IndexedLane:
4351         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
4352                                                                LaneIndex,
4353                                                                false, S, E));
4354         break;
4355       }
4356       return MatchOperand_Success;
4357     }
4358     Error(S, "vector register expected");
4359     return MatchOperand_ParseFail;
4360   }
4361 
4362   if (Parser.getTok().isNot(AsmToken::LCurly))
4363     return MatchOperand_NoMatch;
4364 
4365   Parser.Lex(); // Eat '{' token.
4366   SMLoc RegLoc = Parser.getTok().getLoc();
4367 
4368   int Reg = tryParseRegister();
4369   if (Reg == -1) {
4370     Error(RegLoc, "register expected");
4371     return MatchOperand_ParseFail;
4372   }
4373   unsigned Count = 1;
4374   int Spacing = 0;
4375   unsigned FirstReg = Reg;
4376 
4377   if (hasMVE() && !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4378       Error(Parser.getTok().getLoc(), "vector register in range Q0-Q7 expected");
4379       return MatchOperand_ParseFail;
4380   }
4381   // The list is of D registers, but we also allow Q regs and just interpret
4382   // them as the two D sub-registers.
4383   else if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4384     FirstReg = Reg = getDRegFromQReg(Reg);
4385     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4386                  // it's ambiguous with four-register single spaced.
4387     ++Reg;
4388     ++Count;
4389   }
4390 
4391   SMLoc E;
4392   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4393     return MatchOperand_ParseFail;
4394 
4395   while (Parser.getTok().is(AsmToken::Comma) ||
4396          Parser.getTok().is(AsmToken::Minus)) {
4397     if (Parser.getTok().is(AsmToken::Minus)) {
4398       if (!Spacing)
4399         Spacing = 1; // Register range implies a single spaced list.
4400       else if (Spacing == 2) {
4401         Error(Parser.getTok().getLoc(),
4402               "sequential registers in double spaced list");
4403         return MatchOperand_ParseFail;
4404       }
4405       Parser.Lex(); // Eat the minus.
4406       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4407       int EndReg = tryParseRegister();
4408       if (EndReg == -1) {
4409         Error(AfterMinusLoc, "register expected");
4410         return MatchOperand_ParseFail;
4411       }
4412       // Allow Q regs and just interpret them as the two D sub-registers.
4413       if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4414         EndReg = getDRegFromQReg(EndReg) + 1;
4415       // If the register is the same as the start reg, there's nothing
4416       // more to do.
4417       if (Reg == EndReg)
4418         continue;
4419       // The register must be in the same register class as the first.
4420       if ((hasMVE() &&
4421            !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(EndReg)) ||
4422           (!hasMVE() &&
4423            !ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg))) {
4424         Error(AfterMinusLoc, "invalid register in register list");
4425         return MatchOperand_ParseFail;
4426       }
4427       // Ranges must go from low to high.
4428       if (Reg > EndReg) {
4429         Error(AfterMinusLoc, "bad range in register list");
4430         return MatchOperand_ParseFail;
4431       }
4432       // Parse the lane specifier if present.
4433       VectorLaneTy NextLaneKind;
4434       unsigned NextLaneIndex;
4435       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4436           MatchOperand_Success)
4437         return MatchOperand_ParseFail;
4438       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4439         Error(AfterMinusLoc, "mismatched lane index in register list");
4440         return MatchOperand_ParseFail;
4441       }
4442 
4443       // Add all the registers in the range to the register list.
4444       Count += EndReg - Reg;
4445       Reg = EndReg;
4446       continue;
4447     }
4448     Parser.Lex(); // Eat the comma.
4449     RegLoc = Parser.getTok().getLoc();
4450     int OldReg = Reg;
4451     Reg = tryParseRegister();
4452     if (Reg == -1) {
4453       Error(RegLoc, "register expected");
4454       return MatchOperand_ParseFail;
4455     }
4456 
4457     if (hasMVE()) {
4458       if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4459         Error(RegLoc, "vector register in range Q0-Q7 expected");
4460         return MatchOperand_ParseFail;
4461       }
4462       Spacing = 1;
4463     }
4464     // vector register lists must be contiguous.
4465     // It's OK to use the enumeration values directly here rather, as the
4466     // VFP register classes have the enum sorted properly.
4467     //
4468     // The list is of D registers, but we also allow Q regs and just interpret
4469     // them as the two D sub-registers.
4470     else if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4471       if (!Spacing)
4472         Spacing = 1; // Register range implies a single spaced list.
4473       else if (Spacing == 2) {
4474         Error(RegLoc,
4475               "invalid register in double-spaced list (must be 'D' register')");
4476         return MatchOperand_ParseFail;
4477       }
4478       Reg = getDRegFromQReg(Reg);
4479       if (Reg != OldReg + 1) {
4480         Error(RegLoc, "non-contiguous register range");
4481         return MatchOperand_ParseFail;
4482       }
4483       ++Reg;
4484       Count += 2;
4485       // Parse the lane specifier if present.
4486       VectorLaneTy NextLaneKind;
4487       unsigned NextLaneIndex;
4488       SMLoc LaneLoc = Parser.getTok().getLoc();
4489       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4490           MatchOperand_Success)
4491         return MatchOperand_ParseFail;
4492       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4493         Error(LaneLoc, "mismatched lane index in register list");
4494         return MatchOperand_ParseFail;
4495       }
4496       continue;
4497     }
4498     // Normal D register.
4499     // Figure out the register spacing (single or double) of the list if
4500     // we don't know it already.
4501     if (!Spacing)
4502       Spacing = 1 + (Reg == OldReg + 2);
4503 
4504     // Just check that it's contiguous and keep going.
4505     if (Reg != OldReg + Spacing) {
4506       Error(RegLoc, "non-contiguous register range");
4507       return MatchOperand_ParseFail;
4508     }
4509     ++Count;
4510     // Parse the lane specifier if present.
4511     VectorLaneTy NextLaneKind;
4512     unsigned NextLaneIndex;
4513     SMLoc EndLoc = Parser.getTok().getLoc();
4514     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4515       return MatchOperand_ParseFail;
4516     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4517       Error(EndLoc, "mismatched lane index in register list");
4518       return MatchOperand_ParseFail;
4519     }
4520   }
4521 
4522   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4523     Error(Parser.getTok().getLoc(), "'}' expected");
4524     return MatchOperand_ParseFail;
4525   }
4526   E = Parser.getTok().getEndLoc();
4527   Parser.Lex(); // Eat '}' token.
4528 
4529   switch (LaneKind) {
4530   case NoLanes:
4531   case AllLanes: {
4532     // Two-register operands have been converted to the
4533     // composite register classes.
4534     if (Count == 2 && !hasMVE()) {
4535       const MCRegisterClass *RC = (Spacing == 1) ?
4536         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4537         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4538       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4539     }
4540     auto Create = (LaneKind == NoLanes ? ARMOperand::CreateVectorList :
4541                    ARMOperand::CreateVectorListAllLanes);
4542     Operands.push_back(Create(FirstReg, Count, (Spacing == 2), S, E));
4543     break;
4544   }
4545   case IndexedLane:
4546     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4547                                                            LaneIndex,
4548                                                            (Spacing == 2),
4549                                                            S, E));
4550     break;
4551   }
4552   return MatchOperand_Success;
4553 }
4554 
4555 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4556 OperandMatchResultTy
4557 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4558   MCAsmParser &Parser = getParser();
4559   SMLoc S = Parser.getTok().getLoc();
4560   const AsmToken &Tok = Parser.getTok();
4561   unsigned Opt;
4562 
4563   if (Tok.is(AsmToken::Identifier)) {
4564     StringRef OptStr = Tok.getString();
4565 
4566     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4567       .Case("sy",    ARM_MB::SY)
4568       .Case("st",    ARM_MB::ST)
4569       .Case("ld",    ARM_MB::LD)
4570       .Case("sh",    ARM_MB::ISH)
4571       .Case("ish",   ARM_MB::ISH)
4572       .Case("shst",  ARM_MB::ISHST)
4573       .Case("ishst", ARM_MB::ISHST)
4574       .Case("ishld", ARM_MB::ISHLD)
4575       .Case("nsh",   ARM_MB::NSH)
4576       .Case("un",    ARM_MB::NSH)
4577       .Case("nshst", ARM_MB::NSHST)
4578       .Case("nshld", ARM_MB::NSHLD)
4579       .Case("unst",  ARM_MB::NSHST)
4580       .Case("osh",   ARM_MB::OSH)
4581       .Case("oshst", ARM_MB::OSHST)
4582       .Case("oshld", ARM_MB::OSHLD)
4583       .Default(~0U);
4584 
4585     // ishld, oshld, nshld and ld are only available from ARMv8.
4586     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4587                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4588       Opt = ~0U;
4589 
4590     if (Opt == ~0U)
4591       return MatchOperand_NoMatch;
4592 
4593     Parser.Lex(); // Eat identifier token.
4594   } else if (Tok.is(AsmToken::Hash) ||
4595              Tok.is(AsmToken::Dollar) ||
4596              Tok.is(AsmToken::Integer)) {
4597     if (Parser.getTok().isNot(AsmToken::Integer))
4598       Parser.Lex(); // Eat '#' or '$'.
4599     SMLoc Loc = Parser.getTok().getLoc();
4600 
4601     const MCExpr *MemBarrierID;
4602     if (getParser().parseExpression(MemBarrierID)) {
4603       Error(Loc, "illegal expression");
4604       return MatchOperand_ParseFail;
4605     }
4606 
4607     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4608     if (!CE) {
4609       Error(Loc, "constant expression expected");
4610       return MatchOperand_ParseFail;
4611     }
4612 
4613     int Val = CE->getValue();
4614     if (Val & ~0xf) {
4615       Error(Loc, "immediate value out of range");
4616       return MatchOperand_ParseFail;
4617     }
4618 
4619     Opt = ARM_MB::RESERVED_0 + Val;
4620   } else
4621     return MatchOperand_ParseFail;
4622 
4623   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4624   return MatchOperand_Success;
4625 }
4626 
4627 OperandMatchResultTy
4628 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
4629   MCAsmParser &Parser = getParser();
4630   SMLoc S = Parser.getTok().getLoc();
4631   const AsmToken &Tok = Parser.getTok();
4632 
4633   if (Tok.isNot(AsmToken::Identifier))
4634      return MatchOperand_NoMatch;
4635 
4636   if (!Tok.getString().equals_lower("csync"))
4637     return MatchOperand_NoMatch;
4638 
4639   Parser.Lex(); // Eat identifier token.
4640 
4641   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
4642   return MatchOperand_Success;
4643 }
4644 
4645 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4646 OperandMatchResultTy
4647 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4648   MCAsmParser &Parser = getParser();
4649   SMLoc S = Parser.getTok().getLoc();
4650   const AsmToken &Tok = Parser.getTok();
4651   unsigned Opt;
4652 
4653   if (Tok.is(AsmToken::Identifier)) {
4654     StringRef OptStr = Tok.getString();
4655 
4656     if (OptStr.equals_lower("sy"))
4657       Opt = ARM_ISB::SY;
4658     else
4659       return MatchOperand_NoMatch;
4660 
4661     Parser.Lex(); // Eat identifier token.
4662   } else if (Tok.is(AsmToken::Hash) ||
4663              Tok.is(AsmToken::Dollar) ||
4664              Tok.is(AsmToken::Integer)) {
4665     if (Parser.getTok().isNot(AsmToken::Integer))
4666       Parser.Lex(); // Eat '#' or '$'.
4667     SMLoc Loc = Parser.getTok().getLoc();
4668 
4669     const MCExpr *ISBarrierID;
4670     if (getParser().parseExpression(ISBarrierID)) {
4671       Error(Loc, "illegal expression");
4672       return MatchOperand_ParseFail;
4673     }
4674 
4675     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4676     if (!CE) {
4677       Error(Loc, "constant expression expected");
4678       return MatchOperand_ParseFail;
4679     }
4680 
4681     int Val = CE->getValue();
4682     if (Val & ~0xf) {
4683       Error(Loc, "immediate value out of range");
4684       return MatchOperand_ParseFail;
4685     }
4686 
4687     Opt = ARM_ISB::RESERVED_0 + Val;
4688   } else
4689     return MatchOperand_ParseFail;
4690 
4691   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4692           (ARM_ISB::InstSyncBOpt)Opt, S));
4693   return MatchOperand_Success;
4694 }
4695 
4696 
4697 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4698 OperandMatchResultTy
4699 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4700   MCAsmParser &Parser = getParser();
4701   SMLoc S = Parser.getTok().getLoc();
4702   const AsmToken &Tok = Parser.getTok();
4703   if (!Tok.is(AsmToken::Identifier))
4704     return MatchOperand_NoMatch;
4705   StringRef IFlagsStr = Tok.getString();
4706 
4707   // An iflags string of "none" is interpreted to mean that none of the AIF
4708   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4709   unsigned IFlags = 0;
4710   if (IFlagsStr != "none") {
4711         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4712       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4713         .Case("a", ARM_PROC::A)
4714         .Case("i", ARM_PROC::I)
4715         .Case("f", ARM_PROC::F)
4716         .Default(~0U);
4717 
4718       // If some specific iflag is already set, it means that some letter is
4719       // present more than once, this is not acceptable.
4720       if (Flag == ~0U || (IFlags & Flag))
4721         return MatchOperand_NoMatch;
4722 
4723       IFlags |= Flag;
4724     }
4725   }
4726 
4727   Parser.Lex(); // Eat identifier token.
4728   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4729   return MatchOperand_Success;
4730 }
4731 
4732 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4733 OperandMatchResultTy
4734 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4735   MCAsmParser &Parser = getParser();
4736   SMLoc S = Parser.getTok().getLoc();
4737   const AsmToken &Tok = Parser.getTok();
4738 
4739   if (Tok.is(AsmToken::Integer)) {
4740     int64_t Val = Tok.getIntVal();
4741     if (Val > 255 || Val < 0) {
4742       return MatchOperand_NoMatch;
4743     }
4744     unsigned SYSmvalue = Val & 0xFF;
4745     Parser.Lex();
4746     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4747     return MatchOperand_Success;
4748   }
4749 
4750   if (!Tok.is(AsmToken::Identifier))
4751     return MatchOperand_NoMatch;
4752   StringRef Mask = Tok.getString();
4753 
4754   if (isMClass()) {
4755     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4756     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4757       return MatchOperand_NoMatch;
4758 
4759     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4760 
4761     Parser.Lex(); // Eat identifier token.
4762     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4763     return MatchOperand_Success;
4764   }
4765 
4766   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4767   size_t Start = 0, Next = Mask.find('_');
4768   StringRef Flags = "";
4769   std::string SpecReg = Mask.slice(Start, Next).lower();
4770   if (Next != StringRef::npos)
4771     Flags = Mask.slice(Next+1, Mask.size());
4772 
4773   // FlagsVal contains the complete mask:
4774   // 3-0: Mask
4775   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4776   unsigned FlagsVal = 0;
4777 
4778   if (SpecReg == "apsr") {
4779     FlagsVal = StringSwitch<unsigned>(Flags)
4780     .Case("nzcvq",  0x8) // same as CPSR_f
4781     .Case("g",      0x4) // same as CPSR_s
4782     .Case("nzcvqg", 0xc) // same as CPSR_fs
4783     .Default(~0U);
4784 
4785     if (FlagsVal == ~0U) {
4786       if (!Flags.empty())
4787         return MatchOperand_NoMatch;
4788       else
4789         FlagsVal = 8; // No flag
4790     }
4791   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4792     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4793     if (Flags == "all" || Flags == "")
4794       Flags = "fc";
4795     for (int i = 0, e = Flags.size(); i != e; ++i) {
4796       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4797       .Case("c", 1)
4798       .Case("x", 2)
4799       .Case("s", 4)
4800       .Case("f", 8)
4801       .Default(~0U);
4802 
4803       // If some specific flag is already set, it means that some letter is
4804       // present more than once, this is not acceptable.
4805       if (Flag == ~0U || (FlagsVal & Flag))
4806         return MatchOperand_NoMatch;
4807       FlagsVal |= Flag;
4808     }
4809   } else // No match for special register.
4810     return MatchOperand_NoMatch;
4811 
4812   // Special register without flags is NOT equivalent to "fc" flags.
4813   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4814   // two lines would enable gas compatibility at the expense of breaking
4815   // round-tripping.
4816   //
4817   // if (!FlagsVal)
4818   //  FlagsVal = 0x9;
4819 
4820   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4821   if (SpecReg == "spsr")
4822     FlagsVal |= 16;
4823 
4824   Parser.Lex(); // Eat identifier token.
4825   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4826   return MatchOperand_Success;
4827 }
4828 
4829 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4830 /// use in the MRS/MSR instructions added to support virtualization.
4831 OperandMatchResultTy
4832 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4833   MCAsmParser &Parser = getParser();
4834   SMLoc S = Parser.getTok().getLoc();
4835   const AsmToken &Tok = Parser.getTok();
4836   if (!Tok.is(AsmToken::Identifier))
4837     return MatchOperand_NoMatch;
4838   StringRef RegName = Tok.getString();
4839 
4840   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4841   if (!TheReg)
4842     return MatchOperand_NoMatch;
4843   unsigned Encoding = TheReg->Encoding;
4844 
4845   Parser.Lex(); // Eat identifier token.
4846   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4847   return MatchOperand_Success;
4848 }
4849 
4850 OperandMatchResultTy
4851 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4852                           int High) {
4853   MCAsmParser &Parser = getParser();
4854   const AsmToken &Tok = Parser.getTok();
4855   if (Tok.isNot(AsmToken::Identifier)) {
4856     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4857     return MatchOperand_ParseFail;
4858   }
4859   StringRef ShiftName = Tok.getString();
4860   std::string LowerOp = Op.lower();
4861   std::string UpperOp = Op.upper();
4862   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4863     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4864     return MatchOperand_ParseFail;
4865   }
4866   Parser.Lex(); // Eat shift type token.
4867 
4868   // There must be a '#' and a shift amount.
4869   if (Parser.getTok().isNot(AsmToken::Hash) &&
4870       Parser.getTok().isNot(AsmToken::Dollar)) {
4871     Error(Parser.getTok().getLoc(), "'#' expected");
4872     return MatchOperand_ParseFail;
4873   }
4874   Parser.Lex(); // Eat hash token.
4875 
4876   const MCExpr *ShiftAmount;
4877   SMLoc Loc = Parser.getTok().getLoc();
4878   SMLoc EndLoc;
4879   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4880     Error(Loc, "illegal expression");
4881     return MatchOperand_ParseFail;
4882   }
4883   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4884   if (!CE) {
4885     Error(Loc, "constant expression expected");
4886     return MatchOperand_ParseFail;
4887   }
4888   int Val = CE->getValue();
4889   if (Val < Low || Val > High) {
4890     Error(Loc, "immediate value out of range");
4891     return MatchOperand_ParseFail;
4892   }
4893 
4894   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4895 
4896   return MatchOperand_Success;
4897 }
4898 
4899 OperandMatchResultTy
4900 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4901   MCAsmParser &Parser = getParser();
4902   const AsmToken &Tok = Parser.getTok();
4903   SMLoc S = Tok.getLoc();
4904   if (Tok.isNot(AsmToken::Identifier)) {
4905     Error(S, "'be' or 'le' operand expected");
4906     return MatchOperand_ParseFail;
4907   }
4908   int Val = StringSwitch<int>(Tok.getString().lower())
4909     .Case("be", 1)
4910     .Case("le", 0)
4911     .Default(-1);
4912   Parser.Lex(); // Eat the token.
4913 
4914   if (Val == -1) {
4915     Error(S, "'be' or 'le' operand expected");
4916     return MatchOperand_ParseFail;
4917   }
4918   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4919                                                                   getContext()),
4920                                            S, Tok.getEndLoc()));
4921   return MatchOperand_Success;
4922 }
4923 
4924 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4925 /// instructions. Legal values are:
4926 ///     lsl #n  'n' in [0,31]
4927 ///     asr #n  'n' in [1,32]
4928 ///             n == 32 encoded as n == 0.
4929 OperandMatchResultTy
4930 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4931   MCAsmParser &Parser = getParser();
4932   const AsmToken &Tok = Parser.getTok();
4933   SMLoc S = Tok.getLoc();
4934   if (Tok.isNot(AsmToken::Identifier)) {
4935     Error(S, "shift operator 'asr' or 'lsl' expected");
4936     return MatchOperand_ParseFail;
4937   }
4938   StringRef ShiftName = Tok.getString();
4939   bool isASR;
4940   if (ShiftName == "lsl" || ShiftName == "LSL")
4941     isASR = false;
4942   else if (ShiftName == "asr" || ShiftName == "ASR")
4943     isASR = true;
4944   else {
4945     Error(S, "shift operator 'asr' or 'lsl' expected");
4946     return MatchOperand_ParseFail;
4947   }
4948   Parser.Lex(); // Eat the operator.
4949 
4950   // A '#' and a shift amount.
4951   if (Parser.getTok().isNot(AsmToken::Hash) &&
4952       Parser.getTok().isNot(AsmToken::Dollar)) {
4953     Error(Parser.getTok().getLoc(), "'#' expected");
4954     return MatchOperand_ParseFail;
4955   }
4956   Parser.Lex(); // Eat hash token.
4957   SMLoc ExLoc = Parser.getTok().getLoc();
4958 
4959   const MCExpr *ShiftAmount;
4960   SMLoc EndLoc;
4961   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4962     Error(ExLoc, "malformed shift expression");
4963     return MatchOperand_ParseFail;
4964   }
4965   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4966   if (!CE) {
4967     Error(ExLoc, "shift amount must be an immediate");
4968     return MatchOperand_ParseFail;
4969   }
4970 
4971   int64_t Val = CE->getValue();
4972   if (isASR) {
4973     // Shift amount must be in [1,32]
4974     if (Val < 1 || Val > 32) {
4975       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4976       return MatchOperand_ParseFail;
4977     }
4978     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4979     if (isThumb() && Val == 32) {
4980       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4981       return MatchOperand_ParseFail;
4982     }
4983     if (Val == 32) Val = 0;
4984   } else {
4985     // Shift amount must be in [1,32]
4986     if (Val < 0 || Val > 31) {
4987       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4988       return MatchOperand_ParseFail;
4989     }
4990   }
4991 
4992   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4993 
4994   return MatchOperand_Success;
4995 }
4996 
4997 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4998 /// of instructions. Legal values are:
4999 ///     ror #n  'n' in {0, 8, 16, 24}
5000 OperandMatchResultTy
5001 ARMAsmParser::parseRotImm(OperandVector &Operands) {
5002   MCAsmParser &Parser = getParser();
5003   const AsmToken &Tok = Parser.getTok();
5004   SMLoc S = Tok.getLoc();
5005   if (Tok.isNot(AsmToken::Identifier))
5006     return MatchOperand_NoMatch;
5007   StringRef ShiftName = Tok.getString();
5008   if (ShiftName != "ror" && ShiftName != "ROR")
5009     return MatchOperand_NoMatch;
5010   Parser.Lex(); // Eat the operator.
5011 
5012   // A '#' and a rotate amount.
5013   if (Parser.getTok().isNot(AsmToken::Hash) &&
5014       Parser.getTok().isNot(AsmToken::Dollar)) {
5015     Error(Parser.getTok().getLoc(), "'#' expected");
5016     return MatchOperand_ParseFail;
5017   }
5018   Parser.Lex(); // Eat hash token.
5019   SMLoc ExLoc = Parser.getTok().getLoc();
5020 
5021   const MCExpr *ShiftAmount;
5022   SMLoc EndLoc;
5023   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5024     Error(ExLoc, "malformed rotate expression");
5025     return MatchOperand_ParseFail;
5026   }
5027   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5028   if (!CE) {
5029     Error(ExLoc, "rotate amount must be an immediate");
5030     return MatchOperand_ParseFail;
5031   }
5032 
5033   int64_t Val = CE->getValue();
5034   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
5035   // normally, zero is represented in asm by omitting the rotate operand
5036   // entirely.
5037   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
5038     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
5039     return MatchOperand_ParseFail;
5040   }
5041 
5042   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
5043 
5044   return MatchOperand_Success;
5045 }
5046 
5047 OperandMatchResultTy
5048 ARMAsmParser::parseModImm(OperandVector &Operands) {
5049   MCAsmParser &Parser = getParser();
5050   MCAsmLexer &Lexer = getLexer();
5051   int64_t Imm1, Imm2;
5052 
5053   SMLoc S = Parser.getTok().getLoc();
5054 
5055   // 1) A mod_imm operand can appear in the place of a register name:
5056   //   add r0, #mod_imm
5057   //   add r0, r0, #mod_imm
5058   // to correctly handle the latter, we bail out as soon as we see an
5059   // identifier.
5060   //
5061   // 2) Similarly, we do not want to parse into complex operands:
5062   //   mov r0, #mod_imm
5063   //   mov r0, :lower16:(_foo)
5064   if (Parser.getTok().is(AsmToken::Identifier) ||
5065       Parser.getTok().is(AsmToken::Colon))
5066     return MatchOperand_NoMatch;
5067 
5068   // Hash (dollar) is optional as per the ARMARM
5069   if (Parser.getTok().is(AsmToken::Hash) ||
5070       Parser.getTok().is(AsmToken::Dollar)) {
5071     // Avoid parsing into complex operands (#:)
5072     if (Lexer.peekTok().is(AsmToken::Colon))
5073       return MatchOperand_NoMatch;
5074 
5075     // Eat the hash (dollar)
5076     Parser.Lex();
5077   }
5078 
5079   SMLoc Sx1, Ex1;
5080   Sx1 = Parser.getTok().getLoc();
5081   const MCExpr *Imm1Exp;
5082   if (getParser().parseExpression(Imm1Exp, Ex1)) {
5083     Error(Sx1, "malformed expression");
5084     return MatchOperand_ParseFail;
5085   }
5086 
5087   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
5088 
5089   if (CE) {
5090     // Immediate must fit within 32-bits
5091     Imm1 = CE->getValue();
5092     int Enc = ARM_AM::getSOImmVal(Imm1);
5093     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
5094       // We have a match!
5095       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
5096                                                   (Enc & 0xF00) >> 7,
5097                                                   Sx1, Ex1));
5098       return MatchOperand_Success;
5099     }
5100 
5101     // We have parsed an immediate which is not for us, fallback to a plain
5102     // immediate. This can happen for instruction aliases. For an example,
5103     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
5104     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
5105     // instruction with a mod_imm operand. The alias is defined such that the
5106     // parser method is shared, that's why we have to do this here.
5107     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
5108       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5109       return MatchOperand_Success;
5110     }
5111   } else {
5112     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
5113     // MCFixup). Fallback to a plain immediate.
5114     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5115     return MatchOperand_Success;
5116   }
5117 
5118   // From this point onward, we expect the input to be a (#bits, #rot) pair
5119   if (Parser.getTok().isNot(AsmToken::Comma)) {
5120     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
5121     return MatchOperand_ParseFail;
5122   }
5123 
5124   if (Imm1 & ~0xFF) {
5125     Error(Sx1, "immediate operand must a number in the range [0, 255]");
5126     return MatchOperand_ParseFail;
5127   }
5128 
5129   // Eat the comma
5130   Parser.Lex();
5131 
5132   // Repeat for #rot
5133   SMLoc Sx2, Ex2;
5134   Sx2 = Parser.getTok().getLoc();
5135 
5136   // Eat the optional hash (dollar)
5137   if (Parser.getTok().is(AsmToken::Hash) ||
5138       Parser.getTok().is(AsmToken::Dollar))
5139     Parser.Lex();
5140 
5141   const MCExpr *Imm2Exp;
5142   if (getParser().parseExpression(Imm2Exp, Ex2)) {
5143     Error(Sx2, "malformed expression");
5144     return MatchOperand_ParseFail;
5145   }
5146 
5147   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
5148 
5149   if (CE) {
5150     Imm2 = CE->getValue();
5151     if (!(Imm2 & ~0x1E)) {
5152       // We have a match!
5153       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
5154       return MatchOperand_Success;
5155     }
5156     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
5157     return MatchOperand_ParseFail;
5158   } else {
5159     Error(Sx2, "constant expression expected");
5160     return MatchOperand_ParseFail;
5161   }
5162 }
5163 
5164 OperandMatchResultTy
5165 ARMAsmParser::parseBitfield(OperandVector &Operands) {
5166   MCAsmParser &Parser = getParser();
5167   SMLoc S = Parser.getTok().getLoc();
5168   // The bitfield descriptor is really two operands, the LSB and the width.
5169   if (Parser.getTok().isNot(AsmToken::Hash) &&
5170       Parser.getTok().isNot(AsmToken::Dollar)) {
5171     Error(Parser.getTok().getLoc(), "'#' expected");
5172     return MatchOperand_ParseFail;
5173   }
5174   Parser.Lex(); // Eat hash token.
5175 
5176   const MCExpr *LSBExpr;
5177   SMLoc E = Parser.getTok().getLoc();
5178   if (getParser().parseExpression(LSBExpr)) {
5179     Error(E, "malformed immediate expression");
5180     return MatchOperand_ParseFail;
5181   }
5182   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
5183   if (!CE) {
5184     Error(E, "'lsb' operand must be an immediate");
5185     return MatchOperand_ParseFail;
5186   }
5187 
5188   int64_t LSB = CE->getValue();
5189   // The LSB must be in the range [0,31]
5190   if (LSB < 0 || LSB > 31) {
5191     Error(E, "'lsb' operand must be in the range [0,31]");
5192     return MatchOperand_ParseFail;
5193   }
5194   E = Parser.getTok().getLoc();
5195 
5196   // Expect another immediate operand.
5197   if (Parser.getTok().isNot(AsmToken::Comma)) {
5198     Error(Parser.getTok().getLoc(), "too few operands");
5199     return MatchOperand_ParseFail;
5200   }
5201   Parser.Lex(); // Eat hash token.
5202   if (Parser.getTok().isNot(AsmToken::Hash) &&
5203       Parser.getTok().isNot(AsmToken::Dollar)) {
5204     Error(Parser.getTok().getLoc(), "'#' expected");
5205     return MatchOperand_ParseFail;
5206   }
5207   Parser.Lex(); // Eat hash token.
5208 
5209   const MCExpr *WidthExpr;
5210   SMLoc EndLoc;
5211   if (getParser().parseExpression(WidthExpr, EndLoc)) {
5212     Error(E, "malformed immediate expression");
5213     return MatchOperand_ParseFail;
5214   }
5215   CE = dyn_cast<MCConstantExpr>(WidthExpr);
5216   if (!CE) {
5217     Error(E, "'width' operand must be an immediate");
5218     return MatchOperand_ParseFail;
5219   }
5220 
5221   int64_t Width = CE->getValue();
5222   // The LSB must be in the range [1,32-lsb]
5223   if (Width < 1 || Width > 32 - LSB) {
5224     Error(E, "'width' operand must be in the range [1,32-lsb]");
5225     return MatchOperand_ParseFail;
5226   }
5227 
5228   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
5229 
5230   return MatchOperand_Success;
5231 }
5232 
5233 OperandMatchResultTy
5234 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
5235   // Check for a post-index addressing register operand. Specifically:
5236   // postidx_reg := '+' register {, shift}
5237   //              | '-' register {, shift}
5238   //              | register {, shift}
5239 
5240   // This method must return MatchOperand_NoMatch without consuming any tokens
5241   // in the case where there is no match, as other alternatives take other
5242   // parse methods.
5243   MCAsmParser &Parser = getParser();
5244   AsmToken Tok = Parser.getTok();
5245   SMLoc S = Tok.getLoc();
5246   bool haveEaten = false;
5247   bool isAdd = true;
5248   if (Tok.is(AsmToken::Plus)) {
5249     Parser.Lex(); // Eat the '+' token.
5250     haveEaten = true;
5251   } else if (Tok.is(AsmToken::Minus)) {
5252     Parser.Lex(); // Eat the '-' token.
5253     isAdd = false;
5254     haveEaten = true;
5255   }
5256 
5257   SMLoc E = Parser.getTok().getEndLoc();
5258   int Reg = tryParseRegister();
5259   if (Reg == -1) {
5260     if (!haveEaten)
5261       return MatchOperand_NoMatch;
5262     Error(Parser.getTok().getLoc(), "register expected");
5263     return MatchOperand_ParseFail;
5264   }
5265 
5266   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
5267   unsigned ShiftImm = 0;
5268   if (Parser.getTok().is(AsmToken::Comma)) {
5269     Parser.Lex(); // Eat the ','.
5270     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
5271       return MatchOperand_ParseFail;
5272 
5273     // FIXME: Only approximates end...may include intervening whitespace.
5274     E = Parser.getTok().getLoc();
5275   }
5276 
5277   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
5278                                                   ShiftImm, S, E));
5279 
5280   return MatchOperand_Success;
5281 }
5282 
5283 OperandMatchResultTy
5284 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
5285   // Check for a post-index addressing register operand. Specifically:
5286   // am3offset := '+' register
5287   //              | '-' register
5288   //              | register
5289   //              | # imm
5290   //              | # + imm
5291   //              | # - imm
5292 
5293   // This method must return MatchOperand_NoMatch without consuming any tokens
5294   // in the case where there is no match, as other alternatives take other
5295   // parse methods.
5296   MCAsmParser &Parser = getParser();
5297   AsmToken Tok = Parser.getTok();
5298   SMLoc S = Tok.getLoc();
5299 
5300   // Do immediates first, as we always parse those if we have a '#'.
5301   if (Parser.getTok().is(AsmToken::Hash) ||
5302       Parser.getTok().is(AsmToken::Dollar)) {
5303     Parser.Lex(); // Eat '#' or '$'.
5304     // Explicitly look for a '-', as we need to encode negative zero
5305     // differently.
5306     bool isNegative = Parser.getTok().is(AsmToken::Minus);
5307     const MCExpr *Offset;
5308     SMLoc E;
5309     if (getParser().parseExpression(Offset, E))
5310       return MatchOperand_ParseFail;
5311     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5312     if (!CE) {
5313       Error(S, "constant expression expected");
5314       return MatchOperand_ParseFail;
5315     }
5316     // Negative zero is encoded as the flag value
5317     // std::numeric_limits<int32_t>::min().
5318     int32_t Val = CE->getValue();
5319     if (isNegative && Val == 0)
5320       Val = std::numeric_limits<int32_t>::min();
5321 
5322     Operands.push_back(
5323       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
5324 
5325     return MatchOperand_Success;
5326   }
5327 
5328   bool haveEaten = false;
5329   bool isAdd = true;
5330   if (Tok.is(AsmToken::Plus)) {
5331     Parser.Lex(); // Eat the '+' token.
5332     haveEaten = true;
5333   } else if (Tok.is(AsmToken::Minus)) {
5334     Parser.Lex(); // Eat the '-' token.
5335     isAdd = false;
5336     haveEaten = true;
5337   }
5338 
5339   Tok = Parser.getTok();
5340   int Reg = tryParseRegister();
5341   if (Reg == -1) {
5342     if (!haveEaten)
5343       return MatchOperand_NoMatch;
5344     Error(Tok.getLoc(), "register expected");
5345     return MatchOperand_ParseFail;
5346   }
5347 
5348   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
5349                                                   0, S, Tok.getEndLoc()));
5350 
5351   return MatchOperand_Success;
5352 }
5353 
5354 /// Convert parsed operands to MCInst.  Needed here because this instruction
5355 /// only has two register operands, but multiplication is commutative so
5356 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
5357 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
5358                                     const OperandVector &Operands) {
5359   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
5360   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
5361   // If we have a three-operand form, make sure to set Rn to be the operand
5362   // that isn't the same as Rd.
5363   unsigned RegOp = 4;
5364   if (Operands.size() == 6 &&
5365       ((ARMOperand &)*Operands[4]).getReg() ==
5366           ((ARMOperand &)*Operands[3]).getReg())
5367     RegOp = 5;
5368   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5369   Inst.addOperand(Inst.getOperand(0));
5370   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5371 }
5372 
5373 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5374                                     const OperandVector &Operands) {
5375   int CondOp = -1, ImmOp = -1;
5376   switch(Inst.getOpcode()) {
5377     case ARM::tB:
5378     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5379 
5380     case ARM::t2B:
5381     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5382 
5383     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5384   }
5385   // first decide whether or not the branch should be conditional
5386   // by looking at it's location relative to an IT block
5387   if(inITBlock()) {
5388     // inside an IT block we cannot have any conditional branches. any
5389     // such instructions needs to be converted to unconditional form
5390     switch(Inst.getOpcode()) {
5391       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5392       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5393     }
5394   } else {
5395     // outside IT blocks we can only have unconditional branches with AL
5396     // condition code or conditional branches with non-AL condition code
5397     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5398     switch(Inst.getOpcode()) {
5399       case ARM::tB:
5400       case ARM::tBcc:
5401         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5402         break;
5403       case ARM::t2B:
5404       case ARM::t2Bcc:
5405         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5406         break;
5407     }
5408   }
5409 
5410   // now decide on encoding size based on branch target range
5411   switch(Inst.getOpcode()) {
5412     // classify tB as either t2B or t1B based on range of immediate operand
5413     case ARM::tB: {
5414       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5415       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5416         Inst.setOpcode(ARM::t2B);
5417       break;
5418     }
5419     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5420     case ARM::tBcc: {
5421       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5422       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5423         Inst.setOpcode(ARM::t2Bcc);
5424       break;
5425     }
5426   }
5427   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5428   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5429 }
5430 
5431 void ARMAsmParser::cvtMVEVMOVQtoDReg(
5432   MCInst &Inst, const OperandVector &Operands) {
5433 
5434   // mnemonic, condition code, Rt, Rt2, Qd, idx, Qd again, idx2
5435   assert(Operands.size() == 8);
5436 
5437   ((ARMOperand &)*Operands[2]).addRegOperands(Inst, 1); // Rt
5438   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1); // Rt2
5439   ((ARMOperand &)*Operands[4]).addRegOperands(Inst, 1); // Qd
5440   ((ARMOperand &)*Operands[5]).addMVEPairVectorIndexOperands(Inst, 1); // idx
5441   // skip second copy of Qd in Operands[6]
5442   ((ARMOperand &)*Operands[7]).addMVEPairVectorIndexOperands(Inst, 1); // idx2
5443   ((ARMOperand &)*Operands[1]).addCondCodeOperands(Inst, 2); // condition code
5444 }
5445 
5446 /// Parse an ARM memory expression, return false if successful else return true
5447 /// or an error.  The first token must be a '[' when called.
5448 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5449   MCAsmParser &Parser = getParser();
5450   SMLoc S, E;
5451   if (Parser.getTok().isNot(AsmToken::LBrac))
5452     return TokError("Token is not a Left Bracket");
5453   S = Parser.getTok().getLoc();
5454   Parser.Lex(); // Eat left bracket token.
5455 
5456   const AsmToken &BaseRegTok = Parser.getTok();
5457   int BaseRegNum = tryParseRegister();
5458   if (BaseRegNum == -1)
5459     return Error(BaseRegTok.getLoc(), "register expected");
5460 
5461   // The next token must either be a comma, a colon or a closing bracket.
5462   const AsmToken &Tok = Parser.getTok();
5463   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5464       !Tok.is(AsmToken::RBrac))
5465     return Error(Tok.getLoc(), "malformed memory operand");
5466 
5467   if (Tok.is(AsmToken::RBrac)) {
5468     E = Tok.getEndLoc();
5469     Parser.Lex(); // Eat right bracket token.
5470 
5471     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5472                                              ARM_AM::no_shift, 0, 0, false,
5473                                              S, E));
5474 
5475     // If there's a pre-indexing writeback marker, '!', just add it as a token
5476     // operand. It's rather odd, but syntactically valid.
5477     if (Parser.getTok().is(AsmToken::Exclaim)) {
5478       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5479       Parser.Lex(); // Eat the '!'.
5480     }
5481 
5482     return false;
5483   }
5484 
5485   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5486          "Lost colon or comma in memory operand?!");
5487   if (Tok.is(AsmToken::Comma)) {
5488     Parser.Lex(); // Eat the comma.
5489   }
5490 
5491   // If we have a ':', it's an alignment specifier.
5492   if (Parser.getTok().is(AsmToken::Colon)) {
5493     Parser.Lex(); // Eat the ':'.
5494     E = Parser.getTok().getLoc();
5495     SMLoc AlignmentLoc = Tok.getLoc();
5496 
5497     const MCExpr *Expr;
5498     if (getParser().parseExpression(Expr))
5499      return true;
5500 
5501     // The expression has to be a constant. Memory references with relocations
5502     // don't come through here, as they use the <label> forms of the relevant
5503     // instructions.
5504     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5505     if (!CE)
5506       return Error (E, "constant expression expected");
5507 
5508     unsigned Align = 0;
5509     switch (CE->getValue()) {
5510     default:
5511       return Error(E,
5512                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5513     case 16:  Align = 2; break;
5514     case 32:  Align = 4; break;
5515     case 64:  Align = 8; break;
5516     case 128: Align = 16; break;
5517     case 256: Align = 32; break;
5518     }
5519 
5520     // Now we should have the closing ']'
5521     if (Parser.getTok().isNot(AsmToken::RBrac))
5522       return Error(Parser.getTok().getLoc(), "']' expected");
5523     E = Parser.getTok().getEndLoc();
5524     Parser.Lex(); // Eat right bracket token.
5525 
5526     // Don't worry about range checking the value here. That's handled by
5527     // the is*() predicates.
5528     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5529                                              ARM_AM::no_shift, 0, Align,
5530                                              false, S, E, AlignmentLoc));
5531 
5532     // If there's a pre-indexing writeback marker, '!', just add it as a token
5533     // operand.
5534     if (Parser.getTok().is(AsmToken::Exclaim)) {
5535       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5536       Parser.Lex(); // Eat the '!'.
5537     }
5538 
5539     return false;
5540   }
5541 
5542   // If we have a '#', it's an immediate offset, else assume it's a register
5543   // offset. Be friendly and also accept a plain integer (without a leading
5544   // hash) for gas compatibility.
5545   if (Parser.getTok().is(AsmToken::Hash) ||
5546       Parser.getTok().is(AsmToken::Dollar) ||
5547       Parser.getTok().is(AsmToken::Integer)) {
5548     if (Parser.getTok().isNot(AsmToken::Integer))
5549       Parser.Lex(); // Eat '#' or '$'.
5550     E = Parser.getTok().getLoc();
5551 
5552     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5553     const MCExpr *Offset;
5554     if (getParser().parseExpression(Offset))
5555      return true;
5556 
5557     // The expression has to be a constant. Memory references with relocations
5558     // don't come through here, as they use the <label> forms of the relevant
5559     // instructions.
5560     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5561     if (!CE)
5562       return Error (E, "constant expression expected");
5563 
5564     // If the constant was #-0, represent it as
5565     // std::numeric_limits<int32_t>::min().
5566     int32_t Val = CE->getValue();
5567     if (isNegative && Val == 0)
5568       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5569                                   getContext());
5570 
5571     // Now we should have the closing ']'
5572     if (Parser.getTok().isNot(AsmToken::RBrac))
5573       return Error(Parser.getTok().getLoc(), "']' expected");
5574     E = Parser.getTok().getEndLoc();
5575     Parser.Lex(); // Eat right bracket token.
5576 
5577     // Don't worry about range checking the value here. That's handled by
5578     // the is*() predicates.
5579     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5580                                              ARM_AM::no_shift, 0, 0,
5581                                              false, S, E));
5582 
5583     // If there's a pre-indexing writeback marker, '!', just add it as a token
5584     // operand.
5585     if (Parser.getTok().is(AsmToken::Exclaim)) {
5586       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5587       Parser.Lex(); // Eat the '!'.
5588     }
5589 
5590     return false;
5591   }
5592 
5593   // The register offset is optionally preceded by a '+' or '-'
5594   bool isNegative = false;
5595   if (Parser.getTok().is(AsmToken::Minus)) {
5596     isNegative = true;
5597     Parser.Lex(); // Eat the '-'.
5598   } else if (Parser.getTok().is(AsmToken::Plus)) {
5599     // Nothing to do.
5600     Parser.Lex(); // Eat the '+'.
5601   }
5602 
5603   E = Parser.getTok().getLoc();
5604   int OffsetRegNum = tryParseRegister();
5605   if (OffsetRegNum == -1)
5606     return Error(E, "register expected");
5607 
5608   // If there's a shift operator, handle it.
5609   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5610   unsigned ShiftImm = 0;
5611   if (Parser.getTok().is(AsmToken::Comma)) {
5612     Parser.Lex(); // Eat the ','.
5613     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5614       return true;
5615   }
5616 
5617   // Now we should have the closing ']'
5618   if (Parser.getTok().isNot(AsmToken::RBrac))
5619     return Error(Parser.getTok().getLoc(), "']' expected");
5620   E = Parser.getTok().getEndLoc();
5621   Parser.Lex(); // Eat right bracket token.
5622 
5623   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5624                                            ShiftType, ShiftImm, 0, isNegative,
5625                                            S, E));
5626 
5627   // If there's a pre-indexing writeback marker, '!', just add it as a token
5628   // operand.
5629   if (Parser.getTok().is(AsmToken::Exclaim)) {
5630     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5631     Parser.Lex(); // Eat the '!'.
5632   }
5633 
5634   return false;
5635 }
5636 
5637 /// parseMemRegOffsetShift - one of these two:
5638 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5639 ///   rrx
5640 /// return true if it parses a shift otherwise it returns false.
5641 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5642                                           unsigned &Amount) {
5643   MCAsmParser &Parser = getParser();
5644   SMLoc Loc = Parser.getTok().getLoc();
5645   const AsmToken &Tok = Parser.getTok();
5646   if (Tok.isNot(AsmToken::Identifier))
5647     return Error(Loc, "illegal shift operator");
5648   StringRef ShiftName = Tok.getString();
5649   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5650       ShiftName == "asl" || ShiftName == "ASL")
5651     St = ARM_AM::lsl;
5652   else if (ShiftName == "lsr" || ShiftName == "LSR")
5653     St = ARM_AM::lsr;
5654   else if (ShiftName == "asr" || ShiftName == "ASR")
5655     St = ARM_AM::asr;
5656   else if (ShiftName == "ror" || ShiftName == "ROR")
5657     St = ARM_AM::ror;
5658   else if (ShiftName == "rrx" || ShiftName == "RRX")
5659     St = ARM_AM::rrx;
5660   else
5661     return Error(Loc, "illegal shift operator");
5662   Parser.Lex(); // Eat shift type token.
5663 
5664   // rrx stands alone.
5665   Amount = 0;
5666   if (St != ARM_AM::rrx) {
5667     Loc = Parser.getTok().getLoc();
5668     // A '#' and a shift amount.
5669     const AsmToken &HashTok = Parser.getTok();
5670     if (HashTok.isNot(AsmToken::Hash) &&
5671         HashTok.isNot(AsmToken::Dollar))
5672       return Error(HashTok.getLoc(), "'#' expected");
5673     Parser.Lex(); // Eat hash token.
5674 
5675     const MCExpr *Expr;
5676     if (getParser().parseExpression(Expr))
5677       return true;
5678     // Range check the immediate.
5679     // lsl, ror: 0 <= imm <= 31
5680     // lsr, asr: 0 <= imm <= 32
5681     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5682     if (!CE)
5683       return Error(Loc, "shift amount must be an immediate");
5684     int64_t Imm = CE->getValue();
5685     if (Imm < 0 ||
5686         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5687         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5688       return Error(Loc, "immediate shift value out of range");
5689     // If <ShiftTy> #0, turn it into a no_shift.
5690     if (Imm == 0)
5691       St = ARM_AM::lsl;
5692     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5693     if (Imm == 32)
5694       Imm = 0;
5695     Amount = Imm;
5696   }
5697 
5698   return false;
5699 }
5700 
5701 /// parseFPImm - A floating point immediate expression operand.
5702 OperandMatchResultTy
5703 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5704   MCAsmParser &Parser = getParser();
5705   // Anything that can accept a floating point constant as an operand
5706   // needs to go through here, as the regular parseExpression is
5707   // integer only.
5708   //
5709   // This routine still creates a generic Immediate operand, containing
5710   // a bitcast of the 64-bit floating point value. The various operands
5711   // that accept floats can check whether the value is valid for them
5712   // via the standard is*() predicates.
5713 
5714   SMLoc S = Parser.getTok().getLoc();
5715 
5716   if (Parser.getTok().isNot(AsmToken::Hash) &&
5717       Parser.getTok().isNot(AsmToken::Dollar))
5718     return MatchOperand_NoMatch;
5719 
5720   // Disambiguate the VMOV forms that can accept an FP immediate.
5721   // vmov.f32 <sreg>, #imm
5722   // vmov.f64 <dreg>, #imm
5723   // vmov.f32 <dreg>, #imm  @ vector f32x2
5724   // vmov.f32 <qreg>, #imm  @ vector f32x4
5725   //
5726   // There are also the NEON VMOV instructions which expect an
5727   // integer constant. Make sure we don't try to parse an FPImm
5728   // for these:
5729   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5730   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5731   bool isVmovf = TyOp.isToken() &&
5732                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5733                   TyOp.getToken() == ".f16");
5734   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5735   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5736                                          Mnemonic.getToken() == "fconsts");
5737   if (!(isVmovf || isFconst))
5738     return MatchOperand_NoMatch;
5739 
5740   Parser.Lex(); // Eat '#' or '$'.
5741 
5742   // Handle negation, as that still comes through as a separate token.
5743   bool isNegative = false;
5744   if (Parser.getTok().is(AsmToken::Minus)) {
5745     isNegative = true;
5746     Parser.Lex();
5747   }
5748   const AsmToken &Tok = Parser.getTok();
5749   SMLoc Loc = Tok.getLoc();
5750   if (Tok.is(AsmToken::Real) && isVmovf) {
5751     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5752     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5753     // If we had a '-' in front, toggle the sign bit.
5754     IntVal ^= (uint64_t)isNegative << 31;
5755     Parser.Lex(); // Eat the token.
5756     Operands.push_back(ARMOperand::CreateImm(
5757           MCConstantExpr::create(IntVal, getContext()),
5758           S, Parser.getTok().getLoc()));
5759     return MatchOperand_Success;
5760   }
5761   // Also handle plain integers. Instructions which allow floating point
5762   // immediates also allow a raw encoded 8-bit value.
5763   if (Tok.is(AsmToken::Integer) && isFconst) {
5764     int64_t Val = Tok.getIntVal();
5765     Parser.Lex(); // Eat the token.
5766     if (Val > 255 || Val < 0) {
5767       Error(Loc, "encoded floating point value out of range");
5768       return MatchOperand_ParseFail;
5769     }
5770     float RealVal = ARM_AM::getFPImmFloat(Val);
5771     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5772 
5773     Operands.push_back(ARMOperand::CreateImm(
5774         MCConstantExpr::create(Val, getContext()), S,
5775         Parser.getTok().getLoc()));
5776     return MatchOperand_Success;
5777   }
5778 
5779   Error(Loc, "invalid floating point immediate");
5780   return MatchOperand_ParseFail;
5781 }
5782 
5783 /// Parse a arm instruction operand.  For now this parses the operand regardless
5784 /// of the mnemonic.
5785 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5786   MCAsmParser &Parser = getParser();
5787   SMLoc S, E;
5788 
5789   // Check if the current operand has a custom associated parser, if so, try to
5790   // custom parse the operand, or fallback to the general approach.
5791   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5792   if (ResTy == MatchOperand_Success)
5793     return false;
5794   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5795   // there was a match, but an error occurred, in which case, just return that
5796   // the operand parsing failed.
5797   if (ResTy == MatchOperand_ParseFail)
5798     return true;
5799 
5800   switch (getLexer().getKind()) {
5801   default:
5802     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5803     return true;
5804   case AsmToken::Identifier: {
5805     // If we've seen a branch mnemonic, the next operand must be a label.  This
5806     // is true even if the label is a register name.  So "br r1" means branch to
5807     // label "r1".
5808     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5809     if (!ExpectLabel) {
5810       if (!tryParseRegisterWithWriteBack(Operands))
5811         return false;
5812       int Res = tryParseShiftRegister(Operands);
5813       if (Res == 0) // success
5814         return false;
5815       else if (Res == -1) // irrecoverable error
5816         return true;
5817       // If this is VMRS, check for the apsr_nzcv operand.
5818       if (Mnemonic == "vmrs" &&
5819           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5820         S = Parser.getTok().getLoc();
5821         Parser.Lex();
5822         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5823         return false;
5824       }
5825     }
5826 
5827     // Fall though for the Identifier case that is not a register or a
5828     // special name.
5829     LLVM_FALLTHROUGH;
5830   }
5831   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5832   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5833   case AsmToken::String:  // quoted label names.
5834   case AsmToken::Dot: {   // . as a branch target
5835     // This was not a register so parse other operands that start with an
5836     // identifier (like labels) as expressions and create them as immediates.
5837     const MCExpr *IdVal;
5838     S = Parser.getTok().getLoc();
5839     if (getParser().parseExpression(IdVal))
5840       return true;
5841     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5842     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5843     return false;
5844   }
5845   case AsmToken::LBrac:
5846     return parseMemory(Operands);
5847   case AsmToken::LCurly:
5848     return parseRegisterList(Operands, !Mnemonic.startswith("clr"));
5849   case AsmToken::Dollar:
5850   case AsmToken::Hash:
5851     // #42 -> immediate.
5852     S = Parser.getTok().getLoc();
5853     Parser.Lex();
5854 
5855     if (Parser.getTok().isNot(AsmToken::Colon)) {
5856       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5857       const MCExpr *ImmVal;
5858       if (getParser().parseExpression(ImmVal))
5859         return true;
5860       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5861       if (CE) {
5862         int32_t Val = CE->getValue();
5863         if (isNegative && Val == 0)
5864           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5865                                           getContext());
5866       }
5867       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5868       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5869 
5870       // There can be a trailing '!' on operands that we want as a separate
5871       // '!' Token operand. Handle that here. For example, the compatibility
5872       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5873       if (Parser.getTok().is(AsmToken::Exclaim)) {
5874         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5875                                                    Parser.getTok().getLoc()));
5876         Parser.Lex(); // Eat exclaim token
5877       }
5878       return false;
5879     }
5880     // w/ a ':' after the '#', it's just like a plain ':'.
5881     LLVM_FALLTHROUGH;
5882 
5883   case AsmToken::Colon: {
5884     S = Parser.getTok().getLoc();
5885     // ":lower16:" and ":upper16:" expression prefixes
5886     // FIXME: Check it's an expression prefix,
5887     // e.g. (FOO - :lower16:BAR) isn't legal.
5888     ARMMCExpr::VariantKind RefKind;
5889     if (parsePrefix(RefKind))
5890       return true;
5891 
5892     const MCExpr *SubExprVal;
5893     if (getParser().parseExpression(SubExprVal))
5894       return true;
5895 
5896     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5897                                               getContext());
5898     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5899     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5900     return false;
5901   }
5902   case AsmToken::Equal: {
5903     S = Parser.getTok().getLoc();
5904     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5905       return Error(S, "unexpected token in operand");
5906     Parser.Lex(); // Eat '='
5907     const MCExpr *SubExprVal;
5908     if (getParser().parseExpression(SubExprVal))
5909       return true;
5910     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5911 
5912     // execute-only: we assume that assembly programmers know what they are
5913     // doing and allow literal pool creation here
5914     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5915     return false;
5916   }
5917   }
5918 }
5919 
5920 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5921 //  :lower16: and :upper16:.
5922 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5923   MCAsmParser &Parser = getParser();
5924   RefKind = ARMMCExpr::VK_ARM_None;
5925 
5926   // consume an optional '#' (GNU compatibility)
5927   if (getLexer().is(AsmToken::Hash))
5928     Parser.Lex();
5929 
5930   // :lower16: and :upper16: modifiers
5931   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5932   Parser.Lex(); // Eat ':'
5933 
5934   if (getLexer().isNot(AsmToken::Identifier)) {
5935     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5936     return true;
5937   }
5938 
5939   enum {
5940     COFF = (1 << MCObjectFileInfo::IsCOFF),
5941     ELF = (1 << MCObjectFileInfo::IsELF),
5942     MACHO = (1 << MCObjectFileInfo::IsMachO),
5943     WASM = (1 << MCObjectFileInfo::IsWasm),
5944   };
5945   static const struct PrefixEntry {
5946     const char *Spelling;
5947     ARMMCExpr::VariantKind VariantKind;
5948     uint8_t SupportedFormats;
5949   } PrefixEntries[] = {
5950     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5951     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5952   };
5953 
5954   StringRef IDVal = Parser.getTok().getIdentifier();
5955 
5956   const auto &Prefix =
5957       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5958                    [&IDVal](const PrefixEntry &PE) {
5959                       return PE.Spelling == IDVal;
5960                    });
5961   if (Prefix == std::end(PrefixEntries)) {
5962     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5963     return true;
5964   }
5965 
5966   uint8_t CurrentFormat;
5967   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5968   case MCObjectFileInfo::IsMachO:
5969     CurrentFormat = MACHO;
5970     break;
5971   case MCObjectFileInfo::IsELF:
5972     CurrentFormat = ELF;
5973     break;
5974   case MCObjectFileInfo::IsCOFF:
5975     CurrentFormat = COFF;
5976     break;
5977   case MCObjectFileInfo::IsWasm:
5978     CurrentFormat = WASM;
5979     break;
5980   case MCObjectFileInfo::IsXCOFF:
5981     llvm_unreachable("unexpected object format");
5982     break;
5983   }
5984 
5985   if (~Prefix->SupportedFormats & CurrentFormat) {
5986     Error(Parser.getTok().getLoc(),
5987           "cannot represent relocation in the current file format");
5988     return true;
5989   }
5990 
5991   RefKind = Prefix->VariantKind;
5992   Parser.Lex();
5993 
5994   if (getLexer().isNot(AsmToken::Colon)) {
5995     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5996     return true;
5997   }
5998   Parser.Lex(); // Eat the last ':'
5999 
6000   return false;
6001 }
6002 
6003 /// Given a mnemonic, split out possible predication code and carry
6004 /// setting letters to form a canonical mnemonic and flags.
6005 //
6006 // FIXME: Would be nice to autogen this.
6007 // FIXME: This is a bit of a maze of special cases.
6008 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
6009                                       StringRef ExtraToken,
6010                                       unsigned &PredicationCode,
6011                                       unsigned &VPTPredicationCode,
6012                                       bool &CarrySetting,
6013                                       unsigned &ProcessorIMod,
6014                                       StringRef &ITMask) {
6015   PredicationCode = ARMCC::AL;
6016   VPTPredicationCode = ARMVCC::None;
6017   CarrySetting = false;
6018   ProcessorIMod = 0;
6019 
6020   // Ignore some mnemonics we know aren't predicated forms.
6021   //
6022   // FIXME: Would be nice to autogen this.
6023   if ((Mnemonic == "movs" && isThumb()) ||
6024       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
6025       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
6026       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
6027       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
6028       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
6029       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
6030       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
6031       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
6032       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
6033       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
6034       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
6035       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
6036       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
6037       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
6038       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6039       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6040       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6041       Mnemonic == "wls" || Mnemonic == "le" || Mnemonic == "dls" ||
6042       Mnemonic == "csel" || Mnemonic == "csinc" ||
6043       Mnemonic == "csinv" || Mnemonic == "csneg" || Mnemonic == "cinc" ||
6044       Mnemonic == "cinv" || Mnemonic == "cneg" || Mnemonic == "cset" ||
6045       Mnemonic == "csetm")
6046     return Mnemonic;
6047 
6048   // First, split out any predication code. Ignore mnemonics we know aren't
6049   // predicated but do have a carry-set and so weren't caught above.
6050   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
6051       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
6052       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
6053       Mnemonic != "sbcs" && Mnemonic != "rscs" &&
6054       !(hasMVE() &&
6055         (Mnemonic == "vmine" ||
6056          Mnemonic == "vshle" || Mnemonic == "vshlt" || Mnemonic == "vshllt" ||
6057          Mnemonic == "vrshle" || Mnemonic == "vrshlt" ||
6058          Mnemonic == "vmvne" || Mnemonic == "vorne" ||
6059          Mnemonic == "vnege" || Mnemonic == "vnegt" ||
6060          Mnemonic == "vmule" || Mnemonic == "vmult" ||
6061          Mnemonic == "vrintne" ||
6062          Mnemonic == "vcmult" || Mnemonic == "vcmule" ||
6063          Mnemonic.startswith("vq")))) {
6064     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
6065     if (CC != ~0U) {
6066       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
6067       PredicationCode = CC;
6068     }
6069   }
6070 
6071   // Next, determine if we have a carry setting bit. We explicitly ignore all
6072   // the instructions we know end in 's'.
6073   if (Mnemonic.endswith("s") &&
6074       !(Mnemonic == "cps" || Mnemonic == "mls" ||
6075         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
6076         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
6077         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
6078         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
6079         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
6080         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
6081         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
6082         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
6083         Mnemonic == "bxns" || Mnemonic == "blxns" || Mnemonic == "vfmas" ||
6084         Mnemonic == "vmlas" ||
6085         (Mnemonic == "movs" && isThumb()))) {
6086     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
6087     CarrySetting = true;
6088   }
6089 
6090   // The "cps" instruction can have a interrupt mode operand which is glued into
6091   // the mnemonic. Check if this is the case, split it and parse the imod op
6092   if (Mnemonic.startswith("cps")) {
6093     // Split out any imod code.
6094     unsigned IMod =
6095       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
6096       .Case("ie", ARM_PROC::IE)
6097       .Case("id", ARM_PROC::ID)
6098       .Default(~0U);
6099     if (IMod != ~0U) {
6100       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
6101       ProcessorIMod = IMod;
6102     }
6103   }
6104 
6105   if (isMnemonicVPTPredicable(Mnemonic, ExtraToken) && Mnemonic != "vmovlt" &&
6106       Mnemonic != "vshllt" && Mnemonic != "vrshrnt" && Mnemonic != "vshrnt" &&
6107       Mnemonic != "vqrshrunt" && Mnemonic != "vqshrunt" &&
6108       Mnemonic != "vqrshrnt" && Mnemonic != "vqshrnt" && Mnemonic != "vmullt" &&
6109       Mnemonic != "vqmovnt" && Mnemonic != "vqmovunt" &&
6110       Mnemonic != "vqmovnt" && Mnemonic != "vmovnt" && Mnemonic != "vqdmullt" &&
6111       Mnemonic != "vcvtt" && Mnemonic != "vcvt") {
6112     unsigned CC = ARMVectorCondCodeFromString(Mnemonic.substr(Mnemonic.size()-1));
6113     if (CC != ~0U) {
6114       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-1);
6115       VPTPredicationCode = CC;
6116     }
6117     return Mnemonic;
6118   }
6119 
6120   // The "it" instruction has the condition mask on the end of the mnemonic.
6121   if (Mnemonic.startswith("it")) {
6122     ITMask = Mnemonic.slice(2, Mnemonic.size());
6123     Mnemonic = Mnemonic.slice(0, 2);
6124   }
6125 
6126   if (Mnemonic.startswith("vpst")) {
6127     ITMask = Mnemonic.slice(4, Mnemonic.size());
6128     Mnemonic = Mnemonic.slice(0, 4);
6129   }
6130   else if (Mnemonic.startswith("vpt")) {
6131     ITMask = Mnemonic.slice(3, Mnemonic.size());
6132     Mnemonic = Mnemonic.slice(0, 3);
6133   }
6134 
6135   return Mnemonic;
6136 }
6137 
6138 /// Given a canonical mnemonic, determine if the instruction ever allows
6139 /// inclusion of carry set or predication code operands.
6140 //
6141 // FIXME: It would be nice to autogen this.
6142 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic,
6143                                          StringRef ExtraToken,
6144                                          StringRef FullInst,
6145                                          bool &CanAcceptCarrySet,
6146                                          bool &CanAcceptPredicationCode,
6147                                          bool &CanAcceptVPTPredicationCode) {
6148   CanAcceptVPTPredicationCode = isMnemonicVPTPredicable(Mnemonic, ExtraToken);
6149 
6150   CanAcceptCarrySet =
6151       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6152       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
6153       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
6154       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
6155       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
6156       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
6157       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
6158       (!isThumb() &&
6159        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
6160         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
6161 
6162   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
6163       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
6164       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
6165       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
6166       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
6167       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
6168       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
6169       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
6170       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
6171       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
6172       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
6173       Mnemonic == "vmovx" || Mnemonic == "vins" ||
6174       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6175       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6176       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6177       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
6178       Mnemonic == "pssbb" ||
6179       Mnemonic == "bfcsel" || Mnemonic == "wls" ||
6180       Mnemonic == "dls" || Mnemonic == "le" || Mnemonic == "csel" ||
6181       Mnemonic == "csinc" || Mnemonic == "csinv" || Mnemonic == "csneg" ||
6182       Mnemonic == "cinc" || Mnemonic == "cinv" || Mnemonic == "cneg" ||
6183       Mnemonic == "cset" || Mnemonic == "csetm" ||
6184       Mnemonic.startswith("vpt") || Mnemonic.startswith("vpst") ||
6185       (hasMVE() &&
6186        (Mnemonic.startswith("vst2") || Mnemonic.startswith("vld2") ||
6187         Mnemonic.startswith("vst4") || Mnemonic.startswith("vld4")))) {
6188     // These mnemonics are never predicable
6189     CanAcceptPredicationCode = false;
6190   } else if (!isThumb()) {
6191     // Some instructions are only predicable in Thumb mode
6192     CanAcceptPredicationCode =
6193         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
6194         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
6195         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
6196         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
6197         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
6198         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
6199         Mnemonic != "tsb" &&
6200         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
6201   } else if (isThumbOne()) {
6202     if (hasV6MOps())
6203       CanAcceptPredicationCode = Mnemonic != "movs";
6204     else
6205       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
6206   } else
6207     CanAcceptPredicationCode = true;
6208 }
6209 
6210 // Some Thumb instructions have two operand forms that are not
6211 // available as three operand, convert to two operand form if possible.
6212 //
6213 // FIXME: We would really like to be able to tablegen'erate this.
6214 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
6215                                                  bool CarrySetting,
6216                                                  OperandVector &Operands) {
6217   if (Operands.size() != 6)
6218     return;
6219 
6220   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6221         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
6222   if (!Op3.isReg() || !Op4.isReg())
6223     return;
6224 
6225   auto Op3Reg = Op3.getReg();
6226   auto Op4Reg = Op4.getReg();
6227 
6228   // For most Thumb2 cases we just generate the 3 operand form and reduce
6229   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
6230   // won't accept SP or PC so we do the transformation here taking care
6231   // with immediate range in the 'add sp, sp #imm' case.
6232   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
6233   if (isThumbTwo()) {
6234     if (Mnemonic != "add")
6235       return;
6236     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
6237                         (Op5.isReg() && Op5.getReg() == ARM::PC);
6238     if (!TryTransform) {
6239       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
6240                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
6241                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
6242                        Op5.isImm() && !Op5.isImm0_508s4());
6243     }
6244     if (!TryTransform)
6245       return;
6246   } else if (!isThumbOne())
6247     return;
6248 
6249   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
6250         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6251         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
6252         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
6253     return;
6254 
6255   // If first 2 operands of a 3 operand instruction are the same
6256   // then transform to 2 operand version of the same instruction
6257   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
6258   bool Transform = Op3Reg == Op4Reg;
6259 
6260   // For communtative operations, we might be able to transform if we swap
6261   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
6262   // as tADDrsp.
6263   const ARMOperand *LastOp = &Op5;
6264   bool Swap = false;
6265   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
6266       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
6267        Mnemonic == "and" || Mnemonic == "eor" ||
6268        Mnemonic == "adc" || Mnemonic == "orr")) {
6269     Swap = true;
6270     LastOp = &Op4;
6271     Transform = true;
6272   }
6273 
6274   // If both registers are the same then remove one of them from
6275   // the operand list, with certain exceptions.
6276   if (Transform) {
6277     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
6278     // 2 operand forms don't exist.
6279     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
6280         LastOp->isReg())
6281       Transform = false;
6282 
6283     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
6284     // 3-bits because the ARMARM says not to.
6285     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
6286       Transform = false;
6287   }
6288 
6289   if (Transform) {
6290     if (Swap)
6291       std::swap(Op4, Op5);
6292     Operands.erase(Operands.begin() + 3);
6293   }
6294 }
6295 
6296 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
6297                                           OperandVector &Operands) {
6298   // FIXME: This is all horribly hacky. We really need a better way to deal
6299   // with optional operands like this in the matcher table.
6300 
6301   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
6302   // another does not. Specifically, the MOVW instruction does not. So we
6303   // special case it here and remove the defaulted (non-setting) cc_out
6304   // operand if that's the instruction we're trying to match.
6305   //
6306   // We do this as post-processing of the explicit operands rather than just
6307   // conditionally adding the cc_out in the first place because we need
6308   // to check the type of the parsed immediate operand.
6309   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
6310       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
6311       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
6312       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6313     return true;
6314 
6315   // Register-register 'add' for thumb does not have a cc_out operand
6316   // when there are only two register operands.
6317   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
6318       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6319       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6320       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6321     return true;
6322   // Register-register 'add' for thumb does not have a cc_out operand
6323   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
6324   // have to check the immediate range here since Thumb2 has a variant
6325   // that can handle a different range and has a cc_out operand.
6326   if (((isThumb() && Mnemonic == "add") ||
6327        (isThumbTwo() && Mnemonic == "sub")) &&
6328       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6329       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6330       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
6331       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6332       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
6333        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
6334     return true;
6335   // For Thumb2, add/sub immediate does not have a cc_out operand for the
6336   // imm0_4095 variant. That's the least-preferred variant when
6337   // selecting via the generic "add" mnemonic, so to know that we
6338   // should remove the cc_out operand, we have to explicitly check that
6339   // it's not one of the other variants. Ugh.
6340   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6341       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6342       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6343       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6344     // Nest conditions rather than one big 'if' statement for readability.
6345     //
6346     // If both registers are low, we're in an IT block, and the immediate is
6347     // in range, we should use encoding T1 instead, which has a cc_out.
6348     if (inITBlock() &&
6349         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
6350         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
6351         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
6352       return false;
6353     // Check against T3. If the second register is the PC, this is an
6354     // alternate form of ADR, which uses encoding T4, so check for that too.
6355     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
6356         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
6357       return false;
6358 
6359     // Otherwise, we use encoding T4, which does not have a cc_out
6360     // operand.
6361     return true;
6362   }
6363 
6364   // The thumb2 multiply instruction doesn't have a CCOut register, so
6365   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
6366   // use the 16-bit encoding or not.
6367   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
6368       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6369       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6370       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6371       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
6372       // If the registers aren't low regs, the destination reg isn't the
6373       // same as one of the source regs, or the cc_out operand is zero
6374       // outside of an IT block, we have to use the 32-bit encoding, so
6375       // remove the cc_out operand.
6376       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6377        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6378        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
6379        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6380                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
6381                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6382                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
6383     return true;
6384 
6385   // Also check the 'mul' syntax variant that doesn't specify an explicit
6386   // destination register.
6387   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
6388       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6389       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6390       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6391       // If the registers aren't low regs  or the cc_out operand is zero
6392       // outside of an IT block, we have to use the 32-bit encoding, so
6393       // remove the cc_out operand.
6394       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6395        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6396        !inITBlock()))
6397     return true;
6398 
6399   // Register-register 'add/sub' for thumb does not have a cc_out operand
6400   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
6401   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
6402   // right, this will result in better diagnostics (which operand is off)
6403   // anyway.
6404   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
6405       (Operands.size() == 5 || Operands.size() == 6) &&
6406       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6407       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
6408       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6409       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
6410        (Operands.size() == 6 &&
6411         static_cast<ARMOperand &>(*Operands[5]).isImm())))
6412     return true;
6413 
6414   return false;
6415 }
6416 
6417 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
6418                                               OperandVector &Operands) {
6419   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
6420   unsigned RegIdx = 3;
6421   if ((((Mnemonic == "vrintz" || Mnemonic == "vrintx") && !hasMVE()) ||
6422       Mnemonic == "vrintr") &&
6423       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
6424        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
6425     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6426         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
6427          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
6428       RegIdx = 4;
6429 
6430     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
6431         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6432              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
6433          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6434              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
6435       return true;
6436   }
6437   return false;
6438 }
6439 
6440 bool ARMAsmParser::shouldOmitVectorPredicateOperand(StringRef Mnemonic,
6441                                                     OperandVector &Operands) {
6442   if (!hasMVE() || Operands.size() < 3)
6443     return true;
6444 
6445   if (Mnemonic.startswith("vld2") || Mnemonic.startswith("vld4") ||
6446       Mnemonic.startswith("vst2") || Mnemonic.startswith("vst4"))
6447     return true;
6448 
6449   if (Mnemonic.startswith("vctp"))
6450     return false;
6451 
6452   if (Mnemonic.startswith("vmov") &&
6453       !(Mnemonic.startswith("vmovl") || Mnemonic.startswith("vmovn") ||
6454         Mnemonic.startswith("vmovx"))) {
6455     for (auto &Operand : Operands) {
6456       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6457           ((*Operand).isReg() &&
6458            (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
6459              (*Operand).getReg()) ||
6460             ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6461               (*Operand).getReg())))) {
6462         return true;
6463       }
6464     }
6465     return false;
6466   } else {
6467     for (auto &Operand : Operands) {
6468       // We check the larger class QPR instead of just the legal class
6469       // MQPR, to more accurately report errors when using Q registers
6470       // outside of the allowed range.
6471       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6472           (Operand->isReg() &&
6473            (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6474              Operand->getReg()))))
6475         return false;
6476     }
6477     return true;
6478   }
6479 }
6480 
6481 static bool isDataTypeToken(StringRef Tok) {
6482   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
6483     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6484     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6485     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6486     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6487     Tok == ".f" || Tok == ".d";
6488 }
6489 
6490 // FIXME: This bit should probably be handled via an explicit match class
6491 // in the .td files that matches the suffix instead of having it be
6492 // a literal string token the way it is now.
6493 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6494   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6495 }
6496 
6497 static void applyMnemonicAliases(StringRef &Mnemonic,
6498                                  const FeatureBitset &Features,
6499                                  unsigned VariantID);
6500 
6501 // The GNU assembler has aliases of ldrd and strd with the second register
6502 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6503 //
6504 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6505 // the assmebly parser could then generate confusing diagnostics refering to
6506 // it. If we do find anything that prevents us from doing the transformation we
6507 // bail out, and let the assembly parser report an error on the instruction as
6508 // it is written.
6509 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6510                                      OperandVector &Operands) {
6511   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6512     return;
6513   if (Operands.size() < 4)
6514     return;
6515 
6516   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6517   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6518 
6519   if (!Op2.isReg())
6520     return;
6521   if (!Op3.isMem())
6522     return;
6523 
6524   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6525   if (!GPR.contains(Op2.getReg()))
6526     return;
6527 
6528   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6529   if (!isThumb() && (RtEncoding & 1)) {
6530     // In ARM mode, the registers must be from an aligned pair, this
6531     // restriction does not apply in Thumb mode.
6532     return;
6533   }
6534   if (Op2.getReg() == ARM::PC)
6535     return;
6536   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6537   if (!PairedReg || PairedReg == ARM::PC ||
6538       (PairedReg == ARM::SP && !hasV8Ops()))
6539     return;
6540 
6541   Operands.insert(
6542       Operands.begin() + 3,
6543       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6544 }
6545 
6546 /// Parse an arm instruction mnemonic followed by its operands.
6547 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6548                                     SMLoc NameLoc, OperandVector &Operands) {
6549   MCAsmParser &Parser = getParser();
6550 
6551   // Apply mnemonic aliases before doing anything else, as the destination
6552   // mnemonic may include suffices and we want to handle them normally.
6553   // The generic tblgen'erated code does this later, at the start of
6554   // MatchInstructionImpl(), but that's too late for aliases that include
6555   // any sort of suffix.
6556   const FeatureBitset &AvailableFeatures = getAvailableFeatures();
6557   unsigned AssemblerDialect = getParser().getAssemblerDialect();
6558   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
6559 
6560   // First check for the ARM-specific .req directive.
6561   if (Parser.getTok().is(AsmToken::Identifier) &&
6562       Parser.getTok().getIdentifier() == ".req") {
6563     parseDirectiveReq(Name, NameLoc);
6564     // We always return 'error' for this, as we're done with this
6565     // statement and don't need to match the 'instruction."
6566     return true;
6567   }
6568 
6569   // Create the leading tokens for the mnemonic, split by '.' characters.
6570   size_t Start = 0, Next = Name.find('.');
6571   StringRef Mnemonic = Name.slice(Start, Next);
6572   StringRef ExtraToken = Name.slice(Next, Name.find(' ', Next + 1));
6573 
6574   // Split out the predication code and carry setting flag from the mnemonic.
6575   unsigned PredicationCode;
6576   unsigned VPTPredicationCode;
6577   unsigned ProcessorIMod;
6578   bool CarrySetting;
6579   StringRef ITMask;
6580   Mnemonic = splitMnemonic(Mnemonic, ExtraToken, PredicationCode, VPTPredicationCode,
6581                            CarrySetting, ProcessorIMod, ITMask);
6582 
6583   // In Thumb1, only the branch (B) instruction can be predicated.
6584   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
6585     return Error(NameLoc, "conditional execution not supported in Thumb1");
6586   }
6587 
6588   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
6589 
6590   // Handle the mask for IT and VPT instructions. In ARMOperand and
6591   // MCOperand, this is stored in a format independent of the
6592   // condition code: the lowest set bit indicates the end of the
6593   // encoding, and above that, a 1 bit indicates 'else', and an 0
6594   // indicates 'then'. E.g.
6595   //    IT    -> 1000
6596   //    ITx   -> x100    (ITT -> 0100, ITE -> 1100)
6597   //    ITxy  -> xy10    (e.g. ITET -> 1010)
6598   //    ITxyz -> xyz1    (e.g. ITEET -> 1101)
6599   if (Mnemonic == "it" || Mnemonic.startswith("vpt") ||
6600       Mnemonic.startswith("vpst")) {
6601     SMLoc Loc = Mnemonic == "it"  ? SMLoc::getFromPointer(NameLoc.getPointer() + 2) :
6602                 Mnemonic == "vpt" ? SMLoc::getFromPointer(NameLoc.getPointer() + 3) :
6603                                     SMLoc::getFromPointer(NameLoc.getPointer() + 4);
6604     if (ITMask.size() > 3) {
6605       if (Mnemonic == "it")
6606         return Error(Loc, "too many conditions on IT instruction");
6607       return Error(Loc, "too many conditions on VPT instruction");
6608     }
6609     unsigned Mask = 8;
6610     for (unsigned i = ITMask.size(); i != 0; --i) {
6611       char pos = ITMask[i - 1];
6612       if (pos != 't' && pos != 'e') {
6613         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
6614       }
6615       Mask >>= 1;
6616       if (ITMask[i - 1] == 'e')
6617         Mask |= 8;
6618     }
6619     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
6620   }
6621 
6622   // FIXME: This is all a pretty gross hack. We should automatically handle
6623   // optional operands like this via tblgen.
6624 
6625   // Next, add the CCOut and ConditionCode operands, if needed.
6626   //
6627   // For mnemonics which can ever incorporate a carry setting bit or predication
6628   // code, our matching model involves us always generating CCOut and
6629   // ConditionCode operands to match the mnemonic "as written" and then we let
6630   // the matcher deal with finding the right instruction or generating an
6631   // appropriate error.
6632   bool CanAcceptCarrySet, CanAcceptPredicationCode, CanAcceptVPTPredicationCode;
6633   getMnemonicAcceptInfo(Mnemonic, ExtraToken, Name, CanAcceptCarrySet,
6634                         CanAcceptPredicationCode, CanAcceptVPTPredicationCode);
6635 
6636   // If we had a carry-set on an instruction that can't do that, issue an
6637   // error.
6638   if (!CanAcceptCarrySet && CarrySetting) {
6639     return Error(NameLoc, "instruction '" + Mnemonic +
6640                  "' can not set flags, but 's' suffix specified");
6641   }
6642   // If we had a predication code on an instruction that can't do that, issue an
6643   // error.
6644   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6645     return Error(NameLoc, "instruction '" + Mnemonic +
6646                  "' is not predicable, but condition code specified");
6647   }
6648 
6649   // If we had a VPT predication code on an instruction that can't do that, issue an
6650   // error.
6651   if (!CanAcceptVPTPredicationCode && VPTPredicationCode != ARMVCC::None) {
6652     return Error(NameLoc, "instruction '" + Mnemonic +
6653                  "' is not VPT predicable, but VPT code T/E is specified");
6654   }
6655 
6656   // Add the carry setting operand, if necessary.
6657   if (CanAcceptCarrySet) {
6658     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6659     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6660                                                Loc));
6661   }
6662 
6663   // Add the predication code operand, if necessary.
6664   if (CanAcceptPredicationCode) {
6665     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6666                                       CarrySetting);
6667     Operands.push_back(ARMOperand::CreateCondCode(
6668                        ARMCC::CondCodes(PredicationCode), Loc));
6669   }
6670 
6671   // Add the VPT predication code operand, if necessary.
6672   // FIXME: We don't add them for the instructions filtered below as these can
6673   // have custom operands which need special parsing.  This parsing requires
6674   // the operand to be in the same place in the OperandVector as their
6675   // definition in tblgen.  Since these instructions may also have the
6676   // scalar predication operand we do not add the vector one and leave until
6677   // now to fix it up.
6678   if (CanAcceptVPTPredicationCode && Mnemonic != "vmov" &&
6679       !Mnemonic.startswith("vcmp") &&
6680       !(Mnemonic.startswith("vcvt") && Mnemonic != "vcvta" &&
6681         Mnemonic != "vcvtn" && Mnemonic != "vcvtp" && Mnemonic != "vcvtm")) {
6682     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6683                                       CarrySetting);
6684     Operands.push_back(ARMOperand::CreateVPTPred(
6685                          ARMVCC::VPTCodes(VPTPredicationCode), Loc));
6686   }
6687 
6688   // Add the processor imod operand, if necessary.
6689   if (ProcessorIMod) {
6690     Operands.push_back(ARMOperand::CreateImm(
6691           MCConstantExpr::create(ProcessorIMod, getContext()),
6692                                  NameLoc, NameLoc));
6693   } else if (Mnemonic == "cps" && isMClass()) {
6694     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6695   }
6696 
6697   // Add the remaining tokens in the mnemonic.
6698   while (Next != StringRef::npos) {
6699     Start = Next;
6700     Next = Name.find('.', Start + 1);
6701     ExtraToken = Name.slice(Start, Next);
6702 
6703     // Some NEON instructions have an optional datatype suffix that is
6704     // completely ignored. Check for that.
6705     if (isDataTypeToken(ExtraToken) &&
6706         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6707       continue;
6708 
6709     // For for ARM mode generate an error if the .n qualifier is used.
6710     if (ExtraToken == ".n" && !isThumb()) {
6711       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6712       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6713                    "arm mode");
6714     }
6715 
6716     // The .n qualifier is always discarded as that is what the tables
6717     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6718     // so discard it to avoid errors that can be caused by the matcher.
6719     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6720       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6721       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6722     }
6723   }
6724 
6725   // Read the remaining operands.
6726   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6727     // Read the first operand.
6728     if (parseOperand(Operands, Mnemonic)) {
6729       return true;
6730     }
6731 
6732     while (parseOptionalToken(AsmToken::Comma)) {
6733       // Parse and remember the operand.
6734       if (parseOperand(Operands, Mnemonic)) {
6735         return true;
6736       }
6737     }
6738   }
6739 
6740   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6741     return true;
6742 
6743   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6744 
6745   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6746   // do and don't have a cc_out optional-def operand. With some spot-checks
6747   // of the operand list, we can figure out which variant we're trying to
6748   // parse and adjust accordingly before actually matching. We shouldn't ever
6749   // try to remove a cc_out operand that was explicitly set on the
6750   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6751   // table driven matcher doesn't fit well with the ARM instruction set.
6752   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6753     Operands.erase(Operands.begin() + 1);
6754 
6755   // Some instructions have the same mnemonic, but don't always
6756   // have a predicate. Distinguish them here and delete the
6757   // appropriate predicate if needed.  This could be either the scalar
6758   // predication code or the vector predication code.
6759   if (PredicationCode == ARMCC::AL &&
6760       shouldOmitPredicateOperand(Mnemonic, Operands))
6761     Operands.erase(Operands.begin() + 1);
6762 
6763 
6764   if (hasMVE()) {
6765     if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands) &&
6766         Mnemonic == "vmov" && PredicationCode == ARMCC::LT) {
6767       // Very nasty hack to deal with the vector predicated variant of vmovlt
6768       // the scalar predicated vmov with condition 'lt'.  We can not tell them
6769       // apart until we have parsed their operands.
6770       Operands.erase(Operands.begin() + 1);
6771       Operands.erase(Operands.begin());
6772       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
6773       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
6774                                          Mnemonic.size() - 1 + CarrySetting);
6775       Operands.insert(Operands.begin(),
6776                       ARMOperand::CreateVPTPred(ARMVCC::None, PLoc));
6777       Operands.insert(Operands.begin(),
6778                       ARMOperand::CreateToken(StringRef("vmovlt"), MLoc));
6779     } else if (Mnemonic == "vcvt" && PredicationCode == ARMCC::NE &&
6780                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
6781       // Another nasty hack to deal with the ambiguity between vcvt with scalar
6782       // predication 'ne' and vcvtn with vector predication 'e'.  As above we
6783       // can only distinguish between the two after we have parsed their
6784       // operands.
6785       Operands.erase(Operands.begin() + 1);
6786       Operands.erase(Operands.begin());
6787       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
6788       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
6789                                          Mnemonic.size() - 1 + CarrySetting);
6790       Operands.insert(Operands.begin(),
6791                       ARMOperand::CreateVPTPred(ARMVCC::Else, PLoc));
6792       Operands.insert(Operands.begin(),
6793                       ARMOperand::CreateToken(StringRef("vcvtn"), MLoc));
6794     } else if (Mnemonic == "vmul" && PredicationCode == ARMCC::LT &&
6795                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
6796       // Another hack, this time to distinguish between scalar predicated vmul
6797       // with 'lt' predication code and the vector instruction vmullt with
6798       // vector predication code "none"
6799       Operands.erase(Operands.begin() + 1);
6800       Operands.erase(Operands.begin());
6801       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
6802       Operands.insert(Operands.begin(),
6803                       ARMOperand::CreateToken(StringRef("vmullt"), MLoc));
6804     }
6805     // For vmov and vcmp, as mentioned earlier, we did not add the vector
6806     // predication code, since these may contain operands that require
6807     // special parsing.  So now we have to see if they require vector
6808     // predication and replace the scalar one with the vector predication
6809     // operand if that is the case.
6810     else if (Mnemonic == "vmov" || Mnemonic.startswith("vcmp") ||
6811              (Mnemonic.startswith("vcvt") && !Mnemonic.startswith("vcvta") &&
6812               !Mnemonic.startswith("vcvtn") && !Mnemonic.startswith("vcvtp") &&
6813               !Mnemonic.startswith("vcvtm"))) {
6814       if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
6815         // We could not split the vector predicate off vcvt because it might
6816         // have been the scalar vcvtt instruction.  Now we know its a vector
6817         // instruction, we still need to check whether its the vector
6818         // predicated vcvt with 'Then' predication or the vector vcvtt.  We can
6819         // distinguish the two based on the suffixes, if it is any of
6820         // ".f16.f32", ".f32.f16", ".f16.f64" or ".f64.f16" then it is the vcvtt.
6821         if (Mnemonic.startswith("vcvtt") && Operands.size() >= 4) {
6822           auto Sz1 = static_cast<ARMOperand &>(*Operands[2]);
6823           auto Sz2 = static_cast<ARMOperand &>(*Operands[3]);
6824           if (!(Sz1.isToken() && Sz1.getToken().startswith(".f") &&
6825               Sz2.isToken() && Sz2.getToken().startswith(".f"))) {
6826             Operands.erase(Operands.begin());
6827             SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
6828             VPTPredicationCode = ARMVCC::Then;
6829 
6830             Mnemonic = Mnemonic.substr(0, 4);
6831             Operands.insert(Operands.begin(),
6832                             ARMOperand::CreateToken(Mnemonic, MLoc));
6833           }
6834         }
6835         Operands.erase(Operands.begin() + 1);
6836         SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
6837                                           Mnemonic.size() + CarrySetting);
6838         Operands.insert(Operands.begin() + 1,
6839                         ARMOperand::CreateVPTPred(
6840                             ARMVCC::VPTCodes(VPTPredicationCode), PLoc));
6841       }
6842     } else if (CanAcceptVPTPredicationCode) {
6843       // For all other instructions, make sure only one of the two
6844       // predication operands is left behind, depending on whether we should
6845       // use the vector predication.
6846       if (shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
6847         if (CanAcceptPredicationCode)
6848           Operands.erase(Operands.begin() + 2);
6849         else
6850           Operands.erase(Operands.begin() + 1);
6851       } else if (CanAcceptPredicationCode && PredicationCode == ARMCC::AL) {
6852         Operands.erase(Operands.begin() + 1);
6853       }
6854     }
6855   }
6856 
6857   if (VPTPredicationCode != ARMVCC::None) {
6858     bool usedVPTPredicationCode = false;
6859     for (unsigned I = 1; I < Operands.size(); ++I)
6860       if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
6861         usedVPTPredicationCode = true;
6862     if (!usedVPTPredicationCode) {
6863       // If we have a VPT predication code and we haven't just turned it
6864       // into an operand, then it was a mistake for splitMnemonic to
6865       // separate it from the rest of the mnemonic in the first place,
6866       // and this may lead to wrong disassembly (e.g. scalar floating
6867       // point VCMPE is actually a different instruction from VCMP, so
6868       // we mustn't treat them the same). In that situation, glue it
6869       // back on.
6870       Mnemonic = Name.slice(0, Mnemonic.size() + 1);
6871       Operands.erase(Operands.begin());
6872       Operands.insert(Operands.begin(),
6873                       ARMOperand::CreateToken(Mnemonic, NameLoc));
6874     }
6875   }
6876 
6877     // ARM mode 'blx' need special handling, as the register operand version
6878     // is predicable, but the label operand version is not. So, we can't rely
6879     // on the Mnemonic based checking to correctly figure out when to put
6880     // a k_CondCode operand in the list. If we're trying to match the label
6881     // version, remove the k_CondCode operand here.
6882     if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6883         static_cast<ARMOperand &>(*Operands[2]).isImm())
6884       Operands.erase(Operands.begin() + 1);
6885 
6886     // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6887     // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6888     // a single GPRPair reg operand is used in the .td file to replace the two
6889     // GPRs. However, when parsing from asm, the two GRPs cannot be
6890     // automatically
6891     // expressed as a GPRPair, so we have to manually merge them.
6892     // FIXME: We would really like to be able to tablegen'erate this.
6893     if (!isThumb() && Operands.size() > 4 &&
6894         (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6895          Mnemonic == "stlexd")) {
6896       bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6897       unsigned Idx = isLoad ? 2 : 3;
6898       ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6899       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6900 
6901       const MCRegisterClass &MRC = MRI->getRegClass(ARM::GPRRegClassID);
6902       // Adjust only if Op1 and Op2 are GPRs.
6903       if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6904           MRC.contains(Op2.getReg())) {
6905         unsigned Reg1 = Op1.getReg();
6906         unsigned Reg2 = Op2.getReg();
6907         unsigned Rt = MRI->getEncodingValue(Reg1);
6908         unsigned Rt2 = MRI->getEncodingValue(Reg2);
6909 
6910         // Rt2 must be Rt + 1 and Rt must be even.
6911         if (Rt + 1 != Rt2 || (Rt & 1)) {
6912           return Error(Op2.getStartLoc(),
6913                        isLoad ? "destination operands must be sequential"
6914                               : "source operands must be sequential");
6915         }
6916         unsigned NewReg = MRI->getMatchingSuperReg(
6917             Reg1, ARM::gsub_0, &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6918         Operands[Idx] =
6919             ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6920         Operands.erase(Operands.begin() + Idx + 1);
6921       }
6922   }
6923 
6924   // GNU Assembler extension (compatibility).
6925   fixupGNULDRDAlias(Mnemonic, Operands);
6926 
6927   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6928   // does not fit with other "subs" and tblgen.
6929   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6930   // so the Mnemonic is the original name "subs" and delete the predicate
6931   // operand so it will match the table entry.
6932   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6933       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6934       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6935       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6936       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6937       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6938     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6939     Operands.erase(Operands.begin() + 1);
6940   }
6941   return false;
6942 }
6943 
6944 // Validate context-sensitive operand constraints.
6945 
6946 // return 'true' if register list contains non-low GPR registers,
6947 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6948 // 'containsReg' to true.
6949 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6950                                  unsigned Reg, unsigned HiReg,
6951                                  bool &containsReg) {
6952   containsReg = false;
6953   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6954     unsigned OpReg = Inst.getOperand(i).getReg();
6955     if (OpReg == Reg)
6956       containsReg = true;
6957     // Anything other than a low register isn't legal here.
6958     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6959       return true;
6960   }
6961   return false;
6962 }
6963 
6964 // Check if the specified regisgter is in the register list of the inst,
6965 // starting at the indicated operand number.
6966 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6967   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6968     unsigned OpReg = Inst.getOperand(i).getReg();
6969     if (OpReg == Reg)
6970       return true;
6971   }
6972   return false;
6973 }
6974 
6975 // Return true if instruction has the interesting property of being
6976 // allowed in IT blocks, but not being predicable.
6977 static bool instIsBreakpoint(const MCInst &Inst) {
6978     return Inst.getOpcode() == ARM::tBKPT ||
6979            Inst.getOpcode() == ARM::BKPT ||
6980            Inst.getOpcode() == ARM::tHLT ||
6981            Inst.getOpcode() == ARM::HLT;
6982 }
6983 
6984 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6985                                        const OperandVector &Operands,
6986                                        unsigned ListNo, bool IsARPop) {
6987   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6988   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6989 
6990   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6991   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6992   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6993 
6994   if (!IsARPop && ListContainsSP)
6995     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6996                  "SP may not be in the register list");
6997   else if (ListContainsPC && ListContainsLR)
6998     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6999                  "PC and LR may not be in the register list simultaneously");
7000   return false;
7001 }
7002 
7003 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
7004                                        const OperandVector &Operands,
7005                                        unsigned ListNo) {
7006   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7007   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7008 
7009   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7010   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7011 
7012   if (ListContainsSP && ListContainsPC)
7013     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7014                  "SP and PC may not be in the register list");
7015   else if (ListContainsSP)
7016     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7017                  "SP may not be in the register list");
7018   else if (ListContainsPC)
7019     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7020                  "PC may not be in the register list");
7021   return false;
7022 }
7023 
7024 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
7025                                     const OperandVector &Operands,
7026                                     bool Load, bool ARMMode, bool Writeback) {
7027   unsigned RtIndex = Load || !Writeback ? 0 : 1;
7028   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
7029   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
7030 
7031   if (ARMMode) {
7032     // Rt can't be R14.
7033     if (Rt == 14)
7034       return Error(Operands[3]->getStartLoc(),
7035                   "Rt can't be R14");
7036 
7037     // Rt must be even-numbered.
7038     if ((Rt & 1) == 1)
7039       return Error(Operands[3]->getStartLoc(),
7040                    "Rt must be even-numbered");
7041 
7042     // Rt2 must be Rt + 1.
7043     if (Rt2 != Rt + 1) {
7044       if (Load)
7045         return Error(Operands[3]->getStartLoc(),
7046                      "destination operands must be sequential");
7047       else
7048         return Error(Operands[3]->getStartLoc(),
7049                      "source operands must be sequential");
7050     }
7051 
7052     // FIXME: Diagnose m == 15
7053     // FIXME: Diagnose ldrd with m == t || m == t2.
7054   }
7055 
7056   if (!ARMMode && Load) {
7057     if (Rt2 == Rt)
7058       return Error(Operands[3]->getStartLoc(),
7059                    "destination operands can't be identical");
7060   }
7061 
7062   if (Writeback) {
7063     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7064 
7065     if (Rn == Rt || Rn == Rt2) {
7066       if (Load)
7067         return Error(Operands[3]->getStartLoc(),
7068                      "base register needs to be different from destination "
7069                      "registers");
7070       else
7071         return Error(Operands[3]->getStartLoc(),
7072                      "source register and base register can't be identical");
7073     }
7074 
7075     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
7076     // (Except the immediate form of ldrd?)
7077   }
7078 
7079   return false;
7080 }
7081 
7082 static int findFirstVectorPredOperandIdx(const MCInstrDesc &MCID) {
7083   for (unsigned i = 0; i < MCID.NumOperands; ++i) {
7084     if (ARM::isVpred(MCID.OpInfo[i].OperandType))
7085       return i;
7086   }
7087   return -1;
7088 }
7089 
7090 static bool isVectorPredicable(const MCInstrDesc &MCID) {
7091   return findFirstVectorPredOperandIdx(MCID) != -1;
7092 }
7093 
7094 // FIXME: We would really like to be able to tablegen'erate this.
7095 bool ARMAsmParser::validateInstruction(MCInst &Inst,
7096                                        const OperandVector &Operands) {
7097   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
7098   SMLoc Loc = Operands[0]->getStartLoc();
7099 
7100   // Check the IT block state first.
7101   // NOTE: BKPT and HLT instructions have the interesting property of being
7102   // allowed in IT blocks, but not being predicable. They just always execute.
7103   if (inITBlock() && !instIsBreakpoint(Inst)) {
7104     // The instruction must be predicable.
7105     if (!MCID.isPredicable())
7106       return Error(Loc, "instructions in IT block must be predicable");
7107     ARMCC::CondCodes Cond = ARMCC::CondCodes(
7108         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
7109     if (Cond != currentITCond()) {
7110       // Find the condition code Operand to get its SMLoc information.
7111       SMLoc CondLoc;
7112       for (unsigned I = 1; I < Operands.size(); ++I)
7113         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
7114           CondLoc = Operands[I]->getStartLoc();
7115       return Error(CondLoc, "incorrect condition in IT block; got '" +
7116                                 StringRef(ARMCondCodeToString(Cond)) +
7117                                 "', but expected '" +
7118                                 ARMCondCodeToString(currentITCond()) + "'");
7119     }
7120   // Check for non-'al' condition codes outside of the IT block.
7121   } else if (isThumbTwo() && MCID.isPredicable() &&
7122              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7123              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
7124              Inst.getOpcode() != ARM::t2Bcc &&
7125              Inst.getOpcode() != ARM::t2BFic) {
7126     return Error(Loc, "predicated instructions must be in IT block");
7127   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
7128              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7129                  ARMCC::AL) {
7130     return Warning(Loc, "predicated instructions should be in IT block");
7131   } else if (!MCID.isPredicable()) {
7132     // Check the instruction doesn't have a predicate operand anyway
7133     // that it's not allowed to use. Sometimes this happens in order
7134     // to keep instructions the same shape even though one cannot
7135     // legally be predicated, e.g. vmul.f16 vs vmul.f32.
7136     for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
7137       if (MCID.OpInfo[i].isPredicate()) {
7138         if (Inst.getOperand(i).getImm() != ARMCC::AL)
7139           return Error(Loc, "instruction is not predicable");
7140         break;
7141       }
7142     }
7143   }
7144 
7145   // PC-setting instructions in an IT block, but not the last instruction of
7146   // the block, are UNPREDICTABLE.
7147   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
7148     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
7149   }
7150 
7151   if (inVPTBlock() && !instIsBreakpoint(Inst)) {
7152     unsigned Bit = extractITMaskBit(VPTState.Mask, VPTState.CurPosition);
7153     if (!isVectorPredicable(MCID))
7154       return Error(Loc, "instruction in VPT block must be predicable");
7155     unsigned Pred = Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm();
7156     unsigned VPTPred = Bit ? ARMVCC::Else : ARMVCC::Then;
7157     if (Pred != VPTPred) {
7158       SMLoc PredLoc;
7159       for (unsigned I = 1; I < Operands.size(); ++I)
7160         if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7161           PredLoc = Operands[I]->getStartLoc();
7162       return Error(PredLoc, "incorrect predication in VPT block; got '" +
7163                    StringRef(ARMVPTPredToString(ARMVCC::VPTCodes(Pred))) +
7164                    "', but expected '" +
7165                    ARMVPTPredToString(ARMVCC::VPTCodes(VPTPred)) + "'");
7166     }
7167   }
7168   else if (isVectorPredicable(MCID) &&
7169            Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm() !=
7170            ARMVCC::None)
7171     return Error(Loc, "VPT predicated instructions must be in VPT block");
7172 
7173   const unsigned Opcode = Inst.getOpcode();
7174   switch (Opcode) {
7175   case ARM::t2IT: {
7176     // Encoding is unpredictable if it ever results in a notional 'NV'
7177     // predicate. Since we don't parse 'NV' directly this means an 'AL'
7178     // predicate with an "else" mask bit.
7179     unsigned Cond = Inst.getOperand(0).getImm();
7180     unsigned Mask = Inst.getOperand(1).getImm();
7181 
7182     // Conditions only allowing a 't' are those with no set bit except
7183     // the lowest-order one that indicates the end of the sequence. In
7184     // other words, powers of 2.
7185     if (Cond == ARMCC::AL && countPopulation(Mask) != 1)
7186       return Error(Loc, "unpredictable IT predicate sequence");
7187     break;
7188   }
7189   case ARM::LDRD:
7190     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7191                          /*Writeback*/false))
7192       return true;
7193     break;
7194   case ARM::LDRD_PRE:
7195   case ARM::LDRD_POST:
7196     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7197                          /*Writeback*/true))
7198       return true;
7199     break;
7200   case ARM::t2LDRDi8:
7201     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7202                          /*Writeback*/false))
7203       return true;
7204     break;
7205   case ARM::t2LDRD_PRE:
7206   case ARM::t2LDRD_POST:
7207     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7208                          /*Writeback*/true))
7209       return true;
7210     break;
7211   case ARM::t2BXJ: {
7212     const unsigned RmReg = Inst.getOperand(0).getReg();
7213     // Rm = SP is no longer unpredictable in v8-A
7214     if (RmReg == ARM::SP && !hasV8Ops())
7215       return Error(Operands[2]->getStartLoc(),
7216                    "r13 (SP) is an unpredictable operand to BXJ");
7217     return false;
7218   }
7219   case ARM::STRD:
7220     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7221                          /*Writeback*/false))
7222       return true;
7223     break;
7224   case ARM::STRD_PRE:
7225   case ARM::STRD_POST:
7226     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7227                          /*Writeback*/true))
7228       return true;
7229     break;
7230   case ARM::t2STRD_PRE:
7231   case ARM::t2STRD_POST:
7232     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
7233                          /*Writeback*/true))
7234       return true;
7235     break;
7236   case ARM::STR_PRE_IMM:
7237   case ARM::STR_PRE_REG:
7238   case ARM::t2STR_PRE:
7239   case ARM::STR_POST_IMM:
7240   case ARM::STR_POST_REG:
7241   case ARM::t2STR_POST:
7242   case ARM::STRH_PRE:
7243   case ARM::t2STRH_PRE:
7244   case ARM::STRH_POST:
7245   case ARM::t2STRH_POST:
7246   case ARM::STRB_PRE_IMM:
7247   case ARM::STRB_PRE_REG:
7248   case ARM::t2STRB_PRE:
7249   case ARM::STRB_POST_IMM:
7250   case ARM::STRB_POST_REG:
7251   case ARM::t2STRB_POST: {
7252     // Rt must be different from Rn.
7253     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7254     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7255 
7256     if (Rt == Rn)
7257       return Error(Operands[3]->getStartLoc(),
7258                    "source register and base register can't be identical");
7259     return false;
7260   }
7261   case ARM::LDR_PRE_IMM:
7262   case ARM::LDR_PRE_REG:
7263   case ARM::t2LDR_PRE:
7264   case ARM::LDR_POST_IMM:
7265   case ARM::LDR_POST_REG:
7266   case ARM::t2LDR_POST:
7267   case ARM::LDRH_PRE:
7268   case ARM::t2LDRH_PRE:
7269   case ARM::LDRH_POST:
7270   case ARM::t2LDRH_POST:
7271   case ARM::LDRSH_PRE:
7272   case ARM::t2LDRSH_PRE:
7273   case ARM::LDRSH_POST:
7274   case ARM::t2LDRSH_POST:
7275   case ARM::LDRB_PRE_IMM:
7276   case ARM::LDRB_PRE_REG:
7277   case ARM::t2LDRB_PRE:
7278   case ARM::LDRB_POST_IMM:
7279   case ARM::LDRB_POST_REG:
7280   case ARM::t2LDRB_POST:
7281   case ARM::LDRSB_PRE:
7282   case ARM::t2LDRSB_PRE:
7283   case ARM::LDRSB_POST:
7284   case ARM::t2LDRSB_POST: {
7285     // Rt must be different from Rn.
7286     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7287     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7288 
7289     if (Rt == Rn)
7290       return Error(Operands[3]->getStartLoc(),
7291                    "destination register and base register can't be identical");
7292     return false;
7293   }
7294   case ARM::SBFX:
7295   case ARM::t2SBFX:
7296   case ARM::UBFX:
7297   case ARM::t2UBFX: {
7298     // Width must be in range [1, 32-lsb].
7299     unsigned LSB = Inst.getOperand(2).getImm();
7300     unsigned Widthm1 = Inst.getOperand(3).getImm();
7301     if (Widthm1 >= 32 - LSB)
7302       return Error(Operands[5]->getStartLoc(),
7303                    "bitfield width must be in range [1,32-lsb]");
7304     return false;
7305   }
7306   // Notionally handles ARM::tLDMIA_UPD too.
7307   case ARM::tLDMIA: {
7308     // If we're parsing Thumb2, the .w variant is available and handles
7309     // most cases that are normally illegal for a Thumb1 LDM instruction.
7310     // We'll make the transformation in processInstruction() if necessary.
7311     //
7312     // Thumb LDM instructions are writeback iff the base register is not
7313     // in the register list.
7314     unsigned Rn = Inst.getOperand(0).getReg();
7315     bool HasWritebackToken =
7316         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7317          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
7318     bool ListContainsBase;
7319     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
7320       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
7321                    "registers must be in range r0-r7");
7322     // If we should have writeback, then there should be a '!' token.
7323     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
7324       return Error(Operands[2]->getStartLoc(),
7325                    "writeback operator '!' expected");
7326     // If we should not have writeback, there must not be a '!'. This is
7327     // true even for the 32-bit wide encodings.
7328     if (ListContainsBase && HasWritebackToken)
7329       return Error(Operands[3]->getStartLoc(),
7330                    "writeback operator '!' not allowed when base register "
7331                    "in register list");
7332 
7333     if (validatetLDMRegList(Inst, Operands, 3))
7334       return true;
7335     break;
7336   }
7337   case ARM::LDMIA_UPD:
7338   case ARM::LDMDB_UPD:
7339   case ARM::LDMIB_UPD:
7340   case ARM::LDMDA_UPD:
7341     // ARM variants loading and updating the same register are only officially
7342     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
7343     if (!hasV7Ops())
7344       break;
7345     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7346       return Error(Operands.back()->getStartLoc(),
7347                    "writeback register not allowed in register list");
7348     break;
7349   case ARM::t2LDMIA:
7350   case ARM::t2LDMDB:
7351     if (validatetLDMRegList(Inst, Operands, 3))
7352       return true;
7353     break;
7354   case ARM::t2STMIA:
7355   case ARM::t2STMDB:
7356     if (validatetSTMRegList(Inst, Operands, 3))
7357       return true;
7358     break;
7359   case ARM::t2LDMIA_UPD:
7360   case ARM::t2LDMDB_UPD:
7361   case ARM::t2STMIA_UPD:
7362   case ARM::t2STMDB_UPD:
7363     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7364       return Error(Operands.back()->getStartLoc(),
7365                    "writeback register not allowed in register list");
7366 
7367     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
7368       if (validatetLDMRegList(Inst, Operands, 3))
7369         return true;
7370     } else {
7371       if (validatetSTMRegList(Inst, Operands, 3))
7372         return true;
7373     }
7374     break;
7375 
7376   case ARM::sysLDMIA_UPD:
7377   case ARM::sysLDMDA_UPD:
7378   case ARM::sysLDMDB_UPD:
7379   case ARM::sysLDMIB_UPD:
7380     if (!listContainsReg(Inst, 3, ARM::PC))
7381       return Error(Operands[4]->getStartLoc(),
7382                    "writeback register only allowed on system LDM "
7383                    "if PC in register-list");
7384     break;
7385   case ARM::sysSTMIA_UPD:
7386   case ARM::sysSTMDA_UPD:
7387   case ARM::sysSTMDB_UPD:
7388   case ARM::sysSTMIB_UPD:
7389     return Error(Operands[2]->getStartLoc(),
7390                  "system STM cannot have writeback register");
7391   case ARM::tMUL:
7392     // The second source operand must be the same register as the destination
7393     // operand.
7394     //
7395     // In this case, we must directly check the parsed operands because the
7396     // cvtThumbMultiply() function is written in such a way that it guarantees
7397     // this first statement is always true for the new Inst.  Essentially, the
7398     // destination is unconditionally copied into the second source operand
7399     // without checking to see if it matches what we actually parsed.
7400     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
7401                                  ((ARMOperand &)*Operands[5]).getReg()) &&
7402         (((ARMOperand &)*Operands[3]).getReg() !=
7403          ((ARMOperand &)*Operands[4]).getReg())) {
7404       return Error(Operands[3]->getStartLoc(),
7405                    "destination register must match source register");
7406     }
7407     break;
7408 
7409   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
7410   // so only issue a diagnostic for thumb1. The instructions will be
7411   // switched to the t2 encodings in processInstruction() if necessary.
7412   case ARM::tPOP: {
7413     bool ListContainsBase;
7414     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
7415         !isThumbTwo())
7416       return Error(Operands[2]->getStartLoc(),
7417                    "registers must be in range r0-r7 or pc");
7418     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
7419       return true;
7420     break;
7421   }
7422   case ARM::tPUSH: {
7423     bool ListContainsBase;
7424     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
7425         !isThumbTwo())
7426       return Error(Operands[2]->getStartLoc(),
7427                    "registers must be in range r0-r7 or lr");
7428     if (validatetSTMRegList(Inst, Operands, 2))
7429       return true;
7430     break;
7431   }
7432   case ARM::tSTMIA_UPD: {
7433     bool ListContainsBase, InvalidLowList;
7434     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
7435                                           0, ListContainsBase);
7436     if (InvalidLowList && !isThumbTwo())
7437       return Error(Operands[4]->getStartLoc(),
7438                    "registers must be in range r0-r7");
7439 
7440     // This would be converted to a 32-bit stm, but that's not valid if the
7441     // writeback register is in the list.
7442     if (InvalidLowList && ListContainsBase)
7443       return Error(Operands[4]->getStartLoc(),
7444                    "writeback operator '!' not allowed when base register "
7445                    "in register list");
7446 
7447     if (validatetSTMRegList(Inst, Operands, 4))
7448       return true;
7449     break;
7450   }
7451   case ARM::tADDrSP:
7452     // If the non-SP source operand and the destination operand are not the
7453     // same, we need thumb2 (for the wide encoding), or we have an error.
7454     if (!isThumbTwo() &&
7455         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
7456       return Error(Operands[4]->getStartLoc(),
7457                    "source register must be the same as destination");
7458     }
7459     break;
7460 
7461   case ARM::t2ADDri:
7462   case ARM::t2ADDri12:
7463   case ARM::t2ADDrr:
7464   case ARM::t2ADDrs:
7465   case ARM::t2SUBri:
7466   case ARM::t2SUBri12:
7467   case ARM::t2SUBrr:
7468   case ARM::t2SUBrs:
7469     if (Inst.getOperand(0).getReg() == ARM::SP &&
7470         Inst.getOperand(1).getReg() != ARM::SP)
7471       return Error(Operands[4]->getStartLoc(),
7472                    "source register must be sp if destination is sp");
7473     break;
7474 
7475   // Final range checking for Thumb unconditional branch instructions.
7476   case ARM::tB:
7477     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
7478       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7479     break;
7480   case ARM::t2B: {
7481     int op = (Operands[2]->isImm()) ? 2 : 3;
7482     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
7483       return Error(Operands[op]->getStartLoc(), "branch target out of range");
7484     break;
7485   }
7486   // Final range checking for Thumb conditional branch instructions.
7487   case ARM::tBcc:
7488     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
7489       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7490     break;
7491   case ARM::t2Bcc: {
7492     int Op = (Operands[2]->isImm()) ? 2 : 3;
7493     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
7494       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
7495     break;
7496   }
7497   case ARM::tCBZ:
7498   case ARM::tCBNZ: {
7499     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
7500       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7501     break;
7502   }
7503   case ARM::MOVi16:
7504   case ARM::MOVTi16:
7505   case ARM::t2MOVi16:
7506   case ARM::t2MOVTi16:
7507     {
7508     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
7509     // especially when we turn it into a movw and the expression <symbol> does
7510     // not have a :lower16: or :upper16 as part of the expression.  We don't
7511     // want the behavior of silently truncating, which can be unexpected and
7512     // lead to bugs that are difficult to find since this is an easy mistake
7513     // to make.
7514     int i = (Operands[3]->isImm()) ? 3 : 4;
7515     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
7516     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
7517     if (CE) break;
7518     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
7519     if (!E) break;
7520     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
7521     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
7522                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
7523       return Error(
7524           Op.getStartLoc(),
7525           "immediate expression for mov requires :lower16: or :upper16");
7526     break;
7527   }
7528   case ARM::HINT:
7529   case ARM::t2HINT: {
7530     unsigned Imm8 = Inst.getOperand(0).getImm();
7531     unsigned Pred = Inst.getOperand(1).getImm();
7532     // ESB is not predicable (pred must be AL). Without the RAS extension, this
7533     // behaves as any other unallocated hint.
7534     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
7535       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
7536                                                "predicable, but condition "
7537                                                "code specified");
7538     if (Imm8 == 0x14 && Pred != ARMCC::AL)
7539       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
7540                                                "predicable, but condition "
7541                                                "code specified");
7542     break;
7543   }
7544   case ARM::t2WLS: {
7545     int idx = Opcode == ARM::t2WLS ? 3 : 4;
7546     if (!static_cast<ARMOperand &>(*Operands[idx]).isUnsignedOffset<11, 1>())
7547       return Error(Operands[idx]->getStartLoc(),
7548                    "loop end is out of range or not a positive multiple of 2");
7549     break;
7550   }
7551   case ARM::t2LEUpdate: {
7552     if (Inst.getOperand(2).isImm() &&
7553         !(Inst.getOperand(2).getImm() < 0 &&
7554           Inst.getOperand(2).getImm() >= -4094 &&
7555           (Inst.getOperand(2).getImm() & 1) == 0))
7556       return Error(Operands[2]->getStartLoc(),
7557                    "loop start is out of range or not a negative multiple of 2");
7558     break;
7559   }
7560   case ARM::t2BFi:
7561   case ARM::t2BFr:
7562   case ARM::t2BFLi:
7563   case ARM::t2BFLr: {
7564     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<4, 1>() ||
7565         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
7566       return Error(Operands[2]->getStartLoc(),
7567                    "branch location out of range or not a multiple of 2");
7568 
7569     if (Opcode == ARM::t2BFi) {
7570       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<16, 1>())
7571         return Error(Operands[3]->getStartLoc(),
7572                      "branch target out of range or not a multiple of 2");
7573     } else if (Opcode == ARM::t2BFLi) {
7574       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<18, 1>())
7575         return Error(Operands[3]->getStartLoc(),
7576                      "branch target out of range or not a multiple of 2");
7577     }
7578     break;
7579   }
7580   case ARM::t2BFic: {
7581     if (!static_cast<ARMOperand &>(*Operands[1]).isUnsignedOffset<4, 1>() ||
7582         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
7583       return Error(Operands[1]->getStartLoc(),
7584                    "branch location out of range or not a multiple of 2");
7585 
7586     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<16, 1>())
7587       return Error(Operands[2]->getStartLoc(),
7588                    "branch target out of range or not a multiple of 2");
7589 
7590     assert(Inst.getOperand(0).isImm() == Inst.getOperand(2).isImm() &&
7591            "branch location and else branch target should either both be "
7592            "immediates or both labels");
7593 
7594     if (Inst.getOperand(0).isImm() && Inst.getOperand(2).isImm()) {
7595       int Diff = Inst.getOperand(2).getImm() - Inst.getOperand(0).getImm();
7596       if (Diff != 4 && Diff != 2)
7597         return Error(
7598             Operands[3]->getStartLoc(),
7599             "else branch target must be 2 or 4 greater than the branch location");
7600     }
7601     break;
7602   }
7603   case ARM::t2CLRM: {
7604     for (unsigned i = 2; i < Inst.getNumOperands(); i++) {
7605       if (Inst.getOperand(i).isReg() &&
7606           !ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(
7607               Inst.getOperand(i).getReg())) {
7608         return Error(Operands[2]->getStartLoc(),
7609                      "invalid register in register list. Valid registers are "
7610                      "r0-r12, lr/r14 and APSR.");
7611       }
7612     }
7613     break;
7614   }
7615   case ARM::DSB:
7616   case ARM::t2DSB: {
7617 
7618     if (Inst.getNumOperands() < 2)
7619       break;
7620 
7621     unsigned Option = Inst.getOperand(0).getImm();
7622     unsigned Pred = Inst.getOperand(1).getImm();
7623 
7624     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
7625     if (Option == 0 && Pred != ARMCC::AL)
7626       return Error(Operands[1]->getStartLoc(),
7627                    "instruction 'ssbb' is not predicable, but condition code "
7628                    "specified");
7629     if (Option == 4 && Pred != ARMCC::AL)
7630       return Error(Operands[1]->getStartLoc(),
7631                    "instruction 'pssbb' is not predicable, but condition code "
7632                    "specified");
7633     break;
7634   }
7635   case ARM::VMOVRRS: {
7636     // Source registers must be sequential.
7637     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7638     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7639     if (Sm1 != Sm + 1)
7640       return Error(Operands[5]->getStartLoc(),
7641                    "source operands must be sequential");
7642     break;
7643   }
7644   case ARM::VMOVSRR: {
7645     // Destination registers must be sequential.
7646     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7647     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7648     if (Sm1 != Sm + 1)
7649       return Error(Operands[3]->getStartLoc(),
7650                    "destination operands must be sequential");
7651     break;
7652   }
7653   case ARM::VLDMDIA:
7654   case ARM::VSTMDIA: {
7655     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
7656     auto &RegList = Op.getRegList();
7657     if (RegList.size() < 1 || RegList.size() > 16)
7658       return Error(Operands[3]->getStartLoc(),
7659                    "list of registers must be at least 1 and at most 16");
7660     break;
7661   }
7662   case ARM::MVE_VQDMULLs32bh:
7663   case ARM::MVE_VQDMULLs32th:
7664   case ARM::MVE_VCMULf32:
7665   case ARM::MVE_VMULLs32bh:
7666   case ARM::MVE_VMULLs32th:
7667   case ARM::MVE_VMULLu32bh:
7668   case ARM::MVE_VMULLu32th:
7669   case ARM::MVE_VQDMLADHs32:
7670   case ARM::MVE_VQDMLADHXs32:
7671   case ARM::MVE_VQRDMLADHs32:
7672   case ARM::MVE_VQRDMLADHXs32:
7673   case ARM::MVE_VQDMLSDHs32:
7674   case ARM::MVE_VQDMLSDHXs32:
7675   case ARM::MVE_VQRDMLSDHs32:
7676   case ARM::MVE_VQRDMLSDHXs32: {
7677     if (Operands[3]->getReg() == Operands[4]->getReg()) {
7678       return Error (Operands[3]->getStartLoc(),
7679                     "Qd register and Qn register can't be identical");
7680     }
7681     if (Operands[3]->getReg() == Operands[5]->getReg()) {
7682       return Error (Operands[3]->getStartLoc(),
7683                     "Qd register and Qm register can't be identical");
7684     }
7685     break;
7686   }
7687   case ARM::MVE_VMOV_rr_q: {
7688     if (Operands[4]->getReg() != Operands[6]->getReg())
7689       return Error (Operands[4]->getStartLoc(), "Q-registers must be the same");
7690     if (static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() !=
7691         static_cast<ARMOperand &>(*Operands[7]).getVectorIndex() + 2)
7692       return Error (Operands[5]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
7693     break;
7694   }
7695   case ARM::MVE_VMOV_q_rr: {
7696     if (Operands[2]->getReg() != Operands[4]->getReg())
7697       return Error (Operands[2]->getStartLoc(), "Q-registers must be the same");
7698     if (static_cast<ARMOperand &>(*Operands[3]).getVectorIndex() !=
7699         static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() + 2)
7700       return Error (Operands[3]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
7701     break;
7702   }
7703   }
7704 
7705   return false;
7706 }
7707 
7708 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
7709   switch(Opc) {
7710   default: llvm_unreachable("unexpected opcode!");
7711   // VST1LN
7712   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
7713   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
7714   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
7715   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
7716   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
7717   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
7718   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
7719   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
7720   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
7721 
7722   // VST2LN
7723   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
7724   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
7725   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
7726   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
7727   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
7728 
7729   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
7730   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
7731   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
7732   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
7733   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
7734 
7735   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
7736   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
7737   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
7738   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
7739   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
7740 
7741   // VST3LN
7742   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
7743   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
7744   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
7745   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
7746   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
7747   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
7748   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
7749   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
7750   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
7751   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
7752   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
7753   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
7754   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
7755   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
7756   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
7757 
7758   // VST3
7759   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
7760   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
7761   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
7762   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
7763   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
7764   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
7765   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
7766   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
7767   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
7768   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
7769   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
7770   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
7771   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
7772   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
7773   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
7774   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
7775   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
7776   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
7777 
7778   // VST4LN
7779   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
7780   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
7781   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
7782   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
7783   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
7784   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
7785   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
7786   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
7787   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
7788   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
7789   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
7790   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
7791   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
7792   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
7793   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
7794 
7795   // VST4
7796   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
7797   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
7798   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
7799   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
7800   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
7801   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
7802   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
7803   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
7804   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
7805   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
7806   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
7807   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
7808   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
7809   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
7810   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
7811   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
7812   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
7813   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
7814   }
7815 }
7816 
7817 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
7818   switch(Opc) {
7819   default: llvm_unreachable("unexpected opcode!");
7820   // VLD1LN
7821   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
7822   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
7823   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
7824   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
7825   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
7826   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
7827   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
7828   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
7829   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
7830 
7831   // VLD2LN
7832   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
7833   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
7834   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
7835   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
7836   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
7837   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
7838   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
7839   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
7840   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
7841   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
7842   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
7843   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
7844   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
7845   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
7846   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
7847 
7848   // VLD3DUP
7849   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
7850   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
7851   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
7852   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
7853   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
7854   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
7855   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
7856   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
7857   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
7858   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
7859   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
7860   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
7861   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
7862   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
7863   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
7864   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
7865   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
7866   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
7867 
7868   // VLD3LN
7869   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
7870   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
7871   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
7872   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
7873   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
7874   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
7875   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
7876   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
7877   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
7878   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
7879   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
7880   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
7881   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
7882   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
7883   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
7884 
7885   // VLD3
7886   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
7887   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
7888   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
7889   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
7890   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
7891   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
7892   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
7893   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
7894   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
7895   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
7896   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
7897   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
7898   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
7899   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
7900   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
7901   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
7902   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
7903   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
7904 
7905   // VLD4LN
7906   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
7907   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
7908   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
7909   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
7910   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
7911   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
7912   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
7913   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
7914   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
7915   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
7916   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
7917   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
7918   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
7919   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
7920   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
7921 
7922   // VLD4DUP
7923   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
7924   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
7925   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
7926   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
7927   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
7928   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
7929   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
7930   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
7931   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
7932   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
7933   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
7934   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
7935   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
7936   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
7937   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
7938   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
7939   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
7940   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
7941 
7942   // VLD4
7943   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
7944   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
7945   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
7946   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
7947   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
7948   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
7949   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
7950   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
7951   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
7952   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
7953   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
7954   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
7955   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
7956   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
7957   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
7958   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
7959   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
7960   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
7961   }
7962 }
7963 
7964 bool ARMAsmParser::processInstruction(MCInst &Inst,
7965                                       const OperandVector &Operands,
7966                                       MCStreamer &Out) {
7967   // Check if we have the wide qualifier, because if it's present we
7968   // must avoid selecting a 16-bit thumb instruction.
7969   bool HasWideQualifier = false;
7970   for (auto &Op : Operands) {
7971     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
7972     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
7973       HasWideQualifier = true;
7974       break;
7975     }
7976   }
7977 
7978   switch (Inst.getOpcode()) {
7979   case ARM::MVE_VORNIZ0v4i32:
7980   case ARM::MVE_VORNIZ0v8i16:
7981   case ARM::MVE_VORNIZ8v4i32:
7982   case ARM::MVE_VORNIZ8v8i16:
7983   case ARM::MVE_VORNIZ16v4i32:
7984   case ARM::MVE_VORNIZ24v4i32:
7985   case ARM::MVE_VANDIZ0v4i32:
7986   case ARM::MVE_VANDIZ0v8i16:
7987   case ARM::MVE_VANDIZ8v4i32:
7988   case ARM::MVE_VANDIZ8v8i16:
7989   case ARM::MVE_VANDIZ16v4i32:
7990   case ARM::MVE_VANDIZ24v4i32: {
7991     unsigned Opcode;
7992     bool imm16 = false;
7993     switch(Inst.getOpcode()) {
7994     case ARM::MVE_VORNIZ0v4i32: Opcode = ARM::MVE_VORRIZ0v4i32; break;
7995     case ARM::MVE_VORNIZ0v8i16: Opcode = ARM::MVE_VORRIZ0v8i16; imm16 = true; break;
7996     case ARM::MVE_VORNIZ8v4i32: Opcode = ARM::MVE_VORRIZ8v4i32; break;
7997     case ARM::MVE_VORNIZ8v8i16: Opcode = ARM::MVE_VORRIZ8v8i16; imm16 = true; break;
7998     case ARM::MVE_VORNIZ16v4i32: Opcode = ARM::MVE_VORRIZ16v4i32; break;
7999     case ARM::MVE_VORNIZ24v4i32: Opcode = ARM::MVE_VORRIZ24v4i32; break;
8000     case ARM::MVE_VANDIZ0v4i32: Opcode = ARM::MVE_VBICIZ0v4i32; break;
8001     case ARM::MVE_VANDIZ0v8i16: Opcode = ARM::MVE_VBICIZ0v8i16; imm16 = true; break;
8002     case ARM::MVE_VANDIZ8v4i32: Opcode = ARM::MVE_VBICIZ8v4i32; break;
8003     case ARM::MVE_VANDIZ8v8i16: Opcode = ARM::MVE_VBICIZ8v8i16; imm16 = true; break;
8004     case ARM::MVE_VANDIZ16v4i32: Opcode = ARM::MVE_VBICIZ16v4i32; break;
8005     case ARM::MVE_VANDIZ24v4i32: Opcode = ARM::MVE_VBICIZ24v4i32; break;
8006     default: llvm_unreachable("unexpected opcode");
8007     }
8008 
8009     MCInst TmpInst;
8010     TmpInst.setOpcode(Opcode);
8011     TmpInst.addOperand(Inst.getOperand(0));
8012     TmpInst.addOperand(Inst.getOperand(1));
8013 
8014     // invert immediate
8015     unsigned imm = ~Inst.getOperand(2).getImm() & (imm16 ? 0xffff : 0xffffffff);
8016     TmpInst.addOperand(MCOperand::createImm(imm));
8017 
8018     TmpInst.addOperand(Inst.getOperand(3));
8019     TmpInst.addOperand(Inst.getOperand(4));
8020     Inst = TmpInst;
8021     return true;
8022   }
8023   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
8024   case ARM::LDRT_POST:
8025   case ARM::LDRBT_POST: {
8026     const unsigned Opcode =
8027       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
8028                                            : ARM::LDRBT_POST_IMM;
8029     MCInst TmpInst;
8030     TmpInst.setOpcode(Opcode);
8031     TmpInst.addOperand(Inst.getOperand(0));
8032     TmpInst.addOperand(Inst.getOperand(1));
8033     TmpInst.addOperand(Inst.getOperand(1));
8034     TmpInst.addOperand(MCOperand::createReg(0));
8035     TmpInst.addOperand(MCOperand::createImm(0));
8036     TmpInst.addOperand(Inst.getOperand(2));
8037     TmpInst.addOperand(Inst.getOperand(3));
8038     Inst = TmpInst;
8039     return true;
8040   }
8041   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
8042   case ARM::STRT_POST:
8043   case ARM::STRBT_POST: {
8044     const unsigned Opcode =
8045       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
8046                                            : ARM::STRBT_POST_IMM;
8047     MCInst TmpInst;
8048     TmpInst.setOpcode(Opcode);
8049     TmpInst.addOperand(Inst.getOperand(1));
8050     TmpInst.addOperand(Inst.getOperand(0));
8051     TmpInst.addOperand(Inst.getOperand(1));
8052     TmpInst.addOperand(MCOperand::createReg(0));
8053     TmpInst.addOperand(MCOperand::createImm(0));
8054     TmpInst.addOperand(Inst.getOperand(2));
8055     TmpInst.addOperand(Inst.getOperand(3));
8056     Inst = TmpInst;
8057     return true;
8058   }
8059   // Alias for alternate form of 'ADR Rd, #imm' instruction.
8060   case ARM::ADDri: {
8061     if (Inst.getOperand(1).getReg() != ARM::PC ||
8062         Inst.getOperand(5).getReg() != 0 ||
8063         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
8064       return false;
8065     MCInst TmpInst;
8066     TmpInst.setOpcode(ARM::ADR);
8067     TmpInst.addOperand(Inst.getOperand(0));
8068     if (Inst.getOperand(2).isImm()) {
8069       // Immediate (mod_imm) will be in its encoded form, we must unencode it
8070       // before passing it to the ADR instruction.
8071       unsigned Enc = Inst.getOperand(2).getImm();
8072       TmpInst.addOperand(MCOperand::createImm(
8073         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
8074     } else {
8075       // Turn PC-relative expression into absolute expression.
8076       // Reading PC provides the start of the current instruction + 8 and
8077       // the transform to adr is biased by that.
8078       MCSymbol *Dot = getContext().createTempSymbol();
8079       Out.EmitLabel(Dot);
8080       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
8081       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
8082                                                      MCSymbolRefExpr::VK_None,
8083                                                      getContext());
8084       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
8085       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
8086                                                      getContext());
8087       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
8088                                                         getContext());
8089       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
8090     }
8091     TmpInst.addOperand(Inst.getOperand(3));
8092     TmpInst.addOperand(Inst.getOperand(4));
8093     Inst = TmpInst;
8094     return true;
8095   }
8096   // Aliases for alternate PC+imm syntax of LDR instructions.
8097   case ARM::t2LDRpcrel:
8098     // Select the narrow version if the immediate will fit.
8099     if (Inst.getOperand(1).getImm() > 0 &&
8100         Inst.getOperand(1).getImm() <= 0xff &&
8101         !HasWideQualifier)
8102       Inst.setOpcode(ARM::tLDRpci);
8103     else
8104       Inst.setOpcode(ARM::t2LDRpci);
8105     return true;
8106   case ARM::t2LDRBpcrel:
8107     Inst.setOpcode(ARM::t2LDRBpci);
8108     return true;
8109   case ARM::t2LDRHpcrel:
8110     Inst.setOpcode(ARM::t2LDRHpci);
8111     return true;
8112   case ARM::t2LDRSBpcrel:
8113     Inst.setOpcode(ARM::t2LDRSBpci);
8114     return true;
8115   case ARM::t2LDRSHpcrel:
8116     Inst.setOpcode(ARM::t2LDRSHpci);
8117     return true;
8118   case ARM::LDRConstPool:
8119   case ARM::tLDRConstPool:
8120   case ARM::t2LDRConstPool: {
8121     // Pseudo instruction ldr rt, =immediate is converted to a
8122     // MOV rt, immediate if immediate is known and representable
8123     // otherwise we create a constant pool entry that we load from.
8124     MCInst TmpInst;
8125     if (Inst.getOpcode() == ARM::LDRConstPool)
8126       TmpInst.setOpcode(ARM::LDRi12);
8127     else if (Inst.getOpcode() == ARM::tLDRConstPool)
8128       TmpInst.setOpcode(ARM::tLDRpci);
8129     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
8130       TmpInst.setOpcode(ARM::t2LDRpci);
8131     const ARMOperand &PoolOperand =
8132       (HasWideQualifier ?
8133        static_cast<ARMOperand &>(*Operands[4]) :
8134        static_cast<ARMOperand &>(*Operands[3]));
8135     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
8136     // If SubExprVal is a constant we may be able to use a MOV
8137     if (isa<MCConstantExpr>(SubExprVal) &&
8138         Inst.getOperand(0).getReg() != ARM::PC &&
8139         Inst.getOperand(0).getReg() != ARM::SP) {
8140       int64_t Value =
8141         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
8142       bool UseMov  = true;
8143       bool MovHasS = true;
8144       if (Inst.getOpcode() == ARM::LDRConstPool) {
8145         // ARM Constant
8146         if (ARM_AM::getSOImmVal(Value) != -1) {
8147           Value = ARM_AM::getSOImmVal(Value);
8148           TmpInst.setOpcode(ARM::MOVi);
8149         }
8150         else if (ARM_AM::getSOImmVal(~Value) != -1) {
8151           Value = ARM_AM::getSOImmVal(~Value);
8152           TmpInst.setOpcode(ARM::MVNi);
8153         }
8154         else if (hasV6T2Ops() &&
8155                  Value >=0 && Value < 65536) {
8156           TmpInst.setOpcode(ARM::MOVi16);
8157           MovHasS = false;
8158         }
8159         else
8160           UseMov = false;
8161       }
8162       else {
8163         // Thumb/Thumb2 Constant
8164         if (hasThumb2() &&
8165             ARM_AM::getT2SOImmVal(Value) != -1)
8166           TmpInst.setOpcode(ARM::t2MOVi);
8167         else if (hasThumb2() &&
8168                  ARM_AM::getT2SOImmVal(~Value) != -1) {
8169           TmpInst.setOpcode(ARM::t2MVNi);
8170           Value = ~Value;
8171         }
8172         else if (hasV8MBaseline() &&
8173                  Value >=0 && Value < 65536) {
8174           TmpInst.setOpcode(ARM::t2MOVi16);
8175           MovHasS = false;
8176         }
8177         else
8178           UseMov = false;
8179       }
8180       if (UseMov) {
8181         TmpInst.addOperand(Inst.getOperand(0));           // Rt
8182         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
8183         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8184         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8185         if (MovHasS)
8186           TmpInst.addOperand(MCOperand::createReg(0));    // S
8187         Inst = TmpInst;
8188         return true;
8189       }
8190     }
8191     // No opportunity to use MOV/MVN create constant pool
8192     const MCExpr *CPLoc =
8193       getTargetStreamer().addConstantPoolEntry(SubExprVal,
8194                                                PoolOperand.getStartLoc());
8195     TmpInst.addOperand(Inst.getOperand(0));           // Rt
8196     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
8197     if (TmpInst.getOpcode() == ARM::LDRi12)
8198       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
8199     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8200     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8201     Inst = TmpInst;
8202     return true;
8203   }
8204   // Handle NEON VST complex aliases.
8205   case ARM::VST1LNdWB_register_Asm_8:
8206   case ARM::VST1LNdWB_register_Asm_16:
8207   case ARM::VST1LNdWB_register_Asm_32: {
8208     MCInst TmpInst;
8209     // Shuffle the operands around so the lane index operand is in the
8210     // right place.
8211     unsigned Spacing;
8212     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8213     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8214     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8215     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8216     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8217     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8218     TmpInst.addOperand(Inst.getOperand(1)); // lane
8219     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8220     TmpInst.addOperand(Inst.getOperand(6));
8221     Inst = TmpInst;
8222     return true;
8223   }
8224 
8225   case ARM::VST2LNdWB_register_Asm_8:
8226   case ARM::VST2LNdWB_register_Asm_16:
8227   case ARM::VST2LNdWB_register_Asm_32:
8228   case ARM::VST2LNqWB_register_Asm_16:
8229   case ARM::VST2LNqWB_register_Asm_32: {
8230     MCInst TmpInst;
8231     // Shuffle the operands around so the lane index operand is in the
8232     // right place.
8233     unsigned Spacing;
8234     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8235     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8236     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8237     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8238     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8239     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8240     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8241                                             Spacing));
8242     TmpInst.addOperand(Inst.getOperand(1)); // lane
8243     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8244     TmpInst.addOperand(Inst.getOperand(6));
8245     Inst = TmpInst;
8246     return true;
8247   }
8248 
8249   case ARM::VST3LNdWB_register_Asm_8:
8250   case ARM::VST3LNdWB_register_Asm_16:
8251   case ARM::VST3LNdWB_register_Asm_32:
8252   case ARM::VST3LNqWB_register_Asm_16:
8253   case ARM::VST3LNqWB_register_Asm_32: {
8254     MCInst TmpInst;
8255     // Shuffle the operands around so the lane index operand is in the
8256     // right place.
8257     unsigned Spacing;
8258     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8259     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8260     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8261     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8262     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8263     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8264     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8265                                             Spacing));
8266     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8267                                             Spacing * 2));
8268     TmpInst.addOperand(Inst.getOperand(1)); // lane
8269     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8270     TmpInst.addOperand(Inst.getOperand(6));
8271     Inst = TmpInst;
8272     return true;
8273   }
8274 
8275   case ARM::VST4LNdWB_register_Asm_8:
8276   case ARM::VST4LNdWB_register_Asm_16:
8277   case ARM::VST4LNdWB_register_Asm_32:
8278   case ARM::VST4LNqWB_register_Asm_16:
8279   case ARM::VST4LNqWB_register_Asm_32: {
8280     MCInst TmpInst;
8281     // Shuffle the operands around so the lane index operand is in the
8282     // right place.
8283     unsigned Spacing;
8284     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8285     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8286     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8287     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8288     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8289     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8290     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8291                                             Spacing));
8292     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8293                                             Spacing * 2));
8294     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8295                                             Spacing * 3));
8296     TmpInst.addOperand(Inst.getOperand(1)); // lane
8297     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8298     TmpInst.addOperand(Inst.getOperand(6));
8299     Inst = TmpInst;
8300     return true;
8301   }
8302 
8303   case ARM::VST1LNdWB_fixed_Asm_8:
8304   case ARM::VST1LNdWB_fixed_Asm_16:
8305   case ARM::VST1LNdWB_fixed_Asm_32: {
8306     MCInst TmpInst;
8307     // Shuffle the operands around so the lane index operand is in the
8308     // right place.
8309     unsigned Spacing;
8310     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8311     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8312     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8313     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8314     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8315     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8316     TmpInst.addOperand(Inst.getOperand(1)); // lane
8317     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8318     TmpInst.addOperand(Inst.getOperand(5));
8319     Inst = TmpInst;
8320     return true;
8321   }
8322 
8323   case ARM::VST2LNdWB_fixed_Asm_8:
8324   case ARM::VST2LNdWB_fixed_Asm_16:
8325   case ARM::VST2LNdWB_fixed_Asm_32:
8326   case ARM::VST2LNqWB_fixed_Asm_16:
8327   case ARM::VST2LNqWB_fixed_Asm_32: {
8328     MCInst TmpInst;
8329     // Shuffle the operands around so the lane index operand is in the
8330     // right place.
8331     unsigned Spacing;
8332     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8333     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8334     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8335     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8336     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8337     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8338     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8339                                             Spacing));
8340     TmpInst.addOperand(Inst.getOperand(1)); // lane
8341     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8342     TmpInst.addOperand(Inst.getOperand(5));
8343     Inst = TmpInst;
8344     return true;
8345   }
8346 
8347   case ARM::VST3LNdWB_fixed_Asm_8:
8348   case ARM::VST3LNdWB_fixed_Asm_16:
8349   case ARM::VST3LNdWB_fixed_Asm_32:
8350   case ARM::VST3LNqWB_fixed_Asm_16:
8351   case ARM::VST3LNqWB_fixed_Asm_32: {
8352     MCInst TmpInst;
8353     // Shuffle the operands around so the lane index operand is in the
8354     // right place.
8355     unsigned Spacing;
8356     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8357     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8358     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8359     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8360     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8361     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8362     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8363                                             Spacing));
8364     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8365                                             Spacing * 2));
8366     TmpInst.addOperand(Inst.getOperand(1)); // lane
8367     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8368     TmpInst.addOperand(Inst.getOperand(5));
8369     Inst = TmpInst;
8370     return true;
8371   }
8372 
8373   case ARM::VST4LNdWB_fixed_Asm_8:
8374   case ARM::VST4LNdWB_fixed_Asm_16:
8375   case ARM::VST4LNdWB_fixed_Asm_32:
8376   case ARM::VST4LNqWB_fixed_Asm_16:
8377   case ARM::VST4LNqWB_fixed_Asm_32: {
8378     MCInst TmpInst;
8379     // Shuffle the operands around so the lane index operand is in the
8380     // right place.
8381     unsigned Spacing;
8382     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8383     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8384     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8385     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8386     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8387     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8388     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8389                                             Spacing));
8390     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8391                                             Spacing * 2));
8392     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8393                                             Spacing * 3));
8394     TmpInst.addOperand(Inst.getOperand(1)); // lane
8395     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8396     TmpInst.addOperand(Inst.getOperand(5));
8397     Inst = TmpInst;
8398     return true;
8399   }
8400 
8401   case ARM::VST1LNdAsm_8:
8402   case ARM::VST1LNdAsm_16:
8403   case ARM::VST1LNdAsm_32: {
8404     MCInst TmpInst;
8405     // Shuffle the operands around so the lane index operand is in the
8406     // right place.
8407     unsigned Spacing;
8408     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8409     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8410     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8411     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8412     TmpInst.addOperand(Inst.getOperand(1)); // lane
8413     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8414     TmpInst.addOperand(Inst.getOperand(5));
8415     Inst = TmpInst;
8416     return true;
8417   }
8418 
8419   case ARM::VST2LNdAsm_8:
8420   case ARM::VST2LNdAsm_16:
8421   case ARM::VST2LNdAsm_32:
8422   case ARM::VST2LNqAsm_16:
8423   case ARM::VST2LNqAsm_32: {
8424     MCInst TmpInst;
8425     // Shuffle the operands around so the lane index operand is in the
8426     // right place.
8427     unsigned Spacing;
8428     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8429     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8430     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8431     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8432     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8433                                             Spacing));
8434     TmpInst.addOperand(Inst.getOperand(1)); // lane
8435     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8436     TmpInst.addOperand(Inst.getOperand(5));
8437     Inst = TmpInst;
8438     return true;
8439   }
8440 
8441   case ARM::VST3LNdAsm_8:
8442   case ARM::VST3LNdAsm_16:
8443   case ARM::VST3LNdAsm_32:
8444   case ARM::VST3LNqAsm_16:
8445   case ARM::VST3LNqAsm_32: {
8446     MCInst TmpInst;
8447     // Shuffle the operands around so the lane index operand is in the
8448     // right place.
8449     unsigned Spacing;
8450     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8451     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8452     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8453     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8454     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8455                                             Spacing));
8456     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8457                                             Spacing * 2));
8458     TmpInst.addOperand(Inst.getOperand(1)); // lane
8459     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8460     TmpInst.addOperand(Inst.getOperand(5));
8461     Inst = TmpInst;
8462     return true;
8463   }
8464 
8465   case ARM::VST4LNdAsm_8:
8466   case ARM::VST4LNdAsm_16:
8467   case ARM::VST4LNdAsm_32:
8468   case ARM::VST4LNqAsm_16:
8469   case ARM::VST4LNqAsm_32: {
8470     MCInst TmpInst;
8471     // Shuffle the operands around so the lane index operand is in the
8472     // right place.
8473     unsigned Spacing;
8474     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8475     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8476     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8477     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8478     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8479                                             Spacing));
8480     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8481                                             Spacing * 2));
8482     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8483                                             Spacing * 3));
8484     TmpInst.addOperand(Inst.getOperand(1)); // lane
8485     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8486     TmpInst.addOperand(Inst.getOperand(5));
8487     Inst = TmpInst;
8488     return true;
8489   }
8490 
8491   // Handle NEON VLD complex aliases.
8492   case ARM::VLD1LNdWB_register_Asm_8:
8493   case ARM::VLD1LNdWB_register_Asm_16:
8494   case ARM::VLD1LNdWB_register_Asm_32: {
8495     MCInst TmpInst;
8496     // Shuffle the operands around so the lane index operand is in the
8497     // right place.
8498     unsigned Spacing;
8499     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8500     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8501     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8502     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8503     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8504     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8505     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8506     TmpInst.addOperand(Inst.getOperand(1)); // lane
8507     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8508     TmpInst.addOperand(Inst.getOperand(6));
8509     Inst = TmpInst;
8510     return true;
8511   }
8512 
8513   case ARM::VLD2LNdWB_register_Asm_8:
8514   case ARM::VLD2LNdWB_register_Asm_16:
8515   case ARM::VLD2LNdWB_register_Asm_32:
8516   case ARM::VLD2LNqWB_register_Asm_16:
8517   case ARM::VLD2LNqWB_register_Asm_32: {
8518     MCInst TmpInst;
8519     // Shuffle the operands around so the lane index operand is in the
8520     // right place.
8521     unsigned Spacing;
8522     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8523     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8524     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8525                                             Spacing));
8526     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8527     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8528     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8529     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8530     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8531     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8532                                             Spacing));
8533     TmpInst.addOperand(Inst.getOperand(1)); // lane
8534     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8535     TmpInst.addOperand(Inst.getOperand(6));
8536     Inst = TmpInst;
8537     return true;
8538   }
8539 
8540   case ARM::VLD3LNdWB_register_Asm_8:
8541   case ARM::VLD3LNdWB_register_Asm_16:
8542   case ARM::VLD3LNdWB_register_Asm_32:
8543   case ARM::VLD3LNqWB_register_Asm_16:
8544   case ARM::VLD3LNqWB_register_Asm_32: {
8545     MCInst TmpInst;
8546     // Shuffle the operands around so the lane index operand is in the
8547     // right place.
8548     unsigned Spacing;
8549     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8550     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8551     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8552                                             Spacing));
8553     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8554                                             Spacing * 2));
8555     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8556     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8557     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8558     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8559     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8560     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8561                                             Spacing));
8562     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8563                                             Spacing * 2));
8564     TmpInst.addOperand(Inst.getOperand(1)); // lane
8565     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8566     TmpInst.addOperand(Inst.getOperand(6));
8567     Inst = TmpInst;
8568     return true;
8569   }
8570 
8571   case ARM::VLD4LNdWB_register_Asm_8:
8572   case ARM::VLD4LNdWB_register_Asm_16:
8573   case ARM::VLD4LNdWB_register_Asm_32:
8574   case ARM::VLD4LNqWB_register_Asm_16:
8575   case ARM::VLD4LNqWB_register_Asm_32: {
8576     MCInst TmpInst;
8577     // Shuffle the operands around so the lane index operand is in the
8578     // right place.
8579     unsigned Spacing;
8580     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8581     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8582     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8583                                             Spacing));
8584     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8585                                             Spacing * 2));
8586     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8587                                             Spacing * 3));
8588     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8589     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8590     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8591     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8592     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8593     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8594                                             Spacing));
8595     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8596                                             Spacing * 2));
8597     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8598                                             Spacing * 3));
8599     TmpInst.addOperand(Inst.getOperand(1)); // lane
8600     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8601     TmpInst.addOperand(Inst.getOperand(6));
8602     Inst = TmpInst;
8603     return true;
8604   }
8605 
8606   case ARM::VLD1LNdWB_fixed_Asm_8:
8607   case ARM::VLD1LNdWB_fixed_Asm_16:
8608   case ARM::VLD1LNdWB_fixed_Asm_32: {
8609     MCInst TmpInst;
8610     // Shuffle the operands around so the lane index operand is in the
8611     // right place.
8612     unsigned Spacing;
8613     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8614     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8615     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8616     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8617     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8618     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8619     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8620     TmpInst.addOperand(Inst.getOperand(1)); // lane
8621     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8622     TmpInst.addOperand(Inst.getOperand(5));
8623     Inst = TmpInst;
8624     return true;
8625   }
8626 
8627   case ARM::VLD2LNdWB_fixed_Asm_8:
8628   case ARM::VLD2LNdWB_fixed_Asm_16:
8629   case ARM::VLD2LNdWB_fixed_Asm_32:
8630   case ARM::VLD2LNqWB_fixed_Asm_16:
8631   case ARM::VLD2LNqWB_fixed_Asm_32: {
8632     MCInst TmpInst;
8633     // Shuffle the operands around so the lane index operand is in the
8634     // right place.
8635     unsigned Spacing;
8636     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8637     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8638     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8639                                             Spacing));
8640     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8641     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8642     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8643     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8644     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8645     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8646                                             Spacing));
8647     TmpInst.addOperand(Inst.getOperand(1)); // lane
8648     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8649     TmpInst.addOperand(Inst.getOperand(5));
8650     Inst = TmpInst;
8651     return true;
8652   }
8653 
8654   case ARM::VLD3LNdWB_fixed_Asm_8:
8655   case ARM::VLD3LNdWB_fixed_Asm_16:
8656   case ARM::VLD3LNdWB_fixed_Asm_32:
8657   case ARM::VLD3LNqWB_fixed_Asm_16:
8658   case ARM::VLD3LNqWB_fixed_Asm_32: {
8659     MCInst TmpInst;
8660     // Shuffle the operands around so the lane index operand is in the
8661     // right place.
8662     unsigned Spacing;
8663     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8664     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8665     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8666                                             Spacing));
8667     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8668                                             Spacing * 2));
8669     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8670     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8671     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8672     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8673     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8674     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8675                                             Spacing));
8676     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8677                                             Spacing * 2));
8678     TmpInst.addOperand(Inst.getOperand(1)); // lane
8679     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8680     TmpInst.addOperand(Inst.getOperand(5));
8681     Inst = TmpInst;
8682     return true;
8683   }
8684 
8685   case ARM::VLD4LNdWB_fixed_Asm_8:
8686   case ARM::VLD4LNdWB_fixed_Asm_16:
8687   case ARM::VLD4LNdWB_fixed_Asm_32:
8688   case ARM::VLD4LNqWB_fixed_Asm_16:
8689   case ARM::VLD4LNqWB_fixed_Asm_32: {
8690     MCInst TmpInst;
8691     // Shuffle the operands around so the lane index operand is in the
8692     // right place.
8693     unsigned Spacing;
8694     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8695     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8696     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8697                                             Spacing));
8698     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8699                                             Spacing * 2));
8700     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8701                                             Spacing * 3));
8702     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8703     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8704     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8705     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8706     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8707     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8708                                             Spacing));
8709     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8710                                             Spacing * 2));
8711     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8712                                             Spacing * 3));
8713     TmpInst.addOperand(Inst.getOperand(1)); // lane
8714     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8715     TmpInst.addOperand(Inst.getOperand(5));
8716     Inst = TmpInst;
8717     return true;
8718   }
8719 
8720   case ARM::VLD1LNdAsm_8:
8721   case ARM::VLD1LNdAsm_16:
8722   case ARM::VLD1LNdAsm_32: {
8723     MCInst TmpInst;
8724     // Shuffle the operands around so the lane index operand is in the
8725     // right place.
8726     unsigned Spacing;
8727     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8728     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8729     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8730     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8731     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8732     TmpInst.addOperand(Inst.getOperand(1)); // lane
8733     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8734     TmpInst.addOperand(Inst.getOperand(5));
8735     Inst = TmpInst;
8736     return true;
8737   }
8738 
8739   case ARM::VLD2LNdAsm_8:
8740   case ARM::VLD2LNdAsm_16:
8741   case ARM::VLD2LNdAsm_32:
8742   case ARM::VLD2LNqAsm_16:
8743   case ARM::VLD2LNqAsm_32: {
8744     MCInst TmpInst;
8745     // Shuffle the operands around so the lane index operand is in the
8746     // right place.
8747     unsigned Spacing;
8748     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8749     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8750     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8751                                             Spacing));
8752     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8753     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8754     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8755     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8756                                             Spacing));
8757     TmpInst.addOperand(Inst.getOperand(1)); // lane
8758     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8759     TmpInst.addOperand(Inst.getOperand(5));
8760     Inst = TmpInst;
8761     return true;
8762   }
8763 
8764   case ARM::VLD3LNdAsm_8:
8765   case ARM::VLD3LNdAsm_16:
8766   case ARM::VLD3LNdAsm_32:
8767   case ARM::VLD3LNqAsm_16:
8768   case ARM::VLD3LNqAsm_32: {
8769     MCInst TmpInst;
8770     // Shuffle the operands around so the lane index operand is in the
8771     // right place.
8772     unsigned Spacing;
8773     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8774     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8775     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8776                                             Spacing));
8777     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8778                                             Spacing * 2));
8779     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8780     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8781     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8782     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8783                                             Spacing));
8784     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8785                                             Spacing * 2));
8786     TmpInst.addOperand(Inst.getOperand(1)); // lane
8787     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8788     TmpInst.addOperand(Inst.getOperand(5));
8789     Inst = TmpInst;
8790     return true;
8791   }
8792 
8793   case ARM::VLD4LNdAsm_8:
8794   case ARM::VLD4LNdAsm_16:
8795   case ARM::VLD4LNdAsm_32:
8796   case ARM::VLD4LNqAsm_16:
8797   case ARM::VLD4LNqAsm_32: {
8798     MCInst TmpInst;
8799     // Shuffle the operands around so the lane index operand is in the
8800     // right place.
8801     unsigned Spacing;
8802     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8803     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8804     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8805                                             Spacing));
8806     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8807                                             Spacing * 2));
8808     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8809                                             Spacing * 3));
8810     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8811     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8812     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8813     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8814                                             Spacing));
8815     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8816                                             Spacing * 2));
8817     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8818                                             Spacing * 3));
8819     TmpInst.addOperand(Inst.getOperand(1)); // lane
8820     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8821     TmpInst.addOperand(Inst.getOperand(5));
8822     Inst = TmpInst;
8823     return true;
8824   }
8825 
8826   // VLD3DUP single 3-element structure to all lanes instructions.
8827   case ARM::VLD3DUPdAsm_8:
8828   case ARM::VLD3DUPdAsm_16:
8829   case ARM::VLD3DUPdAsm_32:
8830   case ARM::VLD3DUPqAsm_8:
8831   case ARM::VLD3DUPqAsm_16:
8832   case ARM::VLD3DUPqAsm_32: {
8833     MCInst TmpInst;
8834     unsigned Spacing;
8835     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8836     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8837     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8838                                             Spacing));
8839     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8840                                             Spacing * 2));
8841     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8842     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8843     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8844     TmpInst.addOperand(Inst.getOperand(4));
8845     Inst = TmpInst;
8846     return true;
8847   }
8848 
8849   case ARM::VLD3DUPdWB_fixed_Asm_8:
8850   case ARM::VLD3DUPdWB_fixed_Asm_16:
8851   case ARM::VLD3DUPdWB_fixed_Asm_32:
8852   case ARM::VLD3DUPqWB_fixed_Asm_8:
8853   case ARM::VLD3DUPqWB_fixed_Asm_16:
8854   case ARM::VLD3DUPqWB_fixed_Asm_32: {
8855     MCInst TmpInst;
8856     unsigned Spacing;
8857     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8858     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8859     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8860                                             Spacing));
8861     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8862                                             Spacing * 2));
8863     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8864     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8865     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8866     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8867     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8868     TmpInst.addOperand(Inst.getOperand(4));
8869     Inst = TmpInst;
8870     return true;
8871   }
8872 
8873   case ARM::VLD3DUPdWB_register_Asm_8:
8874   case ARM::VLD3DUPdWB_register_Asm_16:
8875   case ARM::VLD3DUPdWB_register_Asm_32:
8876   case ARM::VLD3DUPqWB_register_Asm_8:
8877   case ARM::VLD3DUPqWB_register_Asm_16:
8878   case ARM::VLD3DUPqWB_register_Asm_32: {
8879     MCInst TmpInst;
8880     unsigned Spacing;
8881     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8882     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8883     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8884                                             Spacing));
8885     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8886                                             Spacing * 2));
8887     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8888     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8889     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8890     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8891     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8892     TmpInst.addOperand(Inst.getOperand(5));
8893     Inst = TmpInst;
8894     return true;
8895   }
8896 
8897   // VLD3 multiple 3-element structure instructions.
8898   case ARM::VLD3dAsm_8:
8899   case ARM::VLD3dAsm_16:
8900   case ARM::VLD3dAsm_32:
8901   case ARM::VLD3qAsm_8:
8902   case ARM::VLD3qAsm_16:
8903   case ARM::VLD3qAsm_32: {
8904     MCInst TmpInst;
8905     unsigned Spacing;
8906     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8907     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8908     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8909                                             Spacing));
8910     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8911                                             Spacing * 2));
8912     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8913     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8914     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8915     TmpInst.addOperand(Inst.getOperand(4));
8916     Inst = TmpInst;
8917     return true;
8918   }
8919 
8920   case ARM::VLD3dWB_fixed_Asm_8:
8921   case ARM::VLD3dWB_fixed_Asm_16:
8922   case ARM::VLD3dWB_fixed_Asm_32:
8923   case ARM::VLD3qWB_fixed_Asm_8:
8924   case ARM::VLD3qWB_fixed_Asm_16:
8925   case ARM::VLD3qWB_fixed_Asm_32: {
8926     MCInst TmpInst;
8927     unsigned Spacing;
8928     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8929     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8930     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8931                                             Spacing));
8932     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8933                                             Spacing * 2));
8934     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8935     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8936     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8937     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8938     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8939     TmpInst.addOperand(Inst.getOperand(4));
8940     Inst = TmpInst;
8941     return true;
8942   }
8943 
8944   case ARM::VLD3dWB_register_Asm_8:
8945   case ARM::VLD3dWB_register_Asm_16:
8946   case ARM::VLD3dWB_register_Asm_32:
8947   case ARM::VLD3qWB_register_Asm_8:
8948   case ARM::VLD3qWB_register_Asm_16:
8949   case ARM::VLD3qWB_register_Asm_32: {
8950     MCInst TmpInst;
8951     unsigned Spacing;
8952     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8953     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8954     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8955                                             Spacing));
8956     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8957                                             Spacing * 2));
8958     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8959     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8960     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8961     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8962     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8963     TmpInst.addOperand(Inst.getOperand(5));
8964     Inst = TmpInst;
8965     return true;
8966   }
8967 
8968   // VLD4DUP single 3-element structure to all lanes instructions.
8969   case ARM::VLD4DUPdAsm_8:
8970   case ARM::VLD4DUPdAsm_16:
8971   case ARM::VLD4DUPdAsm_32:
8972   case ARM::VLD4DUPqAsm_8:
8973   case ARM::VLD4DUPqAsm_16:
8974   case ARM::VLD4DUPqAsm_32: {
8975     MCInst TmpInst;
8976     unsigned Spacing;
8977     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8978     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8979     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8980                                             Spacing));
8981     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8982                                             Spacing * 2));
8983     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8984                                             Spacing * 3));
8985     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8986     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8987     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8988     TmpInst.addOperand(Inst.getOperand(4));
8989     Inst = TmpInst;
8990     return true;
8991   }
8992 
8993   case ARM::VLD4DUPdWB_fixed_Asm_8:
8994   case ARM::VLD4DUPdWB_fixed_Asm_16:
8995   case ARM::VLD4DUPdWB_fixed_Asm_32:
8996   case ARM::VLD4DUPqWB_fixed_Asm_8:
8997   case ARM::VLD4DUPqWB_fixed_Asm_16:
8998   case ARM::VLD4DUPqWB_fixed_Asm_32: {
8999     MCInst TmpInst;
9000     unsigned Spacing;
9001     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9002     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9003     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9004                                             Spacing));
9005     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9006                                             Spacing * 2));
9007     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9008                                             Spacing * 3));
9009     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9010     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9011     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9012     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9013     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9014     TmpInst.addOperand(Inst.getOperand(4));
9015     Inst = TmpInst;
9016     return true;
9017   }
9018 
9019   case ARM::VLD4DUPdWB_register_Asm_8:
9020   case ARM::VLD4DUPdWB_register_Asm_16:
9021   case ARM::VLD4DUPdWB_register_Asm_32:
9022   case ARM::VLD4DUPqWB_register_Asm_8:
9023   case ARM::VLD4DUPqWB_register_Asm_16:
9024   case ARM::VLD4DUPqWB_register_Asm_32: {
9025     MCInst TmpInst;
9026     unsigned Spacing;
9027     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9028     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9029     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9030                                             Spacing));
9031     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9032                                             Spacing * 2));
9033     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9034                                             Spacing * 3));
9035     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9036     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9037     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9038     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9039     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9040     TmpInst.addOperand(Inst.getOperand(5));
9041     Inst = TmpInst;
9042     return true;
9043   }
9044 
9045   // VLD4 multiple 4-element structure instructions.
9046   case ARM::VLD4dAsm_8:
9047   case ARM::VLD4dAsm_16:
9048   case ARM::VLD4dAsm_32:
9049   case ARM::VLD4qAsm_8:
9050   case ARM::VLD4qAsm_16:
9051   case ARM::VLD4qAsm_32: {
9052     MCInst TmpInst;
9053     unsigned Spacing;
9054     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9055     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9056     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9057                                             Spacing));
9058     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9059                                             Spacing * 2));
9060     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9061                                             Spacing * 3));
9062     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9063     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9064     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9065     TmpInst.addOperand(Inst.getOperand(4));
9066     Inst = TmpInst;
9067     return true;
9068   }
9069 
9070   case ARM::VLD4dWB_fixed_Asm_8:
9071   case ARM::VLD4dWB_fixed_Asm_16:
9072   case ARM::VLD4dWB_fixed_Asm_32:
9073   case ARM::VLD4qWB_fixed_Asm_8:
9074   case ARM::VLD4qWB_fixed_Asm_16:
9075   case ARM::VLD4qWB_fixed_Asm_32: {
9076     MCInst TmpInst;
9077     unsigned Spacing;
9078     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9079     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9080     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9081                                             Spacing));
9082     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9083                                             Spacing * 2));
9084     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9085                                             Spacing * 3));
9086     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9087     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9088     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9089     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9090     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9091     TmpInst.addOperand(Inst.getOperand(4));
9092     Inst = TmpInst;
9093     return true;
9094   }
9095 
9096   case ARM::VLD4dWB_register_Asm_8:
9097   case ARM::VLD4dWB_register_Asm_16:
9098   case ARM::VLD4dWB_register_Asm_32:
9099   case ARM::VLD4qWB_register_Asm_8:
9100   case ARM::VLD4qWB_register_Asm_16:
9101   case ARM::VLD4qWB_register_Asm_32: {
9102     MCInst TmpInst;
9103     unsigned Spacing;
9104     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9105     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9106     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9107                                             Spacing));
9108     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9109                                             Spacing * 2));
9110     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9111                                             Spacing * 3));
9112     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9113     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9114     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9115     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9116     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9117     TmpInst.addOperand(Inst.getOperand(5));
9118     Inst = TmpInst;
9119     return true;
9120   }
9121 
9122   // VST3 multiple 3-element structure instructions.
9123   case ARM::VST3dAsm_8:
9124   case ARM::VST3dAsm_16:
9125   case ARM::VST3dAsm_32:
9126   case ARM::VST3qAsm_8:
9127   case ARM::VST3qAsm_16:
9128   case ARM::VST3qAsm_32: {
9129     MCInst TmpInst;
9130     unsigned Spacing;
9131     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9132     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9133     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9134     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9135     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9136                                             Spacing));
9137     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9138                                             Spacing * 2));
9139     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9140     TmpInst.addOperand(Inst.getOperand(4));
9141     Inst = TmpInst;
9142     return true;
9143   }
9144 
9145   case ARM::VST3dWB_fixed_Asm_8:
9146   case ARM::VST3dWB_fixed_Asm_16:
9147   case ARM::VST3dWB_fixed_Asm_32:
9148   case ARM::VST3qWB_fixed_Asm_8:
9149   case ARM::VST3qWB_fixed_Asm_16:
9150   case ARM::VST3qWB_fixed_Asm_32: {
9151     MCInst TmpInst;
9152     unsigned Spacing;
9153     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9154     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9155     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9156     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9157     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9158     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9159     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9160                                             Spacing));
9161     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9162                                             Spacing * 2));
9163     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9164     TmpInst.addOperand(Inst.getOperand(4));
9165     Inst = TmpInst;
9166     return true;
9167   }
9168 
9169   case ARM::VST3dWB_register_Asm_8:
9170   case ARM::VST3dWB_register_Asm_16:
9171   case ARM::VST3dWB_register_Asm_32:
9172   case ARM::VST3qWB_register_Asm_8:
9173   case ARM::VST3qWB_register_Asm_16:
9174   case ARM::VST3qWB_register_Asm_32: {
9175     MCInst TmpInst;
9176     unsigned Spacing;
9177     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9178     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9179     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9180     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9181     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9182     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9183     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9184                                             Spacing));
9185     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9186                                             Spacing * 2));
9187     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9188     TmpInst.addOperand(Inst.getOperand(5));
9189     Inst = TmpInst;
9190     return true;
9191   }
9192 
9193   // VST4 multiple 3-element structure instructions.
9194   case ARM::VST4dAsm_8:
9195   case ARM::VST4dAsm_16:
9196   case ARM::VST4dAsm_32:
9197   case ARM::VST4qAsm_8:
9198   case ARM::VST4qAsm_16:
9199   case ARM::VST4qAsm_32: {
9200     MCInst TmpInst;
9201     unsigned Spacing;
9202     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9203     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9204     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9205     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9206     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9207                                             Spacing));
9208     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9209                                             Spacing * 2));
9210     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9211                                             Spacing * 3));
9212     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9213     TmpInst.addOperand(Inst.getOperand(4));
9214     Inst = TmpInst;
9215     return true;
9216   }
9217 
9218   case ARM::VST4dWB_fixed_Asm_8:
9219   case ARM::VST4dWB_fixed_Asm_16:
9220   case ARM::VST4dWB_fixed_Asm_32:
9221   case ARM::VST4qWB_fixed_Asm_8:
9222   case ARM::VST4qWB_fixed_Asm_16:
9223   case ARM::VST4qWB_fixed_Asm_32: {
9224     MCInst TmpInst;
9225     unsigned Spacing;
9226     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9227     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9228     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9229     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9230     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9231     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9232     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9233                                             Spacing));
9234     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9235                                             Spacing * 2));
9236     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9237                                             Spacing * 3));
9238     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9239     TmpInst.addOperand(Inst.getOperand(4));
9240     Inst = TmpInst;
9241     return true;
9242   }
9243 
9244   case ARM::VST4dWB_register_Asm_8:
9245   case ARM::VST4dWB_register_Asm_16:
9246   case ARM::VST4dWB_register_Asm_32:
9247   case ARM::VST4qWB_register_Asm_8:
9248   case ARM::VST4qWB_register_Asm_16:
9249   case ARM::VST4qWB_register_Asm_32: {
9250     MCInst TmpInst;
9251     unsigned Spacing;
9252     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9253     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9254     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9255     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9256     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9257     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9258     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9259                                             Spacing));
9260     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9261                                             Spacing * 2));
9262     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9263                                             Spacing * 3));
9264     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9265     TmpInst.addOperand(Inst.getOperand(5));
9266     Inst = TmpInst;
9267     return true;
9268   }
9269 
9270   // Handle encoding choice for the shift-immediate instructions.
9271   case ARM::t2LSLri:
9272   case ARM::t2LSRri:
9273   case ARM::t2ASRri:
9274     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9275         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9276         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9277         !HasWideQualifier) {
9278       unsigned NewOpc;
9279       switch (Inst.getOpcode()) {
9280       default: llvm_unreachable("unexpected opcode");
9281       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
9282       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
9283       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
9284       }
9285       // The Thumb1 operands aren't in the same order. Awesome, eh?
9286       MCInst TmpInst;
9287       TmpInst.setOpcode(NewOpc);
9288       TmpInst.addOperand(Inst.getOperand(0));
9289       TmpInst.addOperand(Inst.getOperand(5));
9290       TmpInst.addOperand(Inst.getOperand(1));
9291       TmpInst.addOperand(Inst.getOperand(2));
9292       TmpInst.addOperand(Inst.getOperand(3));
9293       TmpInst.addOperand(Inst.getOperand(4));
9294       Inst = TmpInst;
9295       return true;
9296     }
9297     return false;
9298 
9299   // Handle the Thumb2 mode MOV complex aliases.
9300   case ARM::t2MOVsr:
9301   case ARM::t2MOVSsr: {
9302     // Which instruction to expand to depends on the CCOut operand and
9303     // whether we're in an IT block if the register operands are low
9304     // registers.
9305     bool isNarrow = false;
9306     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9307         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9308         isARMLowRegister(Inst.getOperand(2).getReg()) &&
9309         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
9310         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
9311         !HasWideQualifier)
9312       isNarrow = true;
9313     MCInst TmpInst;
9314     unsigned newOpc;
9315     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
9316     default: llvm_unreachable("unexpected opcode!");
9317     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
9318     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
9319     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
9320     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
9321     }
9322     TmpInst.setOpcode(newOpc);
9323     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9324     if (isNarrow)
9325       TmpInst.addOperand(MCOperand::createReg(
9326           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9327     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9328     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9329     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9330     TmpInst.addOperand(Inst.getOperand(5));
9331     if (!isNarrow)
9332       TmpInst.addOperand(MCOperand::createReg(
9333           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9334     Inst = TmpInst;
9335     return true;
9336   }
9337   case ARM::t2MOVsi:
9338   case ARM::t2MOVSsi: {
9339     // Which instruction to expand to depends on the CCOut operand and
9340     // whether we're in an IT block if the register operands are low
9341     // registers.
9342     bool isNarrow = false;
9343     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9344         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9345         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
9346         !HasWideQualifier)
9347       isNarrow = true;
9348     MCInst TmpInst;
9349     unsigned newOpc;
9350     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
9351     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
9352     bool isMov = false;
9353     // MOV rd, rm, LSL #0 is actually a MOV instruction
9354     if (Shift == ARM_AM::lsl && Amount == 0) {
9355       isMov = true;
9356       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
9357       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
9358       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
9359       // instead.
9360       if (inITBlock()) {
9361         isNarrow = false;
9362       }
9363       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
9364     } else {
9365       switch(Shift) {
9366       default: llvm_unreachable("unexpected opcode!");
9367       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
9368       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
9369       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
9370       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
9371       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
9372       }
9373     }
9374     if (Amount == 32) Amount = 0;
9375     TmpInst.setOpcode(newOpc);
9376     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9377     if (isNarrow && !isMov)
9378       TmpInst.addOperand(MCOperand::createReg(
9379           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9380     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9381     if (newOpc != ARM::t2RRX && !isMov)
9382       TmpInst.addOperand(MCOperand::createImm(Amount));
9383     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9384     TmpInst.addOperand(Inst.getOperand(4));
9385     if (!isNarrow)
9386       TmpInst.addOperand(MCOperand::createReg(
9387           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9388     Inst = TmpInst;
9389     return true;
9390   }
9391   // Handle the ARM mode MOV complex aliases.
9392   case ARM::ASRr:
9393   case ARM::LSRr:
9394   case ARM::LSLr:
9395   case ARM::RORr: {
9396     ARM_AM::ShiftOpc ShiftTy;
9397     switch(Inst.getOpcode()) {
9398     default: llvm_unreachable("unexpected opcode!");
9399     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
9400     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
9401     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
9402     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
9403     }
9404     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
9405     MCInst TmpInst;
9406     TmpInst.setOpcode(ARM::MOVsr);
9407     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9408     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9409     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9410     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9411     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9412     TmpInst.addOperand(Inst.getOperand(4));
9413     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9414     Inst = TmpInst;
9415     return true;
9416   }
9417   case ARM::ASRi:
9418   case ARM::LSRi:
9419   case ARM::LSLi:
9420   case ARM::RORi: {
9421     ARM_AM::ShiftOpc ShiftTy;
9422     switch(Inst.getOpcode()) {
9423     default: llvm_unreachable("unexpected opcode!");
9424     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
9425     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
9426     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
9427     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
9428     }
9429     // A shift by zero is a plain MOVr, not a MOVsi.
9430     unsigned Amt = Inst.getOperand(2).getImm();
9431     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
9432     // A shift by 32 should be encoded as 0 when permitted
9433     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
9434       Amt = 0;
9435     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
9436     MCInst TmpInst;
9437     TmpInst.setOpcode(Opc);
9438     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9439     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9440     if (Opc == ARM::MOVsi)
9441       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9442     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9443     TmpInst.addOperand(Inst.getOperand(4));
9444     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9445     Inst = TmpInst;
9446     return true;
9447   }
9448   case ARM::RRXi: {
9449     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
9450     MCInst TmpInst;
9451     TmpInst.setOpcode(ARM::MOVsi);
9452     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9453     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9454     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9455     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9456     TmpInst.addOperand(Inst.getOperand(3));
9457     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
9458     Inst = TmpInst;
9459     return true;
9460   }
9461   case ARM::t2LDMIA_UPD: {
9462     // If this is a load of a single register, then we should use
9463     // a post-indexed LDR instruction instead, per the ARM ARM.
9464     if (Inst.getNumOperands() != 5)
9465       return false;
9466     MCInst TmpInst;
9467     TmpInst.setOpcode(ARM::t2LDR_POST);
9468     TmpInst.addOperand(Inst.getOperand(4)); // Rt
9469     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9470     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9471     TmpInst.addOperand(MCOperand::createImm(4));
9472     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9473     TmpInst.addOperand(Inst.getOperand(3));
9474     Inst = TmpInst;
9475     return true;
9476   }
9477   case ARM::t2STMDB_UPD: {
9478     // If this is a store of a single register, then we should use
9479     // a pre-indexed STR instruction instead, per the ARM ARM.
9480     if (Inst.getNumOperands() != 5)
9481       return false;
9482     MCInst TmpInst;
9483     TmpInst.setOpcode(ARM::t2STR_PRE);
9484     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9485     TmpInst.addOperand(Inst.getOperand(4)); // Rt
9486     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9487     TmpInst.addOperand(MCOperand::createImm(-4));
9488     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9489     TmpInst.addOperand(Inst.getOperand(3));
9490     Inst = TmpInst;
9491     return true;
9492   }
9493   case ARM::LDMIA_UPD:
9494     // If this is a load of a single register via a 'pop', then we should use
9495     // a post-indexed LDR instruction instead, per the ARM ARM.
9496     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
9497         Inst.getNumOperands() == 5) {
9498       MCInst TmpInst;
9499       TmpInst.setOpcode(ARM::LDR_POST_IMM);
9500       TmpInst.addOperand(Inst.getOperand(4)); // Rt
9501       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9502       TmpInst.addOperand(Inst.getOperand(1)); // Rn
9503       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
9504       TmpInst.addOperand(MCOperand::createImm(4));
9505       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9506       TmpInst.addOperand(Inst.getOperand(3));
9507       Inst = TmpInst;
9508       return true;
9509     }
9510     break;
9511   case ARM::STMDB_UPD:
9512     // If this is a store of a single register via a 'push', then we should use
9513     // a pre-indexed STR instruction instead, per the ARM ARM.
9514     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
9515         Inst.getNumOperands() == 5) {
9516       MCInst TmpInst;
9517       TmpInst.setOpcode(ARM::STR_PRE_IMM);
9518       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9519       TmpInst.addOperand(Inst.getOperand(4)); // Rt
9520       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
9521       TmpInst.addOperand(MCOperand::createImm(-4));
9522       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9523       TmpInst.addOperand(Inst.getOperand(3));
9524       Inst = TmpInst;
9525     }
9526     break;
9527   case ARM::t2ADDri12:
9528     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
9529     // mnemonic was used (not "addw"), encoding T3 is preferred.
9530     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
9531         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
9532       break;
9533     Inst.setOpcode(ARM::t2ADDri);
9534     Inst.addOperand(MCOperand::createReg(0)); // cc_out
9535     break;
9536   case ARM::t2SUBri12:
9537     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
9538     // mnemonic was used (not "subw"), encoding T3 is preferred.
9539     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
9540         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
9541       break;
9542     Inst.setOpcode(ARM::t2SUBri);
9543     Inst.addOperand(MCOperand::createReg(0)); // cc_out
9544     break;
9545   case ARM::tADDi8:
9546     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
9547     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
9548     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
9549     // to encoding T1 if <Rd> is omitted."
9550     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
9551       Inst.setOpcode(ARM::tADDi3);
9552       return true;
9553     }
9554     break;
9555   case ARM::tSUBi8:
9556     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
9557     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
9558     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
9559     // to encoding T1 if <Rd> is omitted."
9560     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
9561       Inst.setOpcode(ARM::tSUBi3);
9562       return true;
9563     }
9564     break;
9565   case ARM::t2ADDri:
9566   case ARM::t2SUBri: {
9567     // If the destination and first source operand are the same, and
9568     // the flags are compatible with the current IT status, use encoding T2
9569     // instead of T3. For compatibility with the system 'as'. Make sure the
9570     // wide encoding wasn't explicit.
9571     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
9572         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
9573         (Inst.getOperand(2).isImm() &&
9574          (unsigned)Inst.getOperand(2).getImm() > 255) ||
9575         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
9576         HasWideQualifier)
9577       break;
9578     MCInst TmpInst;
9579     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
9580                       ARM::tADDi8 : ARM::tSUBi8);
9581     TmpInst.addOperand(Inst.getOperand(0));
9582     TmpInst.addOperand(Inst.getOperand(5));
9583     TmpInst.addOperand(Inst.getOperand(0));
9584     TmpInst.addOperand(Inst.getOperand(2));
9585     TmpInst.addOperand(Inst.getOperand(3));
9586     TmpInst.addOperand(Inst.getOperand(4));
9587     Inst = TmpInst;
9588     return true;
9589   }
9590   case ARM::t2ADDrr: {
9591     // If the destination and first source operand are the same, and
9592     // there's no setting of the flags, use encoding T2 instead of T3.
9593     // Note that this is only for ADD, not SUB. This mirrors the system
9594     // 'as' behaviour.  Also take advantage of ADD being commutative.
9595     // Make sure the wide encoding wasn't explicit.
9596     bool Swap = false;
9597     auto DestReg = Inst.getOperand(0).getReg();
9598     bool Transform = DestReg == Inst.getOperand(1).getReg();
9599     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
9600       Transform = true;
9601       Swap = true;
9602     }
9603     if (!Transform ||
9604         Inst.getOperand(5).getReg() != 0 ||
9605         HasWideQualifier)
9606       break;
9607     MCInst TmpInst;
9608     TmpInst.setOpcode(ARM::tADDhirr);
9609     TmpInst.addOperand(Inst.getOperand(0));
9610     TmpInst.addOperand(Inst.getOperand(0));
9611     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
9612     TmpInst.addOperand(Inst.getOperand(3));
9613     TmpInst.addOperand(Inst.getOperand(4));
9614     Inst = TmpInst;
9615     return true;
9616   }
9617   case ARM::tADDrSP:
9618     // If the non-SP source operand and the destination operand are not the
9619     // same, we need to use the 32-bit encoding if it's available.
9620     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
9621       Inst.setOpcode(ARM::t2ADDrr);
9622       Inst.addOperand(MCOperand::createReg(0)); // cc_out
9623       return true;
9624     }
9625     break;
9626   case ARM::tB:
9627     // A Thumb conditional branch outside of an IT block is a tBcc.
9628     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
9629       Inst.setOpcode(ARM::tBcc);
9630       return true;
9631     }
9632     break;
9633   case ARM::t2B:
9634     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
9635     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
9636       Inst.setOpcode(ARM::t2Bcc);
9637       return true;
9638     }
9639     break;
9640   case ARM::t2Bcc:
9641     // If the conditional is AL or we're in an IT block, we really want t2B.
9642     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
9643       Inst.setOpcode(ARM::t2B);
9644       return true;
9645     }
9646     break;
9647   case ARM::tBcc:
9648     // If the conditional is AL, we really want tB.
9649     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
9650       Inst.setOpcode(ARM::tB);
9651       return true;
9652     }
9653     break;
9654   case ARM::tLDMIA: {
9655     // If the register list contains any high registers, or if the writeback
9656     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
9657     // instead if we're in Thumb2. Otherwise, this should have generated
9658     // an error in validateInstruction().
9659     unsigned Rn = Inst.getOperand(0).getReg();
9660     bool hasWritebackToken =
9661         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
9662          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
9663     bool listContainsBase;
9664     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
9665         (!listContainsBase && !hasWritebackToken) ||
9666         (listContainsBase && hasWritebackToken)) {
9667       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
9668       assert(isThumbTwo());
9669       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
9670       // If we're switching to the updating version, we need to insert
9671       // the writeback tied operand.
9672       if (hasWritebackToken)
9673         Inst.insert(Inst.begin(),
9674                     MCOperand::createReg(Inst.getOperand(0).getReg()));
9675       return true;
9676     }
9677     break;
9678   }
9679   case ARM::tSTMIA_UPD: {
9680     // If the register list contains any high registers, we need to use
9681     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
9682     // should have generated an error in validateInstruction().
9683     unsigned Rn = Inst.getOperand(0).getReg();
9684     bool listContainsBase;
9685     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
9686       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
9687       assert(isThumbTwo());
9688       Inst.setOpcode(ARM::t2STMIA_UPD);
9689       return true;
9690     }
9691     break;
9692   }
9693   case ARM::tPOP: {
9694     bool listContainsBase;
9695     // If the register list contains any high registers, we need to use
9696     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
9697     // should have generated an error in validateInstruction().
9698     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
9699       return false;
9700     assert(isThumbTwo());
9701     Inst.setOpcode(ARM::t2LDMIA_UPD);
9702     // Add the base register and writeback operands.
9703     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9704     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9705     return true;
9706   }
9707   case ARM::tPUSH: {
9708     bool listContainsBase;
9709     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
9710       return false;
9711     assert(isThumbTwo());
9712     Inst.setOpcode(ARM::t2STMDB_UPD);
9713     // Add the base register and writeback operands.
9714     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9715     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9716     return true;
9717   }
9718   case ARM::t2MOVi:
9719     // If we can use the 16-bit encoding and the user didn't explicitly
9720     // request the 32-bit variant, transform it here.
9721     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9722         (Inst.getOperand(1).isImm() &&
9723          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
9724         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9725         !HasWideQualifier) {
9726       // The operands aren't in the same order for tMOVi8...
9727       MCInst TmpInst;
9728       TmpInst.setOpcode(ARM::tMOVi8);
9729       TmpInst.addOperand(Inst.getOperand(0));
9730       TmpInst.addOperand(Inst.getOperand(4));
9731       TmpInst.addOperand(Inst.getOperand(1));
9732       TmpInst.addOperand(Inst.getOperand(2));
9733       TmpInst.addOperand(Inst.getOperand(3));
9734       Inst = TmpInst;
9735       return true;
9736     }
9737     break;
9738 
9739   case ARM::t2MOVr:
9740     // If we can use the 16-bit encoding and the user didn't explicitly
9741     // request the 32-bit variant, transform it here.
9742     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9743         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9744         Inst.getOperand(2).getImm() == ARMCC::AL &&
9745         Inst.getOperand(4).getReg() == ARM::CPSR &&
9746         !HasWideQualifier) {
9747       // The operands aren't the same for tMOV[S]r... (no cc_out)
9748       MCInst TmpInst;
9749       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
9750       TmpInst.addOperand(Inst.getOperand(0));
9751       TmpInst.addOperand(Inst.getOperand(1));
9752       TmpInst.addOperand(Inst.getOperand(2));
9753       TmpInst.addOperand(Inst.getOperand(3));
9754       Inst = TmpInst;
9755       return true;
9756     }
9757     break;
9758 
9759   case ARM::t2SXTH:
9760   case ARM::t2SXTB:
9761   case ARM::t2UXTH:
9762   case ARM::t2UXTB:
9763     // If we can use the 16-bit encoding and the user didn't explicitly
9764     // request the 32-bit variant, transform it here.
9765     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9766         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9767         Inst.getOperand(2).getImm() == 0 &&
9768         !HasWideQualifier) {
9769       unsigned NewOpc;
9770       switch (Inst.getOpcode()) {
9771       default: llvm_unreachable("Illegal opcode!");
9772       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
9773       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
9774       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
9775       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
9776       }
9777       // The operands aren't the same for thumb1 (no rotate operand).
9778       MCInst TmpInst;
9779       TmpInst.setOpcode(NewOpc);
9780       TmpInst.addOperand(Inst.getOperand(0));
9781       TmpInst.addOperand(Inst.getOperand(1));
9782       TmpInst.addOperand(Inst.getOperand(3));
9783       TmpInst.addOperand(Inst.getOperand(4));
9784       Inst = TmpInst;
9785       return true;
9786     }
9787     break;
9788 
9789   case ARM::MOVsi: {
9790     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
9791     // rrx shifts and asr/lsr of #32 is encoded as 0
9792     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
9793       return false;
9794     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
9795       // Shifting by zero is accepted as a vanilla 'MOVr'
9796       MCInst TmpInst;
9797       TmpInst.setOpcode(ARM::MOVr);
9798       TmpInst.addOperand(Inst.getOperand(0));
9799       TmpInst.addOperand(Inst.getOperand(1));
9800       TmpInst.addOperand(Inst.getOperand(3));
9801       TmpInst.addOperand(Inst.getOperand(4));
9802       TmpInst.addOperand(Inst.getOperand(5));
9803       Inst = TmpInst;
9804       return true;
9805     }
9806     return false;
9807   }
9808   case ARM::ANDrsi:
9809   case ARM::ORRrsi:
9810   case ARM::EORrsi:
9811   case ARM::BICrsi:
9812   case ARM::SUBrsi:
9813   case ARM::ADDrsi: {
9814     unsigned newOpc;
9815     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
9816     if (SOpc == ARM_AM::rrx) return false;
9817     switch (Inst.getOpcode()) {
9818     default: llvm_unreachable("unexpected opcode!");
9819     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
9820     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
9821     case ARM::EORrsi: newOpc = ARM::EORrr; break;
9822     case ARM::BICrsi: newOpc = ARM::BICrr; break;
9823     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
9824     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
9825     }
9826     // If the shift is by zero, use the non-shifted instruction definition.
9827     // The exception is for right shifts, where 0 == 32
9828     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
9829         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
9830       MCInst TmpInst;
9831       TmpInst.setOpcode(newOpc);
9832       TmpInst.addOperand(Inst.getOperand(0));
9833       TmpInst.addOperand(Inst.getOperand(1));
9834       TmpInst.addOperand(Inst.getOperand(2));
9835       TmpInst.addOperand(Inst.getOperand(4));
9836       TmpInst.addOperand(Inst.getOperand(5));
9837       TmpInst.addOperand(Inst.getOperand(6));
9838       Inst = TmpInst;
9839       return true;
9840     }
9841     return false;
9842   }
9843   case ARM::ITasm:
9844   case ARM::t2IT: {
9845     // Set up the IT block state according to the IT instruction we just
9846     // matched.
9847     assert(!inITBlock() && "nested IT blocks?!");
9848     startExplicitITBlock(ARMCC::CondCodes(Inst.getOperand(0).getImm()),
9849                          Inst.getOperand(1).getImm());
9850     break;
9851   }
9852   case ARM::t2LSLrr:
9853   case ARM::t2LSRrr:
9854   case ARM::t2ASRrr:
9855   case ARM::t2SBCrr:
9856   case ARM::t2RORrr:
9857   case ARM::t2BICrr:
9858     // Assemblers should use the narrow encodings of these instructions when permissible.
9859     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
9860          isARMLowRegister(Inst.getOperand(2).getReg())) &&
9861         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
9862         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9863         !HasWideQualifier) {
9864       unsigned NewOpc;
9865       switch (Inst.getOpcode()) {
9866         default: llvm_unreachable("unexpected opcode");
9867         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
9868         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
9869         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
9870         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
9871         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
9872         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
9873       }
9874       MCInst TmpInst;
9875       TmpInst.setOpcode(NewOpc);
9876       TmpInst.addOperand(Inst.getOperand(0));
9877       TmpInst.addOperand(Inst.getOperand(5));
9878       TmpInst.addOperand(Inst.getOperand(1));
9879       TmpInst.addOperand(Inst.getOperand(2));
9880       TmpInst.addOperand(Inst.getOperand(3));
9881       TmpInst.addOperand(Inst.getOperand(4));
9882       Inst = TmpInst;
9883       return true;
9884     }
9885     return false;
9886 
9887   case ARM::t2ANDrr:
9888   case ARM::t2EORrr:
9889   case ARM::t2ADCrr:
9890   case ARM::t2ORRrr:
9891     // Assemblers should use the narrow encodings of these instructions when permissible.
9892     // These instructions are special in that they are commutable, so shorter encodings
9893     // are available more often.
9894     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
9895          isARMLowRegister(Inst.getOperand(2).getReg())) &&
9896         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
9897          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
9898         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9899         !HasWideQualifier) {
9900       unsigned NewOpc;
9901       switch (Inst.getOpcode()) {
9902         default: llvm_unreachable("unexpected opcode");
9903         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
9904         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
9905         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
9906         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
9907       }
9908       MCInst TmpInst;
9909       TmpInst.setOpcode(NewOpc);
9910       TmpInst.addOperand(Inst.getOperand(0));
9911       TmpInst.addOperand(Inst.getOperand(5));
9912       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
9913         TmpInst.addOperand(Inst.getOperand(1));
9914         TmpInst.addOperand(Inst.getOperand(2));
9915       } else {
9916         TmpInst.addOperand(Inst.getOperand(2));
9917         TmpInst.addOperand(Inst.getOperand(1));
9918       }
9919       TmpInst.addOperand(Inst.getOperand(3));
9920       TmpInst.addOperand(Inst.getOperand(4));
9921       Inst = TmpInst;
9922       return true;
9923     }
9924     return false;
9925   case ARM::MVE_VPST:
9926   case ARM::MVE_VPTv16i8:
9927   case ARM::MVE_VPTv8i16:
9928   case ARM::MVE_VPTv4i32:
9929   case ARM::MVE_VPTv16u8:
9930   case ARM::MVE_VPTv8u16:
9931   case ARM::MVE_VPTv4u32:
9932   case ARM::MVE_VPTv16s8:
9933   case ARM::MVE_VPTv8s16:
9934   case ARM::MVE_VPTv4s32:
9935   case ARM::MVE_VPTv4f32:
9936   case ARM::MVE_VPTv8f16:
9937   case ARM::MVE_VPTv16i8r:
9938   case ARM::MVE_VPTv8i16r:
9939   case ARM::MVE_VPTv4i32r:
9940   case ARM::MVE_VPTv16u8r:
9941   case ARM::MVE_VPTv8u16r:
9942   case ARM::MVE_VPTv4u32r:
9943   case ARM::MVE_VPTv16s8r:
9944   case ARM::MVE_VPTv8s16r:
9945   case ARM::MVE_VPTv4s32r:
9946   case ARM::MVE_VPTv4f32r:
9947   case ARM::MVE_VPTv8f16r: {
9948     assert(!inVPTBlock() && "Nested VPT blocks are not allowed");
9949     MCOperand &MO = Inst.getOperand(0);
9950     VPTState.Mask = MO.getImm();
9951     VPTState.CurPosition = 0;
9952     break;
9953   }
9954   }
9955   return false;
9956 }
9957 
9958 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
9959   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
9960   // suffix depending on whether they're in an IT block or not.
9961   unsigned Opc = Inst.getOpcode();
9962   const MCInstrDesc &MCID = MII.get(Opc);
9963   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
9964     assert(MCID.hasOptionalDef() &&
9965            "optionally flag setting instruction missing optional def operand");
9966     assert(MCID.NumOperands == Inst.getNumOperands() &&
9967            "operand count mismatch!");
9968     // Find the optional-def operand (cc_out).
9969     unsigned OpNo;
9970     for (OpNo = 0;
9971          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
9972          ++OpNo)
9973       ;
9974     // If we're parsing Thumb1, reject it completely.
9975     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
9976       return Match_RequiresFlagSetting;
9977     // If we're parsing Thumb2, which form is legal depends on whether we're
9978     // in an IT block.
9979     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
9980         !inITBlock())
9981       return Match_RequiresITBlock;
9982     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
9983         inITBlock())
9984       return Match_RequiresNotITBlock;
9985     // LSL with zero immediate is not allowed in an IT block
9986     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
9987       return Match_RequiresNotITBlock;
9988   } else if (isThumbOne()) {
9989     // Some high-register supporting Thumb1 encodings only allow both registers
9990     // to be from r0-r7 when in Thumb2.
9991     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
9992         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9993         isARMLowRegister(Inst.getOperand(2).getReg()))
9994       return Match_RequiresThumb2;
9995     // Others only require ARMv6 or later.
9996     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
9997              isARMLowRegister(Inst.getOperand(0).getReg()) &&
9998              isARMLowRegister(Inst.getOperand(1).getReg()))
9999       return Match_RequiresV6;
10000   }
10001 
10002   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
10003   // than the loop below can handle, so it uses the GPRnopc register class and
10004   // we do SP handling here.
10005   if (Opc == ARM::t2MOVr && !hasV8Ops())
10006   {
10007     // SP as both source and destination is not allowed
10008     if (Inst.getOperand(0).getReg() == ARM::SP &&
10009         Inst.getOperand(1).getReg() == ARM::SP)
10010       return Match_RequiresV8;
10011     // When flags-setting SP as either source or destination is not allowed
10012     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
10013         (Inst.getOperand(0).getReg() == ARM::SP ||
10014          Inst.getOperand(1).getReg() == ARM::SP))
10015       return Match_RequiresV8;
10016   }
10017 
10018   switch (Inst.getOpcode()) {
10019   case ARM::VMRS:
10020   case ARM::VMSR:
10021   case ARM::VMRS_FPCXTS:
10022   case ARM::VMRS_FPCXTNS:
10023   case ARM::VMSR_FPCXTS:
10024   case ARM::VMSR_FPCXTNS:
10025   case ARM::VMRS_FPSCR_NZCVQC:
10026   case ARM::VMSR_FPSCR_NZCVQC:
10027   case ARM::FMSTAT:
10028   case ARM::VMRS_VPR:
10029   case ARM::VMRS_P0:
10030   case ARM::VMSR_VPR:
10031   case ARM::VMSR_P0:
10032     // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
10033     // ARMv8-A.
10034     if (Inst.getOperand(0).isReg() && Inst.getOperand(0).getReg() == ARM::SP &&
10035         (isThumb() && !hasV8Ops()))
10036       return Match_InvalidOperand;
10037     break;
10038   default:
10039     break;
10040   }
10041 
10042   for (unsigned I = 0; I < MCID.NumOperands; ++I)
10043     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
10044       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
10045       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
10046         return Match_RequiresV8;
10047       else if (Inst.getOperand(I).getReg() == ARM::PC)
10048         return Match_InvalidOperand;
10049     }
10050 
10051   return Match_Success;
10052 }
10053 
10054 namespace llvm {
10055 
10056 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
10057   return true; // In an assembly source, no need to second-guess
10058 }
10059 
10060 } // end namespace llvm
10061 
10062 // Returns true if Inst is unpredictable if it is in and IT block, but is not
10063 // the last instruction in the block.
10064 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
10065   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10066 
10067   // All branch & call instructions terminate IT blocks with the exception of
10068   // SVC.
10069   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
10070       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
10071     return true;
10072 
10073   // Any arithmetic instruction which writes to the PC also terminates the IT
10074   // block.
10075   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
10076     return true;
10077 
10078   return false;
10079 }
10080 
10081 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
10082                                           SmallVectorImpl<NearMissInfo> &NearMisses,
10083                                           bool MatchingInlineAsm,
10084                                           bool &EmitInITBlock,
10085                                           MCStreamer &Out) {
10086   // If we can't use an implicit IT block here, just match as normal.
10087   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
10088     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10089 
10090   // Try to match the instruction in an extension of the current IT block (if
10091   // there is one).
10092   if (inImplicitITBlock()) {
10093     extendImplicitITBlock(ITState.Cond);
10094     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10095             Match_Success) {
10096       // The match succeded, but we still have to check that the instruction is
10097       // valid in this implicit IT block.
10098       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10099       if (MCID.isPredicable()) {
10100         ARMCC::CondCodes InstCond =
10101             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10102                 .getImm();
10103         ARMCC::CondCodes ITCond = currentITCond();
10104         if (InstCond == ITCond) {
10105           EmitInITBlock = true;
10106           return Match_Success;
10107         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
10108           invertCurrentITCondition();
10109           EmitInITBlock = true;
10110           return Match_Success;
10111         }
10112       }
10113     }
10114     rewindImplicitITPosition();
10115   }
10116 
10117   // Finish the current IT block, and try to match outside any IT block.
10118   flushPendingInstructions(Out);
10119   unsigned PlainMatchResult =
10120       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10121   if (PlainMatchResult == Match_Success) {
10122     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10123     if (MCID.isPredicable()) {
10124       ARMCC::CondCodes InstCond =
10125           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10126               .getImm();
10127       // Some forms of the branch instruction have their own condition code
10128       // fields, so can be conditionally executed without an IT block.
10129       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
10130         EmitInITBlock = false;
10131         return Match_Success;
10132       }
10133       if (InstCond == ARMCC::AL) {
10134         EmitInITBlock = false;
10135         return Match_Success;
10136       }
10137     } else {
10138       EmitInITBlock = false;
10139       return Match_Success;
10140     }
10141   }
10142 
10143   // Try to match in a new IT block. The matcher doesn't check the actual
10144   // condition, so we create an IT block with a dummy condition, and fix it up
10145   // once we know the actual condition.
10146   startImplicitITBlock();
10147   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10148       Match_Success) {
10149     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10150     if (MCID.isPredicable()) {
10151       ITState.Cond =
10152           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10153               .getImm();
10154       EmitInITBlock = true;
10155       return Match_Success;
10156     }
10157   }
10158   discardImplicitITBlock();
10159 
10160   // If none of these succeed, return the error we got when trying to match
10161   // outside any IT blocks.
10162   EmitInITBlock = false;
10163   return PlainMatchResult;
10164 }
10165 
10166 static std::string ARMMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
10167                                          unsigned VariantID = 0);
10168 
10169 static const char *getSubtargetFeatureName(uint64_t Val);
10170 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
10171                                            OperandVector &Operands,
10172                                            MCStreamer &Out, uint64_t &ErrorInfo,
10173                                            bool MatchingInlineAsm) {
10174   MCInst Inst;
10175   unsigned MatchResult;
10176   bool PendConditionalInstruction = false;
10177 
10178   SmallVector<NearMissInfo, 4> NearMisses;
10179   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
10180                                  PendConditionalInstruction, Out);
10181 
10182   switch (MatchResult) {
10183   case Match_Success:
10184     LLVM_DEBUG(dbgs() << "Parsed as: ";
10185                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10186                dbgs() << "\n");
10187 
10188     // Context sensitive operand constraints aren't handled by the matcher,
10189     // so check them here.
10190     if (validateInstruction(Inst, Operands)) {
10191       // Still progress the IT block, otherwise one wrong condition causes
10192       // nasty cascading errors.
10193       forwardITPosition();
10194       forwardVPTPosition();
10195       return true;
10196     }
10197 
10198     { // processInstruction() updates inITBlock state, we need to save it away
10199       bool wasInITBlock = inITBlock();
10200 
10201       // Some instructions need post-processing to, for example, tweak which
10202       // encoding is selected. Loop on it while changes happen so the
10203       // individual transformations can chain off each other. E.g.,
10204       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
10205       while (processInstruction(Inst, Operands, Out))
10206         LLVM_DEBUG(dbgs() << "Changed to: ";
10207                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10208                    dbgs() << "\n");
10209 
10210       // Only after the instruction is fully processed, we can validate it
10211       if (wasInITBlock && hasV8Ops() && isThumb() &&
10212           !isV8EligibleForIT(&Inst)) {
10213         Warning(IDLoc, "deprecated instruction in IT block");
10214       }
10215     }
10216 
10217     // Only move forward at the very end so that everything in validate
10218     // and process gets a consistent answer about whether we're in an IT
10219     // block.
10220     forwardITPosition();
10221     forwardVPTPosition();
10222 
10223     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
10224     // doesn't actually encode.
10225     if (Inst.getOpcode() == ARM::ITasm)
10226       return false;
10227 
10228     Inst.setLoc(IDLoc);
10229     if (PendConditionalInstruction) {
10230       PendingConditionalInsts.push_back(Inst);
10231       if (isITBlockFull() || isITBlockTerminator(Inst))
10232         flushPendingInstructions(Out);
10233     } else {
10234       Out.EmitInstruction(Inst, getSTI());
10235     }
10236     return false;
10237   case Match_NearMisses:
10238     ReportNearMisses(NearMisses, IDLoc, Operands);
10239     return true;
10240   case Match_MnemonicFail: {
10241     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
10242     std::string Suggestion = ARMMnemonicSpellCheck(
10243       ((ARMOperand &)*Operands[0]).getToken(), FBS);
10244     return Error(IDLoc, "invalid instruction" + Suggestion,
10245                  ((ARMOperand &)*Operands[0]).getLocRange());
10246   }
10247   }
10248 
10249   llvm_unreachable("Implement any new match types added!");
10250 }
10251 
10252 /// parseDirective parses the arm specific directives
10253 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
10254   const MCObjectFileInfo::Environment Format =
10255     getContext().getObjectFileInfo()->getObjectFileType();
10256   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10257   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
10258 
10259   StringRef IDVal = DirectiveID.getIdentifier();
10260   if (IDVal == ".word")
10261     parseLiteralValues(4, DirectiveID.getLoc());
10262   else if (IDVal == ".short" || IDVal == ".hword")
10263     parseLiteralValues(2, DirectiveID.getLoc());
10264   else if (IDVal == ".thumb")
10265     parseDirectiveThumb(DirectiveID.getLoc());
10266   else if (IDVal == ".arm")
10267     parseDirectiveARM(DirectiveID.getLoc());
10268   else if (IDVal == ".thumb_func")
10269     parseDirectiveThumbFunc(DirectiveID.getLoc());
10270   else if (IDVal == ".code")
10271     parseDirectiveCode(DirectiveID.getLoc());
10272   else if (IDVal == ".syntax")
10273     parseDirectiveSyntax(DirectiveID.getLoc());
10274   else if (IDVal == ".unreq")
10275     parseDirectiveUnreq(DirectiveID.getLoc());
10276   else if (IDVal == ".fnend")
10277     parseDirectiveFnEnd(DirectiveID.getLoc());
10278   else if (IDVal == ".cantunwind")
10279     parseDirectiveCantUnwind(DirectiveID.getLoc());
10280   else if (IDVal == ".personality")
10281     parseDirectivePersonality(DirectiveID.getLoc());
10282   else if (IDVal == ".handlerdata")
10283     parseDirectiveHandlerData(DirectiveID.getLoc());
10284   else if (IDVal == ".setfp")
10285     parseDirectiveSetFP(DirectiveID.getLoc());
10286   else if (IDVal == ".pad")
10287     parseDirectivePad(DirectiveID.getLoc());
10288   else if (IDVal == ".save")
10289     parseDirectiveRegSave(DirectiveID.getLoc(), false);
10290   else if (IDVal == ".vsave")
10291     parseDirectiveRegSave(DirectiveID.getLoc(), true);
10292   else if (IDVal == ".ltorg" || IDVal == ".pool")
10293     parseDirectiveLtorg(DirectiveID.getLoc());
10294   else if (IDVal == ".even")
10295     parseDirectiveEven(DirectiveID.getLoc());
10296   else if (IDVal == ".personalityindex")
10297     parseDirectivePersonalityIndex(DirectiveID.getLoc());
10298   else if (IDVal == ".unwind_raw")
10299     parseDirectiveUnwindRaw(DirectiveID.getLoc());
10300   else if (IDVal == ".movsp")
10301     parseDirectiveMovSP(DirectiveID.getLoc());
10302   else if (IDVal == ".arch_extension")
10303     parseDirectiveArchExtension(DirectiveID.getLoc());
10304   else if (IDVal == ".align")
10305     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
10306   else if (IDVal == ".thumb_set")
10307     parseDirectiveThumbSet(DirectiveID.getLoc());
10308   else if (IDVal == ".inst")
10309     parseDirectiveInst(DirectiveID.getLoc());
10310   else if (IDVal == ".inst.n")
10311     parseDirectiveInst(DirectiveID.getLoc(), 'n');
10312   else if (IDVal == ".inst.w")
10313     parseDirectiveInst(DirectiveID.getLoc(), 'w');
10314   else if (!IsMachO && !IsCOFF) {
10315     if (IDVal == ".arch")
10316       parseDirectiveArch(DirectiveID.getLoc());
10317     else if (IDVal == ".cpu")
10318       parseDirectiveCPU(DirectiveID.getLoc());
10319     else if (IDVal == ".eabi_attribute")
10320       parseDirectiveEabiAttr(DirectiveID.getLoc());
10321     else if (IDVal == ".fpu")
10322       parseDirectiveFPU(DirectiveID.getLoc());
10323     else if (IDVal == ".fnstart")
10324       parseDirectiveFnStart(DirectiveID.getLoc());
10325     else if (IDVal == ".object_arch")
10326       parseDirectiveObjectArch(DirectiveID.getLoc());
10327     else if (IDVal == ".tlsdescseq")
10328       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
10329     else
10330       return true;
10331   } else
10332     return true;
10333   return false;
10334 }
10335 
10336 /// parseLiteralValues
10337 ///  ::= .hword expression [, expression]*
10338 ///  ::= .short expression [, expression]*
10339 ///  ::= .word expression [, expression]*
10340 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
10341   auto parseOne = [&]() -> bool {
10342     const MCExpr *Value;
10343     if (getParser().parseExpression(Value))
10344       return true;
10345     getParser().getStreamer().EmitValue(Value, Size, L);
10346     return false;
10347   };
10348   return (parseMany(parseOne));
10349 }
10350 
10351 /// parseDirectiveThumb
10352 ///  ::= .thumb
10353 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
10354   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10355       check(!hasThumb(), L, "target does not support Thumb mode"))
10356     return true;
10357 
10358   if (!isThumb())
10359     SwitchMode();
10360 
10361   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
10362   return false;
10363 }
10364 
10365 /// parseDirectiveARM
10366 ///  ::= .arm
10367 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
10368   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10369       check(!hasARM(), L, "target does not support ARM mode"))
10370     return true;
10371 
10372   if (isThumb())
10373     SwitchMode();
10374   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
10375   return false;
10376 }
10377 
10378 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
10379   // We need to flush the current implicit IT block on a label, because it is
10380   // not legal to branch into an IT block.
10381   flushPendingInstructions(getStreamer());
10382 }
10383 
10384 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
10385   if (NextSymbolIsThumb) {
10386     getParser().getStreamer().EmitThumbFunc(Symbol);
10387     NextSymbolIsThumb = false;
10388   }
10389 }
10390 
10391 /// parseDirectiveThumbFunc
10392 ///  ::= .thumbfunc symbol_name
10393 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
10394   MCAsmParser &Parser = getParser();
10395   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
10396   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10397 
10398   // Darwin asm has (optionally) function name after .thumb_func direction
10399   // ELF doesn't
10400 
10401   if (IsMachO) {
10402     if (Parser.getTok().is(AsmToken::Identifier) ||
10403         Parser.getTok().is(AsmToken::String)) {
10404       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
10405           Parser.getTok().getIdentifier());
10406       getParser().getStreamer().EmitThumbFunc(Func);
10407       Parser.Lex();
10408       if (parseToken(AsmToken::EndOfStatement,
10409                      "unexpected token in '.thumb_func' directive"))
10410         return true;
10411       return false;
10412     }
10413   }
10414 
10415   if (parseToken(AsmToken::EndOfStatement,
10416                  "unexpected token in '.thumb_func' directive"))
10417     return true;
10418 
10419   NextSymbolIsThumb = true;
10420   return false;
10421 }
10422 
10423 /// parseDirectiveSyntax
10424 ///  ::= .syntax unified | divided
10425 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
10426   MCAsmParser &Parser = getParser();
10427   const AsmToken &Tok = Parser.getTok();
10428   if (Tok.isNot(AsmToken::Identifier)) {
10429     Error(L, "unexpected token in .syntax directive");
10430     return false;
10431   }
10432 
10433   StringRef Mode = Tok.getString();
10434   Parser.Lex();
10435   if (check(Mode == "divided" || Mode == "DIVIDED", L,
10436             "'.syntax divided' arm assembly not supported") ||
10437       check(Mode != "unified" && Mode != "UNIFIED", L,
10438             "unrecognized syntax mode in .syntax directive") ||
10439       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10440     return true;
10441 
10442   // TODO tell the MC streamer the mode
10443   // getParser().getStreamer().Emit???();
10444   return false;
10445 }
10446 
10447 /// parseDirectiveCode
10448 ///  ::= .code 16 | 32
10449 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
10450   MCAsmParser &Parser = getParser();
10451   const AsmToken &Tok = Parser.getTok();
10452   if (Tok.isNot(AsmToken::Integer))
10453     return Error(L, "unexpected token in .code directive");
10454   int64_t Val = Parser.getTok().getIntVal();
10455   if (Val != 16 && Val != 32) {
10456     Error(L, "invalid operand to .code directive");
10457     return false;
10458   }
10459   Parser.Lex();
10460 
10461   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10462     return true;
10463 
10464   if (Val == 16) {
10465     if (!hasThumb())
10466       return Error(L, "target does not support Thumb mode");
10467 
10468     if (!isThumb())
10469       SwitchMode();
10470     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
10471   } else {
10472     if (!hasARM())
10473       return Error(L, "target does not support ARM mode");
10474 
10475     if (isThumb())
10476       SwitchMode();
10477     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
10478   }
10479 
10480   return false;
10481 }
10482 
10483 /// parseDirectiveReq
10484 ///  ::= name .req registername
10485 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
10486   MCAsmParser &Parser = getParser();
10487   Parser.Lex(); // Eat the '.req' token.
10488   unsigned Reg;
10489   SMLoc SRegLoc, ERegLoc;
10490   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
10491             "register name expected") ||
10492       parseToken(AsmToken::EndOfStatement,
10493                  "unexpected input in .req directive."))
10494     return true;
10495 
10496   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
10497     return Error(SRegLoc,
10498                  "redefinition of '" + Name + "' does not match original.");
10499 
10500   return false;
10501 }
10502 
10503 /// parseDirectiveUneq
10504 ///  ::= .unreq registername
10505 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
10506   MCAsmParser &Parser = getParser();
10507   if (Parser.getTok().isNot(AsmToken::Identifier))
10508     return Error(L, "unexpected input in .unreq directive.");
10509   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
10510   Parser.Lex(); // Eat the identifier.
10511   if (parseToken(AsmToken::EndOfStatement,
10512                  "unexpected input in '.unreq' directive"))
10513     return true;
10514   return false;
10515 }
10516 
10517 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
10518 // before, if supported by the new target, or emit mapping symbols for the mode
10519 // switch.
10520 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
10521   if (WasThumb != isThumb()) {
10522     if (WasThumb && hasThumb()) {
10523       // Stay in Thumb mode
10524       SwitchMode();
10525     } else if (!WasThumb && hasARM()) {
10526       // Stay in ARM mode
10527       SwitchMode();
10528     } else {
10529       // Mode switch forced, because the new arch doesn't support the old mode.
10530       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
10531                                                             : MCAF_Code32);
10532       // Warn about the implcit mode switch. GAS does not switch modes here,
10533       // but instead stays in the old mode, reporting an error on any following
10534       // instructions as the mode does not exist on the target.
10535       Warning(Loc, Twine("new target does not support ") +
10536                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
10537                        (!WasThumb ? "thumb" : "arm") + " mode");
10538     }
10539   }
10540 }
10541 
10542 /// parseDirectiveArch
10543 ///  ::= .arch token
10544 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
10545   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
10546   ARM::ArchKind ID = ARM::parseArch(Arch);
10547 
10548   if (ID == ARM::ArchKind::INVALID)
10549     return Error(L, "Unknown arch name");
10550 
10551   bool WasThumb = isThumb();
10552   Triple T;
10553   MCSubtargetInfo &STI = copySTI();
10554   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
10555   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
10556   FixModeAfterArchChange(WasThumb, L);
10557 
10558   getTargetStreamer().emitArch(ID);
10559   return false;
10560 }
10561 
10562 /// parseDirectiveEabiAttr
10563 ///  ::= .eabi_attribute int, int [, "str"]
10564 ///  ::= .eabi_attribute Tag_name, int [, "str"]
10565 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
10566   MCAsmParser &Parser = getParser();
10567   int64_t Tag;
10568   SMLoc TagLoc;
10569   TagLoc = Parser.getTok().getLoc();
10570   if (Parser.getTok().is(AsmToken::Identifier)) {
10571     StringRef Name = Parser.getTok().getIdentifier();
10572     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
10573     if (Tag == -1) {
10574       Error(TagLoc, "attribute name not recognised: " + Name);
10575       return false;
10576     }
10577     Parser.Lex();
10578   } else {
10579     const MCExpr *AttrExpr;
10580 
10581     TagLoc = Parser.getTok().getLoc();
10582     if (Parser.parseExpression(AttrExpr))
10583       return true;
10584 
10585     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
10586     if (check(!CE, TagLoc, "expected numeric constant"))
10587       return true;
10588 
10589     Tag = CE->getValue();
10590   }
10591 
10592   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
10593     return true;
10594 
10595   StringRef StringValue = "";
10596   bool IsStringValue = false;
10597 
10598   int64_t IntegerValue = 0;
10599   bool IsIntegerValue = false;
10600 
10601   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
10602     IsStringValue = true;
10603   else if (Tag == ARMBuildAttrs::compatibility) {
10604     IsStringValue = true;
10605     IsIntegerValue = true;
10606   } else if (Tag < 32 || Tag % 2 == 0)
10607     IsIntegerValue = true;
10608   else if (Tag % 2 == 1)
10609     IsStringValue = true;
10610   else
10611     llvm_unreachable("invalid tag type");
10612 
10613   if (IsIntegerValue) {
10614     const MCExpr *ValueExpr;
10615     SMLoc ValueExprLoc = Parser.getTok().getLoc();
10616     if (Parser.parseExpression(ValueExpr))
10617       return true;
10618 
10619     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
10620     if (!CE)
10621       return Error(ValueExprLoc, "expected numeric constant");
10622     IntegerValue = CE->getValue();
10623   }
10624 
10625   if (Tag == ARMBuildAttrs::compatibility) {
10626     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
10627       return true;
10628   }
10629 
10630   if (IsStringValue) {
10631     if (Parser.getTok().isNot(AsmToken::String))
10632       return Error(Parser.getTok().getLoc(), "bad string constant");
10633 
10634     StringValue = Parser.getTok().getStringContents();
10635     Parser.Lex();
10636   }
10637 
10638   if (Parser.parseToken(AsmToken::EndOfStatement,
10639                         "unexpected token in '.eabi_attribute' directive"))
10640     return true;
10641 
10642   if (IsIntegerValue && IsStringValue) {
10643     assert(Tag == ARMBuildAttrs::compatibility);
10644     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
10645   } else if (IsIntegerValue)
10646     getTargetStreamer().emitAttribute(Tag, IntegerValue);
10647   else if (IsStringValue)
10648     getTargetStreamer().emitTextAttribute(Tag, StringValue);
10649   return false;
10650 }
10651 
10652 /// parseDirectiveCPU
10653 ///  ::= .cpu str
10654 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
10655   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
10656   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
10657 
10658   // FIXME: This is using table-gen data, but should be moved to
10659   // ARMTargetParser once that is table-gen'd.
10660   if (!getSTI().isCPUStringValid(CPU))
10661     return Error(L, "Unknown CPU name");
10662 
10663   bool WasThumb = isThumb();
10664   MCSubtargetInfo &STI = copySTI();
10665   STI.setDefaultFeatures(CPU, "");
10666   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
10667   FixModeAfterArchChange(WasThumb, L);
10668 
10669   return false;
10670 }
10671 
10672 /// parseDirectiveFPU
10673 ///  ::= .fpu str
10674 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
10675   SMLoc FPUNameLoc = getTok().getLoc();
10676   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
10677 
10678   unsigned ID = ARM::parseFPU(FPU);
10679   std::vector<StringRef> Features;
10680   if (!ARM::getFPUFeatures(ID, Features))
10681     return Error(FPUNameLoc, "Unknown FPU name");
10682 
10683   MCSubtargetInfo &STI = copySTI();
10684   for (auto Feature : Features)
10685     STI.ApplyFeatureFlag(Feature);
10686   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
10687 
10688   getTargetStreamer().emitFPU(ID);
10689   return false;
10690 }
10691 
10692 /// parseDirectiveFnStart
10693 ///  ::= .fnstart
10694 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
10695   if (parseToken(AsmToken::EndOfStatement,
10696                  "unexpected token in '.fnstart' directive"))
10697     return true;
10698 
10699   if (UC.hasFnStart()) {
10700     Error(L, ".fnstart starts before the end of previous one");
10701     UC.emitFnStartLocNotes();
10702     return true;
10703   }
10704 
10705   // Reset the unwind directives parser state
10706   UC.reset();
10707 
10708   getTargetStreamer().emitFnStart();
10709 
10710   UC.recordFnStart(L);
10711   return false;
10712 }
10713 
10714 /// parseDirectiveFnEnd
10715 ///  ::= .fnend
10716 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
10717   if (parseToken(AsmToken::EndOfStatement,
10718                  "unexpected token in '.fnend' directive"))
10719     return true;
10720   // Check the ordering of unwind directives
10721   if (!UC.hasFnStart())
10722     return Error(L, ".fnstart must precede .fnend directive");
10723 
10724   // Reset the unwind directives parser state
10725   getTargetStreamer().emitFnEnd();
10726 
10727   UC.reset();
10728   return false;
10729 }
10730 
10731 /// parseDirectiveCantUnwind
10732 ///  ::= .cantunwind
10733 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
10734   if (parseToken(AsmToken::EndOfStatement,
10735                  "unexpected token in '.cantunwind' directive"))
10736     return true;
10737 
10738   UC.recordCantUnwind(L);
10739   // Check the ordering of unwind directives
10740   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
10741     return true;
10742 
10743   if (UC.hasHandlerData()) {
10744     Error(L, ".cantunwind can't be used with .handlerdata directive");
10745     UC.emitHandlerDataLocNotes();
10746     return true;
10747   }
10748   if (UC.hasPersonality()) {
10749     Error(L, ".cantunwind can't be used with .personality directive");
10750     UC.emitPersonalityLocNotes();
10751     return true;
10752   }
10753 
10754   getTargetStreamer().emitCantUnwind();
10755   return false;
10756 }
10757 
10758 /// parseDirectivePersonality
10759 ///  ::= .personality name
10760 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
10761   MCAsmParser &Parser = getParser();
10762   bool HasExistingPersonality = UC.hasPersonality();
10763 
10764   // Parse the name of the personality routine
10765   if (Parser.getTok().isNot(AsmToken::Identifier))
10766     return Error(L, "unexpected input in .personality directive.");
10767   StringRef Name(Parser.getTok().getIdentifier());
10768   Parser.Lex();
10769 
10770   if (parseToken(AsmToken::EndOfStatement,
10771                  "unexpected token in '.personality' directive"))
10772     return true;
10773 
10774   UC.recordPersonality(L);
10775 
10776   // Check the ordering of unwind directives
10777   if (!UC.hasFnStart())
10778     return Error(L, ".fnstart must precede .personality directive");
10779   if (UC.cantUnwind()) {
10780     Error(L, ".personality can't be used with .cantunwind directive");
10781     UC.emitCantUnwindLocNotes();
10782     return true;
10783   }
10784   if (UC.hasHandlerData()) {
10785     Error(L, ".personality must precede .handlerdata directive");
10786     UC.emitHandlerDataLocNotes();
10787     return true;
10788   }
10789   if (HasExistingPersonality) {
10790     Error(L, "multiple personality directives");
10791     UC.emitPersonalityLocNotes();
10792     return true;
10793   }
10794 
10795   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
10796   getTargetStreamer().emitPersonality(PR);
10797   return false;
10798 }
10799 
10800 /// parseDirectiveHandlerData
10801 ///  ::= .handlerdata
10802 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
10803   if (parseToken(AsmToken::EndOfStatement,
10804                  "unexpected token in '.handlerdata' directive"))
10805     return true;
10806 
10807   UC.recordHandlerData(L);
10808   // Check the ordering of unwind directives
10809   if (!UC.hasFnStart())
10810     return Error(L, ".fnstart must precede .personality directive");
10811   if (UC.cantUnwind()) {
10812     Error(L, ".handlerdata can't be used with .cantunwind directive");
10813     UC.emitCantUnwindLocNotes();
10814     return true;
10815   }
10816 
10817   getTargetStreamer().emitHandlerData();
10818   return false;
10819 }
10820 
10821 /// parseDirectiveSetFP
10822 ///  ::= .setfp fpreg, spreg [, offset]
10823 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
10824   MCAsmParser &Parser = getParser();
10825   // Check the ordering of unwind directives
10826   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
10827       check(UC.hasHandlerData(), L,
10828             ".setfp must precede .handlerdata directive"))
10829     return true;
10830 
10831   // Parse fpreg
10832   SMLoc FPRegLoc = Parser.getTok().getLoc();
10833   int FPReg = tryParseRegister();
10834 
10835   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
10836       Parser.parseToken(AsmToken::Comma, "comma expected"))
10837     return true;
10838 
10839   // Parse spreg
10840   SMLoc SPRegLoc = Parser.getTok().getLoc();
10841   int SPReg = tryParseRegister();
10842   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
10843       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
10844             "register should be either $sp or the latest fp register"))
10845     return true;
10846 
10847   // Update the frame pointer register
10848   UC.saveFPReg(FPReg);
10849 
10850   // Parse offset
10851   int64_t Offset = 0;
10852   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10853     if (Parser.getTok().isNot(AsmToken::Hash) &&
10854         Parser.getTok().isNot(AsmToken::Dollar))
10855       return Error(Parser.getTok().getLoc(), "'#' expected");
10856     Parser.Lex(); // skip hash token.
10857 
10858     const MCExpr *OffsetExpr;
10859     SMLoc ExLoc = Parser.getTok().getLoc();
10860     SMLoc EndLoc;
10861     if (getParser().parseExpression(OffsetExpr, EndLoc))
10862       return Error(ExLoc, "malformed setfp offset");
10863     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10864     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
10865       return true;
10866     Offset = CE->getValue();
10867   }
10868 
10869   if (Parser.parseToken(AsmToken::EndOfStatement))
10870     return true;
10871 
10872   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
10873                                 static_cast<unsigned>(SPReg), Offset);
10874   return false;
10875 }
10876 
10877 /// parseDirective
10878 ///  ::= .pad offset
10879 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
10880   MCAsmParser &Parser = getParser();
10881   // Check the ordering of unwind directives
10882   if (!UC.hasFnStart())
10883     return Error(L, ".fnstart must precede .pad directive");
10884   if (UC.hasHandlerData())
10885     return Error(L, ".pad must precede .handlerdata directive");
10886 
10887   // Parse the offset
10888   if (Parser.getTok().isNot(AsmToken::Hash) &&
10889       Parser.getTok().isNot(AsmToken::Dollar))
10890     return Error(Parser.getTok().getLoc(), "'#' expected");
10891   Parser.Lex(); // skip hash token.
10892 
10893   const MCExpr *OffsetExpr;
10894   SMLoc ExLoc = Parser.getTok().getLoc();
10895   SMLoc EndLoc;
10896   if (getParser().parseExpression(OffsetExpr, EndLoc))
10897     return Error(ExLoc, "malformed pad offset");
10898   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10899   if (!CE)
10900     return Error(ExLoc, "pad offset must be an immediate");
10901 
10902   if (parseToken(AsmToken::EndOfStatement,
10903                  "unexpected token in '.pad' directive"))
10904     return true;
10905 
10906   getTargetStreamer().emitPad(CE->getValue());
10907   return false;
10908 }
10909 
10910 /// parseDirectiveRegSave
10911 ///  ::= .save  { registers }
10912 ///  ::= .vsave { registers }
10913 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
10914   // Check the ordering of unwind directives
10915   if (!UC.hasFnStart())
10916     return Error(L, ".fnstart must precede .save or .vsave directives");
10917   if (UC.hasHandlerData())
10918     return Error(L, ".save or .vsave must precede .handlerdata directive");
10919 
10920   // RAII object to make sure parsed operands are deleted.
10921   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
10922 
10923   // Parse the register list
10924   if (parseRegisterList(Operands) ||
10925       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10926     return true;
10927   ARMOperand &Op = (ARMOperand &)*Operands[0];
10928   if (!IsVector && !Op.isRegList())
10929     return Error(L, ".save expects GPR registers");
10930   if (IsVector && !Op.isDPRRegList())
10931     return Error(L, ".vsave expects DPR registers");
10932 
10933   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
10934   return false;
10935 }
10936 
10937 /// parseDirectiveInst
10938 ///  ::= .inst opcode [, ...]
10939 ///  ::= .inst.n opcode [, ...]
10940 ///  ::= .inst.w opcode [, ...]
10941 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
10942   int Width = 4;
10943 
10944   if (isThumb()) {
10945     switch (Suffix) {
10946     case 'n':
10947       Width = 2;
10948       break;
10949     case 'w':
10950       break;
10951     default:
10952       Width = 0;
10953       break;
10954     }
10955   } else {
10956     if (Suffix)
10957       return Error(Loc, "width suffixes are invalid in ARM mode");
10958   }
10959 
10960   auto parseOne = [&]() -> bool {
10961     const MCExpr *Expr;
10962     if (getParser().parseExpression(Expr))
10963       return true;
10964     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
10965     if (!Value) {
10966       return Error(Loc, "expected constant expression");
10967     }
10968 
10969     char CurSuffix = Suffix;
10970     switch (Width) {
10971     case 2:
10972       if (Value->getValue() > 0xffff)
10973         return Error(Loc, "inst.n operand is too big, use inst.w instead");
10974       break;
10975     case 4:
10976       if (Value->getValue() > 0xffffffff)
10977         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
10978                               " operand is too big");
10979       break;
10980     case 0:
10981       // Thumb mode, no width indicated. Guess from the opcode, if possible.
10982       if (Value->getValue() < 0xe800)
10983         CurSuffix = 'n';
10984       else if (Value->getValue() >= 0xe8000000)
10985         CurSuffix = 'w';
10986       else
10987         return Error(Loc, "cannot determine Thumb instruction size, "
10988                           "use inst.n/inst.w instead");
10989       break;
10990     default:
10991       llvm_unreachable("only supported widths are 2 and 4");
10992     }
10993 
10994     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
10995     return false;
10996   };
10997 
10998   if (parseOptionalToken(AsmToken::EndOfStatement))
10999     return Error(Loc, "expected expression following directive");
11000   if (parseMany(parseOne))
11001     return true;
11002   return false;
11003 }
11004 
11005 /// parseDirectiveLtorg
11006 ///  ::= .ltorg | .pool
11007 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
11008   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11009     return true;
11010   getTargetStreamer().emitCurrentConstantPool();
11011   return false;
11012 }
11013 
11014 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
11015   const MCSection *Section = getStreamer().getCurrentSectionOnly();
11016 
11017   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11018     return true;
11019 
11020   if (!Section) {
11021     getStreamer().InitSections(false);
11022     Section = getStreamer().getCurrentSectionOnly();
11023   }
11024 
11025   assert(Section && "must have section to emit alignment");
11026   if (Section->UseCodeAlign())
11027     getStreamer().EmitCodeAlignment(2);
11028   else
11029     getStreamer().EmitValueToAlignment(2);
11030 
11031   return false;
11032 }
11033 
11034 /// parseDirectivePersonalityIndex
11035 ///   ::= .personalityindex index
11036 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
11037   MCAsmParser &Parser = getParser();
11038   bool HasExistingPersonality = UC.hasPersonality();
11039 
11040   const MCExpr *IndexExpression;
11041   SMLoc IndexLoc = Parser.getTok().getLoc();
11042   if (Parser.parseExpression(IndexExpression) ||
11043       parseToken(AsmToken::EndOfStatement,
11044                  "unexpected token in '.personalityindex' directive")) {
11045     return true;
11046   }
11047 
11048   UC.recordPersonalityIndex(L);
11049 
11050   if (!UC.hasFnStart()) {
11051     return Error(L, ".fnstart must precede .personalityindex directive");
11052   }
11053   if (UC.cantUnwind()) {
11054     Error(L, ".personalityindex cannot be used with .cantunwind");
11055     UC.emitCantUnwindLocNotes();
11056     return true;
11057   }
11058   if (UC.hasHandlerData()) {
11059     Error(L, ".personalityindex must precede .handlerdata directive");
11060     UC.emitHandlerDataLocNotes();
11061     return true;
11062   }
11063   if (HasExistingPersonality) {
11064     Error(L, "multiple personality directives");
11065     UC.emitPersonalityLocNotes();
11066     return true;
11067   }
11068 
11069   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
11070   if (!CE)
11071     return Error(IndexLoc, "index must be a constant number");
11072   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
11073     return Error(IndexLoc,
11074                  "personality routine index should be in range [0-3]");
11075 
11076   getTargetStreamer().emitPersonalityIndex(CE->getValue());
11077   return false;
11078 }
11079 
11080 /// parseDirectiveUnwindRaw
11081 ///   ::= .unwind_raw offset, opcode [, opcode...]
11082 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
11083   MCAsmParser &Parser = getParser();
11084   int64_t StackOffset;
11085   const MCExpr *OffsetExpr;
11086   SMLoc OffsetLoc = getLexer().getLoc();
11087 
11088   if (!UC.hasFnStart())
11089     return Error(L, ".fnstart must precede .unwind_raw directives");
11090   if (getParser().parseExpression(OffsetExpr))
11091     return Error(OffsetLoc, "expected expression");
11092 
11093   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11094   if (!CE)
11095     return Error(OffsetLoc, "offset must be a constant");
11096 
11097   StackOffset = CE->getValue();
11098 
11099   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
11100     return true;
11101 
11102   SmallVector<uint8_t, 16> Opcodes;
11103 
11104   auto parseOne = [&]() -> bool {
11105     const MCExpr *OE;
11106     SMLoc OpcodeLoc = getLexer().getLoc();
11107     if (check(getLexer().is(AsmToken::EndOfStatement) ||
11108                   Parser.parseExpression(OE),
11109               OpcodeLoc, "expected opcode expression"))
11110       return true;
11111     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
11112     if (!OC)
11113       return Error(OpcodeLoc, "opcode value must be a constant");
11114     const int64_t Opcode = OC->getValue();
11115     if (Opcode & ~0xff)
11116       return Error(OpcodeLoc, "invalid opcode");
11117     Opcodes.push_back(uint8_t(Opcode));
11118     return false;
11119   };
11120 
11121   // Must have at least 1 element
11122   SMLoc OpcodeLoc = getLexer().getLoc();
11123   if (parseOptionalToken(AsmToken::EndOfStatement))
11124     return Error(OpcodeLoc, "expected opcode expression");
11125   if (parseMany(parseOne))
11126     return true;
11127 
11128   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
11129   return false;
11130 }
11131 
11132 /// parseDirectiveTLSDescSeq
11133 ///   ::= .tlsdescseq tls-variable
11134 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
11135   MCAsmParser &Parser = getParser();
11136 
11137   if (getLexer().isNot(AsmToken::Identifier))
11138     return TokError("expected variable after '.tlsdescseq' directive");
11139 
11140   const MCSymbolRefExpr *SRE =
11141     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
11142                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
11143   Lex();
11144 
11145   if (parseToken(AsmToken::EndOfStatement,
11146                  "unexpected token in '.tlsdescseq' directive"))
11147     return true;
11148 
11149   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
11150   return false;
11151 }
11152 
11153 /// parseDirectiveMovSP
11154 ///  ::= .movsp reg [, #offset]
11155 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
11156   MCAsmParser &Parser = getParser();
11157   if (!UC.hasFnStart())
11158     return Error(L, ".fnstart must precede .movsp directives");
11159   if (UC.getFPReg() != ARM::SP)
11160     return Error(L, "unexpected .movsp directive");
11161 
11162   SMLoc SPRegLoc = Parser.getTok().getLoc();
11163   int SPReg = tryParseRegister();
11164   if (SPReg == -1)
11165     return Error(SPRegLoc, "register expected");
11166   if (SPReg == ARM::SP || SPReg == ARM::PC)
11167     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
11168 
11169   int64_t Offset = 0;
11170   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11171     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
11172       return true;
11173 
11174     const MCExpr *OffsetExpr;
11175     SMLoc OffsetLoc = Parser.getTok().getLoc();
11176 
11177     if (Parser.parseExpression(OffsetExpr))
11178       return Error(OffsetLoc, "malformed offset expression");
11179 
11180     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11181     if (!CE)
11182       return Error(OffsetLoc, "offset must be an immediate constant");
11183 
11184     Offset = CE->getValue();
11185   }
11186 
11187   if (parseToken(AsmToken::EndOfStatement,
11188                  "unexpected token in '.movsp' directive"))
11189     return true;
11190 
11191   getTargetStreamer().emitMovSP(SPReg, Offset);
11192   UC.saveFPReg(SPReg);
11193 
11194   return false;
11195 }
11196 
11197 /// parseDirectiveObjectArch
11198 ///   ::= .object_arch name
11199 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
11200   MCAsmParser &Parser = getParser();
11201   if (getLexer().isNot(AsmToken::Identifier))
11202     return Error(getLexer().getLoc(), "unexpected token");
11203 
11204   StringRef Arch = Parser.getTok().getString();
11205   SMLoc ArchLoc = Parser.getTok().getLoc();
11206   Lex();
11207 
11208   ARM::ArchKind ID = ARM::parseArch(Arch);
11209 
11210   if (ID == ARM::ArchKind::INVALID)
11211     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
11212   if (parseToken(AsmToken::EndOfStatement))
11213     return true;
11214 
11215   getTargetStreamer().emitObjectArch(ID);
11216   return false;
11217 }
11218 
11219 /// parseDirectiveAlign
11220 ///   ::= .align
11221 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
11222   // NOTE: if this is not the end of the statement, fall back to the target
11223   // agnostic handling for this directive which will correctly handle this.
11224   if (parseOptionalToken(AsmToken::EndOfStatement)) {
11225     // '.align' is target specifically handled to mean 2**2 byte alignment.
11226     const MCSection *Section = getStreamer().getCurrentSectionOnly();
11227     assert(Section && "must have section to emit alignment");
11228     if (Section->UseCodeAlign())
11229       getStreamer().EmitCodeAlignment(4, 0);
11230     else
11231       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
11232     return false;
11233   }
11234   return true;
11235 }
11236 
11237 /// parseDirectiveThumbSet
11238 ///  ::= .thumb_set name, value
11239 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
11240   MCAsmParser &Parser = getParser();
11241 
11242   StringRef Name;
11243   if (check(Parser.parseIdentifier(Name),
11244             "expected identifier after '.thumb_set'") ||
11245       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
11246     return true;
11247 
11248   MCSymbol *Sym;
11249   const MCExpr *Value;
11250   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
11251                                                Parser, Sym, Value))
11252     return true;
11253 
11254   getTargetStreamer().emitThumbSet(Sym, Value);
11255   return false;
11256 }
11257 
11258 /// Force static initialization.
11259 extern "C" void LLVMInitializeARMAsmParser() {
11260   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
11261   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
11262   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
11263   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
11264 }
11265 
11266 #define GET_REGISTER_MATCHER
11267 #define GET_SUBTARGET_FEATURE_NAME
11268 #define GET_MATCHER_IMPLEMENTATION
11269 #define GET_MNEMONIC_SPELL_CHECKER
11270 #include "ARMGenAsmMatcher.inc"
11271 
11272 // Some diagnostics need to vary with subtarget features, so they are handled
11273 // here. For example, the DPR class has either 16 or 32 registers, depending
11274 // on the FPU available.
11275 const char *
11276 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
11277   switch (MatchError) {
11278   // rGPR contains sp starting with ARMv8.
11279   case Match_rGPR:
11280     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
11281                       : "operand must be a register in range [r0, r12] or r14";
11282   // DPR contains 16 registers for some FPUs, and 32 for others.
11283   case Match_DPR:
11284     return hasD32() ? "operand must be a register in range [d0, d31]"
11285                     : "operand must be a register in range [d0, d15]";
11286   case Match_DPR_RegList:
11287     return hasD32() ? "operand must be a list of registers in range [d0, d31]"
11288                     : "operand must be a list of registers in range [d0, d15]";
11289 
11290   // For all other diags, use the static string from tablegen.
11291   default:
11292     return getMatchKindDiag(MatchError);
11293   }
11294 }
11295 
11296 // Process the list of near-misses, throwing away ones we don't want to report
11297 // to the user, and converting the rest to a source location and string that
11298 // should be reported.
11299 void
11300 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
11301                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
11302                                SMLoc IDLoc, OperandVector &Operands) {
11303   // TODO: If operand didn't match, sub in a dummy one and run target
11304   // predicate, so that we can avoid reporting near-misses that are invalid?
11305   // TODO: Many operand types dont have SuperClasses set, so we report
11306   // redundant ones.
11307   // TODO: Some operands are superclasses of registers (e.g.
11308   // MCK_RegShiftedImm), we don't have any way to represent that currently.
11309   // TODO: This is not all ARM-specific, can some of it be factored out?
11310 
11311   // Record some information about near-misses that we have already seen, so
11312   // that we can avoid reporting redundant ones. For example, if there are
11313   // variants of an instruction that take 8- and 16-bit immediates, we want
11314   // to only report the widest one.
11315   std::multimap<unsigned, unsigned> OperandMissesSeen;
11316   SmallSet<FeatureBitset, 4> FeatureMissesSeen;
11317   bool ReportedTooFewOperands = false;
11318 
11319   // Process the near-misses in reverse order, so that we see more general ones
11320   // first, and so can avoid emitting more specific ones.
11321   for (NearMissInfo &I : reverse(NearMissesIn)) {
11322     switch (I.getKind()) {
11323     case NearMissInfo::NearMissOperand: {
11324       SMLoc OperandLoc =
11325           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
11326       const char *OperandDiag =
11327           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
11328 
11329       // If we have already emitted a message for a superclass, don't also report
11330       // the sub-class. We consider all operand classes that we don't have a
11331       // specialised diagnostic for to be equal for the propose of this check,
11332       // so that we don't report the generic error multiple times on the same
11333       // operand.
11334       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
11335       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
11336       if (std::any_of(PrevReports.first, PrevReports.second,
11337                       [DupCheckMatchClass](
11338                           const std::pair<unsigned, unsigned> Pair) {
11339             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
11340               return Pair.second == DupCheckMatchClass;
11341             else
11342               return isSubclass((MatchClassKind)DupCheckMatchClass,
11343                                 (MatchClassKind)Pair.second);
11344           }))
11345         break;
11346       OperandMissesSeen.insert(
11347           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
11348 
11349       NearMissMessage Message;
11350       Message.Loc = OperandLoc;
11351       if (OperandDiag) {
11352         Message.Message = OperandDiag;
11353       } else if (I.getOperandClass() == InvalidMatchClass) {
11354         Message.Message = "too many operands for instruction";
11355       } else {
11356         Message.Message = "invalid operand for instruction";
11357         LLVM_DEBUG(
11358             dbgs() << "Missing diagnostic string for operand class "
11359                    << getMatchClassName((MatchClassKind)I.getOperandClass())
11360                    << I.getOperandClass() << ", error " << I.getOperandError()
11361                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
11362       }
11363       NearMissesOut.emplace_back(Message);
11364       break;
11365     }
11366     case NearMissInfo::NearMissFeature: {
11367       const FeatureBitset &MissingFeatures = I.getFeatures();
11368       // Don't report the same set of features twice.
11369       if (FeatureMissesSeen.count(MissingFeatures))
11370         break;
11371       FeatureMissesSeen.insert(MissingFeatures);
11372 
11373       // Special case: don't report a feature set which includes arm-mode for
11374       // targets that don't have ARM mode.
11375       if (MissingFeatures.test(Feature_IsARMBit) && !hasARM())
11376         break;
11377       // Don't report any near-misses that both require switching instruction
11378       // set, and adding other subtarget features.
11379       if (isThumb() && MissingFeatures.test(Feature_IsARMBit) &&
11380           MissingFeatures.count() > 1)
11381         break;
11382       if (!isThumb() && MissingFeatures.test(Feature_IsThumbBit) &&
11383           MissingFeatures.count() > 1)
11384         break;
11385       if (!isThumb() && MissingFeatures.test(Feature_IsThumb2Bit) &&
11386           (MissingFeatures & ~FeatureBitset({Feature_IsThumb2Bit,
11387                                              Feature_IsThumbBit})).any())
11388         break;
11389       if (isMClass() && MissingFeatures.test(Feature_HasNEONBit))
11390         break;
11391 
11392       NearMissMessage Message;
11393       Message.Loc = IDLoc;
11394       raw_svector_ostream OS(Message.Message);
11395 
11396       OS << "instruction requires:";
11397       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
11398         if (MissingFeatures.test(i))
11399           OS << ' ' << getSubtargetFeatureName(i);
11400 
11401       NearMissesOut.emplace_back(Message);
11402 
11403       break;
11404     }
11405     case NearMissInfo::NearMissPredicate: {
11406       NearMissMessage Message;
11407       Message.Loc = IDLoc;
11408       switch (I.getPredicateError()) {
11409       case Match_RequiresNotITBlock:
11410         Message.Message = "flag setting instruction only valid outside IT block";
11411         break;
11412       case Match_RequiresITBlock:
11413         Message.Message = "instruction only valid inside IT block";
11414         break;
11415       case Match_RequiresV6:
11416         Message.Message = "instruction variant requires ARMv6 or later";
11417         break;
11418       case Match_RequiresThumb2:
11419         Message.Message = "instruction variant requires Thumb2";
11420         break;
11421       case Match_RequiresV8:
11422         Message.Message = "instruction variant requires ARMv8 or later";
11423         break;
11424       case Match_RequiresFlagSetting:
11425         Message.Message = "no flag-preserving variant of this instruction available";
11426         break;
11427       case Match_InvalidOperand:
11428         Message.Message = "invalid operand for instruction";
11429         break;
11430       default:
11431         llvm_unreachable("Unhandled target predicate error");
11432         break;
11433       }
11434       NearMissesOut.emplace_back(Message);
11435       break;
11436     }
11437     case NearMissInfo::NearMissTooFewOperands: {
11438       if (!ReportedTooFewOperands) {
11439         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
11440         NearMissesOut.emplace_back(NearMissMessage{
11441             EndLoc, StringRef("too few operands for instruction")});
11442         ReportedTooFewOperands = true;
11443       }
11444       break;
11445     }
11446     case NearMissInfo::NoNearMiss:
11447       // This should never leave the matcher.
11448       llvm_unreachable("not a near-miss");
11449       break;
11450     }
11451   }
11452 }
11453 
11454 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
11455                                     SMLoc IDLoc, OperandVector &Operands) {
11456   SmallVector<NearMissMessage, 4> Messages;
11457   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
11458 
11459   if (Messages.size() == 0) {
11460     // No near-misses were found, so the best we can do is "invalid
11461     // instruction".
11462     Error(IDLoc, "invalid instruction");
11463   } else if (Messages.size() == 1) {
11464     // One near miss was found, report it as the sole error.
11465     Error(Messages[0].Loc, Messages[0].Message);
11466   } else {
11467     // More than one near miss, so report a generic "invalid instruction"
11468     // error, followed by notes for each of the near-misses.
11469     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
11470     for (auto &M : Messages) {
11471       Note(M.Loc, M.Message);
11472     }
11473   }
11474 }
11475 
11476 /// parseDirectiveArchExtension
11477 ///   ::= .arch_extension [no]feature
11478 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
11479   // FIXME: This structure should be moved inside ARMTargetParser
11480   // when we start to table-generate them, and we can use the ARM
11481   // flags below, that were generated by table-gen.
11482   static const struct {
11483     const unsigned Kind;
11484     const FeatureBitset ArchCheck;
11485     const FeatureBitset Features;
11486   } Extensions[] = {
11487     { ARM::AEK_CRC, {Feature_HasV8Bit}, {ARM::FeatureCRC} },
11488     { ARM::AEK_CRYPTO,  {Feature_HasV8Bit},
11489       {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
11490     { ARM::AEK_FP, {Feature_HasV8Bit},
11491       {ARM::FeatureVFP2_D16_SP, ARM::FeatureFPARMv8} },
11492     { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM),
11493       {Feature_HasV7Bit, Feature_IsNotMClassBit},
11494       {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
11495     { ARM::AEK_MP, {Feature_HasV7Bit, Feature_IsNotMClassBit},
11496       {ARM::FeatureMP} },
11497     { ARM::AEK_SIMD, {Feature_HasV8Bit},
11498       {ARM::FeatureNEON, ARM::FeatureVFP2_D16_SP, ARM::FeatureFPARMv8} },
11499     { ARM::AEK_SEC, {Feature_HasV6KBit}, {ARM::FeatureTrustZone} },
11500     // FIXME: Only available in A-class, isel not predicated
11501     { ARM::AEK_VIRT, {Feature_HasV7Bit}, {ARM::FeatureVirtualization} },
11502     { ARM::AEK_FP16, {Feature_HasV8_2aBit},
11503       {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
11504     { ARM::AEK_RAS, {Feature_HasV8Bit}, {ARM::FeatureRAS} },
11505     { ARM::AEK_LOB, {Feature_HasV8_1MMainlineBit}, {ARM::FeatureLOB} },
11506     // FIXME: Unsupported extensions.
11507     { ARM::AEK_OS, {}, {} },
11508     { ARM::AEK_IWMMXT, {}, {} },
11509     { ARM::AEK_IWMMXT2, {}, {} },
11510     { ARM::AEK_MAVERICK, {}, {} },
11511     { ARM::AEK_XSCALE, {}, {} },
11512   };
11513 
11514   MCAsmParser &Parser = getParser();
11515 
11516   if (getLexer().isNot(AsmToken::Identifier))
11517     return Error(getLexer().getLoc(), "expected architecture extension name");
11518 
11519   StringRef Name = Parser.getTok().getString();
11520   SMLoc ExtLoc = Parser.getTok().getLoc();
11521   Lex();
11522 
11523   if (parseToken(AsmToken::EndOfStatement,
11524                  "unexpected token in '.arch_extension' directive"))
11525     return true;
11526 
11527   bool EnableFeature = true;
11528   if (Name.startswith_lower("no")) {
11529     EnableFeature = false;
11530     Name = Name.substr(2);
11531   }
11532   unsigned FeatureKind = ARM::parseArchExt(Name);
11533   if (FeatureKind == ARM::AEK_INVALID)
11534     return Error(ExtLoc, "unknown architectural extension: " + Name);
11535 
11536   for (const auto &Extension : Extensions) {
11537     if (Extension.Kind != FeatureKind)
11538       continue;
11539 
11540     if (Extension.Features.none())
11541       return Error(ExtLoc, "unsupported architectural extension: " + Name);
11542 
11543     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
11544       return Error(ExtLoc, "architectural extension '" + Name +
11545                                "' is not "
11546                                "allowed for the current base architecture");
11547 
11548     MCSubtargetInfo &STI = copySTI();
11549     if (EnableFeature) {
11550       STI.SetFeatureBitsTransitively(Extension.Features);
11551     } else {
11552       STI.ClearFeatureBitsTransitively(Extension.Features);
11553     }
11554     FeatureBitset Features = ComputeAvailableFeatures(STI.getFeatureBits());
11555     setAvailableFeatures(Features);
11556     return false;
11557   }
11558 
11559   return Error(ExtLoc, "unknown architectural extension: " + Name);
11560 }
11561 
11562 // Define this matcher function after the auto-generated include so we
11563 // have the match class enum definitions.
11564 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
11565                                                   unsigned Kind) {
11566   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
11567   // If the kind is a token for a literal immediate, check if our asm
11568   // operand matches. This is for InstAliases which have a fixed-value
11569   // immediate in the syntax.
11570   switch (Kind) {
11571   default: break;
11572   case MCK__35_0:
11573     if (Op.isImm())
11574       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
11575         if (CE->getValue() == 0)
11576           return Match_Success;
11577     break;
11578   case MCK__35_8:
11579     if (Op.isImm())
11580       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
11581         if (CE->getValue() == 8)
11582           return Match_Success;
11583     break;
11584   case MCK__35_16:
11585     if (Op.isImm())
11586       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
11587         if (CE->getValue() == 16)
11588           return Match_Success;
11589     break;
11590   case MCK_ModImm:
11591     if (Op.isImm()) {
11592       const MCExpr *SOExpr = Op.getImm();
11593       int64_t Value;
11594       if (!SOExpr->evaluateAsAbsolute(Value))
11595         return Match_Success;
11596       assert((Value >= std::numeric_limits<int32_t>::min() &&
11597               Value <= std::numeric_limits<uint32_t>::max()) &&
11598              "expression value must be representable in 32 bits");
11599     }
11600     break;
11601   case MCK_rGPR:
11602     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
11603       return Match_Success;
11604     return Match_rGPR;
11605   case MCK_GPRPair:
11606     if (Op.isReg() &&
11607         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
11608       return Match_Success;
11609     break;
11610   }
11611   return Match_InvalidOperand;
11612 }
11613 
11614 bool ARMAsmParser::isMnemonicVPTPredicable(StringRef Mnemonic,
11615                                            StringRef ExtraToken) {
11616   if (!hasMVE())
11617     return false;
11618 
11619   return Mnemonic.startswith("vabav") || Mnemonic.startswith("vaddv") ||
11620          Mnemonic.startswith("vaddlv") || Mnemonic.startswith("vminnmv") ||
11621          Mnemonic.startswith("vminnmav") || Mnemonic.startswith("vminv") ||
11622          Mnemonic.startswith("vminav") || Mnemonic.startswith("vmaxnmv") ||
11623          Mnemonic.startswith("vmaxnmav") || Mnemonic.startswith("vmaxv") ||
11624          Mnemonic.startswith("vmaxav") || Mnemonic.startswith("vmladav") ||
11625          Mnemonic.startswith("vrmlaldavh") || Mnemonic.startswith("vrmlalvh") ||
11626          Mnemonic.startswith("vmlsdav") || Mnemonic.startswith("vmlav") ||
11627          Mnemonic.startswith("vmlaldav") || Mnemonic.startswith("vmlalv") ||
11628          Mnemonic.startswith("vmaxnm") || Mnemonic.startswith("vminnm") ||
11629          Mnemonic.startswith("vmax") || Mnemonic.startswith("vmin") ||
11630          Mnemonic.startswith("vshlc") || Mnemonic.startswith("vmovlt") ||
11631          Mnemonic.startswith("vmovlb") || Mnemonic.startswith("vshll") ||
11632          Mnemonic.startswith("vrshrn") || Mnemonic.startswith("vshrn") ||
11633          Mnemonic.startswith("vqrshrun") || Mnemonic.startswith("vqshrun") ||
11634          Mnemonic.startswith("vqrshrn") || Mnemonic.startswith("vqshrn") ||
11635          Mnemonic.startswith("vbic") || Mnemonic.startswith("vrev64") ||
11636          Mnemonic.startswith("vrev32") || Mnemonic.startswith("vrev16") ||
11637          Mnemonic.startswith("vmvn") || Mnemonic.startswith("veor") ||
11638          Mnemonic.startswith("vorn") || Mnemonic.startswith("vorr") ||
11639          Mnemonic.startswith("vand") || Mnemonic.startswith("vmul") ||
11640          Mnemonic.startswith("vqrdmulh") || Mnemonic.startswith("vqdmulh") ||
11641          Mnemonic.startswith("vsub") || Mnemonic.startswith("vadd") ||
11642          Mnemonic.startswith("vqsub") || Mnemonic.startswith("vqadd") ||
11643          Mnemonic.startswith("vabd") || Mnemonic.startswith("vrhadd") ||
11644          Mnemonic.startswith("vhsub") || Mnemonic.startswith("vhadd") ||
11645          Mnemonic.startswith("vdup") || Mnemonic.startswith("vcls") ||
11646          Mnemonic.startswith("vclz") || Mnemonic.startswith("vneg") ||
11647          Mnemonic.startswith("vabs") || Mnemonic.startswith("vqneg") ||
11648          Mnemonic.startswith("vqabs") ||
11649          (Mnemonic.startswith("vrint") && Mnemonic != "vrintr") ||
11650          Mnemonic.startswith("vcmla") || Mnemonic.startswith("vfma") ||
11651          Mnemonic.startswith("vfms") || Mnemonic.startswith("vcadd") ||
11652          Mnemonic.startswith("vadd") || Mnemonic.startswith("vsub") ||
11653          Mnemonic.startswith("vshl") || Mnemonic.startswith("vqshl") ||
11654          Mnemonic.startswith("vqrshl") || Mnemonic.startswith("vrshl") ||
11655          Mnemonic.startswith("vsri") || Mnemonic.startswith("vsli") ||
11656          Mnemonic.startswith("vrshr") || Mnemonic.startswith("vshr") ||
11657          Mnemonic.startswith("vpsel") || Mnemonic.startswith("vcmp") ||
11658          Mnemonic.startswith("vqdmladh") || Mnemonic.startswith("vqrdmladh") ||
11659          Mnemonic.startswith("vqdmlsdh") || Mnemonic.startswith("vqrdmlsdh") ||
11660          Mnemonic.startswith("vcmul") || Mnemonic.startswith("vrmulh") ||
11661          Mnemonic.startswith("vqmovn") || Mnemonic.startswith("vqmovun") ||
11662          Mnemonic.startswith("vmovnt") || Mnemonic.startswith("vmovnb") ||
11663          Mnemonic.startswith("vmaxa") || Mnemonic.startswith("vmaxnma") ||
11664          Mnemonic.startswith("vhcadd") || Mnemonic.startswith("vadc") ||
11665          Mnemonic.startswith("vsbc") || Mnemonic.startswith("vrshr") ||
11666          Mnemonic.startswith("vshr") || Mnemonic.startswith("vstrb") ||
11667          Mnemonic.startswith("vldrb") ||
11668          (Mnemonic.startswith("vstrh") && Mnemonic != "vstrhi") ||
11669          (Mnemonic.startswith("vldrh") && Mnemonic != "vldrhi") ||
11670          Mnemonic.startswith("vstrw") || Mnemonic.startswith("vldrw") ||
11671          Mnemonic.startswith("vldrd") || Mnemonic.startswith("vstrd") ||
11672          Mnemonic.startswith("vqdmull") || Mnemonic.startswith("vbrsr") ||
11673          Mnemonic.startswith("vfmas") || Mnemonic.startswith("vmlas") ||
11674          Mnemonic.startswith("vmla") || Mnemonic.startswith("vqdmlash") ||
11675          Mnemonic.startswith("vqdmlah") || Mnemonic.startswith("vqrdmlash") ||
11676          Mnemonic.startswith("vqrdmlah") || Mnemonic.startswith("viwdup") ||
11677          Mnemonic.startswith("vdwdup") || Mnemonic.startswith("vidup") ||
11678          Mnemonic.startswith("vddup") || Mnemonic.startswith("vctp") ||
11679          Mnemonic.startswith("vpnot") || Mnemonic.startswith("vbic") ||
11680          Mnemonic.startswith("vrmlsldavh") || Mnemonic.startswith("vmlsldav") ||
11681          Mnemonic.startswith("vcvt") ||
11682          (Mnemonic.startswith("vmov") &&
11683           !(ExtraToken == ".f16" || ExtraToken == ".32" ||
11684             ExtraToken == ".16" || ExtraToken == ".8"));
11685 }
11686