1 //===- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "ARMFeatures.h"
11 #include "Utils/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMBaseInfo.h"
14 #include "MCTargetDesc/ARMMCExpr.h"
15 #include "MCTargetDesc/ARMMCTargetDesc.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCObjectFileInfo.h"
33 #include "llvm/MC/MCParser/MCAsmLexer.h"
34 #include "llvm/MC/MCParser/MCAsmParser.h"
35 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
36 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
37 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
38 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/MC/MCSection.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSubtargetInfo.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/SubtargetFeature.h"
45 #include "llvm/Support/ARMBuildAttributes.h"
46 #include "llvm/Support/ARMEHABI.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/SMLoc.h"
53 #include "llvm/Support/TargetParser.h"
54 #include "llvm/Support/TargetRegistry.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <algorithm>
57 #include <cassert>
58 #include <cstddef>
59 #include <cstdint>
60 #include <iterator>
61 #include <limits>
62 #include <memory>
63 #include <string>
64 #include <utility>
65 #include <vector>
66 
67 #define DEBUG_TYPE "asm-parser"
68 
69 using namespace llvm;
70 
71 namespace {
72 
73 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
74 
75 static cl::opt<ImplicitItModeTy> ImplicitItMode(
76     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
77     cl::desc("Allow conditional instructions outdside of an IT block"),
78     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
79                           "Accept in both ISAs, emit implicit ITs in Thumb"),
80                clEnumValN(ImplicitItModeTy::Never, "never",
81                           "Warn in ARM, reject in Thumb"),
82                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
83                           "Accept in ARM, reject in Thumb"),
84                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
85                           "Warn in ARM, emit implicit ITs in Thumb")));
86 
87 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
88                                         cl::init(false));
89 
90 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
91 
92 class UnwindContext {
93   using Locs = SmallVector<SMLoc, 4>;
94 
95   MCAsmParser &Parser;
96   Locs FnStartLocs;
97   Locs CantUnwindLocs;
98   Locs PersonalityLocs;
99   Locs PersonalityIndexLocs;
100   Locs HandlerDataLocs;
101   int FPReg;
102 
103 public:
104   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
105 
106   bool hasFnStart() const { return !FnStartLocs.empty(); }
107   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
108   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
109 
110   bool hasPersonality() const {
111     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
112   }
113 
114   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
115   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
116   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
117   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
118   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
119 
120   void saveFPReg(int Reg) { FPReg = Reg; }
121   int getFPReg() const { return FPReg; }
122 
123   void emitFnStartLocNotes() const {
124     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
125          FI != FE; ++FI)
126       Parser.Note(*FI, ".fnstart was specified here");
127   }
128 
129   void emitCantUnwindLocNotes() const {
130     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
131                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
132       Parser.Note(*UI, ".cantunwind was specified here");
133   }
134 
135   void emitHandlerDataLocNotes() const {
136     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
137                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
138       Parser.Note(*HI, ".handlerdata was specified here");
139   }
140 
141   void emitPersonalityLocNotes() const {
142     for (Locs::const_iterator PI = PersonalityLocs.begin(),
143                               PE = PersonalityLocs.end(),
144                               PII = PersonalityIndexLocs.begin(),
145                               PIE = PersonalityIndexLocs.end();
146          PI != PE || PII != PIE;) {
147       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
148         Parser.Note(*PI++, ".personality was specified here");
149       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
150         Parser.Note(*PII++, ".personalityindex was specified here");
151       else
152         llvm_unreachable(".personality and .personalityindex cannot be "
153                          "at the same location");
154     }
155   }
156 
157   void reset() {
158     FnStartLocs = Locs();
159     CantUnwindLocs = Locs();
160     PersonalityLocs = Locs();
161     HandlerDataLocs = Locs();
162     PersonalityIndexLocs = Locs();
163     FPReg = ARM::SP;
164   }
165 };
166 
167 class ARMAsmParser : public MCTargetAsmParser {
168   const MCRegisterInfo *MRI;
169   UnwindContext UC;
170 
171   ARMTargetStreamer &getTargetStreamer() {
172     assert(getParser().getStreamer().getTargetStreamer() &&
173            "do not have a target streamer");
174     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
175     return static_cast<ARMTargetStreamer &>(TS);
176   }
177 
178   // Map of register aliases registers via the .req directive.
179   StringMap<unsigned> RegisterReqs;
180 
181   bool NextSymbolIsThumb;
182 
183   bool useImplicitITThumb() const {
184     return ImplicitItMode == ImplicitItModeTy::Always ||
185            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
186   }
187 
188   bool useImplicitITARM() const {
189     return ImplicitItMode == ImplicitItModeTy::Always ||
190            ImplicitItMode == ImplicitItModeTy::ARMOnly;
191   }
192 
193   struct {
194     ARMCC::CondCodes Cond;    // Condition for IT block.
195     unsigned Mask:4;          // Condition mask for instructions.
196                               // Starting at first 1 (from lsb).
197                               //   '1'  condition as indicated in IT.
198                               //   '0'  inverse of condition (else).
199                               // Count of instructions in IT block is
200                               // 4 - trailingzeroes(mask)
201                               // Note that this does not have the same encoding
202                               // as in the IT instruction, which also depends
203                               // on the low bit of the condition code.
204 
205     unsigned CurPosition;     // Current position in parsing of IT
206                               // block. In range [0,4], with 0 being the IT
207                               // instruction itself. Initialized according to
208                               // count of instructions in block.  ~0U if no
209                               // active IT block.
210 
211     bool IsExplicit;          // true  - The IT instruction was present in the
212                               //         input, we should not modify it.
213                               // false - The IT instruction was added
214                               //         implicitly, we can extend it if that
215                               //         would be legal.
216   } ITState;
217 
218   SmallVector<MCInst, 4> PendingConditionalInsts;
219 
220   void flushPendingInstructions(MCStreamer &Out) override {
221     if (!inImplicitITBlock()) {
222       assert(PendingConditionalInsts.size() == 0);
223       return;
224     }
225 
226     // Emit the IT instruction
227     unsigned Mask = getITMaskEncoding();
228     MCInst ITInst;
229     ITInst.setOpcode(ARM::t2IT);
230     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
231     ITInst.addOperand(MCOperand::createImm(Mask));
232     Out.EmitInstruction(ITInst, getSTI());
233 
234     // Emit the conditonal instructions
235     assert(PendingConditionalInsts.size() <= 4);
236     for (const MCInst &Inst : PendingConditionalInsts) {
237       Out.EmitInstruction(Inst, getSTI());
238     }
239     PendingConditionalInsts.clear();
240 
241     // Clear the IT state
242     ITState.Mask = 0;
243     ITState.CurPosition = ~0U;
244   }
245 
246   bool inITBlock() { return ITState.CurPosition != ~0U; }
247   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
248   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
249 
250   bool lastInITBlock() {
251     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
252   }
253 
254   void forwardITPosition() {
255     if (!inITBlock()) return;
256     // Move to the next instruction in the IT block, if there is one. If not,
257     // mark the block as done, except for implicit IT blocks, which we leave
258     // open until we find an instruction that can't be added to it.
259     unsigned TZ = countTrailingZeros(ITState.Mask);
260     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
261       ITState.CurPosition = ~0U; // Done with the IT block after this.
262   }
263 
264   // Rewind the state of the current IT block, removing the last slot from it.
265   void rewindImplicitITPosition() {
266     assert(inImplicitITBlock());
267     assert(ITState.CurPosition > 1);
268     ITState.CurPosition--;
269     unsigned TZ = countTrailingZeros(ITState.Mask);
270     unsigned NewMask = 0;
271     NewMask |= ITState.Mask & (0xC << TZ);
272     NewMask |= 0x2 << TZ;
273     ITState.Mask = NewMask;
274   }
275 
276   // Rewind the state of the current IT block, removing the last slot from it.
277   // If we were at the first slot, this closes the IT block.
278   void discardImplicitITBlock() {
279     assert(inImplicitITBlock());
280     assert(ITState.CurPosition == 1);
281     ITState.CurPosition = ~0U;
282   }
283 
284   // Return the low-subreg of a given Q register.
285   unsigned getDRegFromQReg(unsigned QReg) const {
286     return MRI->getSubReg(QReg, ARM::dsub_0);
287   }
288 
289   // Get the encoding of the IT mask, as it will appear in an IT instruction.
290   unsigned getITMaskEncoding() {
291     assert(inITBlock());
292     unsigned Mask = ITState.Mask;
293     unsigned TZ = countTrailingZeros(Mask);
294     if ((ITState.Cond & 1) == 0) {
295       assert(Mask && TZ <= 3 && "illegal IT mask value!");
296       Mask ^= (0xE << TZ) & 0xF;
297     }
298     return Mask;
299   }
300 
301   // Get the condition code corresponding to the current IT block slot.
302   ARMCC::CondCodes currentITCond() {
303     unsigned MaskBit;
304     if (ITState.CurPosition == 1)
305       MaskBit = 1;
306     else
307       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
308 
309     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
310   }
311 
312   // Invert the condition of the current IT block slot without changing any
313   // other slots in the same block.
314   void invertCurrentITCondition() {
315     if (ITState.CurPosition == 1) {
316       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
317     } else {
318       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
319     }
320   }
321 
322   // Returns true if the current IT block is full (all 4 slots used).
323   bool isITBlockFull() {
324     return inITBlock() && (ITState.Mask & 1);
325   }
326 
327   // Extend the current implicit IT block to have one more slot with the given
328   // condition code.
329   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
330     assert(inImplicitITBlock());
331     assert(!isITBlockFull());
332     assert(Cond == ITState.Cond ||
333            Cond == ARMCC::getOppositeCondition(ITState.Cond));
334     unsigned TZ = countTrailingZeros(ITState.Mask);
335     unsigned NewMask = 0;
336     // Keep any existing condition bits.
337     NewMask |= ITState.Mask & (0xE << TZ);
338     // Insert the new condition bit.
339     NewMask |= (Cond == ITState.Cond) << TZ;
340     // Move the trailing 1 down one bit.
341     NewMask |= 1 << (TZ - 1);
342     ITState.Mask = NewMask;
343   }
344 
345   // Create a new implicit IT block with a dummy condition code.
346   void startImplicitITBlock() {
347     assert(!inITBlock());
348     ITState.Cond = ARMCC::AL;
349     ITState.Mask = 8;
350     ITState.CurPosition = 1;
351     ITState.IsExplicit = false;
352   }
353 
354   // Create a new explicit IT block with the given condition and mask. The mask
355   // should be in the parsed format, with a 1 implying 't', regardless of the
356   // low bit of the condition.
357   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
358     assert(!inITBlock());
359     ITState.Cond = Cond;
360     ITState.Mask = Mask;
361     ITState.CurPosition = 0;
362     ITState.IsExplicit = true;
363   }
364 
365   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
366     return getParser().Note(L, Msg, Range);
367   }
368 
369   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
370     return getParser().Warning(L, Msg, Range);
371   }
372 
373   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
374     return getParser().Error(L, Msg, Range);
375   }
376 
377   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
378                            unsigned ListNo, bool IsARPop = false);
379   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
380                            unsigned ListNo);
381 
382   int tryParseRegister();
383   bool tryParseRegisterWithWriteBack(OperandVector &);
384   int tryParseShiftRegister(OperandVector &);
385   bool parseRegisterList(OperandVector &);
386   bool parseMemory(OperandVector &);
387   bool parseOperand(OperandVector &, StringRef Mnemonic);
388   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
389   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
390                               unsigned &ShiftAmount);
391   bool parseLiteralValues(unsigned Size, SMLoc L);
392   bool parseDirectiveThumb(SMLoc L);
393   bool parseDirectiveARM(SMLoc L);
394   bool parseDirectiveThumbFunc(SMLoc L);
395   bool parseDirectiveCode(SMLoc L);
396   bool parseDirectiveSyntax(SMLoc L);
397   bool parseDirectiveReq(StringRef Name, SMLoc L);
398   bool parseDirectiveUnreq(SMLoc L);
399   bool parseDirectiveArch(SMLoc L);
400   bool parseDirectiveEabiAttr(SMLoc L);
401   bool parseDirectiveCPU(SMLoc L);
402   bool parseDirectiveFPU(SMLoc L);
403   bool parseDirectiveFnStart(SMLoc L);
404   bool parseDirectiveFnEnd(SMLoc L);
405   bool parseDirectiveCantUnwind(SMLoc L);
406   bool parseDirectivePersonality(SMLoc L);
407   bool parseDirectiveHandlerData(SMLoc L);
408   bool parseDirectiveSetFP(SMLoc L);
409   bool parseDirectivePad(SMLoc L);
410   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
411   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
412   bool parseDirectiveLtorg(SMLoc L);
413   bool parseDirectiveEven(SMLoc L);
414   bool parseDirectivePersonalityIndex(SMLoc L);
415   bool parseDirectiveUnwindRaw(SMLoc L);
416   bool parseDirectiveTLSDescSeq(SMLoc L);
417   bool parseDirectiveMovSP(SMLoc L);
418   bool parseDirectiveObjectArch(SMLoc L);
419   bool parseDirectiveArchExtension(SMLoc L);
420   bool parseDirectiveAlign(SMLoc L);
421   bool parseDirectiveThumbSet(SMLoc L);
422 
423   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
424                           bool &CarrySetting, unsigned &ProcessorIMod,
425                           StringRef &ITMask);
426   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
427                              bool &CanAcceptCarrySet,
428                              bool &CanAcceptPredicationCode);
429 
430   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
431                                      OperandVector &Operands);
432   bool isThumb() const {
433     // FIXME: Can tablegen auto-generate this?
434     return getSTI().getFeatureBits()[ARM::ModeThumb];
435   }
436 
437   bool isThumbOne() const {
438     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
439   }
440 
441   bool isThumbTwo() const {
442     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
443   }
444 
445   bool hasThumb() const {
446     return getSTI().getFeatureBits()[ARM::HasV4TOps];
447   }
448 
449   bool hasThumb2() const {
450     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
451   }
452 
453   bool hasV6Ops() const {
454     return getSTI().getFeatureBits()[ARM::HasV6Ops];
455   }
456 
457   bool hasV6T2Ops() const {
458     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
459   }
460 
461   bool hasV6MOps() const {
462     return getSTI().getFeatureBits()[ARM::HasV6MOps];
463   }
464 
465   bool hasV7Ops() const {
466     return getSTI().getFeatureBits()[ARM::HasV7Ops];
467   }
468 
469   bool hasV8Ops() const {
470     return getSTI().getFeatureBits()[ARM::HasV8Ops];
471   }
472 
473   bool hasV8MBaseline() const {
474     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
475   }
476 
477   bool hasV8MMainline() const {
478     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
479   }
480 
481   bool has8MSecExt() const {
482     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
483   }
484 
485   bool hasARM() const {
486     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
487   }
488 
489   bool hasDSP() const {
490     return getSTI().getFeatureBits()[ARM::FeatureDSP];
491   }
492 
493   bool hasD16() const {
494     return getSTI().getFeatureBits()[ARM::FeatureD16];
495   }
496 
497   bool hasV8_1aOps() const {
498     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
499   }
500 
501   bool hasRAS() const {
502     return getSTI().getFeatureBits()[ARM::FeatureRAS];
503   }
504 
505   void SwitchMode() {
506     MCSubtargetInfo &STI = copySTI();
507     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
508     setAvailableFeatures(FB);
509   }
510 
511   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
512 
513   bool isMClass() const {
514     return getSTI().getFeatureBits()[ARM::FeatureMClass];
515   }
516 
517   /// @name Auto-generated Match Functions
518   /// {
519 
520 #define GET_ASSEMBLER_HEADER
521 #include "ARMGenAsmMatcher.inc"
522 
523   /// }
524 
525   OperandMatchResultTy parseITCondCode(OperandVector &);
526   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
527   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
528   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
529   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
530   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
531   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
532   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
533   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
534   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
535   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
536                                    int High);
537   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
538     return parsePKHImm(O, "lsl", 0, 31);
539   }
540   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
541     return parsePKHImm(O, "asr", 1, 32);
542   }
543   OperandMatchResultTy parseSetEndImm(OperandVector &);
544   OperandMatchResultTy parseShifterImm(OperandVector &);
545   OperandMatchResultTy parseRotImm(OperandVector &);
546   OperandMatchResultTy parseModImm(OperandVector &);
547   OperandMatchResultTy parseBitfield(OperandVector &);
548   OperandMatchResultTy parsePostIdxReg(OperandVector &);
549   OperandMatchResultTy parseAM3Offset(OperandVector &);
550   OperandMatchResultTy parseFPImm(OperandVector &);
551   OperandMatchResultTy parseVectorList(OperandVector &);
552   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
553                                        SMLoc &EndLoc);
554 
555   // Asm Match Converter Methods
556   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
557   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
558 
559   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
560   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
561   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
562   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
563   bool isITBlockTerminator(MCInst &Inst) const;
564   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
565   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
566                         bool Load, bool ARMMode, bool Writeback);
567 
568 public:
569   enum ARMMatchResultTy {
570     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
571     Match_RequiresNotITBlock,
572     Match_RequiresV6,
573     Match_RequiresThumb2,
574     Match_RequiresV8,
575     Match_RequiresFlagSetting,
576 #define GET_OPERAND_DIAGNOSTIC_TYPES
577 #include "ARMGenAsmMatcher.inc"
578 
579   };
580 
581   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
582                const MCInstrInfo &MII, const MCTargetOptions &Options)
583     : MCTargetAsmParser(Options, STI, MII), UC(Parser) {
584     MCAsmParserExtension::Initialize(Parser);
585 
586     // Cache the MCRegisterInfo.
587     MRI = getContext().getRegisterInfo();
588 
589     // Initialize the set of available features.
590     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
591 
592     // Add build attributes based on the selected target.
593     if (AddBuildAttributes)
594       getTargetStreamer().emitTargetAttributes(STI);
595 
596     // Not in an ITBlock to start with.
597     ITState.CurPosition = ~0U;
598 
599     NextSymbolIsThumb = false;
600   }
601 
602   // Implementation of the MCTargetAsmParser interface:
603   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
604   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
605                         SMLoc NameLoc, OperandVector &Operands) override;
606   bool ParseDirective(AsmToken DirectiveID) override;
607 
608   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
609                                       unsigned Kind) override;
610   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
611 
612   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
613                                OperandVector &Operands, MCStreamer &Out,
614                                uint64_t &ErrorInfo,
615                                bool MatchingInlineAsm) override;
616   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
617                             SmallVectorImpl<NearMissInfo> &NearMisses,
618                             bool MatchingInlineAsm, bool &EmitInITBlock,
619                             MCStreamer &Out);
620 
621   struct NearMissMessage {
622     SMLoc Loc;
623     SmallString<128> Message;
624   };
625 
626   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
627 
628   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
629                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
630                         SMLoc IDLoc, OperandVector &Operands);
631   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
632                         OperandVector &Operands);
633 
634   void onLabelParsed(MCSymbol *Symbol) override;
635 };
636 
637 /// ARMOperand - Instances of this class represent a parsed ARM machine
638 /// operand.
639 class ARMOperand : public MCParsedAsmOperand {
640   enum KindTy {
641     k_CondCode,
642     k_CCOut,
643     k_ITCondMask,
644     k_CoprocNum,
645     k_CoprocReg,
646     k_CoprocOption,
647     k_Immediate,
648     k_MemBarrierOpt,
649     k_InstSyncBarrierOpt,
650     k_TraceSyncBarrierOpt,
651     k_Memory,
652     k_PostIndexRegister,
653     k_MSRMask,
654     k_BankedReg,
655     k_ProcIFlags,
656     k_VectorIndex,
657     k_Register,
658     k_RegisterList,
659     k_DPRRegisterList,
660     k_SPRRegisterList,
661     k_VectorList,
662     k_VectorListAllLanes,
663     k_VectorListIndexed,
664     k_ShiftedRegister,
665     k_ShiftedImmediate,
666     k_ShifterImmediate,
667     k_RotateImmediate,
668     k_ModifiedImmediate,
669     k_ConstantPoolImmediate,
670     k_BitfieldDescriptor,
671     k_Token,
672   } Kind;
673 
674   SMLoc StartLoc, EndLoc, AlignmentLoc;
675   SmallVector<unsigned, 8> Registers;
676 
677   struct CCOp {
678     ARMCC::CondCodes Val;
679   };
680 
681   struct CopOp {
682     unsigned Val;
683   };
684 
685   struct CoprocOptionOp {
686     unsigned Val;
687   };
688 
689   struct ITMaskOp {
690     unsigned Mask:4;
691   };
692 
693   struct MBOptOp {
694     ARM_MB::MemBOpt Val;
695   };
696 
697   struct ISBOptOp {
698     ARM_ISB::InstSyncBOpt Val;
699   };
700 
701   struct TSBOptOp {
702     ARM_TSB::TraceSyncBOpt Val;
703   };
704 
705   struct IFlagsOp {
706     ARM_PROC::IFlags Val;
707   };
708 
709   struct MMaskOp {
710     unsigned Val;
711   };
712 
713   struct BankedRegOp {
714     unsigned Val;
715   };
716 
717   struct TokOp {
718     const char *Data;
719     unsigned Length;
720   };
721 
722   struct RegOp {
723     unsigned RegNum;
724   };
725 
726   // A vector register list is a sequential list of 1 to 4 registers.
727   struct VectorListOp {
728     unsigned RegNum;
729     unsigned Count;
730     unsigned LaneIndex;
731     bool isDoubleSpaced;
732   };
733 
734   struct VectorIndexOp {
735     unsigned Val;
736   };
737 
738   struct ImmOp {
739     const MCExpr *Val;
740   };
741 
742   /// Combined record for all forms of ARM address expressions.
743   struct MemoryOp {
744     unsigned BaseRegNum;
745     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
746     // was specified.
747     const MCConstantExpr *OffsetImm;  // Offset immediate value
748     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
749     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
750     unsigned ShiftImm;        // shift for OffsetReg.
751     unsigned Alignment;       // 0 = no alignment specified
752     // n = alignment in bytes (2, 4, 8, 16, or 32)
753     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
754   };
755 
756   struct PostIdxRegOp {
757     unsigned RegNum;
758     bool isAdd;
759     ARM_AM::ShiftOpc ShiftTy;
760     unsigned ShiftImm;
761   };
762 
763   struct ShifterImmOp {
764     bool isASR;
765     unsigned Imm;
766   };
767 
768   struct RegShiftedRegOp {
769     ARM_AM::ShiftOpc ShiftTy;
770     unsigned SrcReg;
771     unsigned ShiftReg;
772     unsigned ShiftImm;
773   };
774 
775   struct RegShiftedImmOp {
776     ARM_AM::ShiftOpc ShiftTy;
777     unsigned SrcReg;
778     unsigned ShiftImm;
779   };
780 
781   struct RotImmOp {
782     unsigned Imm;
783   };
784 
785   struct ModImmOp {
786     unsigned Bits;
787     unsigned Rot;
788   };
789 
790   struct BitfieldOp {
791     unsigned LSB;
792     unsigned Width;
793   };
794 
795   union {
796     struct CCOp CC;
797     struct CopOp Cop;
798     struct CoprocOptionOp CoprocOption;
799     struct MBOptOp MBOpt;
800     struct ISBOptOp ISBOpt;
801     struct TSBOptOp TSBOpt;
802     struct ITMaskOp ITMask;
803     struct IFlagsOp IFlags;
804     struct MMaskOp MMask;
805     struct BankedRegOp BankedReg;
806     struct TokOp Tok;
807     struct RegOp Reg;
808     struct VectorListOp VectorList;
809     struct VectorIndexOp VectorIndex;
810     struct ImmOp Imm;
811     struct MemoryOp Memory;
812     struct PostIdxRegOp PostIdxReg;
813     struct ShifterImmOp ShifterImm;
814     struct RegShiftedRegOp RegShiftedReg;
815     struct RegShiftedImmOp RegShiftedImm;
816     struct RotImmOp RotImm;
817     struct ModImmOp ModImm;
818     struct BitfieldOp Bitfield;
819   };
820 
821 public:
822   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
823 
824   /// getStartLoc - Get the location of the first token of this operand.
825   SMLoc getStartLoc() const override { return StartLoc; }
826 
827   /// getEndLoc - Get the location of the last token of this operand.
828   SMLoc getEndLoc() const override { return EndLoc; }
829 
830   /// getLocRange - Get the range between the first and last token of this
831   /// operand.
832   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
833 
834   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
835   SMLoc getAlignmentLoc() const {
836     assert(Kind == k_Memory && "Invalid access!");
837     return AlignmentLoc;
838   }
839 
840   ARMCC::CondCodes getCondCode() const {
841     assert(Kind == k_CondCode && "Invalid access!");
842     return CC.Val;
843   }
844 
845   unsigned getCoproc() const {
846     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
847     return Cop.Val;
848   }
849 
850   StringRef getToken() const {
851     assert(Kind == k_Token && "Invalid access!");
852     return StringRef(Tok.Data, Tok.Length);
853   }
854 
855   unsigned getReg() const override {
856     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
857     return Reg.RegNum;
858   }
859 
860   const SmallVectorImpl<unsigned> &getRegList() const {
861     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
862             Kind == k_SPRRegisterList) && "Invalid access!");
863     return Registers;
864   }
865 
866   const MCExpr *getImm() const {
867     assert(isImm() && "Invalid access!");
868     return Imm.Val;
869   }
870 
871   const MCExpr *getConstantPoolImm() const {
872     assert(isConstantPoolImm() && "Invalid access!");
873     return Imm.Val;
874   }
875 
876   unsigned getVectorIndex() const {
877     assert(Kind == k_VectorIndex && "Invalid access!");
878     return VectorIndex.Val;
879   }
880 
881   ARM_MB::MemBOpt getMemBarrierOpt() const {
882     assert(Kind == k_MemBarrierOpt && "Invalid access!");
883     return MBOpt.Val;
884   }
885 
886   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
887     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
888     return ISBOpt.Val;
889   }
890 
891   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
892     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
893     return TSBOpt.Val;
894   }
895 
896   ARM_PROC::IFlags getProcIFlags() const {
897     assert(Kind == k_ProcIFlags && "Invalid access!");
898     return IFlags.Val;
899   }
900 
901   unsigned getMSRMask() const {
902     assert(Kind == k_MSRMask && "Invalid access!");
903     return MMask.Val;
904   }
905 
906   unsigned getBankedReg() const {
907     assert(Kind == k_BankedReg && "Invalid access!");
908     return BankedReg.Val;
909   }
910 
911   bool isCoprocNum() const { return Kind == k_CoprocNum; }
912   bool isCoprocReg() const { return Kind == k_CoprocReg; }
913   bool isCoprocOption() const { return Kind == k_CoprocOption; }
914   bool isCondCode() const { return Kind == k_CondCode; }
915   bool isCCOut() const { return Kind == k_CCOut; }
916   bool isITMask() const { return Kind == k_ITCondMask; }
917   bool isITCondCode() const { return Kind == k_CondCode; }
918   bool isImm() const override {
919     return Kind == k_Immediate;
920   }
921 
922   bool isARMBranchTarget() const {
923     if (!isImm()) return false;
924 
925     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
926       return CE->getValue() % 4 == 0;
927     return true;
928   }
929 
930 
931   bool isThumbBranchTarget() const {
932     if (!isImm()) return false;
933 
934     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
935       return CE->getValue() % 2 == 0;
936     return true;
937   }
938 
939   // checks whether this operand is an unsigned offset which fits is a field
940   // of specified width and scaled by a specific number of bits
941   template<unsigned width, unsigned scale>
942   bool isUnsignedOffset() const {
943     if (!isImm()) return false;
944     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
945     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
946       int64_t Val = CE->getValue();
947       int64_t Align = 1LL << scale;
948       int64_t Max = Align * ((1LL << width) - 1);
949       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
950     }
951     return false;
952   }
953 
954   // checks whether this operand is an signed offset which fits is a field
955   // of specified width and scaled by a specific number of bits
956   template<unsigned width, unsigned scale>
957   bool isSignedOffset() const {
958     if (!isImm()) return false;
959     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
960     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
961       int64_t Val = CE->getValue();
962       int64_t Align = 1LL << scale;
963       int64_t Max = Align * ((1LL << (width-1)) - 1);
964       int64_t Min = -Align * (1LL << (width-1));
965       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
966     }
967     return false;
968   }
969 
970   // checks whether this operand is a memory operand computed as an offset
971   // applied to PC. the offset may have 8 bits of magnitude and is represented
972   // with two bits of shift. textually it may be either [pc, #imm], #imm or
973   // relocable expression...
974   bool isThumbMemPC() const {
975     int64_t Val = 0;
976     if (isImm()) {
977       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
978       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
979       if (!CE) return false;
980       Val = CE->getValue();
981     }
982     else if (isMem()) {
983       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
984       if(Memory.BaseRegNum != ARM::PC) return false;
985       Val = Memory.OffsetImm->getValue();
986     }
987     else return false;
988     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
989   }
990 
991   bool isFPImm() const {
992     if (!isImm()) return false;
993     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
994     if (!CE) return false;
995     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
996     return Val != -1;
997   }
998 
999   template<int64_t N, int64_t M>
1000   bool isImmediate() const {
1001     if (!isImm()) return false;
1002     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1003     if (!CE) return false;
1004     int64_t Value = CE->getValue();
1005     return Value >= N && Value <= M;
1006   }
1007 
1008   template<int64_t N, int64_t M>
1009   bool isImmediateS4() const {
1010     if (!isImm()) return false;
1011     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1012     if (!CE) return false;
1013     int64_t Value = CE->getValue();
1014     return ((Value & 3) == 0) && Value >= N && Value <= M;
1015   }
1016 
1017   bool isFBits16() const {
1018     return isImmediate<0, 17>();
1019   }
1020   bool isFBits32() const {
1021     return isImmediate<1, 33>();
1022   }
1023   bool isImm8s4() const {
1024     return isImmediateS4<-1020, 1020>();
1025   }
1026   bool isImm0_1020s4() const {
1027     return isImmediateS4<0, 1020>();
1028   }
1029   bool isImm0_508s4() const {
1030     return isImmediateS4<0, 508>();
1031   }
1032   bool isImm0_508s4Neg() const {
1033     if (!isImm()) return false;
1034     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1035     if (!CE) return false;
1036     int64_t Value = -CE->getValue();
1037     // explicitly exclude zero. we want that to use the normal 0_508 version.
1038     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1039   }
1040 
1041   bool isImm0_4095Neg() const {
1042     if (!isImm()) return false;
1043     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1044     if (!CE) return false;
1045     // isImm0_4095Neg is used with 32-bit immediates only.
1046     // 32-bit immediates are zero extended to 64-bit when parsed,
1047     // thus simple -CE->getValue() results in a big negative number,
1048     // not a small positive number as intended
1049     if ((CE->getValue() >> 32) > 0) return false;
1050     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1051     return Value > 0 && Value < 4096;
1052   }
1053 
1054   bool isImm0_7() const {
1055     return isImmediate<0, 7>();
1056   }
1057 
1058   bool isImm1_16() const {
1059     return isImmediate<1, 16>();
1060   }
1061 
1062   bool isImm1_32() const {
1063     return isImmediate<1, 32>();
1064   }
1065 
1066   bool isImm8_255() const {
1067     return isImmediate<8, 255>();
1068   }
1069 
1070   bool isImm256_65535Expr() const {
1071     if (!isImm()) return false;
1072     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1073     // If it's not a constant expression, it'll generate a fixup and be
1074     // handled later.
1075     if (!CE) return true;
1076     int64_t Value = CE->getValue();
1077     return Value >= 256 && Value < 65536;
1078   }
1079 
1080   bool isImm0_65535Expr() const {
1081     if (!isImm()) return false;
1082     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1083     // If it's not a constant expression, it'll generate a fixup and be
1084     // handled later.
1085     if (!CE) return true;
1086     int64_t Value = CE->getValue();
1087     return Value >= 0 && Value < 65536;
1088   }
1089 
1090   bool isImm24bit() const {
1091     return isImmediate<0, 0xffffff + 1>();
1092   }
1093 
1094   bool isImmThumbSR() const {
1095     return isImmediate<1, 33>();
1096   }
1097 
1098   bool isPKHLSLImm() const {
1099     return isImmediate<0, 32>();
1100   }
1101 
1102   bool isPKHASRImm() const {
1103     return isImmediate<0, 33>();
1104   }
1105 
1106   bool isAdrLabel() const {
1107     // If we have an immediate that's not a constant, treat it as a label
1108     // reference needing a fixup.
1109     if (isImm() && !isa<MCConstantExpr>(getImm()))
1110       return true;
1111 
1112     // If it is a constant, it must fit into a modified immediate encoding.
1113     if (!isImm()) return false;
1114     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1115     if (!CE) return false;
1116     int64_t Value = CE->getValue();
1117     return (ARM_AM::getSOImmVal(Value) != -1 ||
1118             ARM_AM::getSOImmVal(-Value) != -1);
1119   }
1120 
1121   bool isT2SOImm() const {
1122     // If we have an immediate that's not a constant, treat it as an expression
1123     // needing a fixup.
1124     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1125       // We want to avoid matching :upper16: and :lower16: as we want these
1126       // expressions to match in isImm0_65535Expr()
1127       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1128       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1129                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1130     }
1131     if (!isImm()) return false;
1132     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1133     if (!CE) return false;
1134     int64_t Value = CE->getValue();
1135     return ARM_AM::getT2SOImmVal(Value) != -1;
1136   }
1137 
1138   bool isT2SOImmNot() const {
1139     if (!isImm()) return false;
1140     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1141     if (!CE) return false;
1142     int64_t Value = CE->getValue();
1143     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1144       ARM_AM::getT2SOImmVal(~Value) != -1;
1145   }
1146 
1147   bool isT2SOImmNeg() const {
1148     if (!isImm()) return false;
1149     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1150     if (!CE) return false;
1151     int64_t Value = CE->getValue();
1152     // Only use this when not representable as a plain so_imm.
1153     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1154       ARM_AM::getT2SOImmVal(-Value) != -1;
1155   }
1156 
1157   bool isSetEndImm() const {
1158     if (!isImm()) return false;
1159     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1160     if (!CE) return false;
1161     int64_t Value = CE->getValue();
1162     return Value == 1 || Value == 0;
1163   }
1164 
1165   bool isReg() const override { return Kind == k_Register; }
1166   bool isRegList() const { return Kind == k_RegisterList; }
1167   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1168   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1169   bool isToken() const override { return Kind == k_Token; }
1170   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1171   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1172   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
1173   bool isMem() const override {
1174     if (Kind != k_Memory)
1175       return false;
1176     if (Memory.BaseRegNum &&
1177         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1178       return false;
1179     if (Memory.OffsetRegNum &&
1180         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1181       return false;
1182     return true;
1183   }
1184   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1185   bool isRegShiftedReg() const {
1186     return Kind == k_ShiftedRegister &&
1187            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1188                RegShiftedReg.SrcReg) &&
1189            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1190                RegShiftedReg.ShiftReg);
1191   }
1192   bool isRegShiftedImm() const {
1193     return Kind == k_ShiftedImmediate &&
1194            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1195                RegShiftedImm.SrcReg);
1196   }
1197   bool isRotImm() const { return Kind == k_RotateImmediate; }
1198   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1199 
1200   bool isModImmNot() const {
1201     if (!isImm()) return false;
1202     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1203     if (!CE) return false;
1204     int64_t Value = CE->getValue();
1205     return ARM_AM::getSOImmVal(~Value) != -1;
1206   }
1207 
1208   bool isModImmNeg() const {
1209     if (!isImm()) return false;
1210     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1211     if (!CE) return false;
1212     int64_t Value = CE->getValue();
1213     return ARM_AM::getSOImmVal(Value) == -1 &&
1214       ARM_AM::getSOImmVal(-Value) != -1;
1215   }
1216 
1217   bool isThumbModImmNeg1_7() const {
1218     if (!isImm()) return false;
1219     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1220     if (!CE) return false;
1221     int32_t Value = -(int32_t)CE->getValue();
1222     return 0 < Value && Value < 8;
1223   }
1224 
1225   bool isThumbModImmNeg8_255() const {
1226     if (!isImm()) return false;
1227     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1228     if (!CE) return false;
1229     int32_t Value = -(int32_t)CE->getValue();
1230     return 7 < Value && Value < 256;
1231   }
1232 
1233   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1234   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1235   bool isPostIdxRegShifted() const {
1236     return Kind == k_PostIndexRegister &&
1237            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1238   }
1239   bool isPostIdxReg() const {
1240     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1241   }
1242   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1243     if (!isMem())
1244       return false;
1245     // No offset of any kind.
1246     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1247      (alignOK || Memory.Alignment == Alignment);
1248   }
1249   bool isMemPCRelImm12() const {
1250     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1251       return false;
1252     // Base register must be PC.
1253     if (Memory.BaseRegNum != ARM::PC)
1254       return false;
1255     // Immediate offset in range [-4095, 4095].
1256     if (!Memory.OffsetImm) return true;
1257     int64_t Val = Memory.OffsetImm->getValue();
1258     return (Val > -4096 && Val < 4096) ||
1259            (Val == std::numeric_limits<int32_t>::min());
1260   }
1261 
1262   bool isAlignedMemory() const {
1263     return isMemNoOffset(true);
1264   }
1265 
1266   bool isAlignedMemoryNone() const {
1267     return isMemNoOffset(false, 0);
1268   }
1269 
1270   bool isDupAlignedMemoryNone() const {
1271     return isMemNoOffset(false, 0);
1272   }
1273 
1274   bool isAlignedMemory16() const {
1275     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1276       return true;
1277     return isMemNoOffset(false, 0);
1278   }
1279 
1280   bool isDupAlignedMemory16() const {
1281     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1282       return true;
1283     return isMemNoOffset(false, 0);
1284   }
1285 
1286   bool isAlignedMemory32() const {
1287     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1288       return true;
1289     return isMemNoOffset(false, 0);
1290   }
1291 
1292   bool isDupAlignedMemory32() const {
1293     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1294       return true;
1295     return isMemNoOffset(false, 0);
1296   }
1297 
1298   bool isAlignedMemory64() const {
1299     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1300       return true;
1301     return isMemNoOffset(false, 0);
1302   }
1303 
1304   bool isDupAlignedMemory64() const {
1305     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1306       return true;
1307     return isMemNoOffset(false, 0);
1308   }
1309 
1310   bool isAlignedMemory64or128() const {
1311     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1312       return true;
1313     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1314       return true;
1315     return isMemNoOffset(false, 0);
1316   }
1317 
1318   bool isDupAlignedMemory64or128() const {
1319     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1320       return true;
1321     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1322       return true;
1323     return isMemNoOffset(false, 0);
1324   }
1325 
1326   bool isAlignedMemory64or128or256() const {
1327     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1328       return true;
1329     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1330       return true;
1331     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1332       return true;
1333     return isMemNoOffset(false, 0);
1334   }
1335 
1336   bool isAddrMode2() const {
1337     if (!isMem() || Memory.Alignment != 0) return false;
1338     // Check for register offset.
1339     if (Memory.OffsetRegNum) return true;
1340     // Immediate offset in range [-4095, 4095].
1341     if (!Memory.OffsetImm) return true;
1342     int64_t Val = Memory.OffsetImm->getValue();
1343     return Val > -4096 && Val < 4096;
1344   }
1345 
1346   bool isAM2OffsetImm() const {
1347     if (!isImm()) return false;
1348     // Immediate offset in range [-4095, 4095].
1349     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1350     if (!CE) return false;
1351     int64_t Val = CE->getValue();
1352     return (Val == std::numeric_limits<int32_t>::min()) ||
1353            (Val > -4096 && Val < 4096);
1354   }
1355 
1356   bool isAddrMode3() const {
1357     // If we have an immediate that's not a constant, treat it as a label
1358     // reference needing a fixup. If it is a constant, it's something else
1359     // and we reject it.
1360     if (isImm() && !isa<MCConstantExpr>(getImm()))
1361       return true;
1362     if (!isMem() || Memory.Alignment != 0) return false;
1363     // No shifts are legal for AM3.
1364     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1365     // Check for register offset.
1366     if (Memory.OffsetRegNum) return true;
1367     // Immediate offset in range [-255, 255].
1368     if (!Memory.OffsetImm) return true;
1369     int64_t Val = Memory.OffsetImm->getValue();
1370     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1371     // have to check for this too.
1372     return (Val > -256 && Val < 256) ||
1373            Val == std::numeric_limits<int32_t>::min();
1374   }
1375 
1376   bool isAM3Offset() const {
1377     if (isPostIdxReg())
1378       return true;
1379     if (!isImm())
1380       return false;
1381     // Immediate offset in range [-255, 255].
1382     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1383     if (!CE) return false;
1384     int64_t Val = CE->getValue();
1385     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1386     return (Val > -256 && Val < 256) ||
1387            Val == std::numeric_limits<int32_t>::min();
1388   }
1389 
1390   bool isAddrMode5() const {
1391     // If we have an immediate that's not a constant, treat it as a label
1392     // reference needing a fixup. If it is a constant, it's something else
1393     // and we reject it.
1394     if (isImm() && !isa<MCConstantExpr>(getImm()))
1395       return true;
1396     if (!isMem() || Memory.Alignment != 0) return false;
1397     // Check for register offset.
1398     if (Memory.OffsetRegNum) return false;
1399     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1400     if (!Memory.OffsetImm) return true;
1401     int64_t Val = Memory.OffsetImm->getValue();
1402     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1403       Val == std::numeric_limits<int32_t>::min();
1404   }
1405 
1406   bool isAddrMode5FP16() const {
1407     // If we have an immediate that's not a constant, treat it as a label
1408     // reference needing a fixup. If it is a constant, it's something else
1409     // and we reject it.
1410     if (isImm() && !isa<MCConstantExpr>(getImm()))
1411       return true;
1412     if (!isMem() || Memory.Alignment != 0) return false;
1413     // Check for register offset.
1414     if (Memory.OffsetRegNum) return false;
1415     // Immediate offset in range [-510, 510] and a multiple of 2.
1416     if (!Memory.OffsetImm) return true;
1417     int64_t Val = Memory.OffsetImm->getValue();
1418     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1419            Val == std::numeric_limits<int32_t>::min();
1420   }
1421 
1422   bool isMemTBB() const {
1423     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1424         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1425       return false;
1426     return true;
1427   }
1428 
1429   bool isMemTBH() const {
1430     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1431         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1432         Memory.Alignment != 0 )
1433       return false;
1434     return true;
1435   }
1436 
1437   bool isMemRegOffset() const {
1438     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1439       return false;
1440     return true;
1441   }
1442 
1443   bool isT2MemRegOffset() const {
1444     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1445         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1446       return false;
1447     // Only lsl #{0, 1, 2, 3} allowed.
1448     if (Memory.ShiftType == ARM_AM::no_shift)
1449       return true;
1450     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1451       return false;
1452     return true;
1453   }
1454 
1455   bool isMemThumbRR() const {
1456     // Thumb reg+reg addressing is simple. Just two registers, a base and
1457     // an offset. No shifts, negations or any other complicating factors.
1458     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1459         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1460       return false;
1461     return isARMLowRegister(Memory.BaseRegNum) &&
1462       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1463   }
1464 
1465   bool isMemThumbRIs4() const {
1466     if (!isMem() || Memory.OffsetRegNum != 0 ||
1467         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1468       return false;
1469     // Immediate offset, multiple of 4 in range [0, 124].
1470     if (!Memory.OffsetImm) return true;
1471     int64_t Val = Memory.OffsetImm->getValue();
1472     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1473   }
1474 
1475   bool isMemThumbRIs2() const {
1476     if (!isMem() || Memory.OffsetRegNum != 0 ||
1477         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1478       return false;
1479     // Immediate offset, multiple of 4 in range [0, 62].
1480     if (!Memory.OffsetImm) return true;
1481     int64_t Val = Memory.OffsetImm->getValue();
1482     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1483   }
1484 
1485   bool isMemThumbRIs1() const {
1486     if (!isMem() || Memory.OffsetRegNum != 0 ||
1487         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1488       return false;
1489     // Immediate offset in range [0, 31].
1490     if (!Memory.OffsetImm) return true;
1491     int64_t Val = Memory.OffsetImm->getValue();
1492     return Val >= 0 && Val <= 31;
1493   }
1494 
1495   bool isMemThumbSPI() const {
1496     if (!isMem() || Memory.OffsetRegNum != 0 ||
1497         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1498       return false;
1499     // Immediate offset, multiple of 4 in range [0, 1020].
1500     if (!Memory.OffsetImm) return true;
1501     int64_t Val = Memory.OffsetImm->getValue();
1502     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1503   }
1504 
1505   bool isMemImm8s4Offset() const {
1506     // If we have an immediate that's not a constant, treat it as a label
1507     // reference needing a fixup. If it is a constant, it's something else
1508     // and we reject it.
1509     if (isImm() && !isa<MCConstantExpr>(getImm()))
1510       return true;
1511     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1512       return false;
1513     // Immediate offset a multiple of 4 in range [-1020, 1020].
1514     if (!Memory.OffsetImm) return true;
1515     int64_t Val = Memory.OffsetImm->getValue();
1516     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1517     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1518            Val == std::numeric_limits<int32_t>::min();
1519   }
1520 
1521   bool isMemImm0_1020s4Offset() const {
1522     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1523       return false;
1524     // Immediate offset a multiple of 4 in range [0, 1020].
1525     if (!Memory.OffsetImm) return true;
1526     int64_t Val = Memory.OffsetImm->getValue();
1527     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1528   }
1529 
1530   bool isMemImm8Offset() const {
1531     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1532       return false;
1533     // Base reg of PC isn't allowed for these encodings.
1534     if (Memory.BaseRegNum == ARM::PC) return false;
1535     // Immediate offset in range [-255, 255].
1536     if (!Memory.OffsetImm) return true;
1537     int64_t Val = Memory.OffsetImm->getValue();
1538     return (Val == std::numeric_limits<int32_t>::min()) ||
1539            (Val > -256 && Val < 256);
1540   }
1541 
1542   bool isMemPosImm8Offset() const {
1543     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1544       return false;
1545     // Immediate offset in range [0, 255].
1546     if (!Memory.OffsetImm) return true;
1547     int64_t Val = Memory.OffsetImm->getValue();
1548     return Val >= 0 && Val < 256;
1549   }
1550 
1551   bool isMemNegImm8Offset() const {
1552     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1553       return false;
1554     // Base reg of PC isn't allowed for these encodings.
1555     if (Memory.BaseRegNum == ARM::PC) return false;
1556     // Immediate offset in range [-255, -1].
1557     if (!Memory.OffsetImm) return false;
1558     int64_t Val = Memory.OffsetImm->getValue();
1559     return (Val == std::numeric_limits<int32_t>::min()) ||
1560            (Val > -256 && Val < 0);
1561   }
1562 
1563   bool isMemUImm12Offset() const {
1564     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1565       return false;
1566     // Immediate offset in range [0, 4095].
1567     if (!Memory.OffsetImm) return true;
1568     int64_t Val = Memory.OffsetImm->getValue();
1569     return (Val >= 0 && Val < 4096);
1570   }
1571 
1572   bool isMemImm12Offset() const {
1573     // If we have an immediate that's not a constant, treat it as a label
1574     // reference needing a fixup. If it is a constant, it's something else
1575     // and we reject it.
1576 
1577     if (isImm() && !isa<MCConstantExpr>(getImm()))
1578       return true;
1579 
1580     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1581       return false;
1582     // Immediate offset in range [-4095, 4095].
1583     if (!Memory.OffsetImm) return true;
1584     int64_t Val = Memory.OffsetImm->getValue();
1585     return (Val > -4096 && Val < 4096) ||
1586            (Val == std::numeric_limits<int32_t>::min());
1587   }
1588 
1589   bool isConstPoolAsmImm() const {
1590     // Delay processing of Constant Pool Immediate, this will turn into
1591     // a constant. Match no other operand
1592     return (isConstantPoolImm());
1593   }
1594 
1595   bool isPostIdxImm8() const {
1596     if (!isImm()) return false;
1597     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1598     if (!CE) return false;
1599     int64_t Val = CE->getValue();
1600     return (Val > -256 && Val < 256) ||
1601            (Val == std::numeric_limits<int32_t>::min());
1602   }
1603 
1604   bool isPostIdxImm8s4() const {
1605     if (!isImm()) return false;
1606     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1607     if (!CE) return false;
1608     int64_t Val = CE->getValue();
1609     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1610            (Val == std::numeric_limits<int32_t>::min());
1611   }
1612 
1613   bool isMSRMask() const { return Kind == k_MSRMask; }
1614   bool isBankedReg() const { return Kind == k_BankedReg; }
1615   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1616 
1617   // NEON operands.
1618   bool isSingleSpacedVectorList() const {
1619     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1620   }
1621 
1622   bool isDoubleSpacedVectorList() const {
1623     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1624   }
1625 
1626   bool isVecListOneD() const {
1627     if (!isSingleSpacedVectorList()) return false;
1628     return VectorList.Count == 1;
1629   }
1630 
1631   bool isVecListDPair() const {
1632     if (!isSingleSpacedVectorList()) return false;
1633     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1634               .contains(VectorList.RegNum));
1635   }
1636 
1637   bool isVecListThreeD() const {
1638     if (!isSingleSpacedVectorList()) return false;
1639     return VectorList.Count == 3;
1640   }
1641 
1642   bool isVecListFourD() const {
1643     if (!isSingleSpacedVectorList()) return false;
1644     return VectorList.Count == 4;
1645   }
1646 
1647   bool isVecListDPairSpaced() const {
1648     if (Kind != k_VectorList) return false;
1649     if (isSingleSpacedVectorList()) return false;
1650     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1651               .contains(VectorList.RegNum));
1652   }
1653 
1654   bool isVecListThreeQ() const {
1655     if (!isDoubleSpacedVectorList()) return false;
1656     return VectorList.Count == 3;
1657   }
1658 
1659   bool isVecListFourQ() const {
1660     if (!isDoubleSpacedVectorList()) return false;
1661     return VectorList.Count == 4;
1662   }
1663 
1664   bool isSingleSpacedVectorAllLanes() const {
1665     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1666   }
1667 
1668   bool isDoubleSpacedVectorAllLanes() const {
1669     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1670   }
1671 
1672   bool isVecListOneDAllLanes() const {
1673     if (!isSingleSpacedVectorAllLanes()) return false;
1674     return VectorList.Count == 1;
1675   }
1676 
1677   bool isVecListDPairAllLanes() const {
1678     if (!isSingleSpacedVectorAllLanes()) return false;
1679     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1680               .contains(VectorList.RegNum));
1681   }
1682 
1683   bool isVecListDPairSpacedAllLanes() const {
1684     if (!isDoubleSpacedVectorAllLanes()) return false;
1685     return VectorList.Count == 2;
1686   }
1687 
1688   bool isVecListThreeDAllLanes() const {
1689     if (!isSingleSpacedVectorAllLanes()) return false;
1690     return VectorList.Count == 3;
1691   }
1692 
1693   bool isVecListThreeQAllLanes() const {
1694     if (!isDoubleSpacedVectorAllLanes()) return false;
1695     return VectorList.Count == 3;
1696   }
1697 
1698   bool isVecListFourDAllLanes() const {
1699     if (!isSingleSpacedVectorAllLanes()) return false;
1700     return VectorList.Count == 4;
1701   }
1702 
1703   bool isVecListFourQAllLanes() const {
1704     if (!isDoubleSpacedVectorAllLanes()) return false;
1705     return VectorList.Count == 4;
1706   }
1707 
1708   bool isSingleSpacedVectorIndexed() const {
1709     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1710   }
1711 
1712   bool isDoubleSpacedVectorIndexed() const {
1713     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1714   }
1715 
1716   bool isVecListOneDByteIndexed() const {
1717     if (!isSingleSpacedVectorIndexed()) return false;
1718     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1719   }
1720 
1721   bool isVecListOneDHWordIndexed() const {
1722     if (!isSingleSpacedVectorIndexed()) return false;
1723     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1724   }
1725 
1726   bool isVecListOneDWordIndexed() const {
1727     if (!isSingleSpacedVectorIndexed()) return false;
1728     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1729   }
1730 
1731   bool isVecListTwoDByteIndexed() const {
1732     if (!isSingleSpacedVectorIndexed()) return false;
1733     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1734   }
1735 
1736   bool isVecListTwoDHWordIndexed() const {
1737     if (!isSingleSpacedVectorIndexed()) return false;
1738     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1739   }
1740 
1741   bool isVecListTwoQWordIndexed() const {
1742     if (!isDoubleSpacedVectorIndexed()) return false;
1743     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1744   }
1745 
1746   bool isVecListTwoQHWordIndexed() const {
1747     if (!isDoubleSpacedVectorIndexed()) return false;
1748     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1749   }
1750 
1751   bool isVecListTwoDWordIndexed() const {
1752     if (!isSingleSpacedVectorIndexed()) return false;
1753     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1754   }
1755 
1756   bool isVecListThreeDByteIndexed() const {
1757     if (!isSingleSpacedVectorIndexed()) return false;
1758     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1759   }
1760 
1761   bool isVecListThreeDHWordIndexed() const {
1762     if (!isSingleSpacedVectorIndexed()) return false;
1763     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1764   }
1765 
1766   bool isVecListThreeQWordIndexed() const {
1767     if (!isDoubleSpacedVectorIndexed()) return false;
1768     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1769   }
1770 
1771   bool isVecListThreeQHWordIndexed() const {
1772     if (!isDoubleSpacedVectorIndexed()) return false;
1773     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1774   }
1775 
1776   bool isVecListThreeDWordIndexed() const {
1777     if (!isSingleSpacedVectorIndexed()) return false;
1778     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1779   }
1780 
1781   bool isVecListFourDByteIndexed() const {
1782     if (!isSingleSpacedVectorIndexed()) return false;
1783     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1784   }
1785 
1786   bool isVecListFourDHWordIndexed() const {
1787     if (!isSingleSpacedVectorIndexed()) return false;
1788     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1789   }
1790 
1791   bool isVecListFourQWordIndexed() const {
1792     if (!isDoubleSpacedVectorIndexed()) return false;
1793     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1794   }
1795 
1796   bool isVecListFourQHWordIndexed() const {
1797     if (!isDoubleSpacedVectorIndexed()) return false;
1798     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1799   }
1800 
1801   bool isVecListFourDWordIndexed() const {
1802     if (!isSingleSpacedVectorIndexed()) return false;
1803     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1804   }
1805 
1806   bool isVectorIndex8() const {
1807     if (Kind != k_VectorIndex) return false;
1808     return VectorIndex.Val < 8;
1809   }
1810 
1811   bool isVectorIndex16() const {
1812     if (Kind != k_VectorIndex) return false;
1813     return VectorIndex.Val < 4;
1814   }
1815 
1816   bool isVectorIndex32() const {
1817     if (Kind != k_VectorIndex) return false;
1818     return VectorIndex.Val < 2;
1819   }
1820   bool isVectorIndex64() const {
1821     if (Kind != k_VectorIndex) return false;
1822     return VectorIndex.Val < 1;
1823   }
1824 
1825   bool isNEONi8splat() const {
1826     if (!isImm()) return false;
1827     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1828     // Must be a constant.
1829     if (!CE) return false;
1830     int64_t Value = CE->getValue();
1831     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1832     // value.
1833     return Value >= 0 && Value < 256;
1834   }
1835 
1836   bool isNEONi16splat() const {
1837     if (isNEONByteReplicate(2))
1838       return false; // Leave that for bytes replication and forbid by default.
1839     if (!isImm())
1840       return false;
1841     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1842     // Must be a constant.
1843     if (!CE) return false;
1844     unsigned Value = CE->getValue();
1845     return ARM_AM::isNEONi16splat(Value);
1846   }
1847 
1848   bool isNEONi16splatNot() const {
1849     if (!isImm())
1850       return false;
1851     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1852     // Must be a constant.
1853     if (!CE) return false;
1854     unsigned Value = CE->getValue();
1855     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1856   }
1857 
1858   bool isNEONi32splat() const {
1859     if (isNEONByteReplicate(4))
1860       return false; // Leave that for bytes replication and forbid by default.
1861     if (!isImm())
1862       return false;
1863     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1864     // Must be a constant.
1865     if (!CE) return false;
1866     unsigned Value = CE->getValue();
1867     return ARM_AM::isNEONi32splat(Value);
1868   }
1869 
1870   bool isNEONi32splatNot() const {
1871     if (!isImm())
1872       return false;
1873     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1874     // Must be a constant.
1875     if (!CE) return false;
1876     unsigned Value = CE->getValue();
1877     return ARM_AM::isNEONi32splat(~Value);
1878   }
1879 
1880   static bool isValidNEONi32vmovImm(int64_t Value) {
1881     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1882     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1883     return ((Value & 0xffffffffffffff00) == 0) ||
1884            ((Value & 0xffffffffffff00ff) == 0) ||
1885            ((Value & 0xffffffffff00ffff) == 0) ||
1886            ((Value & 0xffffffff00ffffff) == 0) ||
1887            ((Value & 0xffffffffffff00ff) == 0xff) ||
1888            ((Value & 0xffffffffff00ffff) == 0xffff);
1889   }
1890 
1891   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
1892     assert((Width == 8 || Width == 16 || Width == 32) &&
1893            "Invalid element width");
1894     assert(NumElems * Width <= 64 && "Invalid result width");
1895 
1896     if (!isImm())
1897       return false;
1898     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1899     // Must be a constant.
1900     if (!CE)
1901       return false;
1902     int64_t Value = CE->getValue();
1903     if (!Value)
1904       return false; // Don't bother with zero.
1905     if (Inv)
1906       Value = ~Value;
1907 
1908     uint64_t Mask = (1ull << Width) - 1;
1909     uint64_t Elem = Value & Mask;
1910     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
1911       return false;
1912     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
1913       return false;
1914 
1915     for (unsigned i = 1; i < NumElems; ++i) {
1916       Value >>= Width;
1917       if ((Value & Mask) != Elem)
1918         return false;
1919     }
1920     return true;
1921   }
1922 
1923   bool isNEONByteReplicate(unsigned NumBytes) const {
1924     return isNEONReplicate(8, NumBytes, false);
1925   }
1926 
1927   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
1928     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
1929            "Invalid source width");
1930     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
1931            "Invalid destination width");
1932     assert(FromW < ToW && "ToW is not less than FromW");
1933   }
1934 
1935   template<unsigned FromW, unsigned ToW>
1936   bool isNEONmovReplicate() const {
1937     checkNeonReplicateArgs(FromW, ToW);
1938     if (ToW == 64 && isNEONi64splat())
1939       return false;
1940     return isNEONReplicate(FromW, ToW / FromW, false);
1941   }
1942 
1943   template<unsigned FromW, unsigned ToW>
1944   bool isNEONinvReplicate() const {
1945     checkNeonReplicateArgs(FromW, ToW);
1946     return isNEONReplicate(FromW, ToW / FromW, true);
1947   }
1948 
1949   bool isNEONi32vmov() const {
1950     if (isNEONByteReplicate(4))
1951       return false; // Let it to be classified as byte-replicate case.
1952     if (!isImm())
1953       return false;
1954     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1955     // Must be a constant.
1956     if (!CE)
1957       return false;
1958     return isValidNEONi32vmovImm(CE->getValue());
1959   }
1960 
1961   bool isNEONi32vmovNeg() const {
1962     if (!isImm()) return false;
1963     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1964     // Must be a constant.
1965     if (!CE) return false;
1966     return isValidNEONi32vmovImm(~CE->getValue());
1967   }
1968 
1969   bool isNEONi64splat() 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     uint64_t Value = CE->getValue();
1975     // i64 value with each byte being either 0 or 0xff.
1976     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1977       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1978     return true;
1979   }
1980 
1981   template<int64_t Angle, int64_t Remainder>
1982   bool isComplexRotation() const {
1983     if (!isImm()) return false;
1984 
1985     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1986     if (!CE) return false;
1987     uint64_t Value = CE->getValue();
1988 
1989     return (Value % Angle == Remainder && Value <= 270);
1990   }
1991 
1992   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1993     // Add as immediates when possible.  Null MCExpr = 0.
1994     if (!Expr)
1995       Inst.addOperand(MCOperand::createImm(0));
1996     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1997       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1998     else
1999       Inst.addOperand(MCOperand::createExpr(Expr));
2000   }
2001 
2002   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2003     assert(N == 1 && "Invalid number of operands!");
2004     addExpr(Inst, getImm());
2005   }
2006 
2007   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2008     assert(N == 1 && "Invalid number of operands!");
2009     addExpr(Inst, getImm());
2010   }
2011 
2012   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2013     assert(N == 2 && "Invalid number of operands!");
2014     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2015     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2016     Inst.addOperand(MCOperand::createReg(RegNum));
2017   }
2018 
2019   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2020     assert(N == 1 && "Invalid number of operands!");
2021     Inst.addOperand(MCOperand::createImm(getCoproc()));
2022   }
2023 
2024   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2025     assert(N == 1 && "Invalid number of operands!");
2026     Inst.addOperand(MCOperand::createImm(getCoproc()));
2027   }
2028 
2029   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2030     assert(N == 1 && "Invalid number of operands!");
2031     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2032   }
2033 
2034   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2035     assert(N == 1 && "Invalid number of operands!");
2036     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2037   }
2038 
2039   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2040     assert(N == 1 && "Invalid number of operands!");
2041     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2042   }
2043 
2044   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2045     assert(N == 1 && "Invalid number of operands!");
2046     Inst.addOperand(MCOperand::createReg(getReg()));
2047   }
2048 
2049   void addRegOperands(MCInst &Inst, unsigned N) const {
2050     assert(N == 1 && "Invalid number of operands!");
2051     Inst.addOperand(MCOperand::createReg(getReg()));
2052   }
2053 
2054   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2055     assert(N == 3 && "Invalid number of operands!");
2056     assert(isRegShiftedReg() &&
2057            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2058     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2059     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2060     Inst.addOperand(MCOperand::createImm(
2061       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2062   }
2063 
2064   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2065     assert(N == 2 && "Invalid number of operands!");
2066     assert(isRegShiftedImm() &&
2067            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2068     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2069     // Shift of #32 is encoded as 0 where permitted
2070     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2071     Inst.addOperand(MCOperand::createImm(
2072       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2073   }
2074 
2075   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2076     assert(N == 1 && "Invalid number of operands!");
2077     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2078                                          ShifterImm.Imm));
2079   }
2080 
2081   void addRegListOperands(MCInst &Inst, unsigned N) const {
2082     assert(N == 1 && "Invalid number of operands!");
2083     const SmallVectorImpl<unsigned> &RegList = getRegList();
2084     for (SmallVectorImpl<unsigned>::const_iterator
2085            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2086       Inst.addOperand(MCOperand::createReg(*I));
2087   }
2088 
2089   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2090     addRegListOperands(Inst, N);
2091   }
2092 
2093   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2094     addRegListOperands(Inst, N);
2095   }
2096 
2097   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2098     assert(N == 1 && "Invalid number of operands!");
2099     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2100     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2101   }
2102 
2103   void addModImmOperands(MCInst &Inst, unsigned N) const {
2104     assert(N == 1 && "Invalid number of operands!");
2105 
2106     // Support for fixups (MCFixup)
2107     if (isImm())
2108       return addImmOperands(Inst, N);
2109 
2110     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2111   }
2112 
2113   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2114     assert(N == 1 && "Invalid number of operands!");
2115     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2116     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2117     Inst.addOperand(MCOperand::createImm(Enc));
2118   }
2119 
2120   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2121     assert(N == 1 && "Invalid number of operands!");
2122     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2123     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2124     Inst.addOperand(MCOperand::createImm(Enc));
2125   }
2126 
2127   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2128     assert(N == 1 && "Invalid number of operands!");
2129     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2130     uint32_t Val = -CE->getValue();
2131     Inst.addOperand(MCOperand::createImm(Val));
2132   }
2133 
2134   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2135     assert(N == 1 && "Invalid number of operands!");
2136     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2137     uint32_t Val = -CE->getValue();
2138     Inst.addOperand(MCOperand::createImm(Val));
2139   }
2140 
2141   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2142     assert(N == 1 && "Invalid number of operands!");
2143     // Munge the lsb/width into a bitfield mask.
2144     unsigned lsb = Bitfield.LSB;
2145     unsigned width = Bitfield.Width;
2146     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2147     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2148                       (32 - (lsb + width)));
2149     Inst.addOperand(MCOperand::createImm(Mask));
2150   }
2151 
2152   void addImmOperands(MCInst &Inst, unsigned N) const {
2153     assert(N == 1 && "Invalid number of operands!");
2154     addExpr(Inst, getImm());
2155   }
2156 
2157   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2158     assert(N == 1 && "Invalid number of operands!");
2159     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2160     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2161   }
2162 
2163   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2164     assert(N == 1 && "Invalid number of operands!");
2165     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2166     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2167   }
2168 
2169   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2170     assert(N == 1 && "Invalid number of operands!");
2171     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2172     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2173     Inst.addOperand(MCOperand::createImm(Val));
2174   }
2175 
2176   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2177     assert(N == 1 && "Invalid number of operands!");
2178     // FIXME: We really want to scale the value here, but the LDRD/STRD
2179     // instruction don't encode operands that way yet.
2180     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2181     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2182   }
2183 
2184   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2185     assert(N == 1 && "Invalid number of operands!");
2186     // The immediate is scaled by four in the encoding and is stored
2187     // in the MCInst as such. Lop off the low two bits here.
2188     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2189     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2190   }
2191 
2192   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2193     assert(N == 1 && "Invalid number of operands!");
2194     // The immediate is scaled by four in the encoding and is stored
2195     // in the MCInst as such. Lop off the low two bits here.
2196     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2197     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2198   }
2199 
2200   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2201     assert(N == 1 && "Invalid number of operands!");
2202     // The immediate is scaled by four in the encoding and is stored
2203     // in the MCInst as such. Lop off the low two bits here.
2204     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2205     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2206   }
2207 
2208   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2209     assert(N == 1 && "Invalid number of operands!");
2210     // The constant encodes as the immediate-1, and we store in the instruction
2211     // the bits as encoded, so subtract off one here.
2212     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2213     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2214   }
2215 
2216   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2217     assert(N == 1 && "Invalid number of operands!");
2218     // The constant encodes as the immediate-1, and we store in the instruction
2219     // the bits as encoded, so subtract off one here.
2220     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2221     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2222   }
2223 
2224   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2225     assert(N == 1 && "Invalid number of operands!");
2226     // The constant encodes as the immediate, except for 32, which encodes as
2227     // zero.
2228     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2229     unsigned Imm = CE->getValue();
2230     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2231   }
2232 
2233   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2234     assert(N == 1 && "Invalid number of operands!");
2235     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2236     // the instruction as well.
2237     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2238     int Val = CE->getValue();
2239     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2240   }
2241 
2242   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2243     assert(N == 1 && "Invalid number of operands!");
2244     // The operand is actually a t2_so_imm, but we have its bitwise
2245     // negation in the assembly source, so twiddle it here.
2246     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2247     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2248   }
2249 
2250   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2251     assert(N == 1 && "Invalid number of operands!");
2252     // The operand is actually a t2_so_imm, but we have its
2253     // negation in the assembly source, so twiddle it here.
2254     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2255     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2256   }
2257 
2258   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2259     assert(N == 1 && "Invalid number of operands!");
2260     // The operand is actually an imm0_4095, but we have its
2261     // negation in the assembly source, so twiddle it here.
2262     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2263     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2264   }
2265 
2266   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2267     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2268       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2269       return;
2270     }
2271 
2272     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2273     assert(SR && "Unknown value type!");
2274     Inst.addOperand(MCOperand::createExpr(SR));
2275   }
2276 
2277   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2278     assert(N == 1 && "Invalid number of operands!");
2279     if (isImm()) {
2280       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2281       if (CE) {
2282         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2283         return;
2284       }
2285 
2286       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2287 
2288       assert(SR && "Unknown value type!");
2289       Inst.addOperand(MCOperand::createExpr(SR));
2290       return;
2291     }
2292 
2293     assert(isMem()  && "Unknown value type!");
2294     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2295     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2296   }
2297 
2298   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2299     assert(N == 1 && "Invalid number of operands!");
2300     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2301   }
2302 
2303   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2304     assert(N == 1 && "Invalid number of operands!");
2305     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2306   }
2307 
2308   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2309     assert(N == 1 && "Invalid number of operands!");
2310     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2311   }
2312 
2313   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2314     assert(N == 1 && "Invalid number of operands!");
2315     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2316   }
2317 
2318   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2319     assert(N == 1 && "Invalid number of operands!");
2320     int32_t Imm = Memory.OffsetImm->getValue();
2321     Inst.addOperand(MCOperand::createImm(Imm));
2322   }
2323 
2324   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2325     assert(N == 1 && "Invalid number of operands!");
2326     assert(isImm() && "Not an immediate!");
2327 
2328     // If we have an immediate that's not a constant, treat it as a label
2329     // reference needing a fixup.
2330     if (!isa<MCConstantExpr>(getImm())) {
2331       Inst.addOperand(MCOperand::createExpr(getImm()));
2332       return;
2333     }
2334 
2335     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2336     int Val = CE->getValue();
2337     Inst.addOperand(MCOperand::createImm(Val));
2338   }
2339 
2340   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2341     assert(N == 2 && "Invalid number of operands!");
2342     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2343     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2344   }
2345 
2346   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2347     addAlignedMemoryOperands(Inst, N);
2348   }
2349 
2350   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2351     addAlignedMemoryOperands(Inst, N);
2352   }
2353 
2354   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2355     addAlignedMemoryOperands(Inst, N);
2356   }
2357 
2358   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2359     addAlignedMemoryOperands(Inst, N);
2360   }
2361 
2362   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2363     addAlignedMemoryOperands(Inst, N);
2364   }
2365 
2366   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2367     addAlignedMemoryOperands(Inst, N);
2368   }
2369 
2370   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2371     addAlignedMemoryOperands(Inst, N);
2372   }
2373 
2374   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2375     addAlignedMemoryOperands(Inst, N);
2376   }
2377 
2378   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2379     addAlignedMemoryOperands(Inst, N);
2380   }
2381 
2382   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2383     addAlignedMemoryOperands(Inst, N);
2384   }
2385 
2386   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2387     addAlignedMemoryOperands(Inst, N);
2388   }
2389 
2390   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2391     assert(N == 3 && "Invalid number of operands!");
2392     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2393     if (!Memory.OffsetRegNum) {
2394       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2395       // Special case for #-0
2396       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2397       if (Val < 0) Val = -Val;
2398       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2399     } else {
2400       // For register offset, we encode the shift type and negation flag
2401       // here.
2402       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2403                               Memory.ShiftImm, Memory.ShiftType);
2404     }
2405     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2406     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2407     Inst.addOperand(MCOperand::createImm(Val));
2408   }
2409 
2410   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2411     assert(N == 2 && "Invalid number of operands!");
2412     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2413     assert(CE && "non-constant AM2OffsetImm operand!");
2414     int32_t Val = CE->getValue();
2415     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2416     // Special case for #-0
2417     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2418     if (Val < 0) Val = -Val;
2419     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2420     Inst.addOperand(MCOperand::createReg(0));
2421     Inst.addOperand(MCOperand::createImm(Val));
2422   }
2423 
2424   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2425     assert(N == 3 && "Invalid number of operands!");
2426     // If we have an immediate that's not a constant, treat it as a label
2427     // reference needing a fixup. If it is a constant, it's something else
2428     // and we reject it.
2429     if (isImm()) {
2430       Inst.addOperand(MCOperand::createExpr(getImm()));
2431       Inst.addOperand(MCOperand::createReg(0));
2432       Inst.addOperand(MCOperand::createImm(0));
2433       return;
2434     }
2435 
2436     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2437     if (!Memory.OffsetRegNum) {
2438       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2439       // Special case for #-0
2440       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2441       if (Val < 0) Val = -Val;
2442       Val = ARM_AM::getAM3Opc(AddSub, Val);
2443     } else {
2444       // For register offset, we encode the shift type and negation flag
2445       // here.
2446       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2447     }
2448     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2449     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2450     Inst.addOperand(MCOperand::createImm(Val));
2451   }
2452 
2453   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2454     assert(N == 2 && "Invalid number of operands!");
2455     if (Kind == k_PostIndexRegister) {
2456       int32_t Val =
2457         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2458       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2459       Inst.addOperand(MCOperand::createImm(Val));
2460       return;
2461     }
2462 
2463     // Constant offset.
2464     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2465     int32_t Val = CE->getValue();
2466     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2467     // Special case for #-0
2468     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2469     if (Val < 0) Val = -Val;
2470     Val = ARM_AM::getAM3Opc(AddSub, Val);
2471     Inst.addOperand(MCOperand::createReg(0));
2472     Inst.addOperand(MCOperand::createImm(Val));
2473   }
2474 
2475   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2476     assert(N == 2 && "Invalid number of operands!");
2477     // If we have an immediate that's not a constant, treat it as a label
2478     // reference needing a fixup. If it is a constant, it's something else
2479     // and we reject it.
2480     if (isImm()) {
2481       Inst.addOperand(MCOperand::createExpr(getImm()));
2482       Inst.addOperand(MCOperand::createImm(0));
2483       return;
2484     }
2485 
2486     // The lower two bits are always zero and as such are not encoded.
2487     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2488     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2489     // Special case for #-0
2490     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2491     if (Val < 0) Val = -Val;
2492     Val = ARM_AM::getAM5Opc(AddSub, Val);
2493     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2494     Inst.addOperand(MCOperand::createImm(Val));
2495   }
2496 
2497   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2498     assert(N == 2 && "Invalid number of operands!");
2499     // If we have an immediate that's not a constant, treat it as a label
2500     // reference needing a fixup. If it is a constant, it's something else
2501     // and we reject it.
2502     if (isImm()) {
2503       Inst.addOperand(MCOperand::createExpr(getImm()));
2504       Inst.addOperand(MCOperand::createImm(0));
2505       return;
2506     }
2507 
2508     // The lower bit is always zero and as such is not encoded.
2509     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2510     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2511     // Special case for #-0
2512     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2513     if (Val < 0) Val = -Val;
2514     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2515     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2516     Inst.addOperand(MCOperand::createImm(Val));
2517   }
2518 
2519   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2520     assert(N == 2 && "Invalid number of operands!");
2521     // If we have an immediate that's not a constant, treat it as a label
2522     // reference needing a fixup. If it is a constant, it's something else
2523     // and we reject it.
2524     if (isImm()) {
2525       Inst.addOperand(MCOperand::createExpr(getImm()));
2526       Inst.addOperand(MCOperand::createImm(0));
2527       return;
2528     }
2529 
2530     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2531     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2532     Inst.addOperand(MCOperand::createImm(Val));
2533   }
2534 
2535   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2536     assert(N == 2 && "Invalid number of operands!");
2537     // The lower two bits are always zero and as such are not encoded.
2538     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2539     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2540     Inst.addOperand(MCOperand::createImm(Val));
2541   }
2542 
2543   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2544     assert(N == 2 && "Invalid number of operands!");
2545     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2546     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2547     Inst.addOperand(MCOperand::createImm(Val));
2548   }
2549 
2550   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2551     addMemImm8OffsetOperands(Inst, N);
2552   }
2553 
2554   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2555     addMemImm8OffsetOperands(Inst, N);
2556   }
2557 
2558   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2559     assert(N == 2 && "Invalid number of operands!");
2560     // If this is an immediate, it's a label reference.
2561     if (isImm()) {
2562       addExpr(Inst, getImm());
2563       Inst.addOperand(MCOperand::createImm(0));
2564       return;
2565     }
2566 
2567     // Otherwise, it's a normal memory reg+offset.
2568     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2569     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2570     Inst.addOperand(MCOperand::createImm(Val));
2571   }
2572 
2573   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2574     assert(N == 2 && "Invalid number of operands!");
2575     // If this is an immediate, it's a label reference.
2576     if (isImm()) {
2577       addExpr(Inst, getImm());
2578       Inst.addOperand(MCOperand::createImm(0));
2579       return;
2580     }
2581 
2582     // Otherwise, it's a normal memory reg+offset.
2583     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2584     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2585     Inst.addOperand(MCOperand::createImm(Val));
2586   }
2587 
2588   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2589     assert(N == 1 && "Invalid number of operands!");
2590     // This is container for the immediate that we will create the constant
2591     // pool from
2592     addExpr(Inst, getConstantPoolImm());
2593     return;
2594   }
2595 
2596   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2597     assert(N == 2 && "Invalid number of operands!");
2598     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2599     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2600   }
2601 
2602   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2603     assert(N == 2 && "Invalid number of operands!");
2604     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2605     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2606   }
2607 
2608   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2609     assert(N == 3 && "Invalid number of operands!");
2610     unsigned Val =
2611       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2612                         Memory.ShiftImm, Memory.ShiftType);
2613     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2614     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2615     Inst.addOperand(MCOperand::createImm(Val));
2616   }
2617 
2618   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2619     assert(N == 3 && "Invalid number of operands!");
2620     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2621     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2622     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2623   }
2624 
2625   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2626     assert(N == 2 && "Invalid number of operands!");
2627     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2628     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2629   }
2630 
2631   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2632     assert(N == 2 && "Invalid number of operands!");
2633     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2634     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2635     Inst.addOperand(MCOperand::createImm(Val));
2636   }
2637 
2638   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2639     assert(N == 2 && "Invalid number of operands!");
2640     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2641     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2642     Inst.addOperand(MCOperand::createImm(Val));
2643   }
2644 
2645   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2646     assert(N == 2 && "Invalid number of operands!");
2647     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2648     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2649     Inst.addOperand(MCOperand::createImm(Val));
2650   }
2651 
2652   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2653     assert(N == 2 && "Invalid number of operands!");
2654     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2655     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2656     Inst.addOperand(MCOperand::createImm(Val));
2657   }
2658 
2659   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2660     assert(N == 1 && "Invalid number of operands!");
2661     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2662     assert(CE && "non-constant post-idx-imm8 operand!");
2663     int Imm = CE->getValue();
2664     bool isAdd = Imm >= 0;
2665     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2666     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2667     Inst.addOperand(MCOperand::createImm(Imm));
2668   }
2669 
2670   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2671     assert(N == 1 && "Invalid number of operands!");
2672     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2673     assert(CE && "non-constant post-idx-imm8s4 operand!");
2674     int Imm = CE->getValue();
2675     bool isAdd = Imm >= 0;
2676     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2677     // Immediate is scaled by 4.
2678     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2679     Inst.addOperand(MCOperand::createImm(Imm));
2680   }
2681 
2682   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2683     assert(N == 2 && "Invalid number of operands!");
2684     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2685     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2686   }
2687 
2688   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2689     assert(N == 2 && "Invalid number of operands!");
2690     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2691     // The sign, shift type, and shift amount are encoded in a single operand
2692     // using the AM2 encoding helpers.
2693     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2694     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2695                                      PostIdxReg.ShiftTy);
2696     Inst.addOperand(MCOperand::createImm(Imm));
2697   }
2698 
2699   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2700     assert(N == 1 && "Invalid number of operands!");
2701     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2702   }
2703 
2704   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2705     assert(N == 1 && "Invalid number of operands!");
2706     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2707   }
2708 
2709   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2710     assert(N == 1 && "Invalid number of operands!");
2711     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2712   }
2713 
2714   void addVecListOperands(MCInst &Inst, unsigned N) const {
2715     assert(N == 1 && "Invalid number of operands!");
2716     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2717   }
2718 
2719   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2720     assert(N == 2 && "Invalid number of operands!");
2721     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2722     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2723   }
2724 
2725   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2726     assert(N == 1 && "Invalid number of operands!");
2727     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2728   }
2729 
2730   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2731     assert(N == 1 && "Invalid number of operands!");
2732     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2733   }
2734 
2735   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2736     assert(N == 1 && "Invalid number of operands!");
2737     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2738   }
2739 
2740   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
2741     assert(N == 1 && "Invalid number of operands!");
2742     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2743   }
2744 
2745   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2746     assert(N == 1 && "Invalid number of operands!");
2747     // The immediate encodes the type of constant as well as the value.
2748     // Mask in that this is an i8 splat.
2749     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2750     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2751   }
2752 
2753   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2754     assert(N == 1 && "Invalid number of operands!");
2755     // The immediate encodes the type of constant as well as the value.
2756     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2757     unsigned Value = CE->getValue();
2758     Value = ARM_AM::encodeNEONi16splat(Value);
2759     Inst.addOperand(MCOperand::createImm(Value));
2760   }
2761 
2762   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2763     assert(N == 1 && "Invalid number of operands!");
2764     // The immediate encodes the type of constant as well as the value.
2765     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2766     unsigned Value = CE->getValue();
2767     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2768     Inst.addOperand(MCOperand::createImm(Value));
2769   }
2770 
2771   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2772     assert(N == 1 && "Invalid number of operands!");
2773     // The immediate encodes the type of constant as well as the value.
2774     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2775     unsigned Value = CE->getValue();
2776     Value = ARM_AM::encodeNEONi32splat(Value);
2777     Inst.addOperand(MCOperand::createImm(Value));
2778   }
2779 
2780   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2781     assert(N == 1 && "Invalid number of operands!");
2782     // The immediate encodes the type of constant as well as the value.
2783     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2784     unsigned Value = CE->getValue();
2785     Value = ARM_AM::encodeNEONi32splat(~Value);
2786     Inst.addOperand(MCOperand::createImm(Value));
2787   }
2788 
2789   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
2790     // The immediate encodes the type of constant as well as the value.
2791     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2792     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2793             Inst.getOpcode() == ARM::VMOVv16i8) &&
2794           "All instructions that wants to replicate non-zero byte "
2795           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2796     unsigned Value = CE->getValue();
2797     if (Inv)
2798       Value = ~Value;
2799     unsigned B = Value & 0xff;
2800     B |= 0xe00; // cmode = 0b1110
2801     Inst.addOperand(MCOperand::createImm(B));
2802   }
2803 
2804   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
2805     assert(N == 1 && "Invalid number of operands!");
2806     addNEONi8ReplicateOperands(Inst, true);
2807   }
2808 
2809   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
2810     if (Value >= 256 && Value <= 0xffff)
2811       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2812     else if (Value > 0xffff && Value <= 0xffffff)
2813       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2814     else if (Value > 0xffffff)
2815       Value = (Value >> 24) | 0x600;
2816     return Value;
2817   }
2818 
2819   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2820     assert(N == 1 && "Invalid number of operands!");
2821     // The immediate encodes the type of constant as well as the value.
2822     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2823     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
2824     Inst.addOperand(MCOperand::createImm(Value));
2825   }
2826 
2827   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
2828     assert(N == 1 && "Invalid number of operands!");
2829     addNEONi8ReplicateOperands(Inst, false);
2830   }
2831 
2832   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
2833     assert(N == 1 && "Invalid number of operands!");
2834     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2835     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
2836             Inst.getOpcode() == ARM::VMOVv8i16 ||
2837             Inst.getOpcode() == ARM::VMVNv4i16 ||
2838             Inst.getOpcode() == ARM::VMVNv8i16) &&
2839           "All instructions that want to replicate non-zero half-word "
2840           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
2841     uint64_t Value = CE->getValue();
2842     unsigned Elem = Value & 0xffff;
2843     if (Elem >= 256)
2844       Elem = (Elem >> 8) | 0x200;
2845     Inst.addOperand(MCOperand::createImm(Elem));
2846   }
2847 
2848   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2849     assert(N == 1 && "Invalid number of operands!");
2850     // The immediate encodes the type of constant as well as the value.
2851     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2852     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
2853     Inst.addOperand(MCOperand::createImm(Value));
2854   }
2855 
2856   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
2857     assert(N == 1 && "Invalid number of operands!");
2858     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2859     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
2860             Inst.getOpcode() == ARM::VMOVv4i32 ||
2861             Inst.getOpcode() == ARM::VMVNv2i32 ||
2862             Inst.getOpcode() == ARM::VMVNv4i32) &&
2863           "All instructions that want to replicate non-zero word "
2864           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
2865     uint64_t Value = CE->getValue();
2866     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
2867     Inst.addOperand(MCOperand::createImm(Elem));
2868   }
2869 
2870   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2871     assert(N == 1 && "Invalid number of operands!");
2872     // The immediate encodes the type of constant as well as the value.
2873     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2874     uint64_t Value = CE->getValue();
2875     unsigned Imm = 0;
2876     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2877       Imm |= (Value & 1) << i;
2878     }
2879     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2880   }
2881 
2882   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
2883     assert(N == 1 && "Invalid number of operands!");
2884     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2885     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
2886   }
2887 
2888   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
2889     assert(N == 1 && "Invalid number of operands!");
2890     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2891     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
2892   }
2893 
2894   void print(raw_ostream &OS) const override;
2895 
2896   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2897     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2898     Op->ITMask.Mask = Mask;
2899     Op->StartLoc = S;
2900     Op->EndLoc = S;
2901     return Op;
2902   }
2903 
2904   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2905                                                     SMLoc S) {
2906     auto Op = make_unique<ARMOperand>(k_CondCode);
2907     Op->CC.Val = CC;
2908     Op->StartLoc = S;
2909     Op->EndLoc = S;
2910     return Op;
2911   }
2912 
2913   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2914     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2915     Op->Cop.Val = CopVal;
2916     Op->StartLoc = S;
2917     Op->EndLoc = S;
2918     return Op;
2919   }
2920 
2921   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2922     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2923     Op->Cop.Val = CopVal;
2924     Op->StartLoc = S;
2925     Op->EndLoc = S;
2926     return Op;
2927   }
2928 
2929   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2930                                                         SMLoc E) {
2931     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2932     Op->Cop.Val = Val;
2933     Op->StartLoc = S;
2934     Op->EndLoc = E;
2935     return Op;
2936   }
2937 
2938   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2939     auto Op = make_unique<ARMOperand>(k_CCOut);
2940     Op->Reg.RegNum = RegNum;
2941     Op->StartLoc = S;
2942     Op->EndLoc = S;
2943     return Op;
2944   }
2945 
2946   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2947     auto Op = make_unique<ARMOperand>(k_Token);
2948     Op->Tok.Data = Str.data();
2949     Op->Tok.Length = Str.size();
2950     Op->StartLoc = S;
2951     Op->EndLoc = S;
2952     return Op;
2953   }
2954 
2955   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2956                                                SMLoc E) {
2957     auto Op = make_unique<ARMOperand>(k_Register);
2958     Op->Reg.RegNum = RegNum;
2959     Op->StartLoc = S;
2960     Op->EndLoc = E;
2961     return Op;
2962   }
2963 
2964   static std::unique_ptr<ARMOperand>
2965   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2966                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2967                         SMLoc E) {
2968     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2969     Op->RegShiftedReg.ShiftTy = ShTy;
2970     Op->RegShiftedReg.SrcReg = SrcReg;
2971     Op->RegShiftedReg.ShiftReg = ShiftReg;
2972     Op->RegShiftedReg.ShiftImm = ShiftImm;
2973     Op->StartLoc = S;
2974     Op->EndLoc = E;
2975     return Op;
2976   }
2977 
2978   static std::unique_ptr<ARMOperand>
2979   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2980                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2981     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2982     Op->RegShiftedImm.ShiftTy = ShTy;
2983     Op->RegShiftedImm.SrcReg = SrcReg;
2984     Op->RegShiftedImm.ShiftImm = ShiftImm;
2985     Op->StartLoc = S;
2986     Op->EndLoc = E;
2987     return Op;
2988   }
2989 
2990   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2991                                                       SMLoc S, SMLoc E) {
2992     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2993     Op->ShifterImm.isASR = isASR;
2994     Op->ShifterImm.Imm = Imm;
2995     Op->StartLoc = S;
2996     Op->EndLoc = E;
2997     return Op;
2998   }
2999 
3000   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3001                                                   SMLoc E) {
3002     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
3003     Op->RotImm.Imm = Imm;
3004     Op->StartLoc = S;
3005     Op->EndLoc = E;
3006     return Op;
3007   }
3008 
3009   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3010                                                   SMLoc S, SMLoc E) {
3011     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
3012     Op->ModImm.Bits = Bits;
3013     Op->ModImm.Rot = Rot;
3014     Op->StartLoc = S;
3015     Op->EndLoc = E;
3016     return Op;
3017   }
3018 
3019   static std::unique_ptr<ARMOperand>
3020   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3021     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
3022     Op->Imm.Val = Val;
3023     Op->StartLoc = S;
3024     Op->EndLoc = E;
3025     return Op;
3026   }
3027 
3028   static std::unique_ptr<ARMOperand>
3029   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3030     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
3031     Op->Bitfield.LSB = LSB;
3032     Op->Bitfield.Width = Width;
3033     Op->StartLoc = S;
3034     Op->EndLoc = E;
3035     return Op;
3036   }
3037 
3038   static std::unique_ptr<ARMOperand>
3039   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3040                 SMLoc StartLoc, SMLoc EndLoc) {
3041     assert(Regs.size() > 0 && "RegList contains no registers?");
3042     KindTy Kind = k_RegisterList;
3043 
3044     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
3045       Kind = k_DPRRegisterList;
3046     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
3047              contains(Regs.front().second))
3048       Kind = k_SPRRegisterList;
3049 
3050     // Sort based on the register encoding values.
3051     array_pod_sort(Regs.begin(), Regs.end());
3052 
3053     auto Op = make_unique<ARMOperand>(Kind);
3054     for (SmallVectorImpl<std::pair<unsigned, unsigned>>::const_iterator
3055            I = Regs.begin(), E = Regs.end(); I != E; ++I)
3056       Op->Registers.push_back(I->second);
3057     Op->StartLoc = StartLoc;
3058     Op->EndLoc = EndLoc;
3059     return Op;
3060   }
3061 
3062   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3063                                                       unsigned Count,
3064                                                       bool isDoubleSpaced,
3065                                                       SMLoc S, SMLoc E) {
3066     auto Op = make_unique<ARMOperand>(k_VectorList);
3067     Op->VectorList.RegNum = RegNum;
3068     Op->VectorList.Count = Count;
3069     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3070     Op->StartLoc = S;
3071     Op->EndLoc = E;
3072     return Op;
3073   }
3074 
3075   static std::unique_ptr<ARMOperand>
3076   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3077                            SMLoc S, SMLoc E) {
3078     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
3079     Op->VectorList.RegNum = RegNum;
3080     Op->VectorList.Count = Count;
3081     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3082     Op->StartLoc = S;
3083     Op->EndLoc = E;
3084     return Op;
3085   }
3086 
3087   static std::unique_ptr<ARMOperand>
3088   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3089                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3090     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
3091     Op->VectorList.RegNum = RegNum;
3092     Op->VectorList.Count = Count;
3093     Op->VectorList.LaneIndex = Index;
3094     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3095     Op->StartLoc = S;
3096     Op->EndLoc = E;
3097     return Op;
3098   }
3099 
3100   static std::unique_ptr<ARMOperand>
3101   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3102     auto Op = make_unique<ARMOperand>(k_VectorIndex);
3103     Op->VectorIndex.Val = Idx;
3104     Op->StartLoc = S;
3105     Op->EndLoc = E;
3106     return Op;
3107   }
3108 
3109   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3110                                                SMLoc E) {
3111     auto Op = make_unique<ARMOperand>(k_Immediate);
3112     Op->Imm.Val = Val;
3113     Op->StartLoc = S;
3114     Op->EndLoc = E;
3115     return Op;
3116   }
3117 
3118   static std::unique_ptr<ARMOperand>
3119   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3120             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3121             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3122             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3123     auto Op = make_unique<ARMOperand>(k_Memory);
3124     Op->Memory.BaseRegNum = BaseRegNum;
3125     Op->Memory.OffsetImm = OffsetImm;
3126     Op->Memory.OffsetRegNum = OffsetRegNum;
3127     Op->Memory.ShiftType = ShiftType;
3128     Op->Memory.ShiftImm = ShiftImm;
3129     Op->Memory.Alignment = Alignment;
3130     Op->Memory.isNegative = isNegative;
3131     Op->StartLoc = S;
3132     Op->EndLoc = E;
3133     Op->AlignmentLoc = AlignmentLoc;
3134     return Op;
3135   }
3136 
3137   static std::unique_ptr<ARMOperand>
3138   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3139                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3140     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
3141     Op->PostIdxReg.RegNum = RegNum;
3142     Op->PostIdxReg.isAdd = isAdd;
3143     Op->PostIdxReg.ShiftTy = ShiftTy;
3144     Op->PostIdxReg.ShiftImm = ShiftImm;
3145     Op->StartLoc = S;
3146     Op->EndLoc = E;
3147     return Op;
3148   }
3149 
3150   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3151                                                          SMLoc S) {
3152     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3153     Op->MBOpt.Val = Opt;
3154     Op->StartLoc = S;
3155     Op->EndLoc = S;
3156     return Op;
3157   }
3158 
3159   static std::unique_ptr<ARMOperand>
3160   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3161     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3162     Op->ISBOpt.Val = Opt;
3163     Op->StartLoc = S;
3164     Op->EndLoc = S;
3165     return Op;
3166   }
3167 
3168   static std::unique_ptr<ARMOperand>
3169   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3170     auto Op = make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3171     Op->TSBOpt.Val = Opt;
3172     Op->StartLoc = S;
3173     Op->EndLoc = S;
3174     return Op;
3175   }
3176 
3177   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3178                                                       SMLoc S) {
3179     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3180     Op->IFlags.Val = IFlags;
3181     Op->StartLoc = S;
3182     Op->EndLoc = S;
3183     return Op;
3184   }
3185 
3186   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3187     auto Op = make_unique<ARMOperand>(k_MSRMask);
3188     Op->MMask.Val = MMask;
3189     Op->StartLoc = S;
3190     Op->EndLoc = S;
3191     return Op;
3192   }
3193 
3194   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3195     auto Op = make_unique<ARMOperand>(k_BankedReg);
3196     Op->BankedReg.Val = Reg;
3197     Op->StartLoc = S;
3198     Op->EndLoc = S;
3199     return Op;
3200   }
3201 };
3202 
3203 } // end anonymous namespace.
3204 
3205 void ARMOperand::print(raw_ostream &OS) const {
3206   switch (Kind) {
3207   case k_CondCode:
3208     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3209     break;
3210   case k_CCOut:
3211     OS << "<ccout " << getReg() << ">";
3212     break;
3213   case k_ITCondMask: {
3214     static const char *const MaskStr[] = {
3215       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
3216       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
3217     };
3218     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3219     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3220     break;
3221   }
3222   case k_CoprocNum:
3223     OS << "<coprocessor number: " << getCoproc() << ">";
3224     break;
3225   case k_CoprocReg:
3226     OS << "<coprocessor register: " << getCoproc() << ">";
3227     break;
3228   case k_CoprocOption:
3229     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3230     break;
3231   case k_MSRMask:
3232     OS << "<mask: " << getMSRMask() << ">";
3233     break;
3234   case k_BankedReg:
3235     OS << "<banked reg: " << getBankedReg() << ">";
3236     break;
3237   case k_Immediate:
3238     OS << *getImm();
3239     break;
3240   case k_MemBarrierOpt:
3241     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3242     break;
3243   case k_InstSyncBarrierOpt:
3244     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3245     break;
3246   case k_TraceSyncBarrierOpt:
3247     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3248     break;
3249   case k_Memory:
3250     OS << "<memory "
3251        << " base:" << Memory.BaseRegNum;
3252     OS << ">";
3253     break;
3254   case k_PostIndexRegister:
3255     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3256        << PostIdxReg.RegNum;
3257     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3258       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3259          << PostIdxReg.ShiftImm;
3260     OS << ">";
3261     break;
3262   case k_ProcIFlags: {
3263     OS << "<ARM_PROC::";
3264     unsigned IFlags = getProcIFlags();
3265     for (int i=2; i >= 0; --i)
3266       if (IFlags & (1 << i))
3267         OS << ARM_PROC::IFlagsToString(1 << i);
3268     OS << ">";
3269     break;
3270   }
3271   case k_Register:
3272     OS << "<register " << getReg() << ">";
3273     break;
3274   case k_ShifterImmediate:
3275     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3276        << " #" << ShifterImm.Imm << ">";
3277     break;
3278   case k_ShiftedRegister:
3279     OS << "<so_reg_reg "
3280        << RegShiftedReg.SrcReg << " "
3281        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
3282        << " " << RegShiftedReg.ShiftReg << ">";
3283     break;
3284   case k_ShiftedImmediate:
3285     OS << "<so_reg_imm "
3286        << RegShiftedImm.SrcReg << " "
3287        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
3288        << " #" << RegShiftedImm.ShiftImm << ">";
3289     break;
3290   case k_RotateImmediate:
3291     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3292     break;
3293   case k_ModifiedImmediate:
3294     OS << "<mod_imm #" << ModImm.Bits << ", #"
3295        <<  ModImm.Rot << ")>";
3296     break;
3297   case k_ConstantPoolImmediate:
3298     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3299     break;
3300   case k_BitfieldDescriptor:
3301     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3302        << ", width: " << Bitfield.Width << ">";
3303     break;
3304   case k_RegisterList:
3305   case k_DPRRegisterList:
3306   case k_SPRRegisterList: {
3307     OS << "<register_list ";
3308 
3309     const SmallVectorImpl<unsigned> &RegList = getRegList();
3310     for (SmallVectorImpl<unsigned>::const_iterator
3311            I = RegList.begin(), E = RegList.end(); I != E; ) {
3312       OS << *I;
3313       if (++I < E) OS << ", ";
3314     }
3315 
3316     OS << ">";
3317     break;
3318   }
3319   case k_VectorList:
3320     OS << "<vector_list " << VectorList.Count << " * "
3321        << VectorList.RegNum << ">";
3322     break;
3323   case k_VectorListAllLanes:
3324     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3325        << VectorList.RegNum << ">";
3326     break;
3327   case k_VectorListIndexed:
3328     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3329        << VectorList.Count << " * " << VectorList.RegNum << ">";
3330     break;
3331   case k_Token:
3332     OS << "'" << getToken() << "'";
3333     break;
3334   case k_VectorIndex:
3335     OS << "<vectorindex " << getVectorIndex() << ">";
3336     break;
3337   }
3338 }
3339 
3340 /// @name Auto-generated Match Functions
3341 /// {
3342 
3343 static unsigned MatchRegisterName(StringRef Name);
3344 
3345 /// }
3346 
3347 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3348                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3349   const AsmToken &Tok = getParser().getTok();
3350   StartLoc = Tok.getLoc();
3351   EndLoc = Tok.getEndLoc();
3352   RegNo = tryParseRegister();
3353 
3354   return (RegNo == (unsigned)-1);
3355 }
3356 
3357 /// Try to parse a register name.  The token must be an Identifier when called,
3358 /// and if it is a register name the token is eaten and the register number is
3359 /// returned.  Otherwise return -1.
3360 int ARMAsmParser::tryParseRegister() {
3361   MCAsmParser &Parser = getParser();
3362   const AsmToken &Tok = Parser.getTok();
3363   if (Tok.isNot(AsmToken::Identifier)) return -1;
3364 
3365   std::string lowerCase = Tok.getString().lower();
3366   unsigned RegNum = MatchRegisterName(lowerCase);
3367   if (!RegNum) {
3368     RegNum = StringSwitch<unsigned>(lowerCase)
3369       .Case("r13", ARM::SP)
3370       .Case("r14", ARM::LR)
3371       .Case("r15", ARM::PC)
3372       .Case("ip", ARM::R12)
3373       // Additional register name aliases for 'gas' compatibility.
3374       .Case("a1", ARM::R0)
3375       .Case("a2", ARM::R1)
3376       .Case("a3", ARM::R2)
3377       .Case("a4", ARM::R3)
3378       .Case("v1", ARM::R4)
3379       .Case("v2", ARM::R5)
3380       .Case("v3", ARM::R6)
3381       .Case("v4", ARM::R7)
3382       .Case("v5", ARM::R8)
3383       .Case("v6", ARM::R9)
3384       .Case("v7", ARM::R10)
3385       .Case("v8", ARM::R11)
3386       .Case("sb", ARM::R9)
3387       .Case("sl", ARM::R10)
3388       .Case("fp", ARM::R11)
3389       .Default(0);
3390   }
3391   if (!RegNum) {
3392     // Check for aliases registered via .req. Canonicalize to lower case.
3393     // That's more consistent since register names are case insensitive, and
3394     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3395     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3396     // If no match, return failure.
3397     if (Entry == RegisterReqs.end())
3398       return -1;
3399     Parser.Lex(); // Eat identifier token.
3400     return Entry->getValue();
3401   }
3402 
3403   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3404   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3405     return -1;
3406 
3407   Parser.Lex(); // Eat identifier token.
3408 
3409   return RegNum;
3410 }
3411 
3412 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3413 // If a recoverable error occurs, return 1. If an irrecoverable error
3414 // occurs, return -1. An irrecoverable error is one where tokens have been
3415 // consumed in the process of trying to parse the shifter (i.e., when it is
3416 // indeed a shifter operand, but malformed).
3417 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3418   MCAsmParser &Parser = getParser();
3419   SMLoc S = Parser.getTok().getLoc();
3420   const AsmToken &Tok = Parser.getTok();
3421   if (Tok.isNot(AsmToken::Identifier))
3422     return -1;
3423 
3424   std::string lowerCase = Tok.getString().lower();
3425   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3426       .Case("asl", ARM_AM::lsl)
3427       .Case("lsl", ARM_AM::lsl)
3428       .Case("lsr", ARM_AM::lsr)
3429       .Case("asr", ARM_AM::asr)
3430       .Case("ror", ARM_AM::ror)
3431       .Case("rrx", ARM_AM::rrx)
3432       .Default(ARM_AM::no_shift);
3433 
3434   if (ShiftTy == ARM_AM::no_shift)
3435     return 1;
3436 
3437   Parser.Lex(); // Eat the operator.
3438 
3439   // The source register for the shift has already been added to the
3440   // operand list, so we need to pop it off and combine it into the shifted
3441   // register operand instead.
3442   std::unique_ptr<ARMOperand> PrevOp(
3443       (ARMOperand *)Operands.pop_back_val().release());
3444   if (!PrevOp->isReg())
3445     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3446   int SrcReg = PrevOp->getReg();
3447 
3448   SMLoc EndLoc;
3449   int64_t Imm = 0;
3450   int ShiftReg = 0;
3451   if (ShiftTy == ARM_AM::rrx) {
3452     // RRX Doesn't have an explicit shift amount. The encoder expects
3453     // the shift register to be the same as the source register. Seems odd,
3454     // but OK.
3455     ShiftReg = SrcReg;
3456   } else {
3457     // Figure out if this is shifted by a constant or a register (for non-RRX).
3458     if (Parser.getTok().is(AsmToken::Hash) ||
3459         Parser.getTok().is(AsmToken::Dollar)) {
3460       Parser.Lex(); // Eat hash.
3461       SMLoc ImmLoc = Parser.getTok().getLoc();
3462       const MCExpr *ShiftExpr = nullptr;
3463       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3464         Error(ImmLoc, "invalid immediate shift value");
3465         return -1;
3466       }
3467       // The expression must be evaluatable as an immediate.
3468       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3469       if (!CE) {
3470         Error(ImmLoc, "invalid immediate shift value");
3471         return -1;
3472       }
3473       // Range check the immediate.
3474       // lsl, ror: 0 <= imm <= 31
3475       // lsr, asr: 0 <= imm <= 32
3476       Imm = CE->getValue();
3477       if (Imm < 0 ||
3478           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3479           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3480         Error(ImmLoc, "immediate shift value out of range");
3481         return -1;
3482       }
3483       // shift by zero is a nop. Always send it through as lsl.
3484       // ('as' compatibility)
3485       if (Imm == 0)
3486         ShiftTy = ARM_AM::lsl;
3487     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3488       SMLoc L = Parser.getTok().getLoc();
3489       EndLoc = Parser.getTok().getEndLoc();
3490       ShiftReg = tryParseRegister();
3491       if (ShiftReg == -1) {
3492         Error(L, "expected immediate or register in shift operand");
3493         return -1;
3494       }
3495     } else {
3496       Error(Parser.getTok().getLoc(),
3497             "expected immediate or register in shift operand");
3498       return -1;
3499     }
3500   }
3501 
3502   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3503     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3504                                                          ShiftReg, Imm,
3505                                                          S, EndLoc));
3506   else
3507     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3508                                                           S, EndLoc));
3509 
3510   return 0;
3511 }
3512 
3513 /// Try to parse a register name.  The token must be an Identifier when called.
3514 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3515 /// if there is a "writeback". 'true' if it's not a register.
3516 ///
3517 /// TODO this is likely to change to allow different register types and or to
3518 /// parse for a specific register type.
3519 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3520   MCAsmParser &Parser = getParser();
3521   SMLoc RegStartLoc = Parser.getTok().getLoc();
3522   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
3523   int RegNo = tryParseRegister();
3524   if (RegNo == -1)
3525     return true;
3526 
3527   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
3528 
3529   const AsmToken &ExclaimTok = Parser.getTok();
3530   if (ExclaimTok.is(AsmToken::Exclaim)) {
3531     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3532                                                ExclaimTok.getLoc()));
3533     Parser.Lex(); // Eat exclaim token
3534     return false;
3535   }
3536 
3537   // Also check for an index operand. This is only legal for vector registers,
3538   // but that'll get caught OK in operand matching, so we don't need to
3539   // explicitly filter everything else out here.
3540   if (Parser.getTok().is(AsmToken::LBrac)) {
3541     SMLoc SIdx = Parser.getTok().getLoc();
3542     Parser.Lex(); // Eat left bracket token.
3543 
3544     const MCExpr *ImmVal;
3545     if (getParser().parseExpression(ImmVal))
3546       return true;
3547     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3548     if (!MCE)
3549       return TokError("immediate value expected for vector index");
3550 
3551     if (Parser.getTok().isNot(AsmToken::RBrac))
3552       return Error(Parser.getTok().getLoc(), "']' expected");
3553 
3554     SMLoc E = Parser.getTok().getEndLoc();
3555     Parser.Lex(); // Eat right bracket token.
3556 
3557     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3558                                                      SIdx, E,
3559                                                      getContext()));
3560   }
3561 
3562   return false;
3563 }
3564 
3565 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3566 /// instruction with a symbolic operand name.
3567 /// We accept "crN" syntax for GAS compatibility.
3568 /// <operand-name> ::= <prefix><number>
3569 /// If CoprocOp is 'c', then:
3570 ///   <prefix> ::= c | cr
3571 /// If CoprocOp is 'p', then :
3572 ///   <prefix> ::= p
3573 /// <number> ::= integer in range [0, 15]
3574 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3575   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3576   // but efficient.
3577   if (Name.size() < 2 || Name[0] != CoprocOp)
3578     return -1;
3579   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3580 
3581   switch (Name.size()) {
3582   default: return -1;
3583   case 1:
3584     switch (Name[0]) {
3585     default:  return -1;
3586     case '0': return 0;
3587     case '1': return 1;
3588     case '2': return 2;
3589     case '3': return 3;
3590     case '4': return 4;
3591     case '5': return 5;
3592     case '6': return 6;
3593     case '7': return 7;
3594     case '8': return 8;
3595     case '9': return 9;
3596     }
3597   case 2:
3598     if (Name[0] != '1')
3599       return -1;
3600     switch (Name[1]) {
3601     default:  return -1;
3602     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3603     // However, old cores (v5/v6) did use them in that way.
3604     case '0': return 10;
3605     case '1': return 11;
3606     case '2': return 12;
3607     case '3': return 13;
3608     case '4': return 14;
3609     case '5': return 15;
3610     }
3611   }
3612 }
3613 
3614 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3615 OperandMatchResultTy
3616 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3617   MCAsmParser &Parser = getParser();
3618   SMLoc S = Parser.getTok().getLoc();
3619   const AsmToken &Tok = Parser.getTok();
3620   if (!Tok.is(AsmToken::Identifier))
3621     return MatchOperand_NoMatch;
3622   unsigned CC = ARMCondCodeFromString(Tok.getString());
3623   if (CC == ~0U)
3624     return MatchOperand_NoMatch;
3625   Parser.Lex(); // Eat the token.
3626 
3627   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3628 
3629   return MatchOperand_Success;
3630 }
3631 
3632 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3633 /// token must be an Identifier when called, and if it is a coprocessor
3634 /// number, the token is eaten and the operand is added to the operand list.
3635 OperandMatchResultTy
3636 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3637   MCAsmParser &Parser = getParser();
3638   SMLoc S = Parser.getTok().getLoc();
3639   const AsmToken &Tok = Parser.getTok();
3640   if (Tok.isNot(AsmToken::Identifier))
3641     return MatchOperand_NoMatch;
3642 
3643   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3644   if (Num == -1)
3645     return MatchOperand_NoMatch;
3646   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3647   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3648     return MatchOperand_NoMatch;
3649 
3650   Parser.Lex(); // Eat identifier token.
3651   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3652   return MatchOperand_Success;
3653 }
3654 
3655 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3656 /// token must be an Identifier when called, and if it is a coprocessor
3657 /// number, the token is eaten and the operand is added to the operand list.
3658 OperandMatchResultTy
3659 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3660   MCAsmParser &Parser = getParser();
3661   SMLoc S = Parser.getTok().getLoc();
3662   const AsmToken &Tok = Parser.getTok();
3663   if (Tok.isNot(AsmToken::Identifier))
3664     return MatchOperand_NoMatch;
3665 
3666   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3667   if (Reg == -1)
3668     return MatchOperand_NoMatch;
3669 
3670   Parser.Lex(); // Eat identifier token.
3671   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3672   return MatchOperand_Success;
3673 }
3674 
3675 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3676 /// coproc_option : '{' imm0_255 '}'
3677 OperandMatchResultTy
3678 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3679   MCAsmParser &Parser = getParser();
3680   SMLoc S = Parser.getTok().getLoc();
3681 
3682   // If this isn't a '{', this isn't a coprocessor immediate operand.
3683   if (Parser.getTok().isNot(AsmToken::LCurly))
3684     return MatchOperand_NoMatch;
3685   Parser.Lex(); // Eat the '{'
3686 
3687   const MCExpr *Expr;
3688   SMLoc Loc = Parser.getTok().getLoc();
3689   if (getParser().parseExpression(Expr)) {
3690     Error(Loc, "illegal expression");
3691     return MatchOperand_ParseFail;
3692   }
3693   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3694   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3695     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3696     return MatchOperand_ParseFail;
3697   }
3698   int Val = CE->getValue();
3699 
3700   // Check for and consume the closing '}'
3701   if (Parser.getTok().isNot(AsmToken::RCurly))
3702     return MatchOperand_ParseFail;
3703   SMLoc E = Parser.getTok().getEndLoc();
3704   Parser.Lex(); // Eat the '}'
3705 
3706   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3707   return MatchOperand_Success;
3708 }
3709 
3710 // For register list parsing, we need to map from raw GPR register numbering
3711 // to the enumeration values. The enumeration values aren't sorted by
3712 // register number due to our using "sp", "lr" and "pc" as canonical names.
3713 static unsigned getNextRegister(unsigned Reg) {
3714   // If this is a GPR, we need to do it manually, otherwise we can rely
3715   // on the sort ordering of the enumeration since the other reg-classes
3716   // are sane.
3717   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3718     return Reg + 1;
3719   switch(Reg) {
3720   default: llvm_unreachable("Invalid GPR number!");
3721   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3722   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3723   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3724   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3725   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3726   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3727   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3728   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3729   }
3730 }
3731 
3732 /// Parse a register list.
3733 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3734   MCAsmParser &Parser = getParser();
3735   if (Parser.getTok().isNot(AsmToken::LCurly))
3736     return TokError("Token is not a Left Curly Brace");
3737   SMLoc S = Parser.getTok().getLoc();
3738   Parser.Lex(); // Eat '{' token.
3739   SMLoc RegLoc = Parser.getTok().getLoc();
3740 
3741   // Check the first register in the list to see what register class
3742   // this is a list of.
3743   int Reg = tryParseRegister();
3744   if (Reg == -1)
3745     return Error(RegLoc, "register expected");
3746 
3747   // The reglist instructions have at most 16 registers, so reserve
3748   // space for that many.
3749   int EReg = 0;
3750   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3751 
3752   // Allow Q regs and just interpret them as the two D sub-registers.
3753   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3754     Reg = getDRegFromQReg(Reg);
3755     EReg = MRI->getEncodingValue(Reg);
3756     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3757     ++Reg;
3758   }
3759   const MCRegisterClass *RC;
3760   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3761     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3762   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3763     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3764   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3765     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3766   else
3767     return Error(RegLoc, "invalid register in register list");
3768 
3769   // Store the register.
3770   EReg = MRI->getEncodingValue(Reg);
3771   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3772 
3773   // This starts immediately after the first register token in the list,
3774   // so we can see either a comma or a minus (range separator) as a legal
3775   // next token.
3776   while (Parser.getTok().is(AsmToken::Comma) ||
3777          Parser.getTok().is(AsmToken::Minus)) {
3778     if (Parser.getTok().is(AsmToken::Minus)) {
3779       Parser.Lex(); // Eat the minus.
3780       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3781       int EndReg = tryParseRegister();
3782       if (EndReg == -1)
3783         return Error(AfterMinusLoc, "register expected");
3784       // Allow Q regs and just interpret them as the two D sub-registers.
3785       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3786         EndReg = getDRegFromQReg(EndReg) + 1;
3787       // If the register is the same as the start reg, there's nothing
3788       // more to do.
3789       if (Reg == EndReg)
3790         continue;
3791       // The register must be in the same register class as the first.
3792       if (!RC->contains(EndReg))
3793         return Error(AfterMinusLoc, "invalid register in register list");
3794       // Ranges must go from low to high.
3795       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3796         return Error(AfterMinusLoc, "bad range in register list");
3797 
3798       // Add all the registers in the range to the register list.
3799       while (Reg != EndReg) {
3800         Reg = getNextRegister(Reg);
3801         EReg = MRI->getEncodingValue(Reg);
3802         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3803       }
3804       continue;
3805     }
3806     Parser.Lex(); // Eat the comma.
3807     RegLoc = Parser.getTok().getLoc();
3808     int OldReg = Reg;
3809     const AsmToken RegTok = Parser.getTok();
3810     Reg = tryParseRegister();
3811     if (Reg == -1)
3812       return Error(RegLoc, "register expected");
3813     // Allow Q regs and just interpret them as the two D sub-registers.
3814     bool isQReg = false;
3815     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3816       Reg = getDRegFromQReg(Reg);
3817       isQReg = true;
3818     }
3819     // The register must be in the same register class as the first.
3820     if (!RC->contains(Reg))
3821       return Error(RegLoc, "invalid register in register list");
3822     // List must be monotonically increasing.
3823     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3824       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3825         Warning(RegLoc, "register list not in ascending order");
3826       else
3827         return Error(RegLoc, "register list not in ascending order");
3828     }
3829     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3830       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3831               ") in register list");
3832       continue;
3833     }
3834     // VFP register lists must also be contiguous.
3835     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3836         Reg != OldReg + 1)
3837       return Error(RegLoc, "non-contiguous register range");
3838     EReg = MRI->getEncodingValue(Reg);
3839     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3840     if (isQReg) {
3841       EReg = MRI->getEncodingValue(++Reg);
3842       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3843     }
3844   }
3845 
3846   if (Parser.getTok().isNot(AsmToken::RCurly))
3847     return Error(Parser.getTok().getLoc(), "'}' expected");
3848   SMLoc E = Parser.getTok().getEndLoc();
3849   Parser.Lex(); // Eat '}' token.
3850 
3851   // Push the register list operand.
3852   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3853 
3854   // The ARM system instruction variants for LDM/STM have a '^' token here.
3855   if (Parser.getTok().is(AsmToken::Caret)) {
3856     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3857     Parser.Lex(); // Eat '^' token.
3858   }
3859 
3860   return false;
3861 }
3862 
3863 // Helper function to parse the lane index for vector lists.
3864 OperandMatchResultTy ARMAsmParser::
3865 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3866   MCAsmParser &Parser = getParser();
3867   Index = 0; // Always return a defined index value.
3868   if (Parser.getTok().is(AsmToken::LBrac)) {
3869     Parser.Lex(); // Eat the '['.
3870     if (Parser.getTok().is(AsmToken::RBrac)) {
3871       // "Dn[]" is the 'all lanes' syntax.
3872       LaneKind = AllLanes;
3873       EndLoc = Parser.getTok().getEndLoc();
3874       Parser.Lex(); // Eat the ']'.
3875       return MatchOperand_Success;
3876     }
3877 
3878     // There's an optional '#' token here. Normally there wouldn't be, but
3879     // inline assemble puts one in, and it's friendly to accept that.
3880     if (Parser.getTok().is(AsmToken::Hash))
3881       Parser.Lex(); // Eat '#' or '$'.
3882 
3883     const MCExpr *LaneIndex;
3884     SMLoc Loc = Parser.getTok().getLoc();
3885     if (getParser().parseExpression(LaneIndex)) {
3886       Error(Loc, "illegal expression");
3887       return MatchOperand_ParseFail;
3888     }
3889     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3890     if (!CE) {
3891       Error(Loc, "lane index must be empty or an integer");
3892       return MatchOperand_ParseFail;
3893     }
3894     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3895       Error(Parser.getTok().getLoc(), "']' expected");
3896       return MatchOperand_ParseFail;
3897     }
3898     EndLoc = Parser.getTok().getEndLoc();
3899     Parser.Lex(); // Eat the ']'.
3900     int64_t Val = CE->getValue();
3901 
3902     // FIXME: Make this range check context sensitive for .8, .16, .32.
3903     if (Val < 0 || Val > 7) {
3904       Error(Parser.getTok().getLoc(), "lane index out of range");
3905       return MatchOperand_ParseFail;
3906     }
3907     Index = Val;
3908     LaneKind = IndexedLane;
3909     return MatchOperand_Success;
3910   }
3911   LaneKind = NoLanes;
3912   return MatchOperand_Success;
3913 }
3914 
3915 // parse a vector register list
3916 OperandMatchResultTy
3917 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3918   MCAsmParser &Parser = getParser();
3919   VectorLaneTy LaneKind;
3920   unsigned LaneIndex;
3921   SMLoc S = Parser.getTok().getLoc();
3922   // As an extension (to match gas), support a plain D register or Q register
3923   // (without encosing curly braces) as a single or double entry list,
3924   // respectively.
3925   if (Parser.getTok().is(AsmToken::Identifier)) {
3926     SMLoc E = Parser.getTok().getEndLoc();
3927     int Reg = tryParseRegister();
3928     if (Reg == -1)
3929       return MatchOperand_NoMatch;
3930     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3931       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3932       if (Res != MatchOperand_Success)
3933         return Res;
3934       switch (LaneKind) {
3935       case NoLanes:
3936         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3937         break;
3938       case AllLanes:
3939         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3940                                                                 S, E));
3941         break;
3942       case IndexedLane:
3943         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3944                                                                LaneIndex,
3945                                                                false, S, E));
3946         break;
3947       }
3948       return MatchOperand_Success;
3949     }
3950     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3951       Reg = getDRegFromQReg(Reg);
3952       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3953       if (Res != MatchOperand_Success)
3954         return Res;
3955       switch (LaneKind) {
3956       case NoLanes:
3957         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3958                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3959         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3960         break;
3961       case AllLanes:
3962         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3963                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3964         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3965                                                                 S, E));
3966         break;
3967       case IndexedLane:
3968         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3969                                                                LaneIndex,
3970                                                                false, S, E));
3971         break;
3972       }
3973       return MatchOperand_Success;
3974     }
3975     Error(S, "vector register expected");
3976     return MatchOperand_ParseFail;
3977   }
3978 
3979   if (Parser.getTok().isNot(AsmToken::LCurly))
3980     return MatchOperand_NoMatch;
3981 
3982   Parser.Lex(); // Eat '{' token.
3983   SMLoc RegLoc = Parser.getTok().getLoc();
3984 
3985   int Reg = tryParseRegister();
3986   if (Reg == -1) {
3987     Error(RegLoc, "register expected");
3988     return MatchOperand_ParseFail;
3989   }
3990   unsigned Count = 1;
3991   int Spacing = 0;
3992   unsigned FirstReg = Reg;
3993   // The list is of D registers, but we also allow Q regs and just interpret
3994   // them as the two D sub-registers.
3995   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3996     FirstReg = Reg = getDRegFromQReg(Reg);
3997     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3998                  // it's ambiguous with four-register single spaced.
3999     ++Reg;
4000     ++Count;
4001   }
4002 
4003   SMLoc E;
4004   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4005     return MatchOperand_ParseFail;
4006 
4007   while (Parser.getTok().is(AsmToken::Comma) ||
4008          Parser.getTok().is(AsmToken::Minus)) {
4009     if (Parser.getTok().is(AsmToken::Minus)) {
4010       if (!Spacing)
4011         Spacing = 1; // Register range implies a single spaced list.
4012       else if (Spacing == 2) {
4013         Error(Parser.getTok().getLoc(),
4014               "sequential registers in double spaced list");
4015         return MatchOperand_ParseFail;
4016       }
4017       Parser.Lex(); // Eat the minus.
4018       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4019       int EndReg = tryParseRegister();
4020       if (EndReg == -1) {
4021         Error(AfterMinusLoc, "register expected");
4022         return MatchOperand_ParseFail;
4023       }
4024       // Allow Q regs and just interpret them as the two D sub-registers.
4025       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4026         EndReg = getDRegFromQReg(EndReg) + 1;
4027       // If the register is the same as the start reg, there's nothing
4028       // more to do.
4029       if (Reg == EndReg)
4030         continue;
4031       // The register must be in the same register class as the first.
4032       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
4033         Error(AfterMinusLoc, "invalid register in register list");
4034         return MatchOperand_ParseFail;
4035       }
4036       // Ranges must go from low to high.
4037       if (Reg > EndReg) {
4038         Error(AfterMinusLoc, "bad range in register list");
4039         return MatchOperand_ParseFail;
4040       }
4041       // Parse the lane specifier if present.
4042       VectorLaneTy NextLaneKind;
4043       unsigned NextLaneIndex;
4044       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4045           MatchOperand_Success)
4046         return MatchOperand_ParseFail;
4047       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4048         Error(AfterMinusLoc, "mismatched lane index in register list");
4049         return MatchOperand_ParseFail;
4050       }
4051 
4052       // Add all the registers in the range to the register list.
4053       Count += EndReg - Reg;
4054       Reg = EndReg;
4055       continue;
4056     }
4057     Parser.Lex(); // Eat the comma.
4058     RegLoc = Parser.getTok().getLoc();
4059     int OldReg = Reg;
4060     Reg = tryParseRegister();
4061     if (Reg == -1) {
4062       Error(RegLoc, "register expected");
4063       return MatchOperand_ParseFail;
4064     }
4065     // vector register lists must be contiguous.
4066     // It's OK to use the enumeration values directly here rather, as the
4067     // VFP register classes have the enum sorted properly.
4068     //
4069     // The list is of D registers, but we also allow Q regs and just interpret
4070     // them as the two D sub-registers.
4071     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4072       if (!Spacing)
4073         Spacing = 1; // Register range implies a single spaced list.
4074       else if (Spacing == 2) {
4075         Error(RegLoc,
4076               "invalid register in double-spaced list (must be 'D' register')");
4077         return MatchOperand_ParseFail;
4078       }
4079       Reg = getDRegFromQReg(Reg);
4080       if (Reg != OldReg + 1) {
4081         Error(RegLoc, "non-contiguous register range");
4082         return MatchOperand_ParseFail;
4083       }
4084       ++Reg;
4085       Count += 2;
4086       // Parse the lane specifier if present.
4087       VectorLaneTy NextLaneKind;
4088       unsigned NextLaneIndex;
4089       SMLoc LaneLoc = Parser.getTok().getLoc();
4090       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4091           MatchOperand_Success)
4092         return MatchOperand_ParseFail;
4093       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4094         Error(LaneLoc, "mismatched lane index in register list");
4095         return MatchOperand_ParseFail;
4096       }
4097       continue;
4098     }
4099     // Normal D register.
4100     // Figure out the register spacing (single or double) of the list if
4101     // we don't know it already.
4102     if (!Spacing)
4103       Spacing = 1 + (Reg == OldReg + 2);
4104 
4105     // Just check that it's contiguous and keep going.
4106     if (Reg != OldReg + Spacing) {
4107       Error(RegLoc, "non-contiguous register range");
4108       return MatchOperand_ParseFail;
4109     }
4110     ++Count;
4111     // Parse the lane specifier if present.
4112     VectorLaneTy NextLaneKind;
4113     unsigned NextLaneIndex;
4114     SMLoc EndLoc = Parser.getTok().getLoc();
4115     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4116       return MatchOperand_ParseFail;
4117     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4118       Error(EndLoc, "mismatched lane index in register list");
4119       return MatchOperand_ParseFail;
4120     }
4121   }
4122 
4123   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4124     Error(Parser.getTok().getLoc(), "'}' expected");
4125     return MatchOperand_ParseFail;
4126   }
4127   E = Parser.getTok().getEndLoc();
4128   Parser.Lex(); // Eat '}' token.
4129 
4130   switch (LaneKind) {
4131   case NoLanes:
4132     // Two-register operands have been converted to the
4133     // composite register classes.
4134     if (Count == 2) {
4135       const MCRegisterClass *RC = (Spacing == 1) ?
4136         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4137         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4138       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4139     }
4140     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
4141                                                     (Spacing == 2), S, E));
4142     break;
4143   case AllLanes:
4144     // Two-register operands have been converted to the
4145     // composite register classes.
4146     if (Count == 2) {
4147       const MCRegisterClass *RC = (Spacing == 1) ?
4148         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4149         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4150       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4151     }
4152     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
4153                                                             (Spacing == 2),
4154                                                             S, E));
4155     break;
4156   case IndexedLane:
4157     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4158                                                            LaneIndex,
4159                                                            (Spacing == 2),
4160                                                            S, E));
4161     break;
4162   }
4163   return MatchOperand_Success;
4164 }
4165 
4166 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4167 OperandMatchResultTy
4168 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4169   MCAsmParser &Parser = getParser();
4170   SMLoc S = Parser.getTok().getLoc();
4171   const AsmToken &Tok = Parser.getTok();
4172   unsigned Opt;
4173 
4174   if (Tok.is(AsmToken::Identifier)) {
4175     StringRef OptStr = Tok.getString();
4176 
4177     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4178       .Case("sy",    ARM_MB::SY)
4179       .Case("st",    ARM_MB::ST)
4180       .Case("ld",    ARM_MB::LD)
4181       .Case("sh",    ARM_MB::ISH)
4182       .Case("ish",   ARM_MB::ISH)
4183       .Case("shst",  ARM_MB::ISHST)
4184       .Case("ishst", ARM_MB::ISHST)
4185       .Case("ishld", ARM_MB::ISHLD)
4186       .Case("nsh",   ARM_MB::NSH)
4187       .Case("un",    ARM_MB::NSH)
4188       .Case("nshst", ARM_MB::NSHST)
4189       .Case("nshld", ARM_MB::NSHLD)
4190       .Case("unst",  ARM_MB::NSHST)
4191       .Case("osh",   ARM_MB::OSH)
4192       .Case("oshst", ARM_MB::OSHST)
4193       .Case("oshld", ARM_MB::OSHLD)
4194       .Default(~0U);
4195 
4196     // ishld, oshld, nshld and ld are only available from ARMv8.
4197     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4198                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4199       Opt = ~0U;
4200 
4201     if (Opt == ~0U)
4202       return MatchOperand_NoMatch;
4203 
4204     Parser.Lex(); // Eat identifier token.
4205   } else if (Tok.is(AsmToken::Hash) ||
4206              Tok.is(AsmToken::Dollar) ||
4207              Tok.is(AsmToken::Integer)) {
4208     if (Parser.getTok().isNot(AsmToken::Integer))
4209       Parser.Lex(); // Eat '#' or '$'.
4210     SMLoc Loc = Parser.getTok().getLoc();
4211 
4212     const MCExpr *MemBarrierID;
4213     if (getParser().parseExpression(MemBarrierID)) {
4214       Error(Loc, "illegal expression");
4215       return MatchOperand_ParseFail;
4216     }
4217 
4218     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4219     if (!CE) {
4220       Error(Loc, "constant expression expected");
4221       return MatchOperand_ParseFail;
4222     }
4223 
4224     int Val = CE->getValue();
4225     if (Val & ~0xf) {
4226       Error(Loc, "immediate value out of range");
4227       return MatchOperand_ParseFail;
4228     }
4229 
4230     Opt = ARM_MB::RESERVED_0 + Val;
4231   } else
4232     return MatchOperand_ParseFail;
4233 
4234   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4235   return MatchOperand_Success;
4236 }
4237 
4238 OperandMatchResultTy
4239 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
4240   MCAsmParser &Parser = getParser();
4241   SMLoc S = Parser.getTok().getLoc();
4242   const AsmToken &Tok = Parser.getTok();
4243 
4244   if (Tok.isNot(AsmToken::Identifier))
4245      return MatchOperand_NoMatch;
4246 
4247   if (!Tok.getString().equals_lower("csync"))
4248     return MatchOperand_NoMatch;
4249 
4250   Parser.Lex(); // Eat identifier token.
4251 
4252   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
4253   return MatchOperand_Success;
4254 }
4255 
4256 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4257 OperandMatchResultTy
4258 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4259   MCAsmParser &Parser = getParser();
4260   SMLoc S = Parser.getTok().getLoc();
4261   const AsmToken &Tok = Parser.getTok();
4262   unsigned Opt;
4263 
4264   if (Tok.is(AsmToken::Identifier)) {
4265     StringRef OptStr = Tok.getString();
4266 
4267     if (OptStr.equals_lower("sy"))
4268       Opt = ARM_ISB::SY;
4269     else
4270       return MatchOperand_NoMatch;
4271 
4272     Parser.Lex(); // Eat identifier token.
4273   } else if (Tok.is(AsmToken::Hash) ||
4274              Tok.is(AsmToken::Dollar) ||
4275              Tok.is(AsmToken::Integer)) {
4276     if (Parser.getTok().isNot(AsmToken::Integer))
4277       Parser.Lex(); // Eat '#' or '$'.
4278     SMLoc Loc = Parser.getTok().getLoc();
4279 
4280     const MCExpr *ISBarrierID;
4281     if (getParser().parseExpression(ISBarrierID)) {
4282       Error(Loc, "illegal expression");
4283       return MatchOperand_ParseFail;
4284     }
4285 
4286     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4287     if (!CE) {
4288       Error(Loc, "constant expression expected");
4289       return MatchOperand_ParseFail;
4290     }
4291 
4292     int Val = CE->getValue();
4293     if (Val & ~0xf) {
4294       Error(Loc, "immediate value out of range");
4295       return MatchOperand_ParseFail;
4296     }
4297 
4298     Opt = ARM_ISB::RESERVED_0 + Val;
4299   } else
4300     return MatchOperand_ParseFail;
4301 
4302   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4303           (ARM_ISB::InstSyncBOpt)Opt, S));
4304   return MatchOperand_Success;
4305 }
4306 
4307 
4308 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4309 OperandMatchResultTy
4310 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4311   MCAsmParser &Parser = getParser();
4312   SMLoc S = Parser.getTok().getLoc();
4313   const AsmToken &Tok = Parser.getTok();
4314   if (!Tok.is(AsmToken::Identifier))
4315     return MatchOperand_NoMatch;
4316   StringRef IFlagsStr = Tok.getString();
4317 
4318   // An iflags string of "none" is interpreted to mean that none of the AIF
4319   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4320   unsigned IFlags = 0;
4321   if (IFlagsStr != "none") {
4322         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4323       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4324         .Case("a", ARM_PROC::A)
4325         .Case("i", ARM_PROC::I)
4326         .Case("f", ARM_PROC::F)
4327         .Default(~0U);
4328 
4329       // If some specific iflag is already set, it means that some letter is
4330       // present more than once, this is not acceptable.
4331       if (Flag == ~0U || (IFlags & Flag))
4332         return MatchOperand_NoMatch;
4333 
4334       IFlags |= Flag;
4335     }
4336   }
4337 
4338   Parser.Lex(); // Eat identifier token.
4339   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4340   return MatchOperand_Success;
4341 }
4342 
4343 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4344 OperandMatchResultTy
4345 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4346   MCAsmParser &Parser = getParser();
4347   SMLoc S = Parser.getTok().getLoc();
4348   const AsmToken &Tok = Parser.getTok();
4349 
4350   if (Tok.is(AsmToken::Integer)) {
4351     int64_t Val = Tok.getIntVal();
4352     if (Val > 255 || Val < 0) {
4353       return MatchOperand_NoMatch;
4354     }
4355     unsigned SYSmvalue = Val & 0xFF;
4356     Parser.Lex();
4357     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4358     return MatchOperand_Success;
4359   }
4360 
4361   if (!Tok.is(AsmToken::Identifier))
4362     return MatchOperand_NoMatch;
4363   StringRef Mask = Tok.getString();
4364 
4365   if (isMClass()) {
4366     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4367     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4368       return MatchOperand_NoMatch;
4369 
4370     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4371 
4372     Parser.Lex(); // Eat identifier token.
4373     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4374     return MatchOperand_Success;
4375   }
4376 
4377   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4378   size_t Start = 0, Next = Mask.find('_');
4379   StringRef Flags = "";
4380   std::string SpecReg = Mask.slice(Start, Next).lower();
4381   if (Next != StringRef::npos)
4382     Flags = Mask.slice(Next+1, Mask.size());
4383 
4384   // FlagsVal contains the complete mask:
4385   // 3-0: Mask
4386   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4387   unsigned FlagsVal = 0;
4388 
4389   if (SpecReg == "apsr") {
4390     FlagsVal = StringSwitch<unsigned>(Flags)
4391     .Case("nzcvq",  0x8) // same as CPSR_f
4392     .Case("g",      0x4) // same as CPSR_s
4393     .Case("nzcvqg", 0xc) // same as CPSR_fs
4394     .Default(~0U);
4395 
4396     if (FlagsVal == ~0U) {
4397       if (!Flags.empty())
4398         return MatchOperand_NoMatch;
4399       else
4400         FlagsVal = 8; // No flag
4401     }
4402   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4403     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4404     if (Flags == "all" || Flags == "")
4405       Flags = "fc";
4406     for (int i = 0, e = Flags.size(); i != e; ++i) {
4407       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4408       .Case("c", 1)
4409       .Case("x", 2)
4410       .Case("s", 4)
4411       .Case("f", 8)
4412       .Default(~0U);
4413 
4414       // If some specific flag is already set, it means that some letter is
4415       // present more than once, this is not acceptable.
4416       if (Flag == ~0U || (FlagsVal & Flag))
4417         return MatchOperand_NoMatch;
4418       FlagsVal |= Flag;
4419     }
4420   } else // No match for special register.
4421     return MatchOperand_NoMatch;
4422 
4423   // Special register without flags is NOT equivalent to "fc" flags.
4424   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4425   // two lines would enable gas compatibility at the expense of breaking
4426   // round-tripping.
4427   //
4428   // if (!FlagsVal)
4429   //  FlagsVal = 0x9;
4430 
4431   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4432   if (SpecReg == "spsr")
4433     FlagsVal |= 16;
4434 
4435   Parser.Lex(); // Eat identifier token.
4436   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4437   return MatchOperand_Success;
4438 }
4439 
4440 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4441 /// use in the MRS/MSR instructions added to support virtualization.
4442 OperandMatchResultTy
4443 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4444   MCAsmParser &Parser = getParser();
4445   SMLoc S = Parser.getTok().getLoc();
4446   const AsmToken &Tok = Parser.getTok();
4447   if (!Tok.is(AsmToken::Identifier))
4448     return MatchOperand_NoMatch;
4449   StringRef RegName = Tok.getString();
4450 
4451   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4452   if (!TheReg)
4453     return MatchOperand_NoMatch;
4454   unsigned Encoding = TheReg->Encoding;
4455 
4456   Parser.Lex(); // Eat identifier token.
4457   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4458   return MatchOperand_Success;
4459 }
4460 
4461 OperandMatchResultTy
4462 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4463                           int High) {
4464   MCAsmParser &Parser = getParser();
4465   const AsmToken &Tok = Parser.getTok();
4466   if (Tok.isNot(AsmToken::Identifier)) {
4467     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4468     return MatchOperand_ParseFail;
4469   }
4470   StringRef ShiftName = Tok.getString();
4471   std::string LowerOp = Op.lower();
4472   std::string UpperOp = Op.upper();
4473   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4474     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4475     return MatchOperand_ParseFail;
4476   }
4477   Parser.Lex(); // Eat shift type token.
4478 
4479   // There must be a '#' and a shift amount.
4480   if (Parser.getTok().isNot(AsmToken::Hash) &&
4481       Parser.getTok().isNot(AsmToken::Dollar)) {
4482     Error(Parser.getTok().getLoc(), "'#' expected");
4483     return MatchOperand_ParseFail;
4484   }
4485   Parser.Lex(); // Eat hash token.
4486 
4487   const MCExpr *ShiftAmount;
4488   SMLoc Loc = Parser.getTok().getLoc();
4489   SMLoc EndLoc;
4490   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4491     Error(Loc, "illegal expression");
4492     return MatchOperand_ParseFail;
4493   }
4494   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4495   if (!CE) {
4496     Error(Loc, "constant expression expected");
4497     return MatchOperand_ParseFail;
4498   }
4499   int Val = CE->getValue();
4500   if (Val < Low || Val > High) {
4501     Error(Loc, "immediate value out of range");
4502     return MatchOperand_ParseFail;
4503   }
4504 
4505   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4506 
4507   return MatchOperand_Success;
4508 }
4509 
4510 OperandMatchResultTy
4511 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4512   MCAsmParser &Parser = getParser();
4513   const AsmToken &Tok = Parser.getTok();
4514   SMLoc S = Tok.getLoc();
4515   if (Tok.isNot(AsmToken::Identifier)) {
4516     Error(S, "'be' or 'le' operand expected");
4517     return MatchOperand_ParseFail;
4518   }
4519   int Val = StringSwitch<int>(Tok.getString().lower())
4520     .Case("be", 1)
4521     .Case("le", 0)
4522     .Default(-1);
4523   Parser.Lex(); // Eat the token.
4524 
4525   if (Val == -1) {
4526     Error(S, "'be' or 'le' operand expected");
4527     return MatchOperand_ParseFail;
4528   }
4529   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4530                                                                   getContext()),
4531                                            S, Tok.getEndLoc()));
4532   return MatchOperand_Success;
4533 }
4534 
4535 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4536 /// instructions. Legal values are:
4537 ///     lsl #n  'n' in [0,31]
4538 ///     asr #n  'n' in [1,32]
4539 ///             n == 32 encoded as n == 0.
4540 OperandMatchResultTy
4541 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4542   MCAsmParser &Parser = getParser();
4543   const AsmToken &Tok = Parser.getTok();
4544   SMLoc S = Tok.getLoc();
4545   if (Tok.isNot(AsmToken::Identifier)) {
4546     Error(S, "shift operator 'asr' or 'lsl' expected");
4547     return MatchOperand_ParseFail;
4548   }
4549   StringRef ShiftName = Tok.getString();
4550   bool isASR;
4551   if (ShiftName == "lsl" || ShiftName == "LSL")
4552     isASR = false;
4553   else if (ShiftName == "asr" || ShiftName == "ASR")
4554     isASR = true;
4555   else {
4556     Error(S, "shift operator 'asr' or 'lsl' expected");
4557     return MatchOperand_ParseFail;
4558   }
4559   Parser.Lex(); // Eat the operator.
4560 
4561   // A '#' and a shift amount.
4562   if (Parser.getTok().isNot(AsmToken::Hash) &&
4563       Parser.getTok().isNot(AsmToken::Dollar)) {
4564     Error(Parser.getTok().getLoc(), "'#' expected");
4565     return MatchOperand_ParseFail;
4566   }
4567   Parser.Lex(); // Eat hash token.
4568   SMLoc ExLoc = Parser.getTok().getLoc();
4569 
4570   const MCExpr *ShiftAmount;
4571   SMLoc EndLoc;
4572   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4573     Error(ExLoc, "malformed shift expression");
4574     return MatchOperand_ParseFail;
4575   }
4576   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4577   if (!CE) {
4578     Error(ExLoc, "shift amount must be an immediate");
4579     return MatchOperand_ParseFail;
4580   }
4581 
4582   int64_t Val = CE->getValue();
4583   if (isASR) {
4584     // Shift amount must be in [1,32]
4585     if (Val < 1 || Val > 32) {
4586       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4587       return MatchOperand_ParseFail;
4588     }
4589     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4590     if (isThumb() && Val == 32) {
4591       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4592       return MatchOperand_ParseFail;
4593     }
4594     if (Val == 32) Val = 0;
4595   } else {
4596     // Shift amount must be in [1,32]
4597     if (Val < 0 || Val > 31) {
4598       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4599       return MatchOperand_ParseFail;
4600     }
4601   }
4602 
4603   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4604 
4605   return MatchOperand_Success;
4606 }
4607 
4608 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4609 /// of instructions. Legal values are:
4610 ///     ror #n  'n' in {0, 8, 16, 24}
4611 OperandMatchResultTy
4612 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4613   MCAsmParser &Parser = getParser();
4614   const AsmToken &Tok = Parser.getTok();
4615   SMLoc S = Tok.getLoc();
4616   if (Tok.isNot(AsmToken::Identifier))
4617     return MatchOperand_NoMatch;
4618   StringRef ShiftName = Tok.getString();
4619   if (ShiftName != "ror" && ShiftName != "ROR")
4620     return MatchOperand_NoMatch;
4621   Parser.Lex(); // Eat the operator.
4622 
4623   // A '#' and a rotate amount.
4624   if (Parser.getTok().isNot(AsmToken::Hash) &&
4625       Parser.getTok().isNot(AsmToken::Dollar)) {
4626     Error(Parser.getTok().getLoc(), "'#' expected");
4627     return MatchOperand_ParseFail;
4628   }
4629   Parser.Lex(); // Eat hash token.
4630   SMLoc ExLoc = Parser.getTok().getLoc();
4631 
4632   const MCExpr *ShiftAmount;
4633   SMLoc EndLoc;
4634   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4635     Error(ExLoc, "malformed rotate expression");
4636     return MatchOperand_ParseFail;
4637   }
4638   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4639   if (!CE) {
4640     Error(ExLoc, "rotate amount must be an immediate");
4641     return MatchOperand_ParseFail;
4642   }
4643 
4644   int64_t Val = CE->getValue();
4645   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4646   // normally, zero is represented in asm by omitting the rotate operand
4647   // entirely.
4648   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4649     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4650     return MatchOperand_ParseFail;
4651   }
4652 
4653   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4654 
4655   return MatchOperand_Success;
4656 }
4657 
4658 OperandMatchResultTy
4659 ARMAsmParser::parseModImm(OperandVector &Operands) {
4660   MCAsmParser &Parser = getParser();
4661   MCAsmLexer &Lexer = getLexer();
4662   int64_t Imm1, Imm2;
4663 
4664   SMLoc S = Parser.getTok().getLoc();
4665 
4666   // 1) A mod_imm operand can appear in the place of a register name:
4667   //   add r0, #mod_imm
4668   //   add r0, r0, #mod_imm
4669   // to correctly handle the latter, we bail out as soon as we see an
4670   // identifier.
4671   //
4672   // 2) Similarly, we do not want to parse into complex operands:
4673   //   mov r0, #mod_imm
4674   //   mov r0, :lower16:(_foo)
4675   if (Parser.getTok().is(AsmToken::Identifier) ||
4676       Parser.getTok().is(AsmToken::Colon))
4677     return MatchOperand_NoMatch;
4678 
4679   // Hash (dollar) is optional as per the ARMARM
4680   if (Parser.getTok().is(AsmToken::Hash) ||
4681       Parser.getTok().is(AsmToken::Dollar)) {
4682     // Avoid parsing into complex operands (#:)
4683     if (Lexer.peekTok().is(AsmToken::Colon))
4684       return MatchOperand_NoMatch;
4685 
4686     // Eat the hash (dollar)
4687     Parser.Lex();
4688   }
4689 
4690   SMLoc Sx1, Ex1;
4691   Sx1 = Parser.getTok().getLoc();
4692   const MCExpr *Imm1Exp;
4693   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4694     Error(Sx1, "malformed expression");
4695     return MatchOperand_ParseFail;
4696   }
4697 
4698   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4699 
4700   if (CE) {
4701     // Immediate must fit within 32-bits
4702     Imm1 = CE->getValue();
4703     int Enc = ARM_AM::getSOImmVal(Imm1);
4704     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4705       // We have a match!
4706       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4707                                                   (Enc & 0xF00) >> 7,
4708                                                   Sx1, Ex1));
4709       return MatchOperand_Success;
4710     }
4711 
4712     // We have parsed an immediate which is not for us, fallback to a plain
4713     // immediate. This can happen for instruction aliases. For an example,
4714     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4715     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4716     // instruction with a mod_imm operand. The alias is defined such that the
4717     // parser method is shared, that's why we have to do this here.
4718     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4719       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4720       return MatchOperand_Success;
4721     }
4722   } else {
4723     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4724     // MCFixup). Fallback to a plain immediate.
4725     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4726     return MatchOperand_Success;
4727   }
4728 
4729   // From this point onward, we expect the input to be a (#bits, #rot) pair
4730   if (Parser.getTok().isNot(AsmToken::Comma)) {
4731     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4732     return MatchOperand_ParseFail;
4733   }
4734 
4735   if (Imm1 & ~0xFF) {
4736     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4737     return MatchOperand_ParseFail;
4738   }
4739 
4740   // Eat the comma
4741   Parser.Lex();
4742 
4743   // Repeat for #rot
4744   SMLoc Sx2, Ex2;
4745   Sx2 = Parser.getTok().getLoc();
4746 
4747   // Eat the optional hash (dollar)
4748   if (Parser.getTok().is(AsmToken::Hash) ||
4749       Parser.getTok().is(AsmToken::Dollar))
4750     Parser.Lex();
4751 
4752   const MCExpr *Imm2Exp;
4753   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4754     Error(Sx2, "malformed expression");
4755     return MatchOperand_ParseFail;
4756   }
4757 
4758   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4759 
4760   if (CE) {
4761     Imm2 = CE->getValue();
4762     if (!(Imm2 & ~0x1E)) {
4763       // We have a match!
4764       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4765       return MatchOperand_Success;
4766     }
4767     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4768     return MatchOperand_ParseFail;
4769   } else {
4770     Error(Sx2, "constant expression expected");
4771     return MatchOperand_ParseFail;
4772   }
4773 }
4774 
4775 OperandMatchResultTy
4776 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4777   MCAsmParser &Parser = getParser();
4778   SMLoc S = Parser.getTok().getLoc();
4779   // The bitfield descriptor is really two operands, the LSB and the width.
4780   if (Parser.getTok().isNot(AsmToken::Hash) &&
4781       Parser.getTok().isNot(AsmToken::Dollar)) {
4782     Error(Parser.getTok().getLoc(), "'#' expected");
4783     return MatchOperand_ParseFail;
4784   }
4785   Parser.Lex(); // Eat hash token.
4786 
4787   const MCExpr *LSBExpr;
4788   SMLoc E = Parser.getTok().getLoc();
4789   if (getParser().parseExpression(LSBExpr)) {
4790     Error(E, "malformed immediate expression");
4791     return MatchOperand_ParseFail;
4792   }
4793   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4794   if (!CE) {
4795     Error(E, "'lsb' operand must be an immediate");
4796     return MatchOperand_ParseFail;
4797   }
4798 
4799   int64_t LSB = CE->getValue();
4800   // The LSB must be in the range [0,31]
4801   if (LSB < 0 || LSB > 31) {
4802     Error(E, "'lsb' operand must be in the range [0,31]");
4803     return MatchOperand_ParseFail;
4804   }
4805   E = Parser.getTok().getLoc();
4806 
4807   // Expect another immediate operand.
4808   if (Parser.getTok().isNot(AsmToken::Comma)) {
4809     Error(Parser.getTok().getLoc(), "too few operands");
4810     return MatchOperand_ParseFail;
4811   }
4812   Parser.Lex(); // Eat hash token.
4813   if (Parser.getTok().isNot(AsmToken::Hash) &&
4814       Parser.getTok().isNot(AsmToken::Dollar)) {
4815     Error(Parser.getTok().getLoc(), "'#' expected");
4816     return MatchOperand_ParseFail;
4817   }
4818   Parser.Lex(); // Eat hash token.
4819 
4820   const MCExpr *WidthExpr;
4821   SMLoc EndLoc;
4822   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4823     Error(E, "malformed immediate expression");
4824     return MatchOperand_ParseFail;
4825   }
4826   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4827   if (!CE) {
4828     Error(E, "'width' operand must be an immediate");
4829     return MatchOperand_ParseFail;
4830   }
4831 
4832   int64_t Width = CE->getValue();
4833   // The LSB must be in the range [1,32-lsb]
4834   if (Width < 1 || Width > 32 - LSB) {
4835     Error(E, "'width' operand must be in the range [1,32-lsb]");
4836     return MatchOperand_ParseFail;
4837   }
4838 
4839   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4840 
4841   return MatchOperand_Success;
4842 }
4843 
4844 OperandMatchResultTy
4845 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4846   // Check for a post-index addressing register operand. Specifically:
4847   // postidx_reg := '+' register {, shift}
4848   //              | '-' register {, shift}
4849   //              | register {, shift}
4850 
4851   // This method must return MatchOperand_NoMatch without consuming any tokens
4852   // in the case where there is no match, as other alternatives take other
4853   // parse methods.
4854   MCAsmParser &Parser = getParser();
4855   AsmToken Tok = Parser.getTok();
4856   SMLoc S = Tok.getLoc();
4857   bool haveEaten = false;
4858   bool isAdd = true;
4859   if (Tok.is(AsmToken::Plus)) {
4860     Parser.Lex(); // Eat the '+' token.
4861     haveEaten = true;
4862   } else if (Tok.is(AsmToken::Minus)) {
4863     Parser.Lex(); // Eat the '-' token.
4864     isAdd = false;
4865     haveEaten = true;
4866   }
4867 
4868   SMLoc E = Parser.getTok().getEndLoc();
4869   int Reg = tryParseRegister();
4870   if (Reg == -1) {
4871     if (!haveEaten)
4872       return MatchOperand_NoMatch;
4873     Error(Parser.getTok().getLoc(), "register expected");
4874     return MatchOperand_ParseFail;
4875   }
4876 
4877   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4878   unsigned ShiftImm = 0;
4879   if (Parser.getTok().is(AsmToken::Comma)) {
4880     Parser.Lex(); // Eat the ','.
4881     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4882       return MatchOperand_ParseFail;
4883 
4884     // FIXME: Only approximates end...may include intervening whitespace.
4885     E = Parser.getTok().getLoc();
4886   }
4887 
4888   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4889                                                   ShiftImm, S, E));
4890 
4891   return MatchOperand_Success;
4892 }
4893 
4894 OperandMatchResultTy
4895 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4896   // Check for a post-index addressing register operand. Specifically:
4897   // am3offset := '+' register
4898   //              | '-' register
4899   //              | register
4900   //              | # imm
4901   //              | # + imm
4902   //              | # - imm
4903 
4904   // This method must return MatchOperand_NoMatch without consuming any tokens
4905   // in the case where there is no match, as other alternatives take other
4906   // parse methods.
4907   MCAsmParser &Parser = getParser();
4908   AsmToken Tok = Parser.getTok();
4909   SMLoc S = Tok.getLoc();
4910 
4911   // Do immediates first, as we always parse those if we have a '#'.
4912   if (Parser.getTok().is(AsmToken::Hash) ||
4913       Parser.getTok().is(AsmToken::Dollar)) {
4914     Parser.Lex(); // Eat '#' or '$'.
4915     // Explicitly look for a '-', as we need to encode negative zero
4916     // differently.
4917     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4918     const MCExpr *Offset;
4919     SMLoc E;
4920     if (getParser().parseExpression(Offset, E))
4921       return MatchOperand_ParseFail;
4922     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4923     if (!CE) {
4924       Error(S, "constant expression expected");
4925       return MatchOperand_ParseFail;
4926     }
4927     // Negative zero is encoded as the flag value
4928     // std::numeric_limits<int32_t>::min().
4929     int32_t Val = CE->getValue();
4930     if (isNegative && Val == 0)
4931       Val = std::numeric_limits<int32_t>::min();
4932 
4933     Operands.push_back(
4934       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4935 
4936     return MatchOperand_Success;
4937   }
4938 
4939   bool haveEaten = false;
4940   bool isAdd = true;
4941   if (Tok.is(AsmToken::Plus)) {
4942     Parser.Lex(); // Eat the '+' token.
4943     haveEaten = true;
4944   } else if (Tok.is(AsmToken::Minus)) {
4945     Parser.Lex(); // Eat the '-' token.
4946     isAdd = false;
4947     haveEaten = true;
4948   }
4949 
4950   Tok = Parser.getTok();
4951   int Reg = tryParseRegister();
4952   if (Reg == -1) {
4953     if (!haveEaten)
4954       return MatchOperand_NoMatch;
4955     Error(Tok.getLoc(), "register expected");
4956     return MatchOperand_ParseFail;
4957   }
4958 
4959   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4960                                                   0, S, Tok.getEndLoc()));
4961 
4962   return MatchOperand_Success;
4963 }
4964 
4965 /// Convert parsed operands to MCInst.  Needed here because this instruction
4966 /// only has two register operands, but multiplication is commutative so
4967 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4968 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4969                                     const OperandVector &Operands) {
4970   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4971   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4972   // If we have a three-operand form, make sure to set Rn to be the operand
4973   // that isn't the same as Rd.
4974   unsigned RegOp = 4;
4975   if (Operands.size() == 6 &&
4976       ((ARMOperand &)*Operands[4]).getReg() ==
4977           ((ARMOperand &)*Operands[3]).getReg())
4978     RegOp = 5;
4979   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4980   Inst.addOperand(Inst.getOperand(0));
4981   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4982 }
4983 
4984 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4985                                     const OperandVector &Operands) {
4986   int CondOp = -1, ImmOp = -1;
4987   switch(Inst.getOpcode()) {
4988     case ARM::tB:
4989     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4990 
4991     case ARM::t2B:
4992     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4993 
4994     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4995   }
4996   // first decide whether or not the branch should be conditional
4997   // by looking at it's location relative to an IT block
4998   if(inITBlock()) {
4999     // inside an IT block we cannot have any conditional branches. any
5000     // such instructions needs to be converted to unconditional form
5001     switch(Inst.getOpcode()) {
5002       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5003       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5004     }
5005   } else {
5006     // outside IT blocks we can only have unconditional branches with AL
5007     // condition code or conditional branches with non-AL condition code
5008     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5009     switch(Inst.getOpcode()) {
5010       case ARM::tB:
5011       case ARM::tBcc:
5012         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5013         break;
5014       case ARM::t2B:
5015       case ARM::t2Bcc:
5016         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5017         break;
5018     }
5019   }
5020 
5021   // now decide on encoding size based on branch target range
5022   switch(Inst.getOpcode()) {
5023     // classify tB as either t2B or t1B based on range of immediate operand
5024     case ARM::tB: {
5025       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5026       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5027         Inst.setOpcode(ARM::t2B);
5028       break;
5029     }
5030     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5031     case ARM::tBcc: {
5032       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5033       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5034         Inst.setOpcode(ARM::t2Bcc);
5035       break;
5036     }
5037   }
5038   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5039   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5040 }
5041 
5042 /// Parse an ARM memory expression, return false if successful else return true
5043 /// or an error.  The first token must be a '[' when called.
5044 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5045   MCAsmParser &Parser = getParser();
5046   SMLoc S, E;
5047   if (Parser.getTok().isNot(AsmToken::LBrac))
5048     return TokError("Token is not a Left Bracket");
5049   S = Parser.getTok().getLoc();
5050   Parser.Lex(); // Eat left bracket token.
5051 
5052   const AsmToken &BaseRegTok = Parser.getTok();
5053   int BaseRegNum = tryParseRegister();
5054   if (BaseRegNum == -1)
5055     return Error(BaseRegTok.getLoc(), "register expected");
5056 
5057   // The next token must either be a comma, a colon or a closing bracket.
5058   const AsmToken &Tok = Parser.getTok();
5059   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5060       !Tok.is(AsmToken::RBrac))
5061     return Error(Tok.getLoc(), "malformed memory operand");
5062 
5063   if (Tok.is(AsmToken::RBrac)) {
5064     E = Tok.getEndLoc();
5065     Parser.Lex(); // Eat right bracket token.
5066 
5067     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5068                                              ARM_AM::no_shift, 0, 0, false,
5069                                              S, E));
5070 
5071     // If there's a pre-indexing writeback marker, '!', just add it as a token
5072     // operand. It's rather odd, but syntactically valid.
5073     if (Parser.getTok().is(AsmToken::Exclaim)) {
5074       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5075       Parser.Lex(); // Eat the '!'.
5076     }
5077 
5078     return false;
5079   }
5080 
5081   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5082          "Lost colon or comma in memory operand?!");
5083   if (Tok.is(AsmToken::Comma)) {
5084     Parser.Lex(); // Eat the comma.
5085   }
5086 
5087   // If we have a ':', it's an alignment specifier.
5088   if (Parser.getTok().is(AsmToken::Colon)) {
5089     Parser.Lex(); // Eat the ':'.
5090     E = Parser.getTok().getLoc();
5091     SMLoc AlignmentLoc = Tok.getLoc();
5092 
5093     const MCExpr *Expr;
5094     if (getParser().parseExpression(Expr))
5095      return true;
5096 
5097     // The expression has to be a constant. Memory references with relocations
5098     // don't come through here, as they use the <label> forms of the relevant
5099     // instructions.
5100     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5101     if (!CE)
5102       return Error (E, "constant expression expected");
5103 
5104     unsigned Align = 0;
5105     switch (CE->getValue()) {
5106     default:
5107       return Error(E,
5108                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5109     case 16:  Align = 2; break;
5110     case 32:  Align = 4; break;
5111     case 64:  Align = 8; break;
5112     case 128: Align = 16; break;
5113     case 256: Align = 32; break;
5114     }
5115 
5116     // Now we should have the closing ']'
5117     if (Parser.getTok().isNot(AsmToken::RBrac))
5118       return Error(Parser.getTok().getLoc(), "']' expected");
5119     E = Parser.getTok().getEndLoc();
5120     Parser.Lex(); // Eat right bracket token.
5121 
5122     // Don't worry about range checking the value here. That's handled by
5123     // the is*() predicates.
5124     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5125                                              ARM_AM::no_shift, 0, Align,
5126                                              false, S, E, AlignmentLoc));
5127 
5128     // If there's a pre-indexing writeback marker, '!', just add it as a token
5129     // operand.
5130     if (Parser.getTok().is(AsmToken::Exclaim)) {
5131       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5132       Parser.Lex(); // Eat the '!'.
5133     }
5134 
5135     return false;
5136   }
5137 
5138   // If we have a '#', it's an immediate offset, else assume it's a register
5139   // offset. Be friendly and also accept a plain integer (without a leading
5140   // hash) for gas compatibility.
5141   if (Parser.getTok().is(AsmToken::Hash) ||
5142       Parser.getTok().is(AsmToken::Dollar) ||
5143       Parser.getTok().is(AsmToken::Integer)) {
5144     if (Parser.getTok().isNot(AsmToken::Integer))
5145       Parser.Lex(); // Eat '#' or '$'.
5146     E = Parser.getTok().getLoc();
5147 
5148     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5149     const MCExpr *Offset;
5150     if (getParser().parseExpression(Offset))
5151      return true;
5152 
5153     // The expression has to be a constant. Memory references with relocations
5154     // don't come through here, as they use the <label> forms of the relevant
5155     // instructions.
5156     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5157     if (!CE)
5158       return Error (E, "constant expression expected");
5159 
5160     // If the constant was #-0, represent it as
5161     // std::numeric_limits<int32_t>::min().
5162     int32_t Val = CE->getValue();
5163     if (isNegative && Val == 0)
5164       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5165                                   getContext());
5166 
5167     // Now we should have the closing ']'
5168     if (Parser.getTok().isNot(AsmToken::RBrac))
5169       return Error(Parser.getTok().getLoc(), "']' expected");
5170     E = Parser.getTok().getEndLoc();
5171     Parser.Lex(); // Eat right bracket token.
5172 
5173     // Don't worry about range checking the value here. That's handled by
5174     // the is*() predicates.
5175     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5176                                              ARM_AM::no_shift, 0, 0,
5177                                              false, S, E));
5178 
5179     // If there's a pre-indexing writeback marker, '!', just add it as a token
5180     // operand.
5181     if (Parser.getTok().is(AsmToken::Exclaim)) {
5182       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5183       Parser.Lex(); // Eat the '!'.
5184     }
5185 
5186     return false;
5187   }
5188 
5189   // The register offset is optionally preceded by a '+' or '-'
5190   bool isNegative = false;
5191   if (Parser.getTok().is(AsmToken::Minus)) {
5192     isNegative = true;
5193     Parser.Lex(); // Eat the '-'.
5194   } else if (Parser.getTok().is(AsmToken::Plus)) {
5195     // Nothing to do.
5196     Parser.Lex(); // Eat the '+'.
5197   }
5198 
5199   E = Parser.getTok().getLoc();
5200   int OffsetRegNum = tryParseRegister();
5201   if (OffsetRegNum == -1)
5202     return Error(E, "register expected");
5203 
5204   // If there's a shift operator, handle it.
5205   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5206   unsigned ShiftImm = 0;
5207   if (Parser.getTok().is(AsmToken::Comma)) {
5208     Parser.Lex(); // Eat the ','.
5209     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5210       return true;
5211   }
5212 
5213   // Now we should have the closing ']'
5214   if (Parser.getTok().isNot(AsmToken::RBrac))
5215     return Error(Parser.getTok().getLoc(), "']' expected");
5216   E = Parser.getTok().getEndLoc();
5217   Parser.Lex(); // Eat right bracket token.
5218 
5219   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5220                                            ShiftType, ShiftImm, 0, isNegative,
5221                                            S, E));
5222 
5223   // If there's a pre-indexing writeback marker, '!', just add it as a token
5224   // operand.
5225   if (Parser.getTok().is(AsmToken::Exclaim)) {
5226     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5227     Parser.Lex(); // Eat the '!'.
5228   }
5229 
5230   return false;
5231 }
5232 
5233 /// parseMemRegOffsetShift - one of these two:
5234 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5235 ///   rrx
5236 /// return true if it parses a shift otherwise it returns false.
5237 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5238                                           unsigned &Amount) {
5239   MCAsmParser &Parser = getParser();
5240   SMLoc Loc = Parser.getTok().getLoc();
5241   const AsmToken &Tok = Parser.getTok();
5242   if (Tok.isNot(AsmToken::Identifier))
5243     return Error(Loc, "illegal shift operator");
5244   StringRef ShiftName = Tok.getString();
5245   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5246       ShiftName == "asl" || ShiftName == "ASL")
5247     St = ARM_AM::lsl;
5248   else if (ShiftName == "lsr" || ShiftName == "LSR")
5249     St = ARM_AM::lsr;
5250   else if (ShiftName == "asr" || ShiftName == "ASR")
5251     St = ARM_AM::asr;
5252   else if (ShiftName == "ror" || ShiftName == "ROR")
5253     St = ARM_AM::ror;
5254   else if (ShiftName == "rrx" || ShiftName == "RRX")
5255     St = ARM_AM::rrx;
5256   else
5257     return Error(Loc, "illegal shift operator");
5258   Parser.Lex(); // Eat shift type token.
5259 
5260   // rrx stands alone.
5261   Amount = 0;
5262   if (St != ARM_AM::rrx) {
5263     Loc = Parser.getTok().getLoc();
5264     // A '#' and a shift amount.
5265     const AsmToken &HashTok = Parser.getTok();
5266     if (HashTok.isNot(AsmToken::Hash) &&
5267         HashTok.isNot(AsmToken::Dollar))
5268       return Error(HashTok.getLoc(), "'#' expected");
5269     Parser.Lex(); // Eat hash token.
5270 
5271     const MCExpr *Expr;
5272     if (getParser().parseExpression(Expr))
5273       return true;
5274     // Range check the immediate.
5275     // lsl, ror: 0 <= imm <= 31
5276     // lsr, asr: 0 <= imm <= 32
5277     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5278     if (!CE)
5279       return Error(Loc, "shift amount must be an immediate");
5280     int64_t Imm = CE->getValue();
5281     if (Imm < 0 ||
5282         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5283         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5284       return Error(Loc, "immediate shift value out of range");
5285     // If <ShiftTy> #0, turn it into a no_shift.
5286     if (Imm == 0)
5287       St = ARM_AM::lsl;
5288     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5289     if (Imm == 32)
5290       Imm = 0;
5291     Amount = Imm;
5292   }
5293 
5294   return false;
5295 }
5296 
5297 /// parseFPImm - A floating point immediate expression operand.
5298 OperandMatchResultTy
5299 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5300   MCAsmParser &Parser = getParser();
5301   // Anything that can accept a floating point constant as an operand
5302   // needs to go through here, as the regular parseExpression is
5303   // integer only.
5304   //
5305   // This routine still creates a generic Immediate operand, containing
5306   // a bitcast of the 64-bit floating point value. The various operands
5307   // that accept floats can check whether the value is valid for them
5308   // via the standard is*() predicates.
5309 
5310   SMLoc S = Parser.getTok().getLoc();
5311 
5312   if (Parser.getTok().isNot(AsmToken::Hash) &&
5313       Parser.getTok().isNot(AsmToken::Dollar))
5314     return MatchOperand_NoMatch;
5315 
5316   // Disambiguate the VMOV forms that can accept an FP immediate.
5317   // vmov.f32 <sreg>, #imm
5318   // vmov.f64 <dreg>, #imm
5319   // vmov.f32 <dreg>, #imm  @ vector f32x2
5320   // vmov.f32 <qreg>, #imm  @ vector f32x4
5321   //
5322   // There are also the NEON VMOV instructions which expect an
5323   // integer constant. Make sure we don't try to parse an FPImm
5324   // for these:
5325   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5326   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5327   bool isVmovf = TyOp.isToken() &&
5328                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5329                   TyOp.getToken() == ".f16");
5330   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5331   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5332                                          Mnemonic.getToken() == "fconsts");
5333   if (!(isVmovf || isFconst))
5334     return MatchOperand_NoMatch;
5335 
5336   Parser.Lex(); // Eat '#' or '$'.
5337 
5338   // Handle negation, as that still comes through as a separate token.
5339   bool isNegative = false;
5340   if (Parser.getTok().is(AsmToken::Minus)) {
5341     isNegative = true;
5342     Parser.Lex();
5343   }
5344   const AsmToken &Tok = Parser.getTok();
5345   SMLoc Loc = Tok.getLoc();
5346   if (Tok.is(AsmToken::Real) && isVmovf) {
5347     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5348     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5349     // If we had a '-' in front, toggle the sign bit.
5350     IntVal ^= (uint64_t)isNegative << 31;
5351     Parser.Lex(); // Eat the token.
5352     Operands.push_back(ARMOperand::CreateImm(
5353           MCConstantExpr::create(IntVal, getContext()),
5354           S, Parser.getTok().getLoc()));
5355     return MatchOperand_Success;
5356   }
5357   // Also handle plain integers. Instructions which allow floating point
5358   // immediates also allow a raw encoded 8-bit value.
5359   if (Tok.is(AsmToken::Integer) && isFconst) {
5360     int64_t Val = Tok.getIntVal();
5361     Parser.Lex(); // Eat the token.
5362     if (Val > 255 || Val < 0) {
5363       Error(Loc, "encoded floating point value out of range");
5364       return MatchOperand_ParseFail;
5365     }
5366     float RealVal = ARM_AM::getFPImmFloat(Val);
5367     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5368 
5369     Operands.push_back(ARMOperand::CreateImm(
5370         MCConstantExpr::create(Val, getContext()), S,
5371         Parser.getTok().getLoc()));
5372     return MatchOperand_Success;
5373   }
5374 
5375   Error(Loc, "invalid floating point immediate");
5376   return MatchOperand_ParseFail;
5377 }
5378 
5379 /// Parse a arm instruction operand.  For now this parses the operand regardless
5380 /// of the mnemonic.
5381 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5382   MCAsmParser &Parser = getParser();
5383   SMLoc S, E;
5384 
5385   // Check if the current operand has a custom associated parser, if so, try to
5386   // custom parse the operand, or fallback to the general approach.
5387   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5388   if (ResTy == MatchOperand_Success)
5389     return false;
5390   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5391   // there was a match, but an error occurred, in which case, just return that
5392   // the operand parsing failed.
5393   if (ResTy == MatchOperand_ParseFail)
5394     return true;
5395 
5396   switch (getLexer().getKind()) {
5397   default:
5398     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5399     return true;
5400   case AsmToken::Identifier: {
5401     // If we've seen a branch mnemonic, the next operand must be a label.  This
5402     // is true even if the label is a register name.  So "br r1" means branch to
5403     // label "r1".
5404     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5405     if (!ExpectLabel) {
5406       if (!tryParseRegisterWithWriteBack(Operands))
5407         return false;
5408       int Res = tryParseShiftRegister(Operands);
5409       if (Res == 0) // success
5410         return false;
5411       else if (Res == -1) // irrecoverable error
5412         return true;
5413       // If this is VMRS, check for the apsr_nzcv operand.
5414       if (Mnemonic == "vmrs" &&
5415           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5416         S = Parser.getTok().getLoc();
5417         Parser.Lex();
5418         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5419         return false;
5420       }
5421     }
5422 
5423     // Fall though for the Identifier case that is not a register or a
5424     // special name.
5425     LLVM_FALLTHROUGH;
5426   }
5427   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5428   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5429   case AsmToken::String:  // quoted label names.
5430   case AsmToken::Dot: {   // . as a branch target
5431     // This was not a register so parse other operands that start with an
5432     // identifier (like labels) as expressions and create them as immediates.
5433     const MCExpr *IdVal;
5434     S = Parser.getTok().getLoc();
5435     if (getParser().parseExpression(IdVal))
5436       return true;
5437     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5438     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5439     return false;
5440   }
5441   case AsmToken::LBrac:
5442     return parseMemory(Operands);
5443   case AsmToken::LCurly:
5444     return parseRegisterList(Operands);
5445   case AsmToken::Dollar:
5446   case AsmToken::Hash:
5447     // #42 -> immediate.
5448     S = Parser.getTok().getLoc();
5449     Parser.Lex();
5450 
5451     if (Parser.getTok().isNot(AsmToken::Colon)) {
5452       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5453       const MCExpr *ImmVal;
5454       if (getParser().parseExpression(ImmVal))
5455         return true;
5456       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5457       if (CE) {
5458         int32_t Val = CE->getValue();
5459         if (isNegative && Val == 0)
5460           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5461                                           getContext());
5462       }
5463       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5464       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5465 
5466       // There can be a trailing '!' on operands that we want as a separate
5467       // '!' Token operand. Handle that here. For example, the compatibility
5468       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5469       if (Parser.getTok().is(AsmToken::Exclaim)) {
5470         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5471                                                    Parser.getTok().getLoc()));
5472         Parser.Lex(); // Eat exclaim token
5473       }
5474       return false;
5475     }
5476     // w/ a ':' after the '#', it's just like a plain ':'.
5477     LLVM_FALLTHROUGH;
5478 
5479   case AsmToken::Colon: {
5480     S = Parser.getTok().getLoc();
5481     // ":lower16:" and ":upper16:" expression prefixes
5482     // FIXME: Check it's an expression prefix,
5483     // e.g. (FOO - :lower16:BAR) isn't legal.
5484     ARMMCExpr::VariantKind RefKind;
5485     if (parsePrefix(RefKind))
5486       return true;
5487 
5488     const MCExpr *SubExprVal;
5489     if (getParser().parseExpression(SubExprVal))
5490       return true;
5491 
5492     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5493                                               getContext());
5494     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5495     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5496     return false;
5497   }
5498   case AsmToken::Equal: {
5499     S = Parser.getTok().getLoc();
5500     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5501       return Error(S, "unexpected token in operand");
5502     Parser.Lex(); // Eat '='
5503     const MCExpr *SubExprVal;
5504     if (getParser().parseExpression(SubExprVal))
5505       return true;
5506     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5507 
5508     // execute-only: we assume that assembly programmers know what they are
5509     // doing and allow literal pool creation here
5510     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5511     return false;
5512   }
5513   }
5514 }
5515 
5516 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5517 //  :lower16: and :upper16:.
5518 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5519   MCAsmParser &Parser = getParser();
5520   RefKind = ARMMCExpr::VK_ARM_None;
5521 
5522   // consume an optional '#' (GNU compatibility)
5523   if (getLexer().is(AsmToken::Hash))
5524     Parser.Lex();
5525 
5526   // :lower16: and :upper16: modifiers
5527   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5528   Parser.Lex(); // Eat ':'
5529 
5530   if (getLexer().isNot(AsmToken::Identifier)) {
5531     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5532     return true;
5533   }
5534 
5535   enum {
5536     COFF = (1 << MCObjectFileInfo::IsCOFF),
5537     ELF = (1 << MCObjectFileInfo::IsELF),
5538     MACHO = (1 << MCObjectFileInfo::IsMachO),
5539     WASM = (1 << MCObjectFileInfo::IsWasm),
5540   };
5541   static const struct PrefixEntry {
5542     const char *Spelling;
5543     ARMMCExpr::VariantKind VariantKind;
5544     uint8_t SupportedFormats;
5545   } PrefixEntries[] = {
5546     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5547     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5548   };
5549 
5550   StringRef IDVal = Parser.getTok().getIdentifier();
5551 
5552   const auto &Prefix =
5553       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5554                    [&IDVal](const PrefixEntry &PE) {
5555                       return PE.Spelling == IDVal;
5556                    });
5557   if (Prefix == std::end(PrefixEntries)) {
5558     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5559     return true;
5560   }
5561 
5562   uint8_t CurrentFormat;
5563   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5564   case MCObjectFileInfo::IsMachO:
5565     CurrentFormat = MACHO;
5566     break;
5567   case MCObjectFileInfo::IsELF:
5568     CurrentFormat = ELF;
5569     break;
5570   case MCObjectFileInfo::IsCOFF:
5571     CurrentFormat = COFF;
5572     break;
5573   case MCObjectFileInfo::IsWasm:
5574     CurrentFormat = WASM;
5575     break;
5576   }
5577 
5578   if (~Prefix->SupportedFormats & CurrentFormat) {
5579     Error(Parser.getTok().getLoc(),
5580           "cannot represent relocation in the current file format");
5581     return true;
5582   }
5583 
5584   RefKind = Prefix->VariantKind;
5585   Parser.Lex();
5586 
5587   if (getLexer().isNot(AsmToken::Colon)) {
5588     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5589     return true;
5590   }
5591   Parser.Lex(); // Eat the last ':'
5592 
5593   return false;
5594 }
5595 
5596 /// Given a mnemonic, split out possible predication code and carry
5597 /// setting letters to form a canonical mnemonic and flags.
5598 //
5599 // FIXME: Would be nice to autogen this.
5600 // FIXME: This is a bit of a maze of special cases.
5601 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5602                                       unsigned &PredicationCode,
5603                                       bool &CarrySetting,
5604                                       unsigned &ProcessorIMod,
5605                                       StringRef &ITMask) {
5606   PredicationCode = ARMCC::AL;
5607   CarrySetting = false;
5608   ProcessorIMod = 0;
5609 
5610   // Ignore some mnemonics we know aren't predicated forms.
5611   //
5612   // FIXME: Would be nice to autogen this.
5613   if ((Mnemonic == "movs" && isThumb()) ||
5614       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5615       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5616       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5617       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5618       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5619       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5620       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5621       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5622       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5623       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5624       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5625       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5626       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5627       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
5628       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5629       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
5630       Mnemonic == "vfmal" || Mnemonic == "vfmsl")
5631     return Mnemonic;
5632 
5633   // First, split out any predication code. Ignore mnemonics we know aren't
5634   // predicated but do have a carry-set and so weren't caught above.
5635   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5636       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5637       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5638       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5639     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
5640     if (CC != ~0U) {
5641       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5642       PredicationCode = CC;
5643     }
5644   }
5645 
5646   // Next, determine if we have a carry setting bit. We explicitly ignore all
5647   // the instructions we know end in 's'.
5648   if (Mnemonic.endswith("s") &&
5649       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5650         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5651         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5652         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5653         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5654         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5655         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5656         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5657         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5658         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5659         (Mnemonic == "movs" && isThumb()))) {
5660     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5661     CarrySetting = true;
5662   }
5663 
5664   // The "cps" instruction can have a interrupt mode operand which is glued into
5665   // the mnemonic. Check if this is the case, split it and parse the imod op
5666   if (Mnemonic.startswith("cps")) {
5667     // Split out any imod code.
5668     unsigned IMod =
5669       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5670       .Case("ie", ARM_PROC::IE)
5671       .Case("id", ARM_PROC::ID)
5672       .Default(~0U);
5673     if (IMod != ~0U) {
5674       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5675       ProcessorIMod = IMod;
5676     }
5677   }
5678 
5679   // The "it" instruction has the condition mask on the end of the mnemonic.
5680   if (Mnemonic.startswith("it")) {
5681     ITMask = Mnemonic.slice(2, Mnemonic.size());
5682     Mnemonic = Mnemonic.slice(0, 2);
5683   }
5684 
5685   return Mnemonic;
5686 }
5687 
5688 /// Given a canonical mnemonic, determine if the instruction ever allows
5689 /// inclusion of carry set or predication code operands.
5690 //
5691 // FIXME: It would be nice to autogen this.
5692 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5693                                          bool &CanAcceptCarrySet,
5694                                          bool &CanAcceptPredicationCode) {
5695   CanAcceptCarrySet =
5696       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5697       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5698       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5699       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5700       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5701       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5702       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5703       (!isThumb() &&
5704        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5705         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5706 
5707   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5708       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5709       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5710       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5711       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5712       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5713       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5714       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5715       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5716       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5717       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5718       Mnemonic == "vmovx" || Mnemonic == "vins" ||
5719       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5720       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
5721       Mnemonic == "vfmal" || Mnemonic == "vfmsl") {
5722     // These mnemonics are never predicable
5723     CanAcceptPredicationCode = false;
5724   } else if (!isThumb()) {
5725     // Some instructions are only predicable in Thumb mode
5726     CanAcceptPredicationCode =
5727         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5728         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5729         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
5730         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
5731         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
5732         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
5733         Mnemonic != "tsb" &&
5734         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
5735   } else if (isThumbOne()) {
5736     if (hasV6MOps())
5737       CanAcceptPredicationCode = Mnemonic != "movs";
5738     else
5739       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5740   } else
5741     CanAcceptPredicationCode = true;
5742 }
5743 
5744 // Some Thumb instructions have two operand forms that are not
5745 // available as three operand, convert to two operand form if possible.
5746 //
5747 // FIXME: We would really like to be able to tablegen'erate this.
5748 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5749                                                  bool CarrySetting,
5750                                                  OperandVector &Operands) {
5751   if (Operands.size() != 6)
5752     return;
5753 
5754   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5755         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5756   if (!Op3.isReg() || !Op4.isReg())
5757     return;
5758 
5759   auto Op3Reg = Op3.getReg();
5760   auto Op4Reg = Op4.getReg();
5761 
5762   // For most Thumb2 cases we just generate the 3 operand form and reduce
5763   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5764   // won't accept SP or PC so we do the transformation here taking care
5765   // with immediate range in the 'add sp, sp #imm' case.
5766   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5767   if (isThumbTwo()) {
5768     if (Mnemonic != "add")
5769       return;
5770     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5771                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5772     if (!TryTransform) {
5773       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5774                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5775                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5776                        Op5.isImm() && !Op5.isImm0_508s4());
5777     }
5778     if (!TryTransform)
5779       return;
5780   } else if (!isThumbOne())
5781     return;
5782 
5783   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5784         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5785         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5786         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5787     return;
5788 
5789   // If first 2 operands of a 3 operand instruction are the same
5790   // then transform to 2 operand version of the same instruction
5791   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5792   bool Transform = Op3Reg == Op4Reg;
5793 
5794   // For communtative operations, we might be able to transform if we swap
5795   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5796   // as tADDrsp.
5797   const ARMOperand *LastOp = &Op5;
5798   bool Swap = false;
5799   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5800       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5801        Mnemonic == "and" || Mnemonic == "eor" ||
5802        Mnemonic == "adc" || Mnemonic == "orr")) {
5803     Swap = true;
5804     LastOp = &Op4;
5805     Transform = true;
5806   }
5807 
5808   // If both registers are the same then remove one of them from
5809   // the operand list, with certain exceptions.
5810   if (Transform) {
5811     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5812     // 2 operand forms don't exist.
5813     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5814         LastOp->isReg())
5815       Transform = false;
5816 
5817     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5818     // 3-bits because the ARMARM says not to.
5819     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5820       Transform = false;
5821   }
5822 
5823   if (Transform) {
5824     if (Swap)
5825       std::swap(Op4, Op5);
5826     Operands.erase(Operands.begin() + 3);
5827   }
5828 }
5829 
5830 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5831                                           OperandVector &Operands) {
5832   // FIXME: This is all horribly hacky. We really need a better way to deal
5833   // with optional operands like this in the matcher table.
5834 
5835   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5836   // another does not. Specifically, the MOVW instruction does not. So we
5837   // special case it here and remove the defaulted (non-setting) cc_out
5838   // operand if that's the instruction we're trying to match.
5839   //
5840   // We do this as post-processing of the explicit operands rather than just
5841   // conditionally adding the cc_out in the first place because we need
5842   // to check the type of the parsed immediate operand.
5843   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5844       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5845       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5846       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5847     return true;
5848 
5849   // Register-register 'add' for thumb does not have a cc_out operand
5850   // when there are only two register operands.
5851   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5852       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5853       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5854       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5855     return true;
5856   // Register-register 'add' for thumb does not have a cc_out operand
5857   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5858   // have to check the immediate range here since Thumb2 has a variant
5859   // that can handle a different range and has a cc_out operand.
5860   if (((isThumb() && Mnemonic == "add") ||
5861        (isThumbTwo() && Mnemonic == "sub")) &&
5862       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5863       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5864       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5865       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5866       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5867        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5868     return true;
5869   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5870   // imm0_4095 variant. That's the least-preferred variant when
5871   // selecting via the generic "add" mnemonic, so to know that we
5872   // should remove the cc_out operand, we have to explicitly check that
5873   // it's not one of the other variants. Ugh.
5874   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5875       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5876       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5877       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5878     // Nest conditions rather than one big 'if' statement for readability.
5879     //
5880     // If both registers are low, we're in an IT block, and the immediate is
5881     // in range, we should use encoding T1 instead, which has a cc_out.
5882     if (inITBlock() &&
5883         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5884         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5885         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5886       return false;
5887     // Check against T3. If the second register is the PC, this is an
5888     // alternate form of ADR, which uses encoding T4, so check for that too.
5889     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5890         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5891       return false;
5892 
5893     // Otherwise, we use encoding T4, which does not have a cc_out
5894     // operand.
5895     return true;
5896   }
5897 
5898   // The thumb2 multiply instruction doesn't have a CCOut register, so
5899   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5900   // use the 16-bit encoding or not.
5901   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5902       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5903       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5904       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5905       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5906       // If the registers aren't low regs, the destination reg isn't the
5907       // same as one of the source regs, or the cc_out operand is zero
5908       // outside of an IT block, we have to use the 32-bit encoding, so
5909       // remove the cc_out operand.
5910       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5911        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5912        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5913        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5914                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5915                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5916                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5917     return true;
5918 
5919   // Also check the 'mul' syntax variant that doesn't specify an explicit
5920   // destination register.
5921   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5922       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5923       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5924       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5925       // If the registers aren't low regs  or the cc_out operand is zero
5926       // outside of an IT block, we have to use the 32-bit encoding, so
5927       // remove the cc_out operand.
5928       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5929        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5930        !inITBlock()))
5931     return true;
5932 
5933   // Register-register 'add/sub' for thumb does not have a cc_out operand
5934   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5935   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5936   // right, this will result in better diagnostics (which operand is off)
5937   // anyway.
5938   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5939       (Operands.size() == 5 || Operands.size() == 6) &&
5940       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5941       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5942       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5943       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5944        (Operands.size() == 6 &&
5945         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5946     return true;
5947 
5948   return false;
5949 }
5950 
5951 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5952                                               OperandVector &Operands) {
5953   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
5954   unsigned RegIdx = 3;
5955   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx") &&
5956       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5957        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5958     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5959         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5960          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5961       RegIdx = 4;
5962 
5963     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5964         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5965              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5966          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5967              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5968       return true;
5969   }
5970   return false;
5971 }
5972 
5973 static bool isDataTypeToken(StringRef Tok) {
5974   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5975     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5976     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5977     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5978     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5979     Tok == ".f" || Tok == ".d";
5980 }
5981 
5982 // FIXME: This bit should probably be handled via an explicit match class
5983 // in the .td files that matches the suffix instead of having it be
5984 // a literal string token the way it is now.
5985 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5986   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5987 }
5988 
5989 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5990                                  unsigned VariantID);
5991 
5992 // The GNU assembler has aliases of ldrd and strd with the second register
5993 // omitted. We don't have a way to do that in tablegen, so fix it up here.
5994 //
5995 // We have to be careful to not emit an invalid Rt2 here, because the rest of
5996 // the assmebly parser could then generate confusing diagnostics refering to
5997 // it. If we do find anything that prevents us from doing the transformation we
5998 // bail out, and let the assembly parser report an error on the instruction as
5999 // it is written.
6000 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6001                                      OperandVector &Operands) {
6002   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6003     return;
6004   if (Operands.size() < 4)
6005     return;
6006 
6007   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6008   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6009 
6010   if (!Op2.isReg())
6011     return;
6012   if (!Op3.isMem())
6013     return;
6014 
6015   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6016   if (!GPR.contains(Op2.getReg()))
6017     return;
6018 
6019   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6020   if (!isThumb() && (RtEncoding & 1)) {
6021     // In ARM mode, the registers must be from an aligned pair, this
6022     // restriction does not apply in Thumb mode.
6023     return;
6024   }
6025   if (Op2.getReg() == ARM::PC)
6026     return;
6027   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6028   if (!PairedReg || PairedReg == ARM::PC ||
6029       (PairedReg == ARM::SP && !hasV8Ops()))
6030     return;
6031 
6032   Operands.insert(
6033       Operands.begin() + 3,
6034       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6035 }
6036 
6037 /// Parse an arm instruction mnemonic followed by its operands.
6038 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6039                                     SMLoc NameLoc, OperandVector &Operands) {
6040   MCAsmParser &Parser = getParser();
6041 
6042   // Apply mnemonic aliases before doing anything else, as the destination
6043   // mnemonic may include suffices and we want to handle them normally.
6044   // The generic tblgen'erated code does this later, at the start of
6045   // MatchInstructionImpl(), but that's too late for aliases that include
6046   // any sort of suffix.
6047   uint64_t AvailableFeatures = getAvailableFeatures();
6048   unsigned AssemblerDialect = getParser().getAssemblerDialect();
6049   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
6050 
6051   // First check for the ARM-specific .req directive.
6052   if (Parser.getTok().is(AsmToken::Identifier) &&
6053       Parser.getTok().getIdentifier() == ".req") {
6054     parseDirectiveReq(Name, NameLoc);
6055     // We always return 'error' for this, as we're done with this
6056     // statement and don't need to match the 'instruction."
6057     return true;
6058   }
6059 
6060   // Create the leading tokens for the mnemonic, split by '.' characters.
6061   size_t Start = 0, Next = Name.find('.');
6062   StringRef Mnemonic = Name.slice(Start, Next);
6063 
6064   // Split out the predication code and carry setting flag from the mnemonic.
6065   unsigned PredicationCode;
6066   unsigned ProcessorIMod;
6067   bool CarrySetting;
6068   StringRef ITMask;
6069   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
6070                            ProcessorIMod, ITMask);
6071 
6072   // In Thumb1, only the branch (B) instruction can be predicated.
6073   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
6074     return Error(NameLoc, "conditional execution not supported in Thumb1");
6075   }
6076 
6077   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
6078 
6079   // Handle the IT instruction ITMask. Convert it to a bitmask. This
6080   // is the mask as it will be for the IT encoding if the conditional
6081   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
6082   // where the conditional bit0 is zero, the instruction post-processing
6083   // will adjust the mask accordingly.
6084   if (Mnemonic == "it") {
6085     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
6086     if (ITMask.size() > 3) {
6087       return Error(Loc, "too many conditions on IT instruction");
6088     }
6089     unsigned Mask = 8;
6090     for (unsigned i = ITMask.size(); i != 0; --i) {
6091       char pos = ITMask[i - 1];
6092       if (pos != 't' && pos != 'e') {
6093         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
6094       }
6095       Mask >>= 1;
6096       if (ITMask[i - 1] == 't')
6097         Mask |= 8;
6098     }
6099     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
6100   }
6101 
6102   // FIXME: This is all a pretty gross hack. We should automatically handle
6103   // optional operands like this via tblgen.
6104 
6105   // Next, add the CCOut and ConditionCode operands, if needed.
6106   //
6107   // For mnemonics which can ever incorporate a carry setting bit or predication
6108   // code, our matching model involves us always generating CCOut and
6109   // ConditionCode operands to match the mnemonic "as written" and then we let
6110   // the matcher deal with finding the right instruction or generating an
6111   // appropriate error.
6112   bool CanAcceptCarrySet, CanAcceptPredicationCode;
6113   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
6114 
6115   // If we had a carry-set on an instruction that can't do that, issue an
6116   // error.
6117   if (!CanAcceptCarrySet && CarrySetting) {
6118     return Error(NameLoc, "instruction '" + Mnemonic +
6119                  "' can not set flags, but 's' suffix specified");
6120   }
6121   // If we had a predication code on an instruction that can't do that, issue an
6122   // error.
6123   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6124     return Error(NameLoc, "instruction '" + Mnemonic +
6125                  "' is not predicable, but condition code specified");
6126   }
6127 
6128   // Add the carry setting operand, if necessary.
6129   if (CanAcceptCarrySet) {
6130     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6131     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6132                                                Loc));
6133   }
6134 
6135   // Add the predication code operand, if necessary.
6136   if (CanAcceptPredicationCode) {
6137     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6138                                       CarrySetting);
6139     Operands.push_back(ARMOperand::CreateCondCode(
6140                          ARMCC::CondCodes(PredicationCode), Loc));
6141   }
6142 
6143   // Add the processor imod operand, if necessary.
6144   if (ProcessorIMod) {
6145     Operands.push_back(ARMOperand::CreateImm(
6146           MCConstantExpr::create(ProcessorIMod, getContext()),
6147                                  NameLoc, NameLoc));
6148   } else if (Mnemonic == "cps" && isMClass()) {
6149     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6150   }
6151 
6152   // Add the remaining tokens in the mnemonic.
6153   while (Next != StringRef::npos) {
6154     Start = Next;
6155     Next = Name.find('.', Start + 1);
6156     StringRef ExtraToken = Name.slice(Start, Next);
6157 
6158     // Some NEON instructions have an optional datatype suffix that is
6159     // completely ignored. Check for that.
6160     if (isDataTypeToken(ExtraToken) &&
6161         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6162       continue;
6163 
6164     // For for ARM mode generate an error if the .n qualifier is used.
6165     if (ExtraToken == ".n" && !isThumb()) {
6166       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6167       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6168                    "arm mode");
6169     }
6170 
6171     // The .n qualifier is always discarded as that is what the tables
6172     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6173     // so discard it to avoid errors that can be caused by the matcher.
6174     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6175       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6176       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6177     }
6178   }
6179 
6180   // Read the remaining operands.
6181   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6182     // Read the first operand.
6183     if (parseOperand(Operands, Mnemonic)) {
6184       return true;
6185     }
6186 
6187     while (parseOptionalToken(AsmToken::Comma)) {
6188       // Parse and remember the operand.
6189       if (parseOperand(Operands, Mnemonic)) {
6190         return true;
6191       }
6192     }
6193   }
6194 
6195   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6196     return true;
6197 
6198   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6199 
6200   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6201   // do and don't have a cc_out optional-def operand. With some spot-checks
6202   // of the operand list, we can figure out which variant we're trying to
6203   // parse and adjust accordingly before actually matching. We shouldn't ever
6204   // try to remove a cc_out operand that was explicitly set on the
6205   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6206   // table driven matcher doesn't fit well with the ARM instruction set.
6207   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6208     Operands.erase(Operands.begin() + 1);
6209 
6210   // Some instructions have the same mnemonic, but don't always
6211   // have a predicate. Distinguish them here and delete the
6212   // predicate if needed.
6213   if (PredicationCode == ARMCC::AL &&
6214       shouldOmitPredicateOperand(Mnemonic, Operands))
6215     Operands.erase(Operands.begin() + 1);
6216 
6217   // ARM mode 'blx' need special handling, as the register operand version
6218   // is predicable, but the label operand version is not. So, we can't rely
6219   // on the Mnemonic based checking to correctly figure out when to put
6220   // a k_CondCode operand in the list. If we're trying to match the label
6221   // version, remove the k_CondCode operand here.
6222   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6223       static_cast<ARMOperand &>(*Operands[2]).isImm())
6224     Operands.erase(Operands.begin() + 1);
6225 
6226   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6227   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6228   // a single GPRPair reg operand is used in the .td file to replace the two
6229   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6230   // expressed as a GPRPair, so we have to manually merge them.
6231   // FIXME: We would really like to be able to tablegen'erate this.
6232   if (!isThumb() && Operands.size() > 4 &&
6233       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6234        Mnemonic == "stlexd")) {
6235     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6236     unsigned Idx = isLoad ? 2 : 3;
6237     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6238     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6239 
6240     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6241     // Adjust only if Op1 and Op2 are GPRs.
6242     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6243         MRC.contains(Op2.getReg())) {
6244       unsigned Reg1 = Op1.getReg();
6245       unsigned Reg2 = Op2.getReg();
6246       unsigned Rt = MRI->getEncodingValue(Reg1);
6247       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6248 
6249       // Rt2 must be Rt + 1 and Rt must be even.
6250       if (Rt + 1 != Rt2 || (Rt & 1)) {
6251         return Error(Op2.getStartLoc(),
6252                      isLoad ? "destination operands must be sequential"
6253                             : "source operands must be sequential");
6254       }
6255       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6256           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6257       Operands[Idx] =
6258           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6259       Operands.erase(Operands.begin() + Idx + 1);
6260     }
6261   }
6262 
6263   // GNU Assembler extension (compatibility).
6264   fixupGNULDRDAlias(Mnemonic, Operands);
6265 
6266   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6267   // does not fit with other "subs" and tblgen.
6268   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6269   // so the Mnemonic is the original name "subs" and delete the predicate
6270   // operand so it will match the table entry.
6271   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6272       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6273       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6274       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6275       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6276       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6277     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6278     Operands.erase(Operands.begin() + 1);
6279   }
6280   return false;
6281 }
6282 
6283 // Validate context-sensitive operand constraints.
6284 
6285 // return 'true' if register list contains non-low GPR registers,
6286 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6287 // 'containsReg' to true.
6288 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6289                                  unsigned Reg, unsigned HiReg,
6290                                  bool &containsReg) {
6291   containsReg = false;
6292   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6293     unsigned OpReg = Inst.getOperand(i).getReg();
6294     if (OpReg == Reg)
6295       containsReg = true;
6296     // Anything other than a low register isn't legal here.
6297     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6298       return true;
6299   }
6300   return false;
6301 }
6302 
6303 // Check if the specified regisgter is in the register list of the inst,
6304 // starting at the indicated operand number.
6305 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6306   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6307     unsigned OpReg = Inst.getOperand(i).getReg();
6308     if (OpReg == Reg)
6309       return true;
6310   }
6311   return false;
6312 }
6313 
6314 // Return true if instruction has the interesting property of being
6315 // allowed in IT blocks, but not being predicable.
6316 static bool instIsBreakpoint(const MCInst &Inst) {
6317     return Inst.getOpcode() == ARM::tBKPT ||
6318            Inst.getOpcode() == ARM::BKPT ||
6319            Inst.getOpcode() == ARM::tHLT ||
6320            Inst.getOpcode() == ARM::HLT;
6321 }
6322 
6323 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6324                                        const OperandVector &Operands,
6325                                        unsigned ListNo, bool IsARPop) {
6326   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6327   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6328 
6329   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6330   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6331   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6332 
6333   if (!IsARPop && ListContainsSP)
6334     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6335                  "SP may not be in the register list");
6336   else if (ListContainsPC && ListContainsLR)
6337     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6338                  "PC and LR may not be in the register list simultaneously");
6339   return false;
6340 }
6341 
6342 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6343                                        const OperandVector &Operands,
6344                                        unsigned ListNo) {
6345   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6346   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6347 
6348   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6349   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6350 
6351   if (ListContainsSP && ListContainsPC)
6352     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6353                  "SP and PC may not be in the register list");
6354   else if (ListContainsSP)
6355     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6356                  "SP may not be in the register list");
6357   else if (ListContainsPC)
6358     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6359                  "PC may not be in the register list");
6360   return false;
6361 }
6362 
6363 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
6364                                     const OperandVector &Operands,
6365                                     bool Load, bool ARMMode, bool Writeback) {
6366   unsigned RtIndex = Load || !Writeback ? 0 : 1;
6367   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
6368   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
6369 
6370   if (ARMMode) {
6371     // Rt can't be R14.
6372     if (Rt == 14)
6373       return Error(Operands[3]->getStartLoc(),
6374                   "Rt can't be R14");
6375 
6376     // Rt must be even-numbered.
6377     if ((Rt & 1) == 1)
6378       return Error(Operands[3]->getStartLoc(),
6379                    "Rt must be even-numbered");
6380 
6381     // Rt2 must be Rt + 1.
6382     if (Rt2 != Rt + 1) {
6383       if (Load)
6384         return Error(Operands[3]->getStartLoc(),
6385                      "destination operands must be sequential");
6386       else
6387         return Error(Operands[3]->getStartLoc(),
6388                      "source operands must be sequential");
6389     }
6390 
6391     // FIXME: Diagnose m == 15
6392     // FIXME: Diagnose ldrd with m == t || m == t2.
6393   }
6394 
6395   if (!ARMMode && Load) {
6396     if (Rt2 == Rt)
6397       return Error(Operands[3]->getStartLoc(),
6398                    "destination operands can't be identical");
6399   }
6400 
6401   if (Writeback) {
6402     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6403 
6404     if (Rn == Rt || Rn == Rt2) {
6405       if (Load)
6406         return Error(Operands[3]->getStartLoc(),
6407                      "base register needs to be different from destination "
6408                      "registers");
6409       else
6410         return Error(Operands[3]->getStartLoc(),
6411                      "source register and base register can't be identical");
6412     }
6413 
6414     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
6415     // (Except the immediate form of ldrd?)
6416   }
6417 
6418   return false;
6419 }
6420 
6421 
6422 // FIXME: We would really like to be able to tablegen'erate this.
6423 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6424                                        const OperandVector &Operands) {
6425   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6426   SMLoc Loc = Operands[0]->getStartLoc();
6427 
6428   // Check the IT block state first.
6429   // NOTE: BKPT and HLT instructions have the interesting property of being
6430   // allowed in IT blocks, but not being predicable. They just always execute.
6431   if (inITBlock() && !instIsBreakpoint(Inst)) {
6432     // The instruction must be predicable.
6433     if (!MCID.isPredicable())
6434       return Error(Loc, "instructions in IT block must be predicable");
6435     ARMCC::CondCodes Cond = ARMCC::CondCodes(
6436         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
6437     if (Cond != currentITCond()) {
6438       // Find the condition code Operand to get its SMLoc information.
6439       SMLoc CondLoc;
6440       for (unsigned I = 1; I < Operands.size(); ++I)
6441         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6442           CondLoc = Operands[I]->getStartLoc();
6443       return Error(CondLoc, "incorrect condition in IT block; got '" +
6444                                 StringRef(ARMCondCodeToString(Cond)) +
6445                                 "', but expected '" +
6446                                 ARMCondCodeToString(currentITCond()) + "'");
6447     }
6448   // Check for non-'al' condition codes outside of the IT block.
6449   } else if (isThumbTwo() && MCID.isPredicable() &&
6450              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6451              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6452              Inst.getOpcode() != ARM::t2Bcc) {
6453     return Error(Loc, "predicated instructions must be in IT block");
6454   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6455              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6456                  ARMCC::AL) {
6457     return Warning(Loc, "predicated instructions should be in IT block");
6458   }
6459 
6460   // PC-setting instructions in an IT block, but not the last instruction of
6461   // the block, are UNPREDICTABLE.
6462   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6463     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6464   }
6465 
6466   const unsigned Opcode = Inst.getOpcode();
6467   switch (Opcode) {
6468   case ARM::t2IT: {
6469     // Encoding is unpredictable if it ever results in a notional 'NV'
6470     // predicate. Since we don't parse 'NV' directly this means an 'AL'
6471     // predicate with an "else" mask bit.
6472     unsigned Cond = Inst.getOperand(0).getImm();
6473     unsigned Mask = Inst.getOperand(1).getImm();
6474 
6475     // Mask hasn't been modified to the IT instruction encoding yet so
6476     // conditions only allowing a 't' are a block of 1s starting at bit 3
6477     // followed by all 0s. Easiest way is to just list the 4 possibilities.
6478     if (Cond == ARMCC::AL && Mask != 8 && Mask != 12 && Mask != 14 &&
6479         Mask != 15)
6480       return Error(Loc, "unpredictable IT predicate sequence");
6481     break;
6482   }
6483   case ARM::LDRD:
6484     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
6485                          /*Writeback*/false))
6486       return true;
6487     break;
6488   case ARM::LDRD_PRE:
6489   case ARM::LDRD_POST:
6490     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
6491                          /*Writeback*/true))
6492       return true;
6493     break;
6494   case ARM::t2LDRDi8:
6495     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
6496                          /*Writeback*/false))
6497       return true;
6498     break;
6499   case ARM::t2LDRD_PRE:
6500   case ARM::t2LDRD_POST:
6501     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
6502                          /*Writeback*/true))
6503       return true;
6504     break;
6505   case ARM::t2BXJ: {
6506     const unsigned RmReg = Inst.getOperand(0).getReg();
6507     // Rm = SP is no longer unpredictable in v8-A
6508     if (RmReg == ARM::SP && !hasV8Ops())
6509       return Error(Operands[2]->getStartLoc(),
6510                    "r13 (SP) is an unpredictable operand to BXJ");
6511     return false;
6512   }
6513   case ARM::STRD:
6514     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
6515                          /*Writeback*/false))
6516       return true;
6517     break;
6518   case ARM::STRD_PRE:
6519   case ARM::STRD_POST:
6520     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
6521                          /*Writeback*/true))
6522       return true;
6523     break;
6524   case ARM::t2STRD_PRE:
6525   case ARM::t2STRD_POST:
6526     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
6527                          /*Writeback*/true))
6528       return true;
6529     break;
6530   case ARM::STR_PRE_IMM:
6531   case ARM::STR_PRE_REG:
6532   case ARM::t2STR_PRE:
6533   case ARM::STR_POST_IMM:
6534   case ARM::STR_POST_REG:
6535   case ARM::t2STR_POST:
6536   case ARM::STRH_PRE:
6537   case ARM::t2STRH_PRE:
6538   case ARM::STRH_POST:
6539   case ARM::t2STRH_POST:
6540   case ARM::STRB_PRE_IMM:
6541   case ARM::STRB_PRE_REG:
6542   case ARM::t2STRB_PRE:
6543   case ARM::STRB_POST_IMM:
6544   case ARM::STRB_POST_REG:
6545   case ARM::t2STRB_POST: {
6546     // Rt must be different from Rn.
6547     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6548     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6549 
6550     if (Rt == Rn)
6551       return Error(Operands[3]->getStartLoc(),
6552                    "source register and base register can't be identical");
6553     return false;
6554   }
6555   case ARM::LDR_PRE_IMM:
6556   case ARM::LDR_PRE_REG:
6557   case ARM::t2LDR_PRE:
6558   case ARM::LDR_POST_IMM:
6559   case ARM::LDR_POST_REG:
6560   case ARM::t2LDR_POST:
6561   case ARM::LDRH_PRE:
6562   case ARM::t2LDRH_PRE:
6563   case ARM::LDRH_POST:
6564   case ARM::t2LDRH_POST:
6565   case ARM::LDRSH_PRE:
6566   case ARM::t2LDRSH_PRE:
6567   case ARM::LDRSH_POST:
6568   case ARM::t2LDRSH_POST:
6569   case ARM::LDRB_PRE_IMM:
6570   case ARM::LDRB_PRE_REG:
6571   case ARM::t2LDRB_PRE:
6572   case ARM::LDRB_POST_IMM:
6573   case ARM::LDRB_POST_REG:
6574   case ARM::t2LDRB_POST:
6575   case ARM::LDRSB_PRE:
6576   case ARM::t2LDRSB_PRE:
6577   case ARM::LDRSB_POST:
6578   case ARM::t2LDRSB_POST: {
6579     // Rt must be different from Rn.
6580     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6581     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6582 
6583     if (Rt == Rn)
6584       return Error(Operands[3]->getStartLoc(),
6585                    "destination register and base register can't be identical");
6586     return false;
6587   }
6588   case ARM::SBFX:
6589   case ARM::t2SBFX:
6590   case ARM::UBFX:
6591   case ARM::t2UBFX: {
6592     // Width must be in range [1, 32-lsb].
6593     unsigned LSB = Inst.getOperand(2).getImm();
6594     unsigned Widthm1 = Inst.getOperand(3).getImm();
6595     if (Widthm1 >= 32 - LSB)
6596       return Error(Operands[5]->getStartLoc(),
6597                    "bitfield width must be in range [1,32-lsb]");
6598     return false;
6599   }
6600   // Notionally handles ARM::tLDMIA_UPD too.
6601   case ARM::tLDMIA: {
6602     // If we're parsing Thumb2, the .w variant is available and handles
6603     // most cases that are normally illegal for a Thumb1 LDM instruction.
6604     // We'll make the transformation in processInstruction() if necessary.
6605     //
6606     // Thumb LDM instructions are writeback iff the base register is not
6607     // in the register list.
6608     unsigned Rn = Inst.getOperand(0).getReg();
6609     bool HasWritebackToken =
6610         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6611          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6612     bool ListContainsBase;
6613     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6614       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6615                    "registers must be in range r0-r7");
6616     // If we should have writeback, then there should be a '!' token.
6617     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6618       return Error(Operands[2]->getStartLoc(),
6619                    "writeback operator '!' expected");
6620     // If we should not have writeback, there must not be a '!'. This is
6621     // true even for the 32-bit wide encodings.
6622     if (ListContainsBase && HasWritebackToken)
6623       return Error(Operands[3]->getStartLoc(),
6624                    "writeback operator '!' not allowed when base register "
6625                    "in register list");
6626 
6627     if (validatetLDMRegList(Inst, Operands, 3))
6628       return true;
6629     break;
6630   }
6631   case ARM::LDMIA_UPD:
6632   case ARM::LDMDB_UPD:
6633   case ARM::LDMIB_UPD:
6634   case ARM::LDMDA_UPD:
6635     // ARM variants loading and updating the same register are only officially
6636     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6637     if (!hasV7Ops())
6638       break;
6639     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6640       return Error(Operands.back()->getStartLoc(),
6641                    "writeback register not allowed in register list");
6642     break;
6643   case ARM::t2LDMIA:
6644   case ARM::t2LDMDB:
6645     if (validatetLDMRegList(Inst, Operands, 3))
6646       return true;
6647     break;
6648   case ARM::t2STMIA:
6649   case ARM::t2STMDB:
6650     if (validatetSTMRegList(Inst, Operands, 3))
6651       return true;
6652     break;
6653   case ARM::t2LDMIA_UPD:
6654   case ARM::t2LDMDB_UPD:
6655   case ARM::t2STMIA_UPD:
6656   case ARM::t2STMDB_UPD:
6657     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6658       return Error(Operands.back()->getStartLoc(),
6659                    "writeback register not allowed in register list");
6660 
6661     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6662       if (validatetLDMRegList(Inst, Operands, 3))
6663         return true;
6664     } else {
6665       if (validatetSTMRegList(Inst, Operands, 3))
6666         return true;
6667     }
6668     break;
6669 
6670   case ARM::sysLDMIA_UPD:
6671   case ARM::sysLDMDA_UPD:
6672   case ARM::sysLDMDB_UPD:
6673   case ARM::sysLDMIB_UPD:
6674     if (!listContainsReg(Inst, 3, ARM::PC))
6675       return Error(Operands[4]->getStartLoc(),
6676                    "writeback register only allowed on system LDM "
6677                    "if PC in register-list");
6678     break;
6679   case ARM::sysSTMIA_UPD:
6680   case ARM::sysSTMDA_UPD:
6681   case ARM::sysSTMDB_UPD:
6682   case ARM::sysSTMIB_UPD:
6683     return Error(Operands[2]->getStartLoc(),
6684                  "system STM cannot have writeback register");
6685   case ARM::tMUL:
6686     // The second source operand must be the same register as the destination
6687     // operand.
6688     //
6689     // In this case, we must directly check the parsed operands because the
6690     // cvtThumbMultiply() function is written in such a way that it guarantees
6691     // this first statement is always true for the new Inst.  Essentially, the
6692     // destination is unconditionally copied into the second source operand
6693     // without checking to see if it matches what we actually parsed.
6694     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6695                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6696         (((ARMOperand &)*Operands[3]).getReg() !=
6697          ((ARMOperand &)*Operands[4]).getReg())) {
6698       return Error(Operands[3]->getStartLoc(),
6699                    "destination register must match source register");
6700     }
6701     break;
6702 
6703   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6704   // so only issue a diagnostic for thumb1. The instructions will be
6705   // switched to the t2 encodings in processInstruction() if necessary.
6706   case ARM::tPOP: {
6707     bool ListContainsBase;
6708     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6709         !isThumbTwo())
6710       return Error(Operands[2]->getStartLoc(),
6711                    "registers must be in range r0-r7 or pc");
6712     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6713       return true;
6714     break;
6715   }
6716   case ARM::tPUSH: {
6717     bool ListContainsBase;
6718     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6719         !isThumbTwo())
6720       return Error(Operands[2]->getStartLoc(),
6721                    "registers must be in range r0-r7 or lr");
6722     if (validatetSTMRegList(Inst, Operands, 2))
6723       return true;
6724     break;
6725   }
6726   case ARM::tSTMIA_UPD: {
6727     bool ListContainsBase, InvalidLowList;
6728     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6729                                           0, ListContainsBase);
6730     if (InvalidLowList && !isThumbTwo())
6731       return Error(Operands[4]->getStartLoc(),
6732                    "registers must be in range r0-r7");
6733 
6734     // This would be converted to a 32-bit stm, but that's not valid if the
6735     // writeback register is in the list.
6736     if (InvalidLowList && ListContainsBase)
6737       return Error(Operands[4]->getStartLoc(),
6738                    "writeback operator '!' not allowed when base register "
6739                    "in register list");
6740 
6741     if (validatetSTMRegList(Inst, Operands, 4))
6742       return true;
6743     break;
6744   }
6745   case ARM::tADDrSP:
6746     // If the non-SP source operand and the destination operand are not the
6747     // same, we need thumb2 (for the wide encoding), or we have an error.
6748     if (!isThumbTwo() &&
6749         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6750       return Error(Operands[4]->getStartLoc(),
6751                    "source register must be the same as destination");
6752     }
6753     break;
6754 
6755   // Final range checking for Thumb unconditional branch instructions.
6756   case ARM::tB:
6757     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6758       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6759     break;
6760   case ARM::t2B: {
6761     int op = (Operands[2]->isImm()) ? 2 : 3;
6762     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6763       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6764     break;
6765   }
6766   // Final range checking for Thumb conditional branch instructions.
6767   case ARM::tBcc:
6768     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6769       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6770     break;
6771   case ARM::t2Bcc: {
6772     int Op = (Operands[2]->isImm()) ? 2 : 3;
6773     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6774       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6775     break;
6776   }
6777   case ARM::tCBZ:
6778   case ARM::tCBNZ: {
6779     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6780       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6781     break;
6782   }
6783   case ARM::MOVi16:
6784   case ARM::MOVTi16:
6785   case ARM::t2MOVi16:
6786   case ARM::t2MOVTi16:
6787     {
6788     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6789     // especially when we turn it into a movw and the expression <symbol> does
6790     // not have a :lower16: or :upper16 as part of the expression.  We don't
6791     // want the behavior of silently truncating, which can be unexpected and
6792     // lead to bugs that are difficult to find since this is an easy mistake
6793     // to make.
6794     int i = (Operands[3]->isImm()) ? 3 : 4;
6795     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6796     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6797     if (CE) break;
6798     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6799     if (!E) break;
6800     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6801     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6802                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6803       return Error(
6804           Op.getStartLoc(),
6805           "immediate expression for mov requires :lower16: or :upper16");
6806     break;
6807   }
6808   case ARM::HINT:
6809   case ARM::t2HINT: {
6810     unsigned Imm8 = Inst.getOperand(0).getImm();
6811     unsigned Pred = Inst.getOperand(1).getImm();
6812     // ESB is not predicable (pred must be AL). Without the RAS extension, this
6813     // behaves as any other unallocated hint.
6814     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
6815       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6816                                                "predicable, but condition "
6817                                                "code specified");
6818     if (Imm8 == 0x14 && Pred != ARMCC::AL)
6819       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
6820                                                "predicable, but condition "
6821                                                "code specified");
6822     break;
6823   }
6824   case ARM::VMOVRRS: {
6825     // Source registers must be sequential.
6826     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6827     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6828     if (Sm1 != Sm + 1)
6829       return Error(Operands[5]->getStartLoc(),
6830                    "source operands must be sequential");
6831     break;
6832   }
6833   case ARM::VMOVSRR: {
6834     // Destination registers must be sequential.
6835     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6836     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6837     if (Sm1 != Sm + 1)
6838       return Error(Operands[3]->getStartLoc(),
6839                    "destination operands must be sequential");
6840     break;
6841   }
6842   }
6843 
6844   return false;
6845 }
6846 
6847 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6848   switch(Opc) {
6849   default: llvm_unreachable("unexpected opcode!");
6850   // VST1LN
6851   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6852   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6853   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6854   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6855   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6856   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6857   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6858   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6859   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6860 
6861   // VST2LN
6862   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6863   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6864   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6865   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6866   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6867 
6868   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6869   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6870   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6871   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6872   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6873 
6874   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6875   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6876   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6877   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6878   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6879 
6880   // VST3LN
6881   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6882   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6883   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6884   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6885   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6886   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6887   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6888   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6889   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6890   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6891   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6892   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6893   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6894   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6895   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6896 
6897   // VST3
6898   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6899   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6900   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6901   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6902   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6903   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6904   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6905   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6906   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6907   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6908   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6909   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6910   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6911   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6912   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6913   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6914   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6915   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6916 
6917   // VST4LN
6918   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6919   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6920   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6921   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6922   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6923   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6924   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6925   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6926   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6927   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6928   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6929   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6930   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6931   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6932   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6933 
6934   // VST4
6935   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6936   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6937   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6938   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6939   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6940   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6941   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6942   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6943   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6944   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6945   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6946   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6947   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6948   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6949   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6950   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6951   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6952   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6953   }
6954 }
6955 
6956 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6957   switch(Opc) {
6958   default: llvm_unreachable("unexpected opcode!");
6959   // VLD1LN
6960   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6961   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6962   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6963   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6964   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6965   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6966   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6967   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6968   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6969 
6970   // VLD2LN
6971   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6972   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6973   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6974   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6975   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6976   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6977   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6978   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6979   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6980   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6981   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6982   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6983   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6984   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6985   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6986 
6987   // VLD3DUP
6988   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6989   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6990   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6991   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6992   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6993   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6994   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6995   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6996   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6997   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6998   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6999   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
7000   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
7001   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
7002   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
7003   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
7004   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
7005   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
7006 
7007   // VLD3LN
7008   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
7009   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
7010   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
7011   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
7012   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
7013   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
7014   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
7015   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
7016   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
7017   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
7018   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
7019   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
7020   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
7021   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
7022   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
7023 
7024   // VLD3
7025   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
7026   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
7027   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
7028   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
7029   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
7030   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
7031   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
7032   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
7033   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
7034   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
7035   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
7036   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
7037   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
7038   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
7039   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
7040   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
7041   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
7042   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
7043 
7044   // VLD4LN
7045   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
7046   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
7047   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
7048   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
7049   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
7050   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
7051   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
7052   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
7053   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
7054   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
7055   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
7056   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
7057   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
7058   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
7059   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
7060 
7061   // VLD4DUP
7062   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
7063   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
7064   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
7065   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
7066   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
7067   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
7068   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
7069   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
7070   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
7071   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
7072   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
7073   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
7074   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
7075   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
7076   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
7077   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
7078   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
7079   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
7080 
7081   // VLD4
7082   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
7083   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
7084   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
7085   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
7086   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
7087   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
7088   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
7089   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
7090   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
7091   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
7092   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
7093   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
7094   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
7095   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
7096   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
7097   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
7098   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
7099   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
7100   }
7101 }
7102 
7103 bool ARMAsmParser::processInstruction(MCInst &Inst,
7104                                       const OperandVector &Operands,
7105                                       MCStreamer &Out) {
7106   // Check if we have the wide qualifier, because if it's present we
7107   // must avoid selecting a 16-bit thumb instruction.
7108   bool HasWideQualifier = false;
7109   for (auto &Op : Operands) {
7110     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
7111     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
7112       HasWideQualifier = true;
7113       break;
7114     }
7115   }
7116 
7117   switch (Inst.getOpcode()) {
7118   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
7119   case ARM::LDRT_POST:
7120   case ARM::LDRBT_POST: {
7121     const unsigned Opcode =
7122       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
7123                                            : ARM::LDRBT_POST_IMM;
7124     MCInst TmpInst;
7125     TmpInst.setOpcode(Opcode);
7126     TmpInst.addOperand(Inst.getOperand(0));
7127     TmpInst.addOperand(Inst.getOperand(1));
7128     TmpInst.addOperand(Inst.getOperand(1));
7129     TmpInst.addOperand(MCOperand::createReg(0));
7130     TmpInst.addOperand(MCOperand::createImm(0));
7131     TmpInst.addOperand(Inst.getOperand(2));
7132     TmpInst.addOperand(Inst.getOperand(3));
7133     Inst = TmpInst;
7134     return true;
7135   }
7136   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
7137   case ARM::STRT_POST:
7138   case ARM::STRBT_POST: {
7139     const unsigned Opcode =
7140       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
7141                                            : ARM::STRBT_POST_IMM;
7142     MCInst TmpInst;
7143     TmpInst.setOpcode(Opcode);
7144     TmpInst.addOperand(Inst.getOperand(1));
7145     TmpInst.addOperand(Inst.getOperand(0));
7146     TmpInst.addOperand(Inst.getOperand(1));
7147     TmpInst.addOperand(MCOperand::createReg(0));
7148     TmpInst.addOperand(MCOperand::createImm(0));
7149     TmpInst.addOperand(Inst.getOperand(2));
7150     TmpInst.addOperand(Inst.getOperand(3));
7151     Inst = TmpInst;
7152     return true;
7153   }
7154   // Alias for alternate form of 'ADR Rd, #imm' instruction.
7155   case ARM::ADDri: {
7156     if (Inst.getOperand(1).getReg() != ARM::PC ||
7157         Inst.getOperand(5).getReg() != 0 ||
7158         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
7159       return false;
7160     MCInst TmpInst;
7161     TmpInst.setOpcode(ARM::ADR);
7162     TmpInst.addOperand(Inst.getOperand(0));
7163     if (Inst.getOperand(2).isImm()) {
7164       // Immediate (mod_imm) will be in its encoded form, we must unencode it
7165       // before passing it to the ADR instruction.
7166       unsigned Enc = Inst.getOperand(2).getImm();
7167       TmpInst.addOperand(MCOperand::createImm(
7168         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
7169     } else {
7170       // Turn PC-relative expression into absolute expression.
7171       // Reading PC provides the start of the current instruction + 8 and
7172       // the transform to adr is biased by that.
7173       MCSymbol *Dot = getContext().createTempSymbol();
7174       Out.EmitLabel(Dot);
7175       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
7176       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
7177                                                      MCSymbolRefExpr::VK_None,
7178                                                      getContext());
7179       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
7180       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
7181                                                      getContext());
7182       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
7183                                                         getContext());
7184       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
7185     }
7186     TmpInst.addOperand(Inst.getOperand(3));
7187     TmpInst.addOperand(Inst.getOperand(4));
7188     Inst = TmpInst;
7189     return true;
7190   }
7191   // Aliases for alternate PC+imm syntax of LDR instructions.
7192   case ARM::t2LDRpcrel:
7193     // Select the narrow version if the immediate will fit.
7194     if (Inst.getOperand(1).getImm() > 0 &&
7195         Inst.getOperand(1).getImm() <= 0xff &&
7196         !HasWideQualifier)
7197       Inst.setOpcode(ARM::tLDRpci);
7198     else
7199       Inst.setOpcode(ARM::t2LDRpci);
7200     return true;
7201   case ARM::t2LDRBpcrel:
7202     Inst.setOpcode(ARM::t2LDRBpci);
7203     return true;
7204   case ARM::t2LDRHpcrel:
7205     Inst.setOpcode(ARM::t2LDRHpci);
7206     return true;
7207   case ARM::t2LDRSBpcrel:
7208     Inst.setOpcode(ARM::t2LDRSBpci);
7209     return true;
7210   case ARM::t2LDRSHpcrel:
7211     Inst.setOpcode(ARM::t2LDRSHpci);
7212     return true;
7213   case ARM::LDRConstPool:
7214   case ARM::tLDRConstPool:
7215   case ARM::t2LDRConstPool: {
7216     // Pseudo instruction ldr rt, =immediate is converted to a
7217     // MOV rt, immediate if immediate is known and representable
7218     // otherwise we create a constant pool entry that we load from.
7219     MCInst TmpInst;
7220     if (Inst.getOpcode() == ARM::LDRConstPool)
7221       TmpInst.setOpcode(ARM::LDRi12);
7222     else if (Inst.getOpcode() == ARM::tLDRConstPool)
7223       TmpInst.setOpcode(ARM::tLDRpci);
7224     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
7225       TmpInst.setOpcode(ARM::t2LDRpci);
7226     const ARMOperand &PoolOperand =
7227       (HasWideQualifier ?
7228        static_cast<ARMOperand &>(*Operands[4]) :
7229        static_cast<ARMOperand &>(*Operands[3]));
7230     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
7231     // If SubExprVal is a constant we may be able to use a MOV
7232     if (isa<MCConstantExpr>(SubExprVal) &&
7233         Inst.getOperand(0).getReg() != ARM::PC &&
7234         Inst.getOperand(0).getReg() != ARM::SP) {
7235       int64_t Value =
7236         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
7237       bool UseMov  = true;
7238       bool MovHasS = true;
7239       if (Inst.getOpcode() == ARM::LDRConstPool) {
7240         // ARM Constant
7241         if (ARM_AM::getSOImmVal(Value) != -1) {
7242           Value = ARM_AM::getSOImmVal(Value);
7243           TmpInst.setOpcode(ARM::MOVi);
7244         }
7245         else if (ARM_AM::getSOImmVal(~Value) != -1) {
7246           Value = ARM_AM::getSOImmVal(~Value);
7247           TmpInst.setOpcode(ARM::MVNi);
7248         }
7249         else if (hasV6T2Ops() &&
7250                  Value >=0 && Value < 65536) {
7251           TmpInst.setOpcode(ARM::MOVi16);
7252           MovHasS = false;
7253         }
7254         else
7255           UseMov = false;
7256       }
7257       else {
7258         // Thumb/Thumb2 Constant
7259         if (hasThumb2() &&
7260             ARM_AM::getT2SOImmVal(Value) != -1)
7261           TmpInst.setOpcode(ARM::t2MOVi);
7262         else if (hasThumb2() &&
7263                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7264           TmpInst.setOpcode(ARM::t2MVNi);
7265           Value = ~Value;
7266         }
7267         else if (hasV8MBaseline() &&
7268                  Value >=0 && Value < 65536) {
7269           TmpInst.setOpcode(ARM::t2MOVi16);
7270           MovHasS = false;
7271         }
7272         else
7273           UseMov = false;
7274       }
7275       if (UseMov) {
7276         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7277         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7278         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7279         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7280         if (MovHasS)
7281           TmpInst.addOperand(MCOperand::createReg(0));    // S
7282         Inst = TmpInst;
7283         return true;
7284       }
7285     }
7286     // No opportunity to use MOV/MVN create constant pool
7287     const MCExpr *CPLoc =
7288       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7289                                                PoolOperand.getStartLoc());
7290     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7291     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7292     if (TmpInst.getOpcode() == ARM::LDRi12)
7293       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7294     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7295     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7296     Inst = TmpInst;
7297     return true;
7298   }
7299   // Handle NEON VST complex aliases.
7300   case ARM::VST1LNdWB_register_Asm_8:
7301   case ARM::VST1LNdWB_register_Asm_16:
7302   case ARM::VST1LNdWB_register_Asm_32: {
7303     MCInst TmpInst;
7304     // Shuffle the operands around so the lane index operand is in the
7305     // right place.
7306     unsigned Spacing;
7307     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7308     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7309     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7310     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7311     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7312     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7313     TmpInst.addOperand(Inst.getOperand(1)); // lane
7314     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7315     TmpInst.addOperand(Inst.getOperand(6));
7316     Inst = TmpInst;
7317     return true;
7318   }
7319 
7320   case ARM::VST2LNdWB_register_Asm_8:
7321   case ARM::VST2LNdWB_register_Asm_16:
7322   case ARM::VST2LNdWB_register_Asm_32:
7323   case ARM::VST2LNqWB_register_Asm_16:
7324   case ARM::VST2LNqWB_register_Asm_32: {
7325     MCInst TmpInst;
7326     // Shuffle the operands around so the lane index operand is in the
7327     // right place.
7328     unsigned Spacing;
7329     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7330     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7331     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7332     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7333     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7334     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7335     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7336                                             Spacing));
7337     TmpInst.addOperand(Inst.getOperand(1)); // lane
7338     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7339     TmpInst.addOperand(Inst.getOperand(6));
7340     Inst = TmpInst;
7341     return true;
7342   }
7343 
7344   case ARM::VST3LNdWB_register_Asm_8:
7345   case ARM::VST3LNdWB_register_Asm_16:
7346   case ARM::VST3LNdWB_register_Asm_32:
7347   case ARM::VST3LNqWB_register_Asm_16:
7348   case ARM::VST3LNqWB_register_Asm_32: {
7349     MCInst TmpInst;
7350     // Shuffle the operands around so the lane index operand is in the
7351     // right place.
7352     unsigned Spacing;
7353     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7354     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7355     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7356     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7357     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7358     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7359     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7360                                             Spacing));
7361     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7362                                             Spacing * 2));
7363     TmpInst.addOperand(Inst.getOperand(1)); // lane
7364     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7365     TmpInst.addOperand(Inst.getOperand(6));
7366     Inst = TmpInst;
7367     return true;
7368   }
7369 
7370   case ARM::VST4LNdWB_register_Asm_8:
7371   case ARM::VST4LNdWB_register_Asm_16:
7372   case ARM::VST4LNdWB_register_Asm_32:
7373   case ARM::VST4LNqWB_register_Asm_16:
7374   case ARM::VST4LNqWB_register_Asm_32: {
7375     MCInst TmpInst;
7376     // Shuffle the operands around so the lane index operand is in the
7377     // right place.
7378     unsigned Spacing;
7379     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7380     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7381     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7382     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7383     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7384     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7385     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7386                                             Spacing));
7387     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7388                                             Spacing * 2));
7389     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7390                                             Spacing * 3));
7391     TmpInst.addOperand(Inst.getOperand(1)); // lane
7392     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7393     TmpInst.addOperand(Inst.getOperand(6));
7394     Inst = TmpInst;
7395     return true;
7396   }
7397 
7398   case ARM::VST1LNdWB_fixed_Asm_8:
7399   case ARM::VST1LNdWB_fixed_Asm_16:
7400   case ARM::VST1LNdWB_fixed_Asm_32: {
7401     MCInst TmpInst;
7402     // Shuffle the operands around so the lane index operand is in the
7403     // right place.
7404     unsigned Spacing;
7405     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7406     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7407     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7408     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7409     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7410     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7411     TmpInst.addOperand(Inst.getOperand(1)); // lane
7412     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7413     TmpInst.addOperand(Inst.getOperand(5));
7414     Inst = TmpInst;
7415     return true;
7416   }
7417 
7418   case ARM::VST2LNdWB_fixed_Asm_8:
7419   case ARM::VST2LNdWB_fixed_Asm_16:
7420   case ARM::VST2LNdWB_fixed_Asm_32:
7421   case ARM::VST2LNqWB_fixed_Asm_16:
7422   case ARM::VST2LNqWB_fixed_Asm_32: {
7423     MCInst TmpInst;
7424     // Shuffle the operands around so the lane index operand is in the
7425     // right place.
7426     unsigned Spacing;
7427     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7428     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7429     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7430     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7431     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7432     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7433     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7434                                             Spacing));
7435     TmpInst.addOperand(Inst.getOperand(1)); // lane
7436     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7437     TmpInst.addOperand(Inst.getOperand(5));
7438     Inst = TmpInst;
7439     return true;
7440   }
7441 
7442   case ARM::VST3LNdWB_fixed_Asm_8:
7443   case ARM::VST3LNdWB_fixed_Asm_16:
7444   case ARM::VST3LNdWB_fixed_Asm_32:
7445   case ARM::VST3LNqWB_fixed_Asm_16:
7446   case ARM::VST3LNqWB_fixed_Asm_32: {
7447     MCInst TmpInst;
7448     // Shuffle the operands around so the lane index operand is in the
7449     // right place.
7450     unsigned Spacing;
7451     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7452     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7453     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7454     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7455     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7456     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7457     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7458                                             Spacing));
7459     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7460                                             Spacing * 2));
7461     TmpInst.addOperand(Inst.getOperand(1)); // lane
7462     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7463     TmpInst.addOperand(Inst.getOperand(5));
7464     Inst = TmpInst;
7465     return true;
7466   }
7467 
7468   case ARM::VST4LNdWB_fixed_Asm_8:
7469   case ARM::VST4LNdWB_fixed_Asm_16:
7470   case ARM::VST4LNdWB_fixed_Asm_32:
7471   case ARM::VST4LNqWB_fixed_Asm_16:
7472   case ARM::VST4LNqWB_fixed_Asm_32: {
7473     MCInst TmpInst;
7474     // Shuffle the operands around so the lane index operand is in the
7475     // right place.
7476     unsigned Spacing;
7477     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7478     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7479     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7480     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7481     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7482     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7483     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7484                                             Spacing));
7485     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7486                                             Spacing * 2));
7487     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7488                                             Spacing * 3));
7489     TmpInst.addOperand(Inst.getOperand(1)); // lane
7490     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7491     TmpInst.addOperand(Inst.getOperand(5));
7492     Inst = TmpInst;
7493     return true;
7494   }
7495 
7496   case ARM::VST1LNdAsm_8:
7497   case ARM::VST1LNdAsm_16:
7498   case ARM::VST1LNdAsm_32: {
7499     MCInst TmpInst;
7500     // Shuffle the operands around so the lane index operand is in the
7501     // right place.
7502     unsigned Spacing;
7503     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7504     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7505     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7506     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7507     TmpInst.addOperand(Inst.getOperand(1)); // lane
7508     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7509     TmpInst.addOperand(Inst.getOperand(5));
7510     Inst = TmpInst;
7511     return true;
7512   }
7513 
7514   case ARM::VST2LNdAsm_8:
7515   case ARM::VST2LNdAsm_16:
7516   case ARM::VST2LNdAsm_32:
7517   case ARM::VST2LNqAsm_16:
7518   case ARM::VST2LNqAsm_32: {
7519     MCInst TmpInst;
7520     // Shuffle the operands around so the lane index operand is in the
7521     // right place.
7522     unsigned Spacing;
7523     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7524     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7525     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7526     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7527     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7528                                             Spacing));
7529     TmpInst.addOperand(Inst.getOperand(1)); // lane
7530     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7531     TmpInst.addOperand(Inst.getOperand(5));
7532     Inst = TmpInst;
7533     return true;
7534   }
7535 
7536   case ARM::VST3LNdAsm_8:
7537   case ARM::VST3LNdAsm_16:
7538   case ARM::VST3LNdAsm_32:
7539   case ARM::VST3LNqAsm_16:
7540   case ARM::VST3LNqAsm_32: {
7541     MCInst TmpInst;
7542     // Shuffle the operands around so the lane index operand is in the
7543     // right place.
7544     unsigned Spacing;
7545     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7546     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7547     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7548     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7549     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7550                                             Spacing));
7551     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7552                                             Spacing * 2));
7553     TmpInst.addOperand(Inst.getOperand(1)); // lane
7554     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7555     TmpInst.addOperand(Inst.getOperand(5));
7556     Inst = TmpInst;
7557     return true;
7558   }
7559 
7560   case ARM::VST4LNdAsm_8:
7561   case ARM::VST4LNdAsm_16:
7562   case ARM::VST4LNdAsm_32:
7563   case ARM::VST4LNqAsm_16:
7564   case ARM::VST4LNqAsm_32: {
7565     MCInst TmpInst;
7566     // Shuffle the operands around so the lane index operand is in the
7567     // right place.
7568     unsigned Spacing;
7569     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7570     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7571     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7572     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7573     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7574                                             Spacing));
7575     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7576                                             Spacing * 2));
7577     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7578                                             Spacing * 3));
7579     TmpInst.addOperand(Inst.getOperand(1)); // lane
7580     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7581     TmpInst.addOperand(Inst.getOperand(5));
7582     Inst = TmpInst;
7583     return true;
7584   }
7585 
7586   // Handle NEON VLD complex aliases.
7587   case ARM::VLD1LNdWB_register_Asm_8:
7588   case ARM::VLD1LNdWB_register_Asm_16:
7589   case ARM::VLD1LNdWB_register_Asm_32: {
7590     MCInst TmpInst;
7591     // Shuffle the operands around so the lane index operand is in the
7592     // right place.
7593     unsigned Spacing;
7594     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7595     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7596     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7597     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7598     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7599     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7600     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7601     TmpInst.addOperand(Inst.getOperand(1)); // lane
7602     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7603     TmpInst.addOperand(Inst.getOperand(6));
7604     Inst = TmpInst;
7605     return true;
7606   }
7607 
7608   case ARM::VLD2LNdWB_register_Asm_8:
7609   case ARM::VLD2LNdWB_register_Asm_16:
7610   case ARM::VLD2LNdWB_register_Asm_32:
7611   case ARM::VLD2LNqWB_register_Asm_16:
7612   case ARM::VLD2LNqWB_register_Asm_32: {
7613     MCInst TmpInst;
7614     // Shuffle the operands around so the lane index operand is in the
7615     // right place.
7616     unsigned Spacing;
7617     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7618     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7619     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7620                                             Spacing));
7621     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7622     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7623     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7624     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7625     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7626     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7627                                             Spacing));
7628     TmpInst.addOperand(Inst.getOperand(1)); // lane
7629     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7630     TmpInst.addOperand(Inst.getOperand(6));
7631     Inst = TmpInst;
7632     return true;
7633   }
7634 
7635   case ARM::VLD3LNdWB_register_Asm_8:
7636   case ARM::VLD3LNdWB_register_Asm_16:
7637   case ARM::VLD3LNdWB_register_Asm_32:
7638   case ARM::VLD3LNqWB_register_Asm_16:
7639   case ARM::VLD3LNqWB_register_Asm_32: {
7640     MCInst TmpInst;
7641     // Shuffle the operands around so the lane index operand is in the
7642     // right place.
7643     unsigned Spacing;
7644     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7645     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7646     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7647                                             Spacing));
7648     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7649                                             Spacing * 2));
7650     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7651     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7652     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7653     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7654     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7655     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7656                                             Spacing));
7657     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7658                                             Spacing * 2));
7659     TmpInst.addOperand(Inst.getOperand(1)); // lane
7660     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7661     TmpInst.addOperand(Inst.getOperand(6));
7662     Inst = TmpInst;
7663     return true;
7664   }
7665 
7666   case ARM::VLD4LNdWB_register_Asm_8:
7667   case ARM::VLD4LNdWB_register_Asm_16:
7668   case ARM::VLD4LNdWB_register_Asm_32:
7669   case ARM::VLD4LNqWB_register_Asm_16:
7670   case ARM::VLD4LNqWB_register_Asm_32: {
7671     MCInst TmpInst;
7672     // Shuffle the operands around so the lane index operand is in the
7673     // right place.
7674     unsigned Spacing;
7675     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7676     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7677     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7678                                             Spacing));
7679     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7680                                             Spacing * 2));
7681     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7682                                             Spacing * 3));
7683     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7684     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7685     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7686     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7687     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7688     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7689                                             Spacing));
7690     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7691                                             Spacing * 2));
7692     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7693                                             Spacing * 3));
7694     TmpInst.addOperand(Inst.getOperand(1)); // lane
7695     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7696     TmpInst.addOperand(Inst.getOperand(6));
7697     Inst = TmpInst;
7698     return true;
7699   }
7700 
7701   case ARM::VLD1LNdWB_fixed_Asm_8:
7702   case ARM::VLD1LNdWB_fixed_Asm_16:
7703   case ARM::VLD1LNdWB_fixed_Asm_32: {
7704     MCInst TmpInst;
7705     // Shuffle the operands around so the lane index operand is in the
7706     // right place.
7707     unsigned Spacing;
7708     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7709     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7710     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7711     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7712     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7713     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7714     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7715     TmpInst.addOperand(Inst.getOperand(1)); // lane
7716     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7717     TmpInst.addOperand(Inst.getOperand(5));
7718     Inst = TmpInst;
7719     return true;
7720   }
7721 
7722   case ARM::VLD2LNdWB_fixed_Asm_8:
7723   case ARM::VLD2LNdWB_fixed_Asm_16:
7724   case ARM::VLD2LNdWB_fixed_Asm_32:
7725   case ARM::VLD2LNqWB_fixed_Asm_16:
7726   case ARM::VLD2LNqWB_fixed_Asm_32: {
7727     MCInst TmpInst;
7728     // Shuffle the operands around so the lane index operand is in the
7729     // right place.
7730     unsigned Spacing;
7731     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7732     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7733     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7734                                             Spacing));
7735     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7736     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7737     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7738     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7739     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7740     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7741                                             Spacing));
7742     TmpInst.addOperand(Inst.getOperand(1)); // lane
7743     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7744     TmpInst.addOperand(Inst.getOperand(5));
7745     Inst = TmpInst;
7746     return true;
7747   }
7748 
7749   case ARM::VLD3LNdWB_fixed_Asm_8:
7750   case ARM::VLD3LNdWB_fixed_Asm_16:
7751   case ARM::VLD3LNdWB_fixed_Asm_32:
7752   case ARM::VLD3LNqWB_fixed_Asm_16:
7753   case ARM::VLD3LNqWB_fixed_Asm_32: {
7754     MCInst TmpInst;
7755     // Shuffle the operands around so the lane index operand is in the
7756     // right place.
7757     unsigned Spacing;
7758     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7759     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7760     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7761                                             Spacing));
7762     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7763                                             Spacing * 2));
7764     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7765     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7766     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7767     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7768     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7769     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7770                                             Spacing));
7771     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7772                                             Spacing * 2));
7773     TmpInst.addOperand(Inst.getOperand(1)); // lane
7774     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7775     TmpInst.addOperand(Inst.getOperand(5));
7776     Inst = TmpInst;
7777     return true;
7778   }
7779 
7780   case ARM::VLD4LNdWB_fixed_Asm_8:
7781   case ARM::VLD4LNdWB_fixed_Asm_16:
7782   case ARM::VLD4LNdWB_fixed_Asm_32:
7783   case ARM::VLD4LNqWB_fixed_Asm_16:
7784   case ARM::VLD4LNqWB_fixed_Asm_32: {
7785     MCInst TmpInst;
7786     // Shuffle the operands around so the lane index operand is in the
7787     // right place.
7788     unsigned Spacing;
7789     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7790     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7791     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7792                                             Spacing));
7793     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7794                                             Spacing * 2));
7795     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7796                                             Spacing * 3));
7797     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7798     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7799     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7800     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7801     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7802     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7803                                             Spacing));
7804     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7805                                             Spacing * 2));
7806     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7807                                             Spacing * 3));
7808     TmpInst.addOperand(Inst.getOperand(1)); // lane
7809     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7810     TmpInst.addOperand(Inst.getOperand(5));
7811     Inst = TmpInst;
7812     return true;
7813   }
7814 
7815   case ARM::VLD1LNdAsm_8:
7816   case ARM::VLD1LNdAsm_16:
7817   case ARM::VLD1LNdAsm_32: {
7818     MCInst TmpInst;
7819     // Shuffle the operands around so the lane index operand is in the
7820     // right place.
7821     unsigned Spacing;
7822     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7823     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7824     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7825     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7826     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7827     TmpInst.addOperand(Inst.getOperand(1)); // lane
7828     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7829     TmpInst.addOperand(Inst.getOperand(5));
7830     Inst = TmpInst;
7831     return true;
7832   }
7833 
7834   case ARM::VLD2LNdAsm_8:
7835   case ARM::VLD2LNdAsm_16:
7836   case ARM::VLD2LNdAsm_32:
7837   case ARM::VLD2LNqAsm_16:
7838   case ARM::VLD2LNqAsm_32: {
7839     MCInst TmpInst;
7840     // Shuffle the operands around so the lane index operand is in the
7841     // right place.
7842     unsigned Spacing;
7843     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7844     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7845     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7846                                             Spacing));
7847     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7848     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7849     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7850     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7851                                             Spacing));
7852     TmpInst.addOperand(Inst.getOperand(1)); // lane
7853     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7854     TmpInst.addOperand(Inst.getOperand(5));
7855     Inst = TmpInst;
7856     return true;
7857   }
7858 
7859   case ARM::VLD3LNdAsm_8:
7860   case ARM::VLD3LNdAsm_16:
7861   case ARM::VLD3LNdAsm_32:
7862   case ARM::VLD3LNqAsm_16:
7863   case ARM::VLD3LNqAsm_32: {
7864     MCInst TmpInst;
7865     // Shuffle the operands around so the lane index operand is in the
7866     // right place.
7867     unsigned Spacing;
7868     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7869     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7870     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7871                                             Spacing));
7872     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7873                                             Spacing * 2));
7874     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7875     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7876     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7877     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7878                                             Spacing));
7879     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7880                                             Spacing * 2));
7881     TmpInst.addOperand(Inst.getOperand(1)); // lane
7882     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7883     TmpInst.addOperand(Inst.getOperand(5));
7884     Inst = TmpInst;
7885     return true;
7886   }
7887 
7888   case ARM::VLD4LNdAsm_8:
7889   case ARM::VLD4LNdAsm_16:
7890   case ARM::VLD4LNdAsm_32:
7891   case ARM::VLD4LNqAsm_16:
7892   case ARM::VLD4LNqAsm_32: {
7893     MCInst TmpInst;
7894     // Shuffle the operands around so the lane index operand is in the
7895     // right place.
7896     unsigned Spacing;
7897     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7898     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7899     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7900                                             Spacing));
7901     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7902                                             Spacing * 2));
7903     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7904                                             Spacing * 3));
7905     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7906     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7907     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7908     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7909                                             Spacing));
7910     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7911                                             Spacing * 2));
7912     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7913                                             Spacing * 3));
7914     TmpInst.addOperand(Inst.getOperand(1)); // lane
7915     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7916     TmpInst.addOperand(Inst.getOperand(5));
7917     Inst = TmpInst;
7918     return true;
7919   }
7920 
7921   // VLD3DUP single 3-element structure to all lanes instructions.
7922   case ARM::VLD3DUPdAsm_8:
7923   case ARM::VLD3DUPdAsm_16:
7924   case ARM::VLD3DUPdAsm_32:
7925   case ARM::VLD3DUPqAsm_8:
7926   case ARM::VLD3DUPqAsm_16:
7927   case ARM::VLD3DUPqAsm_32: {
7928     MCInst TmpInst;
7929     unsigned Spacing;
7930     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7931     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7932     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7933                                             Spacing));
7934     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7935                                             Spacing * 2));
7936     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7937     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7938     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7939     TmpInst.addOperand(Inst.getOperand(4));
7940     Inst = TmpInst;
7941     return true;
7942   }
7943 
7944   case ARM::VLD3DUPdWB_fixed_Asm_8:
7945   case ARM::VLD3DUPdWB_fixed_Asm_16:
7946   case ARM::VLD3DUPdWB_fixed_Asm_32:
7947   case ARM::VLD3DUPqWB_fixed_Asm_8:
7948   case ARM::VLD3DUPqWB_fixed_Asm_16:
7949   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7950     MCInst TmpInst;
7951     unsigned Spacing;
7952     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7953     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7954     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7955                                             Spacing));
7956     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7957                                             Spacing * 2));
7958     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7959     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7960     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7961     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7962     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7963     TmpInst.addOperand(Inst.getOperand(4));
7964     Inst = TmpInst;
7965     return true;
7966   }
7967 
7968   case ARM::VLD3DUPdWB_register_Asm_8:
7969   case ARM::VLD3DUPdWB_register_Asm_16:
7970   case ARM::VLD3DUPdWB_register_Asm_32:
7971   case ARM::VLD3DUPqWB_register_Asm_8:
7972   case ARM::VLD3DUPqWB_register_Asm_16:
7973   case ARM::VLD3DUPqWB_register_Asm_32: {
7974     MCInst TmpInst;
7975     unsigned Spacing;
7976     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7977     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7978     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7979                                             Spacing));
7980     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7981                                             Spacing * 2));
7982     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7983     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7984     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7985     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7986     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7987     TmpInst.addOperand(Inst.getOperand(5));
7988     Inst = TmpInst;
7989     return true;
7990   }
7991 
7992   // VLD3 multiple 3-element structure instructions.
7993   case ARM::VLD3dAsm_8:
7994   case ARM::VLD3dAsm_16:
7995   case ARM::VLD3dAsm_32:
7996   case ARM::VLD3qAsm_8:
7997   case ARM::VLD3qAsm_16:
7998   case ARM::VLD3qAsm_32: {
7999     MCInst TmpInst;
8000     unsigned Spacing;
8001     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8002     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8003     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8004                                             Spacing));
8005     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8006                                             Spacing * 2));
8007     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8008     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8009     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8010     TmpInst.addOperand(Inst.getOperand(4));
8011     Inst = TmpInst;
8012     return true;
8013   }
8014 
8015   case ARM::VLD3dWB_fixed_Asm_8:
8016   case ARM::VLD3dWB_fixed_Asm_16:
8017   case ARM::VLD3dWB_fixed_Asm_32:
8018   case ARM::VLD3qWB_fixed_Asm_8:
8019   case ARM::VLD3qWB_fixed_Asm_16:
8020   case ARM::VLD3qWB_fixed_Asm_32: {
8021     MCInst TmpInst;
8022     unsigned Spacing;
8023     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8024     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8025     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8026                                             Spacing));
8027     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8028                                             Spacing * 2));
8029     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8030     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8031     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8032     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8033     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8034     TmpInst.addOperand(Inst.getOperand(4));
8035     Inst = TmpInst;
8036     return true;
8037   }
8038 
8039   case ARM::VLD3dWB_register_Asm_8:
8040   case ARM::VLD3dWB_register_Asm_16:
8041   case ARM::VLD3dWB_register_Asm_32:
8042   case ARM::VLD3qWB_register_Asm_8:
8043   case ARM::VLD3qWB_register_Asm_16:
8044   case ARM::VLD3qWB_register_Asm_32: {
8045     MCInst TmpInst;
8046     unsigned Spacing;
8047     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8048     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8049     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8050                                             Spacing));
8051     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8052                                             Spacing * 2));
8053     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8054     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8055     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8056     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8057     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8058     TmpInst.addOperand(Inst.getOperand(5));
8059     Inst = TmpInst;
8060     return true;
8061   }
8062 
8063   // VLD4DUP single 3-element structure to all lanes instructions.
8064   case ARM::VLD4DUPdAsm_8:
8065   case ARM::VLD4DUPdAsm_16:
8066   case ARM::VLD4DUPdAsm_32:
8067   case ARM::VLD4DUPqAsm_8:
8068   case ARM::VLD4DUPqAsm_16:
8069   case ARM::VLD4DUPqAsm_32: {
8070     MCInst TmpInst;
8071     unsigned Spacing;
8072     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8073     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8074     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8075                                             Spacing));
8076     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8077                                             Spacing * 2));
8078     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8079                                             Spacing * 3));
8080     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8081     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8082     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8083     TmpInst.addOperand(Inst.getOperand(4));
8084     Inst = TmpInst;
8085     return true;
8086   }
8087 
8088   case ARM::VLD4DUPdWB_fixed_Asm_8:
8089   case ARM::VLD4DUPdWB_fixed_Asm_16:
8090   case ARM::VLD4DUPdWB_fixed_Asm_32:
8091   case ARM::VLD4DUPqWB_fixed_Asm_8:
8092   case ARM::VLD4DUPqWB_fixed_Asm_16:
8093   case ARM::VLD4DUPqWB_fixed_Asm_32: {
8094     MCInst TmpInst;
8095     unsigned Spacing;
8096     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8097     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8098     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8099                                             Spacing));
8100     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8101                                             Spacing * 2));
8102     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8103                                             Spacing * 3));
8104     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8105     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8106     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8107     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8108     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8109     TmpInst.addOperand(Inst.getOperand(4));
8110     Inst = TmpInst;
8111     return true;
8112   }
8113 
8114   case ARM::VLD4DUPdWB_register_Asm_8:
8115   case ARM::VLD4DUPdWB_register_Asm_16:
8116   case ARM::VLD4DUPdWB_register_Asm_32:
8117   case ARM::VLD4DUPqWB_register_Asm_8:
8118   case ARM::VLD4DUPqWB_register_Asm_16:
8119   case ARM::VLD4DUPqWB_register_Asm_32: {
8120     MCInst TmpInst;
8121     unsigned Spacing;
8122     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8123     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8124     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8125                                             Spacing));
8126     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8127                                             Spacing * 2));
8128     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8129                                             Spacing * 3));
8130     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8131     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8132     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8133     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8134     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8135     TmpInst.addOperand(Inst.getOperand(5));
8136     Inst = TmpInst;
8137     return true;
8138   }
8139 
8140   // VLD4 multiple 4-element structure instructions.
8141   case ARM::VLD4dAsm_8:
8142   case ARM::VLD4dAsm_16:
8143   case ARM::VLD4dAsm_32:
8144   case ARM::VLD4qAsm_8:
8145   case ARM::VLD4qAsm_16:
8146   case ARM::VLD4qAsm_32: {
8147     MCInst TmpInst;
8148     unsigned Spacing;
8149     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8150     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8151     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8152                                             Spacing));
8153     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8154                                             Spacing * 2));
8155     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8156                                             Spacing * 3));
8157     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8158     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8159     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8160     TmpInst.addOperand(Inst.getOperand(4));
8161     Inst = TmpInst;
8162     return true;
8163   }
8164 
8165   case ARM::VLD4dWB_fixed_Asm_8:
8166   case ARM::VLD4dWB_fixed_Asm_16:
8167   case ARM::VLD4dWB_fixed_Asm_32:
8168   case ARM::VLD4qWB_fixed_Asm_8:
8169   case ARM::VLD4qWB_fixed_Asm_16:
8170   case ARM::VLD4qWB_fixed_Asm_32: {
8171     MCInst TmpInst;
8172     unsigned Spacing;
8173     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8174     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8175     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8176                                             Spacing));
8177     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8178                                             Spacing * 2));
8179     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8180                                             Spacing * 3));
8181     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8182     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8183     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8184     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8185     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8186     TmpInst.addOperand(Inst.getOperand(4));
8187     Inst = TmpInst;
8188     return true;
8189   }
8190 
8191   case ARM::VLD4dWB_register_Asm_8:
8192   case ARM::VLD4dWB_register_Asm_16:
8193   case ARM::VLD4dWB_register_Asm_32:
8194   case ARM::VLD4qWB_register_Asm_8:
8195   case ARM::VLD4qWB_register_Asm_16:
8196   case ARM::VLD4qWB_register_Asm_32: {
8197     MCInst TmpInst;
8198     unsigned Spacing;
8199     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8200     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8201     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8202                                             Spacing));
8203     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8204                                             Spacing * 2));
8205     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8206                                             Spacing * 3));
8207     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8208     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8209     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8210     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8211     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8212     TmpInst.addOperand(Inst.getOperand(5));
8213     Inst = TmpInst;
8214     return true;
8215   }
8216 
8217   // VST3 multiple 3-element structure instructions.
8218   case ARM::VST3dAsm_8:
8219   case ARM::VST3dAsm_16:
8220   case ARM::VST3dAsm_32:
8221   case ARM::VST3qAsm_8:
8222   case ARM::VST3qAsm_16:
8223   case ARM::VST3qAsm_32: {
8224     MCInst TmpInst;
8225     unsigned Spacing;
8226     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8227     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8228     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8229     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8230     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8231                                             Spacing));
8232     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8233                                             Spacing * 2));
8234     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8235     TmpInst.addOperand(Inst.getOperand(4));
8236     Inst = TmpInst;
8237     return true;
8238   }
8239 
8240   case ARM::VST3dWB_fixed_Asm_8:
8241   case ARM::VST3dWB_fixed_Asm_16:
8242   case ARM::VST3dWB_fixed_Asm_32:
8243   case ARM::VST3qWB_fixed_Asm_8:
8244   case ARM::VST3qWB_fixed_Asm_16:
8245   case ARM::VST3qWB_fixed_Asm_32: {
8246     MCInst TmpInst;
8247     unsigned Spacing;
8248     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8249     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8250     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8251     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8252     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8253     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8254     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8255                                             Spacing));
8256     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8257                                             Spacing * 2));
8258     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8259     TmpInst.addOperand(Inst.getOperand(4));
8260     Inst = TmpInst;
8261     return true;
8262   }
8263 
8264   case ARM::VST3dWB_register_Asm_8:
8265   case ARM::VST3dWB_register_Asm_16:
8266   case ARM::VST3dWB_register_Asm_32:
8267   case ARM::VST3qWB_register_Asm_8:
8268   case ARM::VST3qWB_register_Asm_16:
8269   case ARM::VST3qWB_register_Asm_32: {
8270     MCInst TmpInst;
8271     unsigned Spacing;
8272     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8273     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8274     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8275     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8276     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8277     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8278     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8279                                             Spacing));
8280     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8281                                             Spacing * 2));
8282     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8283     TmpInst.addOperand(Inst.getOperand(5));
8284     Inst = TmpInst;
8285     return true;
8286   }
8287 
8288   // VST4 multiple 3-element structure instructions.
8289   case ARM::VST4dAsm_8:
8290   case ARM::VST4dAsm_16:
8291   case ARM::VST4dAsm_32:
8292   case ARM::VST4qAsm_8:
8293   case ARM::VST4qAsm_16:
8294   case ARM::VST4qAsm_32: {
8295     MCInst TmpInst;
8296     unsigned Spacing;
8297     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8298     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8299     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8300     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8301     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8302                                             Spacing));
8303     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8304                                             Spacing * 2));
8305     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8306                                             Spacing * 3));
8307     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8308     TmpInst.addOperand(Inst.getOperand(4));
8309     Inst = TmpInst;
8310     return true;
8311   }
8312 
8313   case ARM::VST4dWB_fixed_Asm_8:
8314   case ARM::VST4dWB_fixed_Asm_16:
8315   case ARM::VST4dWB_fixed_Asm_32:
8316   case ARM::VST4qWB_fixed_Asm_8:
8317   case ARM::VST4qWB_fixed_Asm_16:
8318   case ARM::VST4qWB_fixed_Asm_32: {
8319     MCInst TmpInst;
8320     unsigned Spacing;
8321     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8322     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8323     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8324     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8325     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8326     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8327     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8328                                             Spacing));
8329     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8330                                             Spacing * 2));
8331     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8332                                             Spacing * 3));
8333     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8334     TmpInst.addOperand(Inst.getOperand(4));
8335     Inst = TmpInst;
8336     return true;
8337   }
8338 
8339   case ARM::VST4dWB_register_Asm_8:
8340   case ARM::VST4dWB_register_Asm_16:
8341   case ARM::VST4dWB_register_Asm_32:
8342   case ARM::VST4qWB_register_Asm_8:
8343   case ARM::VST4qWB_register_Asm_16:
8344   case ARM::VST4qWB_register_Asm_32: {
8345     MCInst TmpInst;
8346     unsigned Spacing;
8347     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8348     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8349     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8350     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8351     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8352     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8353     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8354                                             Spacing));
8355     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8356                                             Spacing * 2));
8357     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8358                                             Spacing * 3));
8359     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8360     TmpInst.addOperand(Inst.getOperand(5));
8361     Inst = TmpInst;
8362     return true;
8363   }
8364 
8365   // Handle encoding choice for the shift-immediate instructions.
8366   case ARM::t2LSLri:
8367   case ARM::t2LSRri:
8368   case ARM::t2ASRri:
8369     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8370         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8371         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8372         !HasWideQualifier) {
8373       unsigned NewOpc;
8374       switch (Inst.getOpcode()) {
8375       default: llvm_unreachable("unexpected opcode");
8376       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8377       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8378       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8379       }
8380       // The Thumb1 operands aren't in the same order. Awesome, eh?
8381       MCInst TmpInst;
8382       TmpInst.setOpcode(NewOpc);
8383       TmpInst.addOperand(Inst.getOperand(0));
8384       TmpInst.addOperand(Inst.getOperand(5));
8385       TmpInst.addOperand(Inst.getOperand(1));
8386       TmpInst.addOperand(Inst.getOperand(2));
8387       TmpInst.addOperand(Inst.getOperand(3));
8388       TmpInst.addOperand(Inst.getOperand(4));
8389       Inst = TmpInst;
8390       return true;
8391     }
8392     return false;
8393 
8394   // Handle the Thumb2 mode MOV complex aliases.
8395   case ARM::t2MOVsr:
8396   case ARM::t2MOVSsr: {
8397     // Which instruction to expand to depends on the CCOut operand and
8398     // whether we're in an IT block if the register operands are low
8399     // registers.
8400     bool isNarrow = false;
8401     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8402         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8403         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8404         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8405         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8406         !HasWideQualifier)
8407       isNarrow = true;
8408     MCInst TmpInst;
8409     unsigned newOpc;
8410     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8411     default: llvm_unreachable("unexpected opcode!");
8412     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8413     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8414     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8415     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8416     }
8417     TmpInst.setOpcode(newOpc);
8418     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8419     if (isNarrow)
8420       TmpInst.addOperand(MCOperand::createReg(
8421           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8422     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8423     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8424     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8425     TmpInst.addOperand(Inst.getOperand(5));
8426     if (!isNarrow)
8427       TmpInst.addOperand(MCOperand::createReg(
8428           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8429     Inst = TmpInst;
8430     return true;
8431   }
8432   case ARM::t2MOVsi:
8433   case ARM::t2MOVSsi: {
8434     // Which instruction to expand to depends on the CCOut operand and
8435     // whether we're in an IT block if the register operands are low
8436     // registers.
8437     bool isNarrow = false;
8438     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8439         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8440         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8441         !HasWideQualifier)
8442       isNarrow = true;
8443     MCInst TmpInst;
8444     unsigned newOpc;
8445     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8446     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8447     bool isMov = false;
8448     // MOV rd, rm, LSL #0 is actually a MOV instruction
8449     if (Shift == ARM_AM::lsl && Amount == 0) {
8450       isMov = true;
8451       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8452       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8453       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8454       // instead.
8455       if (inITBlock()) {
8456         isNarrow = false;
8457       }
8458       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8459     } else {
8460       switch(Shift) {
8461       default: llvm_unreachable("unexpected opcode!");
8462       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8463       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8464       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8465       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8466       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8467       }
8468     }
8469     if (Amount == 32) Amount = 0;
8470     TmpInst.setOpcode(newOpc);
8471     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8472     if (isNarrow && !isMov)
8473       TmpInst.addOperand(MCOperand::createReg(
8474           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8475     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8476     if (newOpc != ARM::t2RRX && !isMov)
8477       TmpInst.addOperand(MCOperand::createImm(Amount));
8478     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8479     TmpInst.addOperand(Inst.getOperand(4));
8480     if (!isNarrow)
8481       TmpInst.addOperand(MCOperand::createReg(
8482           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8483     Inst = TmpInst;
8484     return true;
8485   }
8486   // Handle the ARM mode MOV complex aliases.
8487   case ARM::ASRr:
8488   case ARM::LSRr:
8489   case ARM::LSLr:
8490   case ARM::RORr: {
8491     ARM_AM::ShiftOpc ShiftTy;
8492     switch(Inst.getOpcode()) {
8493     default: llvm_unreachable("unexpected opcode!");
8494     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8495     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8496     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8497     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8498     }
8499     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8500     MCInst TmpInst;
8501     TmpInst.setOpcode(ARM::MOVsr);
8502     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8503     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8504     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8505     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8506     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8507     TmpInst.addOperand(Inst.getOperand(4));
8508     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8509     Inst = TmpInst;
8510     return true;
8511   }
8512   case ARM::ASRi:
8513   case ARM::LSRi:
8514   case ARM::LSLi:
8515   case ARM::RORi: {
8516     ARM_AM::ShiftOpc ShiftTy;
8517     switch(Inst.getOpcode()) {
8518     default: llvm_unreachable("unexpected opcode!");
8519     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8520     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8521     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8522     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8523     }
8524     // A shift by zero is a plain MOVr, not a MOVsi.
8525     unsigned Amt = Inst.getOperand(2).getImm();
8526     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8527     // A shift by 32 should be encoded as 0 when permitted
8528     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8529       Amt = 0;
8530     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8531     MCInst TmpInst;
8532     TmpInst.setOpcode(Opc);
8533     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8534     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8535     if (Opc == ARM::MOVsi)
8536       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8537     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8538     TmpInst.addOperand(Inst.getOperand(4));
8539     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8540     Inst = TmpInst;
8541     return true;
8542   }
8543   case ARM::RRXi: {
8544     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8545     MCInst TmpInst;
8546     TmpInst.setOpcode(ARM::MOVsi);
8547     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8548     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8549     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8550     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8551     TmpInst.addOperand(Inst.getOperand(3));
8552     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8553     Inst = TmpInst;
8554     return true;
8555   }
8556   case ARM::t2LDMIA_UPD: {
8557     // If this is a load of a single register, then we should use
8558     // a post-indexed LDR instruction instead, per the ARM ARM.
8559     if (Inst.getNumOperands() != 5)
8560       return false;
8561     MCInst TmpInst;
8562     TmpInst.setOpcode(ARM::t2LDR_POST);
8563     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8564     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8565     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8566     TmpInst.addOperand(MCOperand::createImm(4));
8567     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8568     TmpInst.addOperand(Inst.getOperand(3));
8569     Inst = TmpInst;
8570     return true;
8571   }
8572   case ARM::t2STMDB_UPD: {
8573     // If this is a store of a single register, then we should use
8574     // a pre-indexed STR instruction instead, per the ARM ARM.
8575     if (Inst.getNumOperands() != 5)
8576       return false;
8577     MCInst TmpInst;
8578     TmpInst.setOpcode(ARM::t2STR_PRE);
8579     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8580     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8581     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8582     TmpInst.addOperand(MCOperand::createImm(-4));
8583     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8584     TmpInst.addOperand(Inst.getOperand(3));
8585     Inst = TmpInst;
8586     return true;
8587   }
8588   case ARM::LDMIA_UPD:
8589     // If this is a load of a single register via a 'pop', then we should use
8590     // a post-indexed LDR instruction instead, per the ARM ARM.
8591     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8592         Inst.getNumOperands() == 5) {
8593       MCInst TmpInst;
8594       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8595       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8596       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8597       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8598       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8599       TmpInst.addOperand(MCOperand::createImm(4));
8600       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8601       TmpInst.addOperand(Inst.getOperand(3));
8602       Inst = TmpInst;
8603       return true;
8604     }
8605     break;
8606   case ARM::STMDB_UPD:
8607     // If this is a store of a single register via a 'push', then we should use
8608     // a pre-indexed STR instruction instead, per the ARM ARM.
8609     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8610         Inst.getNumOperands() == 5) {
8611       MCInst TmpInst;
8612       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8613       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8614       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8615       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8616       TmpInst.addOperand(MCOperand::createImm(-4));
8617       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8618       TmpInst.addOperand(Inst.getOperand(3));
8619       Inst = TmpInst;
8620     }
8621     break;
8622   case ARM::t2ADDri12:
8623     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8624     // mnemonic was used (not "addw"), encoding T3 is preferred.
8625     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8626         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8627       break;
8628     Inst.setOpcode(ARM::t2ADDri);
8629     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8630     break;
8631   case ARM::t2SUBri12:
8632     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8633     // mnemonic was used (not "subw"), encoding T3 is preferred.
8634     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8635         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8636       break;
8637     Inst.setOpcode(ARM::t2SUBri);
8638     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8639     break;
8640   case ARM::tADDi8:
8641     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8642     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8643     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8644     // to encoding T1 if <Rd> is omitted."
8645     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8646       Inst.setOpcode(ARM::tADDi3);
8647       return true;
8648     }
8649     break;
8650   case ARM::tSUBi8:
8651     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8652     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8653     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8654     // to encoding T1 if <Rd> is omitted."
8655     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8656       Inst.setOpcode(ARM::tSUBi3);
8657       return true;
8658     }
8659     break;
8660   case ARM::t2ADDri:
8661   case ARM::t2SUBri: {
8662     // If the destination and first source operand are the same, and
8663     // the flags are compatible with the current IT status, use encoding T2
8664     // instead of T3. For compatibility with the system 'as'. Make sure the
8665     // wide encoding wasn't explicit.
8666     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8667         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8668         (Inst.getOperand(2).isImm() &&
8669          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8670         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8671         HasWideQualifier)
8672       break;
8673     MCInst TmpInst;
8674     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8675                       ARM::tADDi8 : ARM::tSUBi8);
8676     TmpInst.addOperand(Inst.getOperand(0));
8677     TmpInst.addOperand(Inst.getOperand(5));
8678     TmpInst.addOperand(Inst.getOperand(0));
8679     TmpInst.addOperand(Inst.getOperand(2));
8680     TmpInst.addOperand(Inst.getOperand(3));
8681     TmpInst.addOperand(Inst.getOperand(4));
8682     Inst = TmpInst;
8683     return true;
8684   }
8685   case ARM::t2ADDrr: {
8686     // If the destination and first source operand are the same, and
8687     // there's no setting of the flags, use encoding T2 instead of T3.
8688     // Note that this is only for ADD, not SUB. This mirrors the system
8689     // 'as' behaviour.  Also take advantage of ADD being commutative.
8690     // Make sure the wide encoding wasn't explicit.
8691     bool Swap = false;
8692     auto DestReg = Inst.getOperand(0).getReg();
8693     bool Transform = DestReg == Inst.getOperand(1).getReg();
8694     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8695       Transform = true;
8696       Swap = true;
8697     }
8698     if (!Transform ||
8699         Inst.getOperand(5).getReg() != 0 ||
8700         HasWideQualifier)
8701       break;
8702     MCInst TmpInst;
8703     TmpInst.setOpcode(ARM::tADDhirr);
8704     TmpInst.addOperand(Inst.getOperand(0));
8705     TmpInst.addOperand(Inst.getOperand(0));
8706     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8707     TmpInst.addOperand(Inst.getOperand(3));
8708     TmpInst.addOperand(Inst.getOperand(4));
8709     Inst = TmpInst;
8710     return true;
8711   }
8712   case ARM::tADDrSP:
8713     // If the non-SP source operand and the destination operand are not the
8714     // same, we need to use the 32-bit encoding if it's available.
8715     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8716       Inst.setOpcode(ARM::t2ADDrr);
8717       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8718       return true;
8719     }
8720     break;
8721   case ARM::tB:
8722     // A Thumb conditional branch outside of an IT block is a tBcc.
8723     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8724       Inst.setOpcode(ARM::tBcc);
8725       return true;
8726     }
8727     break;
8728   case ARM::t2B:
8729     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8730     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8731       Inst.setOpcode(ARM::t2Bcc);
8732       return true;
8733     }
8734     break;
8735   case ARM::t2Bcc:
8736     // If the conditional is AL or we're in an IT block, we really want t2B.
8737     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8738       Inst.setOpcode(ARM::t2B);
8739       return true;
8740     }
8741     break;
8742   case ARM::tBcc:
8743     // If the conditional is AL, we really want tB.
8744     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8745       Inst.setOpcode(ARM::tB);
8746       return true;
8747     }
8748     break;
8749   case ARM::tLDMIA: {
8750     // If the register list contains any high registers, or if the writeback
8751     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8752     // instead if we're in Thumb2. Otherwise, this should have generated
8753     // an error in validateInstruction().
8754     unsigned Rn = Inst.getOperand(0).getReg();
8755     bool hasWritebackToken =
8756         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8757          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8758     bool listContainsBase;
8759     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8760         (!listContainsBase && !hasWritebackToken) ||
8761         (listContainsBase && hasWritebackToken)) {
8762       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8763       assert(isThumbTwo());
8764       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8765       // If we're switching to the updating version, we need to insert
8766       // the writeback tied operand.
8767       if (hasWritebackToken)
8768         Inst.insert(Inst.begin(),
8769                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8770       return true;
8771     }
8772     break;
8773   }
8774   case ARM::tSTMIA_UPD: {
8775     // If the register list contains any high registers, we need to use
8776     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8777     // should have generated an error in validateInstruction().
8778     unsigned Rn = Inst.getOperand(0).getReg();
8779     bool listContainsBase;
8780     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8781       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8782       assert(isThumbTwo());
8783       Inst.setOpcode(ARM::t2STMIA_UPD);
8784       return true;
8785     }
8786     break;
8787   }
8788   case ARM::tPOP: {
8789     bool listContainsBase;
8790     // If the register list contains any high registers, we need to use
8791     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8792     // should have generated an error in validateInstruction().
8793     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8794       return false;
8795     assert(isThumbTwo());
8796     Inst.setOpcode(ARM::t2LDMIA_UPD);
8797     // Add the base register and writeback operands.
8798     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8799     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8800     return true;
8801   }
8802   case ARM::tPUSH: {
8803     bool listContainsBase;
8804     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8805       return false;
8806     assert(isThumbTwo());
8807     Inst.setOpcode(ARM::t2STMDB_UPD);
8808     // Add the base register and writeback operands.
8809     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8810     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8811     return true;
8812   }
8813   case ARM::t2MOVi:
8814     // If we can use the 16-bit encoding and the user didn't explicitly
8815     // request the 32-bit variant, transform it here.
8816     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8817         (Inst.getOperand(1).isImm() &&
8818          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8819         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8820         !HasWideQualifier) {
8821       // The operands aren't in the same order for tMOVi8...
8822       MCInst TmpInst;
8823       TmpInst.setOpcode(ARM::tMOVi8);
8824       TmpInst.addOperand(Inst.getOperand(0));
8825       TmpInst.addOperand(Inst.getOperand(4));
8826       TmpInst.addOperand(Inst.getOperand(1));
8827       TmpInst.addOperand(Inst.getOperand(2));
8828       TmpInst.addOperand(Inst.getOperand(3));
8829       Inst = TmpInst;
8830       return true;
8831     }
8832     break;
8833 
8834   case ARM::t2MOVr:
8835     // If we can use the 16-bit encoding and the user didn't explicitly
8836     // request the 32-bit variant, transform it here.
8837     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8838         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8839         Inst.getOperand(2).getImm() == ARMCC::AL &&
8840         Inst.getOperand(4).getReg() == ARM::CPSR &&
8841         !HasWideQualifier) {
8842       // The operands aren't the same for tMOV[S]r... (no cc_out)
8843       MCInst TmpInst;
8844       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8845       TmpInst.addOperand(Inst.getOperand(0));
8846       TmpInst.addOperand(Inst.getOperand(1));
8847       TmpInst.addOperand(Inst.getOperand(2));
8848       TmpInst.addOperand(Inst.getOperand(3));
8849       Inst = TmpInst;
8850       return true;
8851     }
8852     break;
8853 
8854   case ARM::t2SXTH:
8855   case ARM::t2SXTB:
8856   case ARM::t2UXTH:
8857   case ARM::t2UXTB:
8858     // If we can use the 16-bit encoding and the user didn't explicitly
8859     // request the 32-bit variant, transform it here.
8860     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8861         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8862         Inst.getOperand(2).getImm() == 0 &&
8863         !HasWideQualifier) {
8864       unsigned NewOpc;
8865       switch (Inst.getOpcode()) {
8866       default: llvm_unreachable("Illegal opcode!");
8867       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8868       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8869       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8870       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8871       }
8872       // The operands aren't the same for thumb1 (no rotate operand).
8873       MCInst TmpInst;
8874       TmpInst.setOpcode(NewOpc);
8875       TmpInst.addOperand(Inst.getOperand(0));
8876       TmpInst.addOperand(Inst.getOperand(1));
8877       TmpInst.addOperand(Inst.getOperand(3));
8878       TmpInst.addOperand(Inst.getOperand(4));
8879       Inst = TmpInst;
8880       return true;
8881     }
8882     break;
8883 
8884   case ARM::MOVsi: {
8885     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8886     // rrx shifts and asr/lsr of #32 is encoded as 0
8887     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8888       return false;
8889     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8890       // Shifting by zero is accepted as a vanilla 'MOVr'
8891       MCInst TmpInst;
8892       TmpInst.setOpcode(ARM::MOVr);
8893       TmpInst.addOperand(Inst.getOperand(0));
8894       TmpInst.addOperand(Inst.getOperand(1));
8895       TmpInst.addOperand(Inst.getOperand(3));
8896       TmpInst.addOperand(Inst.getOperand(4));
8897       TmpInst.addOperand(Inst.getOperand(5));
8898       Inst = TmpInst;
8899       return true;
8900     }
8901     return false;
8902   }
8903   case ARM::ANDrsi:
8904   case ARM::ORRrsi:
8905   case ARM::EORrsi:
8906   case ARM::BICrsi:
8907   case ARM::SUBrsi:
8908   case ARM::ADDrsi: {
8909     unsigned newOpc;
8910     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8911     if (SOpc == ARM_AM::rrx) return false;
8912     switch (Inst.getOpcode()) {
8913     default: llvm_unreachable("unexpected opcode!");
8914     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8915     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8916     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8917     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8918     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8919     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8920     }
8921     // If the shift is by zero, use the non-shifted instruction definition.
8922     // The exception is for right shifts, where 0 == 32
8923     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8924         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8925       MCInst TmpInst;
8926       TmpInst.setOpcode(newOpc);
8927       TmpInst.addOperand(Inst.getOperand(0));
8928       TmpInst.addOperand(Inst.getOperand(1));
8929       TmpInst.addOperand(Inst.getOperand(2));
8930       TmpInst.addOperand(Inst.getOperand(4));
8931       TmpInst.addOperand(Inst.getOperand(5));
8932       TmpInst.addOperand(Inst.getOperand(6));
8933       Inst = TmpInst;
8934       return true;
8935     }
8936     return false;
8937   }
8938   case ARM::ITasm:
8939   case ARM::t2IT: {
8940     MCOperand &MO = Inst.getOperand(1);
8941     unsigned Mask = MO.getImm();
8942     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8943 
8944     // Set up the IT block state according to the IT instruction we just
8945     // matched.
8946     assert(!inITBlock() && "nested IT blocks?!");
8947     startExplicitITBlock(Cond, Mask);
8948     MO.setImm(getITMaskEncoding());
8949     break;
8950   }
8951   case ARM::t2LSLrr:
8952   case ARM::t2LSRrr:
8953   case ARM::t2ASRrr:
8954   case ARM::t2SBCrr:
8955   case ARM::t2RORrr:
8956   case ARM::t2BICrr:
8957     // Assemblers should use the narrow encodings of these instructions when permissible.
8958     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8959          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8960         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8961         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8962         !HasWideQualifier) {
8963       unsigned NewOpc;
8964       switch (Inst.getOpcode()) {
8965         default: llvm_unreachable("unexpected opcode");
8966         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8967         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8968         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8969         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8970         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8971         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8972       }
8973       MCInst TmpInst;
8974       TmpInst.setOpcode(NewOpc);
8975       TmpInst.addOperand(Inst.getOperand(0));
8976       TmpInst.addOperand(Inst.getOperand(5));
8977       TmpInst.addOperand(Inst.getOperand(1));
8978       TmpInst.addOperand(Inst.getOperand(2));
8979       TmpInst.addOperand(Inst.getOperand(3));
8980       TmpInst.addOperand(Inst.getOperand(4));
8981       Inst = TmpInst;
8982       return true;
8983     }
8984     return false;
8985 
8986   case ARM::t2ANDrr:
8987   case ARM::t2EORrr:
8988   case ARM::t2ADCrr:
8989   case ARM::t2ORRrr:
8990     // Assemblers should use the narrow encodings of these instructions when permissible.
8991     // These instructions are special in that they are commutable, so shorter encodings
8992     // are available more often.
8993     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8994          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8995         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8996          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8997         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8998         !HasWideQualifier) {
8999       unsigned NewOpc;
9000       switch (Inst.getOpcode()) {
9001         default: llvm_unreachable("unexpected opcode");
9002         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
9003         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
9004         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
9005         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
9006       }
9007       MCInst TmpInst;
9008       TmpInst.setOpcode(NewOpc);
9009       TmpInst.addOperand(Inst.getOperand(0));
9010       TmpInst.addOperand(Inst.getOperand(5));
9011       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
9012         TmpInst.addOperand(Inst.getOperand(1));
9013         TmpInst.addOperand(Inst.getOperand(2));
9014       } else {
9015         TmpInst.addOperand(Inst.getOperand(2));
9016         TmpInst.addOperand(Inst.getOperand(1));
9017       }
9018       TmpInst.addOperand(Inst.getOperand(3));
9019       TmpInst.addOperand(Inst.getOperand(4));
9020       Inst = TmpInst;
9021       return true;
9022     }
9023     return false;
9024   }
9025   return false;
9026 }
9027 
9028 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
9029   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
9030   // suffix depending on whether they're in an IT block or not.
9031   unsigned Opc = Inst.getOpcode();
9032   const MCInstrDesc &MCID = MII.get(Opc);
9033   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
9034     assert(MCID.hasOptionalDef() &&
9035            "optionally flag setting instruction missing optional def operand");
9036     assert(MCID.NumOperands == Inst.getNumOperands() &&
9037            "operand count mismatch!");
9038     // Find the optional-def operand (cc_out).
9039     unsigned OpNo;
9040     for (OpNo = 0;
9041          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
9042          ++OpNo)
9043       ;
9044     // If we're parsing Thumb1, reject it completely.
9045     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
9046       return Match_RequiresFlagSetting;
9047     // If we're parsing Thumb2, which form is legal depends on whether we're
9048     // in an IT block.
9049     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
9050         !inITBlock())
9051       return Match_RequiresITBlock;
9052     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
9053         inITBlock())
9054       return Match_RequiresNotITBlock;
9055     // LSL with zero immediate is not allowed in an IT block
9056     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
9057       return Match_RequiresNotITBlock;
9058   } else if (isThumbOne()) {
9059     // Some high-register supporting Thumb1 encodings only allow both registers
9060     // to be from r0-r7 when in Thumb2.
9061     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
9062         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9063         isARMLowRegister(Inst.getOperand(2).getReg()))
9064       return Match_RequiresThumb2;
9065     // Others only require ARMv6 or later.
9066     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
9067              isARMLowRegister(Inst.getOperand(0).getReg()) &&
9068              isARMLowRegister(Inst.getOperand(1).getReg()))
9069       return Match_RequiresV6;
9070   }
9071 
9072   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
9073   // than the loop below can handle, so it uses the GPRnopc register class and
9074   // we do SP handling here.
9075   if (Opc == ARM::t2MOVr && !hasV8Ops())
9076   {
9077     // SP as both source and destination is not allowed
9078     if (Inst.getOperand(0).getReg() == ARM::SP &&
9079         Inst.getOperand(1).getReg() == ARM::SP)
9080       return Match_RequiresV8;
9081     // When flags-setting SP as either source or destination is not allowed
9082     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
9083         (Inst.getOperand(0).getReg() == ARM::SP ||
9084          Inst.getOperand(1).getReg() == ARM::SP))
9085       return Match_RequiresV8;
9086   }
9087 
9088   // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
9089   // ARMv8-A.
9090   if ((Inst.getOpcode() == ARM::VMRS || Inst.getOpcode() == ARM::VMSR) &&
9091       Inst.getOperand(0).getReg() == ARM::SP && (isThumb() && !hasV8Ops()))
9092     return Match_InvalidOperand;
9093 
9094   for (unsigned I = 0; I < MCID.NumOperands; ++I)
9095     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
9096       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
9097       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
9098         return Match_RequiresV8;
9099       else if (Inst.getOperand(I).getReg() == ARM::PC)
9100         return Match_InvalidOperand;
9101     }
9102 
9103   return Match_Success;
9104 }
9105 
9106 namespace llvm {
9107 
9108 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
9109   return true; // In an assembly source, no need to second-guess
9110 }
9111 
9112 } // end namespace llvm
9113 
9114 // Returns true if Inst is unpredictable if it is in and IT block, but is not
9115 // the last instruction in the block.
9116 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
9117   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9118 
9119   // All branch & call instructions terminate IT blocks with the exception of
9120   // SVC.
9121   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
9122       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
9123     return true;
9124 
9125   // Any arithmetic instruction which writes to the PC also terminates the IT
9126   // block.
9127   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
9128     MCOperand &Op = Inst.getOperand(OpIdx);
9129     if (Op.isReg() && Op.getReg() == ARM::PC)
9130       return true;
9131   }
9132 
9133   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
9134     return true;
9135 
9136   // Instructions with variable operand lists, which write to the variable
9137   // operands. We only care about Thumb instructions here, as ARM instructions
9138   // obviously can't be in an IT block.
9139   switch (Inst.getOpcode()) {
9140   case ARM::tLDMIA:
9141   case ARM::t2LDMIA:
9142   case ARM::t2LDMIA_UPD:
9143   case ARM::t2LDMDB:
9144   case ARM::t2LDMDB_UPD:
9145     if (listContainsReg(Inst, 3, ARM::PC))
9146       return true;
9147     break;
9148   case ARM::tPOP:
9149     if (listContainsReg(Inst, 2, ARM::PC))
9150       return true;
9151     break;
9152   }
9153 
9154   return false;
9155 }
9156 
9157 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
9158                                           SmallVectorImpl<NearMissInfo> &NearMisses,
9159                                           bool MatchingInlineAsm,
9160                                           bool &EmitInITBlock,
9161                                           MCStreamer &Out) {
9162   // If we can't use an implicit IT block here, just match as normal.
9163   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
9164     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
9165 
9166   // Try to match the instruction in an extension of the current IT block (if
9167   // there is one).
9168   if (inImplicitITBlock()) {
9169     extendImplicitITBlock(ITState.Cond);
9170     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
9171             Match_Success) {
9172       // The match succeded, but we still have to check that the instruction is
9173       // valid in this implicit IT block.
9174       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9175       if (MCID.isPredicable()) {
9176         ARMCC::CondCodes InstCond =
9177             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9178                 .getImm();
9179         ARMCC::CondCodes ITCond = currentITCond();
9180         if (InstCond == ITCond) {
9181           EmitInITBlock = true;
9182           return Match_Success;
9183         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
9184           invertCurrentITCondition();
9185           EmitInITBlock = true;
9186           return Match_Success;
9187         }
9188       }
9189     }
9190     rewindImplicitITPosition();
9191   }
9192 
9193   // Finish the current IT block, and try to match outside any IT block.
9194   flushPendingInstructions(Out);
9195   unsigned PlainMatchResult =
9196       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
9197   if (PlainMatchResult == Match_Success) {
9198     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9199     if (MCID.isPredicable()) {
9200       ARMCC::CondCodes InstCond =
9201           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9202               .getImm();
9203       // Some forms of the branch instruction have their own condition code
9204       // fields, so can be conditionally executed without an IT block.
9205       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
9206         EmitInITBlock = false;
9207         return Match_Success;
9208       }
9209       if (InstCond == ARMCC::AL) {
9210         EmitInITBlock = false;
9211         return Match_Success;
9212       }
9213     } else {
9214       EmitInITBlock = false;
9215       return Match_Success;
9216     }
9217   }
9218 
9219   // Try to match in a new IT block. The matcher doesn't check the actual
9220   // condition, so we create an IT block with a dummy condition, and fix it up
9221   // once we know the actual condition.
9222   startImplicitITBlock();
9223   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
9224       Match_Success) {
9225     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9226     if (MCID.isPredicable()) {
9227       ITState.Cond =
9228           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9229               .getImm();
9230       EmitInITBlock = true;
9231       return Match_Success;
9232     }
9233   }
9234   discardImplicitITBlock();
9235 
9236   // If none of these succeed, return the error we got when trying to match
9237   // outside any IT blocks.
9238   EmitInITBlock = false;
9239   return PlainMatchResult;
9240 }
9241 
9242 static std::string ARMMnemonicSpellCheck(StringRef S, uint64_t FBS,
9243                                          unsigned VariantID = 0);
9244 
9245 static const char *getSubtargetFeatureName(uint64_t Val);
9246 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
9247                                            OperandVector &Operands,
9248                                            MCStreamer &Out, uint64_t &ErrorInfo,
9249                                            bool MatchingInlineAsm) {
9250   MCInst Inst;
9251   unsigned MatchResult;
9252   bool PendConditionalInstruction = false;
9253 
9254   SmallVector<NearMissInfo, 4> NearMisses;
9255   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
9256                                  PendConditionalInstruction, Out);
9257 
9258   switch (MatchResult) {
9259   case Match_Success:
9260     // Context sensitive operand constraints aren't handled by the matcher,
9261     // so check them here.
9262     if (validateInstruction(Inst, Operands)) {
9263       // Still progress the IT block, otherwise one wrong condition causes
9264       // nasty cascading errors.
9265       forwardITPosition();
9266       return true;
9267     }
9268 
9269     { // processInstruction() updates inITBlock state, we need to save it away
9270       bool wasInITBlock = inITBlock();
9271 
9272       // Some instructions need post-processing to, for example, tweak which
9273       // encoding is selected. Loop on it while changes happen so the
9274       // individual transformations can chain off each other. E.g.,
9275       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9276       while (processInstruction(Inst, Operands, Out))
9277         ;
9278 
9279       // Only after the instruction is fully processed, we can validate it
9280       if (wasInITBlock && hasV8Ops() && isThumb() &&
9281           !isV8EligibleForIT(&Inst)) {
9282         Warning(IDLoc, "deprecated instruction in IT block");
9283       }
9284     }
9285 
9286     // Only move forward at the very end so that everything in validate
9287     // and process gets a consistent answer about whether we're in an IT
9288     // block.
9289     forwardITPosition();
9290 
9291     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9292     // doesn't actually encode.
9293     if (Inst.getOpcode() == ARM::ITasm)
9294       return false;
9295 
9296     Inst.setLoc(IDLoc);
9297     if (PendConditionalInstruction) {
9298       PendingConditionalInsts.push_back(Inst);
9299       if (isITBlockFull() || isITBlockTerminator(Inst))
9300         flushPendingInstructions(Out);
9301     } else {
9302       Out.EmitInstruction(Inst, getSTI());
9303     }
9304     return false;
9305   case Match_NearMisses:
9306     ReportNearMisses(NearMisses, IDLoc, Operands);
9307     return true;
9308   case Match_MnemonicFail: {
9309     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
9310     std::string Suggestion = ARMMnemonicSpellCheck(
9311       ((ARMOperand &)*Operands[0]).getToken(), FBS);
9312     return Error(IDLoc, "invalid instruction" + Suggestion,
9313                  ((ARMOperand &)*Operands[0]).getLocRange());
9314   }
9315   }
9316 
9317   llvm_unreachable("Implement any new match types added!");
9318 }
9319 
9320 /// parseDirective parses the arm specific directives
9321 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9322   const MCObjectFileInfo::Environment Format =
9323     getContext().getObjectFileInfo()->getObjectFileType();
9324   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9325   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9326 
9327   StringRef IDVal = DirectiveID.getIdentifier();
9328   if (IDVal == ".word")
9329     parseLiteralValues(4, DirectiveID.getLoc());
9330   else if (IDVal == ".short" || IDVal == ".hword")
9331     parseLiteralValues(2, DirectiveID.getLoc());
9332   else if (IDVal == ".thumb")
9333     parseDirectiveThumb(DirectiveID.getLoc());
9334   else if (IDVal == ".arm")
9335     parseDirectiveARM(DirectiveID.getLoc());
9336   else if (IDVal == ".thumb_func")
9337     parseDirectiveThumbFunc(DirectiveID.getLoc());
9338   else if (IDVal == ".code")
9339     parseDirectiveCode(DirectiveID.getLoc());
9340   else if (IDVal == ".syntax")
9341     parseDirectiveSyntax(DirectiveID.getLoc());
9342   else if (IDVal == ".unreq")
9343     parseDirectiveUnreq(DirectiveID.getLoc());
9344   else if (IDVal == ".fnend")
9345     parseDirectiveFnEnd(DirectiveID.getLoc());
9346   else if (IDVal == ".cantunwind")
9347     parseDirectiveCantUnwind(DirectiveID.getLoc());
9348   else if (IDVal == ".personality")
9349     parseDirectivePersonality(DirectiveID.getLoc());
9350   else if (IDVal == ".handlerdata")
9351     parseDirectiveHandlerData(DirectiveID.getLoc());
9352   else if (IDVal == ".setfp")
9353     parseDirectiveSetFP(DirectiveID.getLoc());
9354   else if (IDVal == ".pad")
9355     parseDirectivePad(DirectiveID.getLoc());
9356   else if (IDVal == ".save")
9357     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9358   else if (IDVal == ".vsave")
9359     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9360   else if (IDVal == ".ltorg" || IDVal == ".pool")
9361     parseDirectiveLtorg(DirectiveID.getLoc());
9362   else if (IDVal == ".even")
9363     parseDirectiveEven(DirectiveID.getLoc());
9364   else if (IDVal == ".personalityindex")
9365     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9366   else if (IDVal == ".unwind_raw")
9367     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9368   else if (IDVal == ".movsp")
9369     parseDirectiveMovSP(DirectiveID.getLoc());
9370   else if (IDVal == ".arch_extension")
9371     parseDirectiveArchExtension(DirectiveID.getLoc());
9372   else if (IDVal == ".align")
9373     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9374   else if (IDVal == ".thumb_set")
9375     parseDirectiveThumbSet(DirectiveID.getLoc());
9376   else if (IDVal == ".inst")
9377     parseDirectiveInst(DirectiveID.getLoc());
9378   else if (IDVal == ".inst.n")
9379     parseDirectiveInst(DirectiveID.getLoc(), 'n');
9380   else if (IDVal == ".inst.w")
9381     parseDirectiveInst(DirectiveID.getLoc(), 'w');
9382   else if (!IsMachO && !IsCOFF) {
9383     if (IDVal == ".arch")
9384       parseDirectiveArch(DirectiveID.getLoc());
9385     else if (IDVal == ".cpu")
9386       parseDirectiveCPU(DirectiveID.getLoc());
9387     else if (IDVal == ".eabi_attribute")
9388       parseDirectiveEabiAttr(DirectiveID.getLoc());
9389     else if (IDVal == ".fpu")
9390       parseDirectiveFPU(DirectiveID.getLoc());
9391     else if (IDVal == ".fnstart")
9392       parseDirectiveFnStart(DirectiveID.getLoc());
9393     else if (IDVal == ".object_arch")
9394       parseDirectiveObjectArch(DirectiveID.getLoc());
9395     else if (IDVal == ".tlsdescseq")
9396       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9397     else
9398       return true;
9399   } else
9400     return true;
9401   return false;
9402 }
9403 
9404 /// parseLiteralValues
9405 ///  ::= .hword expression [, expression]*
9406 ///  ::= .short expression [, expression]*
9407 ///  ::= .word expression [, expression]*
9408 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9409   auto parseOne = [&]() -> bool {
9410     const MCExpr *Value;
9411     if (getParser().parseExpression(Value))
9412       return true;
9413     getParser().getStreamer().EmitValue(Value, Size, L);
9414     return false;
9415   };
9416   return (parseMany(parseOne));
9417 }
9418 
9419 /// parseDirectiveThumb
9420 ///  ::= .thumb
9421 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9422   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9423       check(!hasThumb(), L, "target does not support Thumb mode"))
9424     return true;
9425 
9426   if (!isThumb())
9427     SwitchMode();
9428 
9429   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9430   return false;
9431 }
9432 
9433 /// parseDirectiveARM
9434 ///  ::= .arm
9435 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9436   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9437       check(!hasARM(), L, "target does not support ARM mode"))
9438     return true;
9439 
9440   if (isThumb())
9441     SwitchMode();
9442   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9443   return false;
9444 }
9445 
9446 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9447   // We need to flush the current implicit IT block on a label, because it is
9448   // not legal to branch into an IT block.
9449   flushPendingInstructions(getStreamer());
9450   if (NextSymbolIsThumb) {
9451     getParser().getStreamer().EmitThumbFunc(Symbol);
9452     NextSymbolIsThumb = false;
9453   }
9454 }
9455 
9456 /// parseDirectiveThumbFunc
9457 ///  ::= .thumbfunc symbol_name
9458 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9459   MCAsmParser &Parser = getParser();
9460   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9461   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9462 
9463   // Darwin asm has (optionally) function name after .thumb_func direction
9464   // ELF doesn't
9465 
9466   if (IsMachO) {
9467     if (Parser.getTok().is(AsmToken::Identifier) ||
9468         Parser.getTok().is(AsmToken::String)) {
9469       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9470           Parser.getTok().getIdentifier());
9471       getParser().getStreamer().EmitThumbFunc(Func);
9472       Parser.Lex();
9473       if (parseToken(AsmToken::EndOfStatement,
9474                      "unexpected token in '.thumb_func' directive"))
9475         return true;
9476       return false;
9477     }
9478   }
9479 
9480   if (parseToken(AsmToken::EndOfStatement,
9481                  "unexpected token in '.thumb_func' directive"))
9482     return true;
9483 
9484   NextSymbolIsThumb = true;
9485   return false;
9486 }
9487 
9488 /// parseDirectiveSyntax
9489 ///  ::= .syntax unified | divided
9490 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9491   MCAsmParser &Parser = getParser();
9492   const AsmToken &Tok = Parser.getTok();
9493   if (Tok.isNot(AsmToken::Identifier)) {
9494     Error(L, "unexpected token in .syntax directive");
9495     return false;
9496   }
9497 
9498   StringRef Mode = Tok.getString();
9499   Parser.Lex();
9500   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9501             "'.syntax divided' arm assembly not supported") ||
9502       check(Mode != "unified" && Mode != "UNIFIED", L,
9503             "unrecognized syntax mode in .syntax directive") ||
9504       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9505     return true;
9506 
9507   // TODO tell the MC streamer the mode
9508   // getParser().getStreamer().Emit???();
9509   return false;
9510 }
9511 
9512 /// parseDirectiveCode
9513 ///  ::= .code 16 | 32
9514 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9515   MCAsmParser &Parser = getParser();
9516   const AsmToken &Tok = Parser.getTok();
9517   if (Tok.isNot(AsmToken::Integer))
9518     return Error(L, "unexpected token in .code directive");
9519   int64_t Val = Parser.getTok().getIntVal();
9520   if (Val != 16 && Val != 32) {
9521     Error(L, "invalid operand to .code directive");
9522     return false;
9523   }
9524   Parser.Lex();
9525 
9526   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9527     return true;
9528 
9529   if (Val == 16) {
9530     if (!hasThumb())
9531       return Error(L, "target does not support Thumb mode");
9532 
9533     if (!isThumb())
9534       SwitchMode();
9535     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9536   } else {
9537     if (!hasARM())
9538       return Error(L, "target does not support ARM mode");
9539 
9540     if (isThumb())
9541       SwitchMode();
9542     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9543   }
9544 
9545   return false;
9546 }
9547 
9548 /// parseDirectiveReq
9549 ///  ::= name .req registername
9550 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9551   MCAsmParser &Parser = getParser();
9552   Parser.Lex(); // Eat the '.req' token.
9553   unsigned Reg;
9554   SMLoc SRegLoc, ERegLoc;
9555   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9556             "register name expected") ||
9557       parseToken(AsmToken::EndOfStatement,
9558                  "unexpected input in .req directive."))
9559     return true;
9560 
9561   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9562     return Error(SRegLoc,
9563                  "redefinition of '" + Name + "' does not match original.");
9564 
9565   return false;
9566 }
9567 
9568 /// parseDirectiveUneq
9569 ///  ::= .unreq registername
9570 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9571   MCAsmParser &Parser = getParser();
9572   if (Parser.getTok().isNot(AsmToken::Identifier))
9573     return Error(L, "unexpected input in .unreq directive.");
9574   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9575   Parser.Lex(); // Eat the identifier.
9576   if (parseToken(AsmToken::EndOfStatement,
9577                  "unexpected input in '.unreq' directive"))
9578     return true;
9579   return false;
9580 }
9581 
9582 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9583 // before, if supported by the new target, or emit mapping symbols for the mode
9584 // switch.
9585 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9586   if (WasThumb != isThumb()) {
9587     if (WasThumb && hasThumb()) {
9588       // Stay in Thumb mode
9589       SwitchMode();
9590     } else if (!WasThumb && hasARM()) {
9591       // Stay in ARM mode
9592       SwitchMode();
9593     } else {
9594       // Mode switch forced, because the new arch doesn't support the old mode.
9595       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9596                                                             : MCAF_Code32);
9597       // Warn about the implcit mode switch. GAS does not switch modes here,
9598       // but instead stays in the old mode, reporting an error on any following
9599       // instructions as the mode does not exist on the target.
9600       Warning(Loc, Twine("new target does not support ") +
9601                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9602                        (!WasThumb ? "thumb" : "arm") + " mode");
9603     }
9604   }
9605 }
9606 
9607 /// parseDirectiveArch
9608 ///  ::= .arch token
9609 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9610   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9611   ARM::ArchKind ID = ARM::parseArch(Arch);
9612 
9613   if (ID == ARM::ArchKind::INVALID)
9614     return Error(L, "Unknown arch name");
9615 
9616   bool WasThumb = isThumb();
9617   Triple T;
9618   MCSubtargetInfo &STI = copySTI();
9619   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9620   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9621   FixModeAfterArchChange(WasThumb, L);
9622 
9623   getTargetStreamer().emitArch(ID);
9624   return false;
9625 }
9626 
9627 /// parseDirectiveEabiAttr
9628 ///  ::= .eabi_attribute int, int [, "str"]
9629 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9630 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9631   MCAsmParser &Parser = getParser();
9632   int64_t Tag;
9633   SMLoc TagLoc;
9634   TagLoc = Parser.getTok().getLoc();
9635   if (Parser.getTok().is(AsmToken::Identifier)) {
9636     StringRef Name = Parser.getTok().getIdentifier();
9637     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9638     if (Tag == -1) {
9639       Error(TagLoc, "attribute name not recognised: " + Name);
9640       return false;
9641     }
9642     Parser.Lex();
9643   } else {
9644     const MCExpr *AttrExpr;
9645 
9646     TagLoc = Parser.getTok().getLoc();
9647     if (Parser.parseExpression(AttrExpr))
9648       return true;
9649 
9650     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9651     if (check(!CE, TagLoc, "expected numeric constant"))
9652       return true;
9653 
9654     Tag = CE->getValue();
9655   }
9656 
9657   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9658     return true;
9659 
9660   StringRef StringValue = "";
9661   bool IsStringValue = false;
9662 
9663   int64_t IntegerValue = 0;
9664   bool IsIntegerValue = false;
9665 
9666   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9667     IsStringValue = true;
9668   else if (Tag == ARMBuildAttrs::compatibility) {
9669     IsStringValue = true;
9670     IsIntegerValue = true;
9671   } else if (Tag < 32 || Tag % 2 == 0)
9672     IsIntegerValue = true;
9673   else if (Tag % 2 == 1)
9674     IsStringValue = true;
9675   else
9676     llvm_unreachable("invalid tag type");
9677 
9678   if (IsIntegerValue) {
9679     const MCExpr *ValueExpr;
9680     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9681     if (Parser.parseExpression(ValueExpr))
9682       return true;
9683 
9684     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9685     if (!CE)
9686       return Error(ValueExprLoc, "expected numeric constant");
9687     IntegerValue = CE->getValue();
9688   }
9689 
9690   if (Tag == ARMBuildAttrs::compatibility) {
9691     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9692       return true;
9693   }
9694 
9695   if (IsStringValue) {
9696     if (Parser.getTok().isNot(AsmToken::String))
9697       return Error(Parser.getTok().getLoc(), "bad string constant");
9698 
9699     StringValue = Parser.getTok().getStringContents();
9700     Parser.Lex();
9701   }
9702 
9703   if (Parser.parseToken(AsmToken::EndOfStatement,
9704                         "unexpected token in '.eabi_attribute' directive"))
9705     return true;
9706 
9707   if (IsIntegerValue && IsStringValue) {
9708     assert(Tag == ARMBuildAttrs::compatibility);
9709     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9710   } else if (IsIntegerValue)
9711     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9712   else if (IsStringValue)
9713     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9714   return false;
9715 }
9716 
9717 /// parseDirectiveCPU
9718 ///  ::= .cpu str
9719 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9720   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9721   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9722 
9723   // FIXME: This is using table-gen data, but should be moved to
9724   // ARMTargetParser once that is table-gen'd.
9725   if (!getSTI().isCPUStringValid(CPU))
9726     return Error(L, "Unknown CPU name");
9727 
9728   bool WasThumb = isThumb();
9729   MCSubtargetInfo &STI = copySTI();
9730   STI.setDefaultFeatures(CPU, "");
9731   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9732   FixModeAfterArchChange(WasThumb, L);
9733 
9734   return false;
9735 }
9736 
9737 /// parseDirectiveFPU
9738 ///  ::= .fpu str
9739 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9740   SMLoc FPUNameLoc = getTok().getLoc();
9741   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9742 
9743   unsigned ID = ARM::parseFPU(FPU);
9744   std::vector<StringRef> Features;
9745   if (!ARM::getFPUFeatures(ID, Features))
9746     return Error(FPUNameLoc, "Unknown FPU name");
9747 
9748   MCSubtargetInfo &STI = copySTI();
9749   for (auto Feature : Features)
9750     STI.ApplyFeatureFlag(Feature);
9751   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9752 
9753   getTargetStreamer().emitFPU(ID);
9754   return false;
9755 }
9756 
9757 /// parseDirectiveFnStart
9758 ///  ::= .fnstart
9759 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9760   if (parseToken(AsmToken::EndOfStatement,
9761                  "unexpected token in '.fnstart' directive"))
9762     return true;
9763 
9764   if (UC.hasFnStart()) {
9765     Error(L, ".fnstart starts before the end of previous one");
9766     UC.emitFnStartLocNotes();
9767     return true;
9768   }
9769 
9770   // Reset the unwind directives parser state
9771   UC.reset();
9772 
9773   getTargetStreamer().emitFnStart();
9774 
9775   UC.recordFnStart(L);
9776   return false;
9777 }
9778 
9779 /// parseDirectiveFnEnd
9780 ///  ::= .fnend
9781 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9782   if (parseToken(AsmToken::EndOfStatement,
9783                  "unexpected token in '.fnend' directive"))
9784     return true;
9785   // Check the ordering of unwind directives
9786   if (!UC.hasFnStart())
9787     return Error(L, ".fnstart must precede .fnend directive");
9788 
9789   // Reset the unwind directives parser state
9790   getTargetStreamer().emitFnEnd();
9791 
9792   UC.reset();
9793   return false;
9794 }
9795 
9796 /// parseDirectiveCantUnwind
9797 ///  ::= .cantunwind
9798 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9799   if (parseToken(AsmToken::EndOfStatement,
9800                  "unexpected token in '.cantunwind' directive"))
9801     return true;
9802 
9803   UC.recordCantUnwind(L);
9804   // Check the ordering of unwind directives
9805   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9806     return true;
9807 
9808   if (UC.hasHandlerData()) {
9809     Error(L, ".cantunwind can't be used with .handlerdata directive");
9810     UC.emitHandlerDataLocNotes();
9811     return true;
9812   }
9813   if (UC.hasPersonality()) {
9814     Error(L, ".cantunwind can't be used with .personality directive");
9815     UC.emitPersonalityLocNotes();
9816     return true;
9817   }
9818 
9819   getTargetStreamer().emitCantUnwind();
9820   return false;
9821 }
9822 
9823 /// parseDirectivePersonality
9824 ///  ::= .personality name
9825 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9826   MCAsmParser &Parser = getParser();
9827   bool HasExistingPersonality = UC.hasPersonality();
9828 
9829   // Parse the name of the personality routine
9830   if (Parser.getTok().isNot(AsmToken::Identifier))
9831     return Error(L, "unexpected input in .personality directive.");
9832   StringRef Name(Parser.getTok().getIdentifier());
9833   Parser.Lex();
9834 
9835   if (parseToken(AsmToken::EndOfStatement,
9836                  "unexpected token in '.personality' directive"))
9837     return true;
9838 
9839   UC.recordPersonality(L);
9840 
9841   // Check the ordering of unwind directives
9842   if (!UC.hasFnStart())
9843     return Error(L, ".fnstart must precede .personality directive");
9844   if (UC.cantUnwind()) {
9845     Error(L, ".personality can't be used with .cantunwind directive");
9846     UC.emitCantUnwindLocNotes();
9847     return true;
9848   }
9849   if (UC.hasHandlerData()) {
9850     Error(L, ".personality must precede .handlerdata directive");
9851     UC.emitHandlerDataLocNotes();
9852     return true;
9853   }
9854   if (HasExistingPersonality) {
9855     Error(L, "multiple personality directives");
9856     UC.emitPersonalityLocNotes();
9857     return true;
9858   }
9859 
9860   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9861   getTargetStreamer().emitPersonality(PR);
9862   return false;
9863 }
9864 
9865 /// parseDirectiveHandlerData
9866 ///  ::= .handlerdata
9867 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9868   if (parseToken(AsmToken::EndOfStatement,
9869                  "unexpected token in '.handlerdata' directive"))
9870     return true;
9871 
9872   UC.recordHandlerData(L);
9873   // Check the ordering of unwind directives
9874   if (!UC.hasFnStart())
9875     return Error(L, ".fnstart must precede .personality directive");
9876   if (UC.cantUnwind()) {
9877     Error(L, ".handlerdata can't be used with .cantunwind directive");
9878     UC.emitCantUnwindLocNotes();
9879     return true;
9880   }
9881 
9882   getTargetStreamer().emitHandlerData();
9883   return false;
9884 }
9885 
9886 /// parseDirectiveSetFP
9887 ///  ::= .setfp fpreg, spreg [, offset]
9888 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9889   MCAsmParser &Parser = getParser();
9890   // Check the ordering of unwind directives
9891   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9892       check(UC.hasHandlerData(), L,
9893             ".setfp must precede .handlerdata directive"))
9894     return true;
9895 
9896   // Parse fpreg
9897   SMLoc FPRegLoc = Parser.getTok().getLoc();
9898   int FPReg = tryParseRegister();
9899 
9900   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9901       Parser.parseToken(AsmToken::Comma, "comma expected"))
9902     return true;
9903 
9904   // Parse spreg
9905   SMLoc SPRegLoc = Parser.getTok().getLoc();
9906   int SPReg = tryParseRegister();
9907   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9908       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9909             "register should be either $sp or the latest fp register"))
9910     return true;
9911 
9912   // Update the frame pointer register
9913   UC.saveFPReg(FPReg);
9914 
9915   // Parse offset
9916   int64_t Offset = 0;
9917   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9918     if (Parser.getTok().isNot(AsmToken::Hash) &&
9919         Parser.getTok().isNot(AsmToken::Dollar))
9920       return Error(Parser.getTok().getLoc(), "'#' expected");
9921     Parser.Lex(); // skip hash token.
9922 
9923     const MCExpr *OffsetExpr;
9924     SMLoc ExLoc = Parser.getTok().getLoc();
9925     SMLoc EndLoc;
9926     if (getParser().parseExpression(OffsetExpr, EndLoc))
9927       return Error(ExLoc, "malformed setfp offset");
9928     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9929     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9930       return true;
9931     Offset = CE->getValue();
9932   }
9933 
9934   if (Parser.parseToken(AsmToken::EndOfStatement))
9935     return true;
9936 
9937   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9938                                 static_cast<unsigned>(SPReg), Offset);
9939   return false;
9940 }
9941 
9942 /// parseDirective
9943 ///  ::= .pad offset
9944 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9945   MCAsmParser &Parser = getParser();
9946   // Check the ordering of unwind directives
9947   if (!UC.hasFnStart())
9948     return Error(L, ".fnstart must precede .pad directive");
9949   if (UC.hasHandlerData())
9950     return Error(L, ".pad must precede .handlerdata directive");
9951 
9952   // Parse the offset
9953   if (Parser.getTok().isNot(AsmToken::Hash) &&
9954       Parser.getTok().isNot(AsmToken::Dollar))
9955     return Error(Parser.getTok().getLoc(), "'#' expected");
9956   Parser.Lex(); // skip hash token.
9957 
9958   const MCExpr *OffsetExpr;
9959   SMLoc ExLoc = Parser.getTok().getLoc();
9960   SMLoc EndLoc;
9961   if (getParser().parseExpression(OffsetExpr, EndLoc))
9962     return Error(ExLoc, "malformed pad offset");
9963   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9964   if (!CE)
9965     return Error(ExLoc, "pad offset must be an immediate");
9966 
9967   if (parseToken(AsmToken::EndOfStatement,
9968                  "unexpected token in '.pad' directive"))
9969     return true;
9970 
9971   getTargetStreamer().emitPad(CE->getValue());
9972   return false;
9973 }
9974 
9975 /// parseDirectiveRegSave
9976 ///  ::= .save  { registers }
9977 ///  ::= .vsave { registers }
9978 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9979   // Check the ordering of unwind directives
9980   if (!UC.hasFnStart())
9981     return Error(L, ".fnstart must precede .save or .vsave directives");
9982   if (UC.hasHandlerData())
9983     return Error(L, ".save or .vsave must precede .handlerdata directive");
9984 
9985   // RAII object to make sure parsed operands are deleted.
9986   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9987 
9988   // Parse the register list
9989   if (parseRegisterList(Operands) ||
9990       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9991     return true;
9992   ARMOperand &Op = (ARMOperand &)*Operands[0];
9993   if (!IsVector && !Op.isRegList())
9994     return Error(L, ".save expects GPR registers");
9995   if (IsVector && !Op.isDPRRegList())
9996     return Error(L, ".vsave expects DPR registers");
9997 
9998   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9999   return false;
10000 }
10001 
10002 /// parseDirectiveInst
10003 ///  ::= .inst opcode [, ...]
10004 ///  ::= .inst.n opcode [, ...]
10005 ///  ::= .inst.w opcode [, ...]
10006 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
10007   int Width = 4;
10008 
10009   if (isThumb()) {
10010     switch (Suffix) {
10011     case 'n':
10012       Width = 2;
10013       break;
10014     case 'w':
10015       break;
10016     default:
10017       Width = 0;
10018       break;
10019     }
10020   } else {
10021     if (Suffix)
10022       return Error(Loc, "width suffixes are invalid in ARM mode");
10023   }
10024 
10025   auto parseOne = [&]() -> bool {
10026     const MCExpr *Expr;
10027     if (getParser().parseExpression(Expr))
10028       return true;
10029     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
10030     if (!Value) {
10031       return Error(Loc, "expected constant expression");
10032     }
10033 
10034     char CurSuffix = Suffix;
10035     switch (Width) {
10036     case 2:
10037       if (Value->getValue() > 0xffff)
10038         return Error(Loc, "inst.n operand is too big, use inst.w instead");
10039       break;
10040     case 4:
10041       if (Value->getValue() > 0xffffffff)
10042         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
10043                               " operand is too big");
10044       break;
10045     case 0:
10046       // Thumb mode, no width indicated. Guess from the opcode, if possible.
10047       if (Value->getValue() < 0xe800)
10048         CurSuffix = 'n';
10049       else if (Value->getValue() >= 0xe8000000)
10050         CurSuffix = 'w';
10051       else
10052         return Error(Loc, "cannot determine Thumb instruction size, "
10053                           "use inst.n/inst.w instead");
10054       break;
10055     default:
10056       llvm_unreachable("only supported widths are 2 and 4");
10057     }
10058 
10059     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
10060     return false;
10061   };
10062 
10063   if (parseOptionalToken(AsmToken::EndOfStatement))
10064     return Error(Loc, "expected expression following directive");
10065   if (parseMany(parseOne))
10066     return true;
10067   return false;
10068 }
10069 
10070 /// parseDirectiveLtorg
10071 ///  ::= .ltorg | .pool
10072 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
10073   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10074     return true;
10075   getTargetStreamer().emitCurrentConstantPool();
10076   return false;
10077 }
10078 
10079 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
10080   const MCSection *Section = getStreamer().getCurrentSectionOnly();
10081 
10082   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10083     return true;
10084 
10085   if (!Section) {
10086     getStreamer().InitSections(false);
10087     Section = getStreamer().getCurrentSectionOnly();
10088   }
10089 
10090   assert(Section && "must have section to emit alignment");
10091   if (Section->UseCodeAlign())
10092     getStreamer().EmitCodeAlignment(2);
10093   else
10094     getStreamer().EmitValueToAlignment(2);
10095 
10096   return false;
10097 }
10098 
10099 /// parseDirectivePersonalityIndex
10100 ///   ::= .personalityindex index
10101 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
10102   MCAsmParser &Parser = getParser();
10103   bool HasExistingPersonality = UC.hasPersonality();
10104 
10105   const MCExpr *IndexExpression;
10106   SMLoc IndexLoc = Parser.getTok().getLoc();
10107   if (Parser.parseExpression(IndexExpression) ||
10108       parseToken(AsmToken::EndOfStatement,
10109                  "unexpected token in '.personalityindex' directive")) {
10110     return true;
10111   }
10112 
10113   UC.recordPersonalityIndex(L);
10114 
10115   if (!UC.hasFnStart()) {
10116     return Error(L, ".fnstart must precede .personalityindex directive");
10117   }
10118   if (UC.cantUnwind()) {
10119     Error(L, ".personalityindex cannot be used with .cantunwind");
10120     UC.emitCantUnwindLocNotes();
10121     return true;
10122   }
10123   if (UC.hasHandlerData()) {
10124     Error(L, ".personalityindex must precede .handlerdata directive");
10125     UC.emitHandlerDataLocNotes();
10126     return true;
10127   }
10128   if (HasExistingPersonality) {
10129     Error(L, "multiple personality directives");
10130     UC.emitPersonalityLocNotes();
10131     return true;
10132   }
10133 
10134   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
10135   if (!CE)
10136     return Error(IndexLoc, "index must be a constant number");
10137   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
10138     return Error(IndexLoc,
10139                  "personality routine index should be in range [0-3]");
10140 
10141   getTargetStreamer().emitPersonalityIndex(CE->getValue());
10142   return false;
10143 }
10144 
10145 /// parseDirectiveUnwindRaw
10146 ///   ::= .unwind_raw offset, opcode [, opcode...]
10147 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
10148   MCAsmParser &Parser = getParser();
10149   int64_t StackOffset;
10150   const MCExpr *OffsetExpr;
10151   SMLoc OffsetLoc = getLexer().getLoc();
10152 
10153   if (!UC.hasFnStart())
10154     return Error(L, ".fnstart must precede .unwind_raw directives");
10155   if (getParser().parseExpression(OffsetExpr))
10156     return Error(OffsetLoc, "expected expression");
10157 
10158   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10159   if (!CE)
10160     return Error(OffsetLoc, "offset must be a constant");
10161 
10162   StackOffset = CE->getValue();
10163 
10164   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
10165     return true;
10166 
10167   SmallVector<uint8_t, 16> Opcodes;
10168 
10169   auto parseOne = [&]() -> bool {
10170     const MCExpr *OE;
10171     SMLoc OpcodeLoc = getLexer().getLoc();
10172     if (check(getLexer().is(AsmToken::EndOfStatement) ||
10173                   Parser.parseExpression(OE),
10174               OpcodeLoc, "expected opcode expression"))
10175       return true;
10176     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
10177     if (!OC)
10178       return Error(OpcodeLoc, "opcode value must be a constant");
10179     const int64_t Opcode = OC->getValue();
10180     if (Opcode & ~0xff)
10181       return Error(OpcodeLoc, "invalid opcode");
10182     Opcodes.push_back(uint8_t(Opcode));
10183     return false;
10184   };
10185 
10186   // Must have at least 1 element
10187   SMLoc OpcodeLoc = getLexer().getLoc();
10188   if (parseOptionalToken(AsmToken::EndOfStatement))
10189     return Error(OpcodeLoc, "expected opcode expression");
10190   if (parseMany(parseOne))
10191     return true;
10192 
10193   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
10194   return false;
10195 }
10196 
10197 /// parseDirectiveTLSDescSeq
10198 ///   ::= .tlsdescseq tls-variable
10199 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
10200   MCAsmParser &Parser = getParser();
10201 
10202   if (getLexer().isNot(AsmToken::Identifier))
10203     return TokError("expected variable after '.tlsdescseq' directive");
10204 
10205   const MCSymbolRefExpr *SRE =
10206     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10207                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10208   Lex();
10209 
10210   if (parseToken(AsmToken::EndOfStatement,
10211                  "unexpected token in '.tlsdescseq' directive"))
10212     return true;
10213 
10214   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10215   return false;
10216 }
10217 
10218 /// parseDirectiveMovSP
10219 ///  ::= .movsp reg [, #offset]
10220 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10221   MCAsmParser &Parser = getParser();
10222   if (!UC.hasFnStart())
10223     return Error(L, ".fnstart must precede .movsp directives");
10224   if (UC.getFPReg() != ARM::SP)
10225     return Error(L, "unexpected .movsp directive");
10226 
10227   SMLoc SPRegLoc = Parser.getTok().getLoc();
10228   int SPReg = tryParseRegister();
10229   if (SPReg == -1)
10230     return Error(SPRegLoc, "register expected");
10231   if (SPReg == ARM::SP || SPReg == ARM::PC)
10232     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10233 
10234   int64_t Offset = 0;
10235   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10236     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10237       return true;
10238 
10239     const MCExpr *OffsetExpr;
10240     SMLoc OffsetLoc = Parser.getTok().getLoc();
10241 
10242     if (Parser.parseExpression(OffsetExpr))
10243       return Error(OffsetLoc, "malformed offset expression");
10244 
10245     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10246     if (!CE)
10247       return Error(OffsetLoc, "offset must be an immediate constant");
10248 
10249     Offset = CE->getValue();
10250   }
10251 
10252   if (parseToken(AsmToken::EndOfStatement,
10253                  "unexpected token in '.movsp' directive"))
10254     return true;
10255 
10256   getTargetStreamer().emitMovSP(SPReg, Offset);
10257   UC.saveFPReg(SPReg);
10258 
10259   return false;
10260 }
10261 
10262 /// parseDirectiveObjectArch
10263 ///   ::= .object_arch name
10264 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10265   MCAsmParser &Parser = getParser();
10266   if (getLexer().isNot(AsmToken::Identifier))
10267     return Error(getLexer().getLoc(), "unexpected token");
10268 
10269   StringRef Arch = Parser.getTok().getString();
10270   SMLoc ArchLoc = Parser.getTok().getLoc();
10271   Lex();
10272 
10273   ARM::ArchKind ID = ARM::parseArch(Arch);
10274 
10275   if (ID == ARM::ArchKind::INVALID)
10276     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10277   if (parseToken(AsmToken::EndOfStatement))
10278     return true;
10279 
10280   getTargetStreamer().emitObjectArch(ID);
10281   return false;
10282 }
10283 
10284 /// parseDirectiveAlign
10285 ///   ::= .align
10286 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10287   // NOTE: if this is not the end of the statement, fall back to the target
10288   // agnostic handling for this directive which will correctly handle this.
10289   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10290     // '.align' is target specifically handled to mean 2**2 byte alignment.
10291     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10292     assert(Section && "must have section to emit alignment");
10293     if (Section->UseCodeAlign())
10294       getStreamer().EmitCodeAlignment(4, 0);
10295     else
10296       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10297     return false;
10298   }
10299   return true;
10300 }
10301 
10302 /// parseDirectiveThumbSet
10303 ///  ::= .thumb_set name, value
10304 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10305   MCAsmParser &Parser = getParser();
10306 
10307   StringRef Name;
10308   if (check(Parser.parseIdentifier(Name),
10309             "expected identifier after '.thumb_set'") ||
10310       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10311     return true;
10312 
10313   MCSymbol *Sym;
10314   const MCExpr *Value;
10315   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10316                                                Parser, Sym, Value))
10317     return true;
10318 
10319   getTargetStreamer().emitThumbSet(Sym, Value);
10320   return false;
10321 }
10322 
10323 /// Force static initialization.
10324 extern "C" void LLVMInitializeARMAsmParser() {
10325   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10326   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10327   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10328   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10329 }
10330 
10331 #define GET_REGISTER_MATCHER
10332 #define GET_SUBTARGET_FEATURE_NAME
10333 #define GET_MATCHER_IMPLEMENTATION
10334 #define GET_MNEMONIC_SPELL_CHECKER
10335 #include "ARMGenAsmMatcher.inc"
10336 
10337 // Some diagnostics need to vary with subtarget features, so they are handled
10338 // here. For example, the DPR class has either 16 or 32 registers, depending
10339 // on the FPU available.
10340 const char *
10341 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
10342   switch (MatchError) {
10343   // rGPR contains sp starting with ARMv8.
10344   case Match_rGPR:
10345     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
10346                       : "operand must be a register in range [r0, r12] or r14";
10347   // DPR contains 16 registers for some FPUs, and 32 for others.
10348   case Match_DPR:
10349     return hasD16() ? "operand must be a register in range [d0, d15]"
10350                     : "operand must be a register in range [d0, d31]";
10351   case Match_DPR_RegList:
10352     return hasD16() ? "operand must be a list of registers in range [d0, d15]"
10353                     : "operand must be a list of registers in range [d0, d31]";
10354 
10355   // For all other diags, use the static string from tablegen.
10356   default:
10357     return getMatchKindDiag(MatchError);
10358   }
10359 }
10360 
10361 // Process the list of near-misses, throwing away ones we don't want to report
10362 // to the user, and converting the rest to a source location and string that
10363 // should be reported.
10364 void
10365 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
10366                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
10367                                SMLoc IDLoc, OperandVector &Operands) {
10368   // TODO: If operand didn't match, sub in a dummy one and run target
10369   // predicate, so that we can avoid reporting near-misses that are invalid?
10370   // TODO: Many operand types dont have SuperClasses set, so we report
10371   // redundant ones.
10372   // TODO: Some operands are superclasses of registers (e.g.
10373   // MCK_RegShiftedImm), we don't have any way to represent that currently.
10374   // TODO: This is not all ARM-specific, can some of it be factored out?
10375 
10376   // Record some information about near-misses that we have already seen, so
10377   // that we can avoid reporting redundant ones. For example, if there are
10378   // variants of an instruction that take 8- and 16-bit immediates, we want
10379   // to only report the widest one.
10380   std::multimap<unsigned, unsigned> OperandMissesSeen;
10381   SmallSet<uint64_t, 4> FeatureMissesSeen;
10382   bool ReportedTooFewOperands = false;
10383 
10384   // Process the near-misses in reverse order, so that we see more general ones
10385   // first, and so can avoid emitting more specific ones.
10386   for (NearMissInfo &I : reverse(NearMissesIn)) {
10387     switch (I.getKind()) {
10388     case NearMissInfo::NearMissOperand: {
10389       SMLoc OperandLoc =
10390           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
10391       const char *OperandDiag =
10392           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
10393 
10394       // If we have already emitted a message for a superclass, don't also report
10395       // the sub-class. We consider all operand classes that we don't have a
10396       // specialised diagnostic for to be equal for the propose of this check,
10397       // so that we don't report the generic error multiple times on the same
10398       // operand.
10399       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
10400       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
10401       if (std::any_of(PrevReports.first, PrevReports.second,
10402                       [DupCheckMatchClass](
10403                           const std::pair<unsigned, unsigned> Pair) {
10404             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
10405               return Pair.second == DupCheckMatchClass;
10406             else
10407               return isSubclass((MatchClassKind)DupCheckMatchClass,
10408                                 (MatchClassKind)Pair.second);
10409           }))
10410         break;
10411       OperandMissesSeen.insert(
10412           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
10413 
10414       NearMissMessage Message;
10415       Message.Loc = OperandLoc;
10416       if (OperandDiag) {
10417         Message.Message = OperandDiag;
10418       } else if (I.getOperandClass() == InvalidMatchClass) {
10419         Message.Message = "too many operands for instruction";
10420       } else {
10421         Message.Message = "invalid operand for instruction";
10422         LLVM_DEBUG(
10423             dbgs() << "Missing diagnostic string for operand class "
10424                    << getMatchClassName((MatchClassKind)I.getOperandClass())
10425                    << I.getOperandClass() << ", error " << I.getOperandError()
10426                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
10427       }
10428       NearMissesOut.emplace_back(Message);
10429       break;
10430     }
10431     case NearMissInfo::NearMissFeature: {
10432       uint64_t MissingFeatures = I.getFeatures();
10433       // Don't report the same set of features twice.
10434       if (FeatureMissesSeen.count(MissingFeatures))
10435         break;
10436       FeatureMissesSeen.insert(MissingFeatures);
10437 
10438       // Special case: don't report a feature set which includes arm-mode for
10439       // targets that don't have ARM mode.
10440       if ((MissingFeatures & Feature_IsARM) && !hasARM())
10441         break;
10442       // Don't report any near-misses that both require switching instruction
10443       // set, and adding other subtarget features.
10444       if (isThumb() && (MissingFeatures & Feature_IsARM) &&
10445           (MissingFeatures & ~Feature_IsARM))
10446         break;
10447       if (!isThumb() && (MissingFeatures & Feature_IsThumb) &&
10448           (MissingFeatures & ~Feature_IsThumb))
10449         break;
10450       if (!isThumb() && (MissingFeatures & Feature_IsThumb2) &&
10451           (MissingFeatures & ~(Feature_IsThumb2 | Feature_IsThumb)))
10452         break;
10453       if (isMClass() && (MissingFeatures & Feature_HasNEON))
10454         break;
10455 
10456       NearMissMessage Message;
10457       Message.Loc = IDLoc;
10458       raw_svector_ostream OS(Message.Message);
10459 
10460       OS << "instruction requires:";
10461       uint64_t Mask = 1;
10462       for (unsigned MaskPos = 0; MaskPos < (sizeof(MissingFeatures) * 8 - 1);
10463            ++MaskPos) {
10464         if (MissingFeatures & Mask) {
10465           OS << " " << getSubtargetFeatureName(MissingFeatures & Mask);
10466         }
10467         Mask <<= 1;
10468       }
10469       NearMissesOut.emplace_back(Message);
10470 
10471       break;
10472     }
10473     case NearMissInfo::NearMissPredicate: {
10474       NearMissMessage Message;
10475       Message.Loc = IDLoc;
10476       switch (I.getPredicateError()) {
10477       case Match_RequiresNotITBlock:
10478         Message.Message = "flag setting instruction only valid outside IT block";
10479         break;
10480       case Match_RequiresITBlock:
10481         Message.Message = "instruction only valid inside IT block";
10482         break;
10483       case Match_RequiresV6:
10484         Message.Message = "instruction variant requires ARMv6 or later";
10485         break;
10486       case Match_RequiresThumb2:
10487         Message.Message = "instruction variant requires Thumb2";
10488         break;
10489       case Match_RequiresV8:
10490         Message.Message = "instruction variant requires ARMv8 or later";
10491         break;
10492       case Match_RequiresFlagSetting:
10493         Message.Message = "no flag-preserving variant of this instruction available";
10494         break;
10495       case Match_InvalidOperand:
10496         Message.Message = "invalid operand for instruction";
10497         break;
10498       default:
10499         llvm_unreachable("Unhandled target predicate error");
10500         break;
10501       }
10502       NearMissesOut.emplace_back(Message);
10503       break;
10504     }
10505     case NearMissInfo::NearMissTooFewOperands: {
10506       if (!ReportedTooFewOperands) {
10507         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
10508         NearMissesOut.emplace_back(NearMissMessage{
10509             EndLoc, StringRef("too few operands for instruction")});
10510         ReportedTooFewOperands = true;
10511       }
10512       break;
10513     }
10514     case NearMissInfo::NoNearMiss:
10515       // This should never leave the matcher.
10516       llvm_unreachable("not a near-miss");
10517       break;
10518     }
10519   }
10520 }
10521 
10522 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
10523                                     SMLoc IDLoc, OperandVector &Operands) {
10524   SmallVector<NearMissMessage, 4> Messages;
10525   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
10526 
10527   if (Messages.size() == 0) {
10528     // No near-misses were found, so the best we can do is "invalid
10529     // instruction".
10530     Error(IDLoc, "invalid instruction");
10531   } else if (Messages.size() == 1) {
10532     // One near miss was found, report it as the sole error.
10533     Error(Messages[0].Loc, Messages[0].Message);
10534   } else {
10535     // More than one near miss, so report a generic "invalid instruction"
10536     // error, followed by notes for each of the near-misses.
10537     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
10538     for (auto &M : Messages) {
10539       Note(M.Loc, M.Message);
10540     }
10541   }
10542 }
10543 
10544 // FIXME: This structure should be moved inside ARMTargetParser
10545 // when we start to table-generate them, and we can use the ARM
10546 // flags below, that were generated by table-gen.
10547 static const struct {
10548   const unsigned Kind;
10549   const uint64_t ArchCheck;
10550   const FeatureBitset Features;
10551 } Extensions[] = {
10552   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10553   { ARM::AEK_CRYPTO,  Feature_HasV8,
10554     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10555   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10556   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10557     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10558   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10559   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10560   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10561   // FIXME: Only available in A-class, isel not predicated
10562   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10563   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10564   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10565   // FIXME: Unsupported extensions.
10566   { ARM::AEK_OS, Feature_None, {} },
10567   { ARM::AEK_IWMMXT, Feature_None, {} },
10568   { ARM::AEK_IWMMXT2, Feature_None, {} },
10569   { ARM::AEK_MAVERICK, Feature_None, {} },
10570   { ARM::AEK_XSCALE, Feature_None, {} },
10571 };
10572 
10573 /// parseDirectiveArchExtension
10574 ///   ::= .arch_extension [no]feature
10575 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10576   MCAsmParser &Parser = getParser();
10577 
10578   if (getLexer().isNot(AsmToken::Identifier))
10579     return Error(getLexer().getLoc(), "expected architecture extension name");
10580 
10581   StringRef Name = Parser.getTok().getString();
10582   SMLoc ExtLoc = Parser.getTok().getLoc();
10583   Lex();
10584 
10585   if (parseToken(AsmToken::EndOfStatement,
10586                  "unexpected token in '.arch_extension' directive"))
10587     return true;
10588 
10589   bool EnableFeature = true;
10590   if (Name.startswith_lower("no")) {
10591     EnableFeature = false;
10592     Name = Name.substr(2);
10593   }
10594   unsigned FeatureKind = ARM::parseArchExt(Name);
10595   if (FeatureKind == ARM::AEK_INVALID)
10596     return Error(ExtLoc, "unknown architectural extension: " + Name);
10597 
10598   for (const auto &Extension : Extensions) {
10599     if (Extension.Kind != FeatureKind)
10600       continue;
10601 
10602     if (Extension.Features.none())
10603       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10604 
10605     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10606       return Error(ExtLoc, "architectural extension '" + Name +
10607                                "' is not "
10608                                "allowed for the current base architecture");
10609 
10610     MCSubtargetInfo &STI = copySTI();
10611     FeatureBitset ToggleFeatures = EnableFeature
10612       ? (~STI.getFeatureBits() & Extension.Features)
10613       : ( STI.getFeatureBits() & Extension.Features);
10614 
10615     uint64_t Features =
10616         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10617     setAvailableFeatures(Features);
10618     return false;
10619   }
10620 
10621   return Error(ExtLoc, "unknown architectural extension: " + Name);
10622 }
10623 
10624 // Define this matcher function after the auto-generated include so we
10625 // have the match class enum definitions.
10626 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10627                                                   unsigned Kind) {
10628   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10629   // If the kind is a token for a literal immediate, check if our asm
10630   // operand matches. This is for InstAliases which have a fixed-value
10631   // immediate in the syntax.
10632   switch (Kind) {
10633   default: break;
10634   case MCK__35_0:
10635     if (Op.isImm())
10636       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10637         if (CE->getValue() == 0)
10638           return Match_Success;
10639     break;
10640   case MCK_ModImm:
10641     if (Op.isImm()) {
10642       const MCExpr *SOExpr = Op.getImm();
10643       int64_t Value;
10644       if (!SOExpr->evaluateAsAbsolute(Value))
10645         return Match_Success;
10646       assert((Value >= std::numeric_limits<int32_t>::min() &&
10647               Value <= std::numeric_limits<uint32_t>::max()) &&
10648              "expression value must be representable in 32 bits");
10649     }
10650     break;
10651   case MCK_rGPR:
10652     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10653       return Match_Success;
10654     return Match_rGPR;
10655   case MCK_GPRPair:
10656     if (Op.isReg() &&
10657         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10658       return Match_Success;
10659     break;
10660   }
10661   return Match_InvalidOperand;
10662 }
10663