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 "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/BinaryFormat/COFF.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCAssembler.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
27 #include "llvm/MC/MCELFStreamer.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/MCAsmParserUtils.h"
36 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
37 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MC/MCSection.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSubtargetInfo.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Support/ARMBuildAttributes.h"
44 #include "llvm/Support/ARMEHABI.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/SourceMgr.h"
49 #include "llvm/Support/TargetParser.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/raw_ostream.h"
52 
53 using namespace llvm;
54 
55 namespace {
56 
57 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
58 
59 static cl::opt<ImplicitItModeTy> ImplicitItMode(
60     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
61     cl::desc("Allow conditional instructions outdside of an IT block"),
62     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
63                           "Accept in both ISAs, emit implicit ITs in Thumb"),
64                clEnumValN(ImplicitItModeTy::Never, "never",
65                           "Warn in ARM, reject in Thumb"),
66                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
67                           "Accept in ARM, reject in Thumb"),
68                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
69                           "Warn in ARM, emit implicit ITs in Thumb")));
70 
71 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
72                                         cl::init(false));
73 
74 class ARMOperand;
75 
76 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
77 
78 class UnwindContext {
79   MCAsmParser &Parser;
80 
81   typedef SmallVector<SMLoc, 4> Locs;
82 
83   Locs FnStartLocs;
84   Locs CantUnwindLocs;
85   Locs PersonalityLocs;
86   Locs PersonalityIndexLocs;
87   Locs HandlerDataLocs;
88   int FPReg;
89 
90 public:
91   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
92 
93   bool hasFnStart() const { return !FnStartLocs.empty(); }
94   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
95   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
96   bool hasPersonality() const {
97     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
98   }
99 
100   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
101   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
102   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
103   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
104   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
105 
106   void saveFPReg(int Reg) { FPReg = Reg; }
107   int getFPReg() const { return FPReg; }
108 
109   void emitFnStartLocNotes() const {
110     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
111          FI != FE; ++FI)
112       Parser.Note(*FI, ".fnstart was specified here");
113   }
114   void emitCantUnwindLocNotes() const {
115     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
116                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
117       Parser.Note(*UI, ".cantunwind was specified here");
118   }
119   void emitHandlerDataLocNotes() const {
120     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
121                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
122       Parser.Note(*HI, ".handlerdata was specified here");
123   }
124   void emitPersonalityLocNotes() const {
125     for (Locs::const_iterator PI = PersonalityLocs.begin(),
126                               PE = PersonalityLocs.end(),
127                               PII = PersonalityIndexLocs.begin(),
128                               PIE = PersonalityIndexLocs.end();
129          PI != PE || PII != PIE;) {
130       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
131         Parser.Note(*PI++, ".personality was specified here");
132       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
133         Parser.Note(*PII++, ".personalityindex was specified here");
134       else
135         llvm_unreachable(".personality and .personalityindex cannot be "
136                          "at the same location");
137     }
138   }
139 
140   void reset() {
141     FnStartLocs = Locs();
142     CantUnwindLocs = Locs();
143     PersonalityLocs = Locs();
144     HandlerDataLocs = Locs();
145     PersonalityIndexLocs = Locs();
146     FPReg = ARM::SP;
147   }
148 };
149 
150 class ARMAsmParser : public MCTargetAsmParser {
151   const MCInstrInfo &MII;
152   const MCRegisterInfo *MRI;
153   UnwindContext UC;
154 
155   ARMTargetStreamer &getTargetStreamer() {
156     assert(getParser().getStreamer().getTargetStreamer() &&
157            "do not have a target streamer");
158     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
159     return static_cast<ARMTargetStreamer &>(TS);
160   }
161 
162   // Map of register aliases registers via the .req directive.
163   StringMap<unsigned> RegisterReqs;
164 
165   bool NextSymbolIsThumb;
166 
167   bool useImplicitITThumb() const {
168     return ImplicitItMode == ImplicitItModeTy::Always ||
169            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
170   }
171 
172   bool useImplicitITARM() const {
173     return ImplicitItMode == ImplicitItModeTy::Always ||
174            ImplicitItMode == ImplicitItModeTy::ARMOnly;
175   }
176 
177   struct {
178     ARMCC::CondCodes Cond;    // Condition for IT block.
179     unsigned Mask:4;          // Condition mask for instructions.
180                               // Starting at first 1 (from lsb).
181                               //   '1'  condition as indicated in IT.
182                               //   '0'  inverse of condition (else).
183                               // Count of instructions in IT block is
184                               // 4 - trailingzeroes(mask)
185                               // Note that this does not have the same encoding
186                               // as in the IT instruction, which also depends
187                               // on the low bit of the condition code.
188 
189     unsigned CurPosition;     // Current position in parsing of IT
190                               // block. In range [0,4], with 0 being the IT
191                               // instruction itself. Initialized according to
192                               // count of instructions in block.  ~0U if no
193                               // active IT block.
194 
195     bool IsExplicit;          // true  - The IT instruction was present in the
196                               //         input, we should not modify it.
197                               // false - The IT instruction was added
198                               //         implicitly, we can extend it if that
199                               //         would be legal.
200   } ITState;
201 
202   llvm::SmallVector<MCInst, 4> PendingConditionalInsts;
203 
204   void flushPendingInstructions(MCStreamer &Out) override {
205     if (!inImplicitITBlock()) {
206       assert(PendingConditionalInsts.size() == 0);
207       return;
208     }
209 
210     // Emit the IT instruction
211     unsigned Mask = getITMaskEncoding();
212     MCInst ITInst;
213     ITInst.setOpcode(ARM::t2IT);
214     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
215     ITInst.addOperand(MCOperand::createImm(Mask));
216     Out.EmitInstruction(ITInst, getSTI());
217 
218     // Emit the conditonal instructions
219     assert(PendingConditionalInsts.size() <= 4);
220     for (const MCInst &Inst : PendingConditionalInsts) {
221       Out.EmitInstruction(Inst, getSTI());
222     }
223     PendingConditionalInsts.clear();
224 
225     // Clear the IT state
226     ITState.Mask = 0;
227     ITState.CurPosition = ~0U;
228   }
229 
230   bool inITBlock() { return ITState.CurPosition != ~0U; }
231   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
232   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
233   bool lastInITBlock() {
234     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
235   }
236   void forwardITPosition() {
237     if (!inITBlock()) return;
238     // Move to the next instruction in the IT block, if there is one. If not,
239     // mark the block as done, except for implicit IT blocks, which we leave
240     // open until we find an instruction that can't be added to it.
241     unsigned TZ = countTrailingZeros(ITState.Mask);
242     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
243       ITState.CurPosition = ~0U; // Done with the IT block after this.
244   }
245 
246   // Rewind the state of the current IT block, removing the last slot from it.
247   void rewindImplicitITPosition() {
248     assert(inImplicitITBlock());
249     assert(ITState.CurPosition > 1);
250     ITState.CurPosition--;
251     unsigned TZ = countTrailingZeros(ITState.Mask);
252     unsigned NewMask = 0;
253     NewMask |= ITState.Mask & (0xC << TZ);
254     NewMask |= 0x2 << TZ;
255     ITState.Mask = NewMask;
256   }
257 
258   // Rewind the state of the current IT block, removing the last slot from it.
259   // If we were at the first slot, this closes the IT block.
260   void discardImplicitITBlock() {
261     assert(inImplicitITBlock());
262     assert(ITState.CurPosition == 1);
263     ITState.CurPosition = ~0U;
264     return;
265   }
266 
267   // Get the encoding of the IT mask, as it will appear in an IT instruction.
268   unsigned getITMaskEncoding() {
269     assert(inITBlock());
270     unsigned Mask = ITState.Mask;
271     unsigned TZ = countTrailingZeros(Mask);
272     if ((ITState.Cond & 1) == 0) {
273       assert(Mask && TZ <= 3 && "illegal IT mask value!");
274       Mask ^= (0xE << TZ) & 0xF;
275     }
276     return Mask;
277   }
278 
279   // Get the condition code corresponding to the current IT block slot.
280   ARMCC::CondCodes currentITCond() {
281     unsigned MaskBit;
282     if (ITState.CurPosition == 1)
283       MaskBit = 1;
284     else
285       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
286 
287     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
288   }
289 
290   // Invert the condition of the current IT block slot without changing any
291   // other slots in the same block.
292   void invertCurrentITCondition() {
293     if (ITState.CurPosition == 1) {
294       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
295     } else {
296       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
297     }
298   }
299 
300   // Returns true if the current IT block is full (all 4 slots used).
301   bool isITBlockFull() {
302     return inITBlock() && (ITState.Mask & 1);
303   }
304 
305   // Extend the current implicit IT block to have one more slot with the given
306   // condition code.
307   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
308     assert(inImplicitITBlock());
309     assert(!isITBlockFull());
310     assert(Cond == ITState.Cond ||
311            Cond == ARMCC::getOppositeCondition(ITState.Cond));
312     unsigned TZ = countTrailingZeros(ITState.Mask);
313     unsigned NewMask = 0;
314     // Keep any existing condition bits.
315     NewMask |= ITState.Mask & (0xE << TZ);
316     // Insert the new condition bit.
317     NewMask |= (Cond == ITState.Cond) << TZ;
318     // Move the trailing 1 down one bit.
319     NewMask |= 1 << (TZ - 1);
320     ITState.Mask = NewMask;
321   }
322 
323   // Create a new implicit IT block with a dummy condition code.
324   void startImplicitITBlock() {
325     assert(!inITBlock());
326     ITState.Cond = ARMCC::AL;
327     ITState.Mask = 8;
328     ITState.CurPosition = 1;
329     ITState.IsExplicit = false;
330     return;
331   }
332 
333   // Create a new explicit IT block with the given condition and mask. The mask
334   // should be in the parsed format, with a 1 implying 't', regardless of the
335   // low bit of the condition.
336   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
337     assert(!inITBlock());
338     ITState.Cond = Cond;
339     ITState.Mask = Mask;
340     ITState.CurPosition = 0;
341     ITState.IsExplicit = true;
342     return;
343   }
344 
345   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
346     return getParser().Note(L, Msg, Range);
347   }
348   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
349     return getParser().Warning(L, Msg, Range);
350   }
351   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
352     return getParser().Error(L, Msg, Range);
353   }
354 
355   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
356                            unsigned ListNo, bool IsARPop = false);
357   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
358                            unsigned ListNo);
359 
360   int tryParseRegister();
361   bool tryParseRegisterWithWriteBack(OperandVector &);
362   int tryParseShiftRegister(OperandVector &);
363   bool parseRegisterList(OperandVector &);
364   bool parseMemory(OperandVector &);
365   bool parseOperand(OperandVector &, StringRef Mnemonic);
366   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
367   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
368                               unsigned &ShiftAmount);
369   bool parseLiteralValues(unsigned Size, SMLoc L);
370   bool parseDirectiveThumb(SMLoc L);
371   bool parseDirectiveARM(SMLoc L);
372   bool parseDirectiveThumbFunc(SMLoc L);
373   bool parseDirectiveCode(SMLoc L);
374   bool parseDirectiveSyntax(SMLoc L);
375   bool parseDirectiveReq(StringRef Name, SMLoc L);
376   bool parseDirectiveUnreq(SMLoc L);
377   bool parseDirectiveArch(SMLoc L);
378   bool parseDirectiveEabiAttr(SMLoc L);
379   bool parseDirectiveCPU(SMLoc L);
380   bool parseDirectiveFPU(SMLoc L);
381   bool parseDirectiveFnStart(SMLoc L);
382   bool parseDirectiveFnEnd(SMLoc L);
383   bool parseDirectiveCantUnwind(SMLoc L);
384   bool parseDirectivePersonality(SMLoc L);
385   bool parseDirectiveHandlerData(SMLoc L);
386   bool parseDirectiveSetFP(SMLoc L);
387   bool parseDirectivePad(SMLoc L);
388   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
389   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
390   bool parseDirectiveLtorg(SMLoc L);
391   bool parseDirectiveEven(SMLoc L);
392   bool parseDirectivePersonalityIndex(SMLoc L);
393   bool parseDirectiveUnwindRaw(SMLoc L);
394   bool parseDirectiveTLSDescSeq(SMLoc L);
395   bool parseDirectiveMovSP(SMLoc L);
396   bool parseDirectiveObjectArch(SMLoc L);
397   bool parseDirectiveArchExtension(SMLoc L);
398   bool parseDirectiveAlign(SMLoc L);
399   bool parseDirectiveThumbSet(SMLoc L);
400 
401   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
402                           bool &CarrySetting, unsigned &ProcessorIMod,
403                           StringRef &ITMask);
404   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
405                              bool &CanAcceptCarrySet,
406                              bool &CanAcceptPredicationCode);
407 
408   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
409                                      OperandVector &Operands);
410   bool isThumb() const {
411     // FIXME: Can tablegen auto-generate this?
412     return getSTI().getFeatureBits()[ARM::ModeThumb];
413   }
414   bool isThumbOne() const {
415     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
416   }
417   bool isThumbTwo() const {
418     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
419   }
420   bool hasThumb() const {
421     return getSTI().getFeatureBits()[ARM::HasV4TOps];
422   }
423   bool hasThumb2() const {
424     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
425   }
426   bool hasV6Ops() const {
427     return getSTI().getFeatureBits()[ARM::HasV6Ops];
428   }
429   bool hasV6T2Ops() const {
430     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
431   }
432   bool hasV6MOps() const {
433     return getSTI().getFeatureBits()[ARM::HasV6MOps];
434   }
435   bool hasV7Ops() const {
436     return getSTI().getFeatureBits()[ARM::HasV7Ops];
437   }
438   bool hasV8Ops() const {
439     return getSTI().getFeatureBits()[ARM::HasV8Ops];
440   }
441   bool hasV8MBaseline() const {
442     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
443   }
444   bool hasV8MMainline() const {
445     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
446   }
447   bool has8MSecExt() const {
448     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
449   }
450   bool hasARM() const {
451     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
452   }
453   bool hasDSP() const {
454     return getSTI().getFeatureBits()[ARM::FeatureDSP];
455   }
456   bool hasD16() const {
457     return getSTI().getFeatureBits()[ARM::FeatureD16];
458   }
459   bool hasV8_1aOps() const {
460     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
461   }
462   bool hasRAS() const {
463     return getSTI().getFeatureBits()[ARM::FeatureRAS];
464   }
465 
466   void SwitchMode() {
467     MCSubtargetInfo &STI = copySTI();
468     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
469     setAvailableFeatures(FB);
470   }
471   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
472   bool isMClass() const {
473     return getSTI().getFeatureBits()[ARM::FeatureMClass];
474   }
475 
476   /// @name Auto-generated Match Functions
477   /// {
478 
479 #define GET_ASSEMBLER_HEADER
480 #include "ARMGenAsmMatcher.inc"
481 
482   /// }
483 
484   OperandMatchResultTy parseITCondCode(OperandVector &);
485   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
486   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
487   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
488   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
489   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
490   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
491   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
492   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
493   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
494                                    int High);
495   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
496     return parsePKHImm(O, "lsl", 0, 31);
497   }
498   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
499     return parsePKHImm(O, "asr", 1, 32);
500   }
501   OperandMatchResultTy parseSetEndImm(OperandVector &);
502   OperandMatchResultTy parseShifterImm(OperandVector &);
503   OperandMatchResultTy parseRotImm(OperandVector &);
504   OperandMatchResultTy parseModImm(OperandVector &);
505   OperandMatchResultTy parseBitfield(OperandVector &);
506   OperandMatchResultTy parsePostIdxReg(OperandVector &);
507   OperandMatchResultTy parseAM3Offset(OperandVector &);
508   OperandMatchResultTy parseFPImm(OperandVector &);
509   OperandMatchResultTy parseVectorList(OperandVector &);
510   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
511                                        SMLoc &EndLoc);
512 
513   // Asm Match Converter Methods
514   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
515   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
516 
517   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
518   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
519   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
520   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
521   bool isITBlockTerminator(MCInst &Inst) const;
522 
523 public:
524   enum ARMMatchResultTy {
525     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
526     Match_RequiresNotITBlock,
527     Match_RequiresV6,
528     Match_RequiresThumb2,
529     Match_RequiresV8,
530     Match_RequiresFlagSetting,
531 #define GET_OPERAND_DIAGNOSTIC_TYPES
532 #include "ARMGenAsmMatcher.inc"
533 
534   };
535 
536   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
537                const MCInstrInfo &MII, const MCTargetOptions &Options)
538     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
539     MCAsmParserExtension::Initialize(Parser);
540 
541     // Cache the MCRegisterInfo.
542     MRI = getContext().getRegisterInfo();
543 
544     // Initialize the set of available features.
545     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
546 
547     // Add build attributes based on the selected target.
548     if (AddBuildAttributes)
549       getTargetStreamer().emitTargetAttributes(STI);
550 
551     // Not in an ITBlock to start with.
552     ITState.CurPosition = ~0U;
553 
554     NextSymbolIsThumb = false;
555   }
556 
557   // Implementation of the MCTargetAsmParser interface:
558   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
559   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
560                         SMLoc NameLoc, OperandVector &Operands) override;
561   bool ParseDirective(AsmToken DirectiveID) override;
562 
563   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
564                                       unsigned Kind) override;
565   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
566 
567   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
568                                OperandVector &Operands, MCStreamer &Out,
569                                uint64_t &ErrorInfo,
570                                bool MatchingInlineAsm) override;
571   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
572                             uint64_t &ErrorInfo, bool MatchingInlineAsm,
573                             bool &EmitInITBlock, MCStreamer &Out);
574   void onLabelParsed(MCSymbol *Symbol) override;
575 };
576 } // end anonymous namespace
577 
578 namespace {
579 
580 /// ARMOperand - Instances of this class represent a parsed ARM machine
581 /// operand.
582 class ARMOperand : public MCParsedAsmOperand {
583   enum KindTy {
584     k_CondCode,
585     k_CCOut,
586     k_ITCondMask,
587     k_CoprocNum,
588     k_CoprocReg,
589     k_CoprocOption,
590     k_Immediate,
591     k_MemBarrierOpt,
592     k_InstSyncBarrierOpt,
593     k_Memory,
594     k_PostIndexRegister,
595     k_MSRMask,
596     k_BankedReg,
597     k_ProcIFlags,
598     k_VectorIndex,
599     k_Register,
600     k_RegisterList,
601     k_DPRRegisterList,
602     k_SPRRegisterList,
603     k_VectorList,
604     k_VectorListAllLanes,
605     k_VectorListIndexed,
606     k_ShiftedRegister,
607     k_ShiftedImmediate,
608     k_ShifterImmediate,
609     k_RotateImmediate,
610     k_ModifiedImmediate,
611     k_ConstantPoolImmediate,
612     k_BitfieldDescriptor,
613     k_Token,
614   } Kind;
615 
616   SMLoc StartLoc, EndLoc, AlignmentLoc;
617   SmallVector<unsigned, 8> Registers;
618 
619   struct CCOp {
620     ARMCC::CondCodes Val;
621   };
622 
623   struct CopOp {
624     unsigned Val;
625   };
626 
627   struct CoprocOptionOp {
628     unsigned Val;
629   };
630 
631   struct ITMaskOp {
632     unsigned Mask:4;
633   };
634 
635   struct MBOptOp {
636     ARM_MB::MemBOpt Val;
637   };
638 
639   struct ISBOptOp {
640     ARM_ISB::InstSyncBOpt Val;
641   };
642 
643   struct IFlagsOp {
644     ARM_PROC::IFlags Val;
645   };
646 
647   struct MMaskOp {
648     unsigned Val;
649   };
650 
651   struct BankedRegOp {
652     unsigned Val;
653   };
654 
655   struct TokOp {
656     const char *Data;
657     unsigned Length;
658   };
659 
660   struct RegOp {
661     unsigned RegNum;
662   };
663 
664   // A vector register list is a sequential list of 1 to 4 registers.
665   struct VectorListOp {
666     unsigned RegNum;
667     unsigned Count;
668     unsigned LaneIndex;
669     bool isDoubleSpaced;
670   };
671 
672   struct VectorIndexOp {
673     unsigned Val;
674   };
675 
676   struct ImmOp {
677     const MCExpr *Val;
678   };
679 
680   /// Combined record for all forms of ARM address expressions.
681   struct MemoryOp {
682     unsigned BaseRegNum;
683     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
684     // was specified.
685     const MCConstantExpr *OffsetImm;  // Offset immediate value
686     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
687     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
688     unsigned ShiftImm;        // shift for OffsetReg.
689     unsigned Alignment;       // 0 = no alignment specified
690     // n = alignment in bytes (2, 4, 8, 16, or 32)
691     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
692   };
693 
694   struct PostIdxRegOp {
695     unsigned RegNum;
696     bool isAdd;
697     ARM_AM::ShiftOpc ShiftTy;
698     unsigned ShiftImm;
699   };
700 
701   struct ShifterImmOp {
702     bool isASR;
703     unsigned Imm;
704   };
705 
706   struct RegShiftedRegOp {
707     ARM_AM::ShiftOpc ShiftTy;
708     unsigned SrcReg;
709     unsigned ShiftReg;
710     unsigned ShiftImm;
711   };
712 
713   struct RegShiftedImmOp {
714     ARM_AM::ShiftOpc ShiftTy;
715     unsigned SrcReg;
716     unsigned ShiftImm;
717   };
718 
719   struct RotImmOp {
720     unsigned Imm;
721   };
722 
723   struct ModImmOp {
724     unsigned Bits;
725     unsigned Rot;
726   };
727 
728   struct BitfieldOp {
729     unsigned LSB;
730     unsigned Width;
731   };
732 
733   union {
734     struct CCOp CC;
735     struct CopOp Cop;
736     struct CoprocOptionOp CoprocOption;
737     struct MBOptOp MBOpt;
738     struct ISBOptOp ISBOpt;
739     struct ITMaskOp ITMask;
740     struct IFlagsOp IFlags;
741     struct MMaskOp MMask;
742     struct BankedRegOp BankedReg;
743     struct TokOp Tok;
744     struct RegOp Reg;
745     struct VectorListOp VectorList;
746     struct VectorIndexOp VectorIndex;
747     struct ImmOp Imm;
748     struct MemoryOp Memory;
749     struct PostIdxRegOp PostIdxReg;
750     struct ShifterImmOp ShifterImm;
751     struct RegShiftedRegOp RegShiftedReg;
752     struct RegShiftedImmOp RegShiftedImm;
753     struct RotImmOp RotImm;
754     struct ModImmOp ModImm;
755     struct BitfieldOp Bitfield;
756   };
757 
758 public:
759   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
760 
761   /// getStartLoc - Get the location of the first token of this operand.
762   SMLoc getStartLoc() const override { return StartLoc; }
763   /// getEndLoc - Get the location of the last token of this operand.
764   SMLoc getEndLoc() const override { return EndLoc; }
765   /// getLocRange - Get the range between the first and last token of this
766   /// operand.
767   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
768 
769   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
770   SMLoc getAlignmentLoc() const {
771     assert(Kind == k_Memory && "Invalid access!");
772     return AlignmentLoc;
773   }
774 
775   ARMCC::CondCodes getCondCode() const {
776     assert(Kind == k_CondCode && "Invalid access!");
777     return CC.Val;
778   }
779 
780   unsigned getCoproc() const {
781     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
782     return Cop.Val;
783   }
784 
785   StringRef getToken() const {
786     assert(Kind == k_Token && "Invalid access!");
787     return StringRef(Tok.Data, Tok.Length);
788   }
789 
790   unsigned getReg() const override {
791     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
792     return Reg.RegNum;
793   }
794 
795   const SmallVectorImpl<unsigned> &getRegList() const {
796     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
797             Kind == k_SPRRegisterList) && "Invalid access!");
798     return Registers;
799   }
800 
801   const MCExpr *getImm() const {
802     assert(isImm() && "Invalid access!");
803     return Imm.Val;
804   }
805 
806   const MCExpr *getConstantPoolImm() const {
807     assert(isConstantPoolImm() && "Invalid access!");
808     return Imm.Val;
809   }
810 
811   unsigned getVectorIndex() const {
812     assert(Kind == k_VectorIndex && "Invalid access!");
813     return VectorIndex.Val;
814   }
815 
816   ARM_MB::MemBOpt getMemBarrierOpt() const {
817     assert(Kind == k_MemBarrierOpt && "Invalid access!");
818     return MBOpt.Val;
819   }
820 
821   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
822     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
823     return ISBOpt.Val;
824   }
825 
826   ARM_PROC::IFlags getProcIFlags() const {
827     assert(Kind == k_ProcIFlags && "Invalid access!");
828     return IFlags.Val;
829   }
830 
831   unsigned getMSRMask() const {
832     assert(Kind == k_MSRMask && "Invalid access!");
833     return MMask.Val;
834   }
835 
836   unsigned getBankedReg() const {
837     assert(Kind == k_BankedReg && "Invalid access!");
838     return BankedReg.Val;
839   }
840 
841   bool isCoprocNum() const { return Kind == k_CoprocNum; }
842   bool isCoprocReg() const { return Kind == k_CoprocReg; }
843   bool isCoprocOption() const { return Kind == k_CoprocOption; }
844   bool isCondCode() const { return Kind == k_CondCode; }
845   bool isCCOut() const { return Kind == k_CCOut; }
846   bool isITMask() const { return Kind == k_ITCondMask; }
847   bool isITCondCode() const { return Kind == k_CondCode; }
848   bool isImm() const override {
849     return Kind == k_Immediate;
850   }
851 
852   bool isARMBranchTarget() const {
853     if (!isImm()) return false;
854 
855     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
856       return CE->getValue() % 4 == 0;
857     return true;
858   }
859 
860 
861   bool isThumbBranchTarget() const {
862     if (!isImm()) return false;
863 
864     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
865       return CE->getValue() % 2 == 0;
866     return true;
867   }
868 
869   // checks whether this operand is an unsigned offset which fits is a field
870   // of specified width and scaled by a specific number of bits
871   template<unsigned width, unsigned scale>
872   bool isUnsignedOffset() const {
873     if (!isImm()) return false;
874     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
875     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
876       int64_t Val = CE->getValue();
877       int64_t Align = 1LL << scale;
878       int64_t Max = Align * ((1LL << width) - 1);
879       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
880     }
881     return false;
882   }
883   // checks whether this operand is an signed offset which fits is a field
884   // of specified width and scaled by a specific number of bits
885   template<unsigned width, unsigned scale>
886   bool isSignedOffset() const {
887     if (!isImm()) return false;
888     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
889     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
890       int64_t Val = CE->getValue();
891       int64_t Align = 1LL << scale;
892       int64_t Max = Align * ((1LL << (width-1)) - 1);
893       int64_t Min = -Align * (1LL << (width-1));
894       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
895     }
896     return false;
897   }
898 
899   // checks whether this operand is a memory operand computed as an offset
900   // applied to PC. the offset may have 8 bits of magnitude and is represented
901   // with two bits of shift. textually it may be either [pc, #imm], #imm or
902   // relocable expression...
903   bool isThumbMemPC() const {
904     int64_t Val = 0;
905     if (isImm()) {
906       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
907       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
908       if (!CE) return false;
909       Val = CE->getValue();
910     }
911     else if (isMem()) {
912       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
913       if(Memory.BaseRegNum != ARM::PC) return false;
914       Val = Memory.OffsetImm->getValue();
915     }
916     else return false;
917     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
918   }
919   bool isFPImm() const {
920     if (!isImm()) return false;
921     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
922     if (!CE) return false;
923     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
924     return Val != -1;
925   }
926 
927   template<int64_t N, int64_t M>
928   bool isImmediate() const {
929     if (!isImm()) return false;
930     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
931     if (!CE) return false;
932     int64_t Value = CE->getValue();
933     return Value >= N && Value <= M;
934   }
935   template<int64_t N, int64_t M>
936   bool isImmediateS4() const {
937     if (!isImm()) return false;
938     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
939     if (!CE) return false;
940     int64_t Value = CE->getValue();
941     return ((Value & 3) == 0) && Value >= N && Value <= M;
942   }
943   bool isFBits16() const {
944     return isImmediate<0, 17>();
945   }
946   bool isFBits32() const {
947     return isImmediate<1, 33>();
948   }
949   bool isImm8s4() const {
950     return isImmediateS4<-1020, 1020>();
951   }
952   bool isImm0_1020s4() const {
953     return isImmediateS4<0, 1020>();
954   }
955   bool isImm0_508s4() const {
956     return isImmediateS4<0, 508>();
957   }
958   bool isImm0_508s4Neg() const {
959     if (!isImm()) return false;
960     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
961     if (!CE) return false;
962     int64_t Value = -CE->getValue();
963     // explicitly exclude zero. we want that to use the normal 0_508 version.
964     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
965   }
966   bool isImm0_4095Neg() const {
967     if (!isImm()) return false;
968     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
969     if (!CE) return false;
970     int64_t Value = -CE->getValue();
971     return Value > 0 && Value < 4096;
972   }
973   bool isImm0_7() const {
974     return isImmediate<0, 7>();
975   }
976   bool isImm1_16() const {
977     return isImmediate<1, 16>();
978   }
979   bool isImm1_32() const {
980     return isImmediate<1, 32>();
981   }
982   bool isImm8_255() const {
983     return isImmediate<8, 255>();
984   }
985   bool isImm256_65535Expr() const {
986     if (!isImm()) return false;
987     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
988     // If it's not a constant expression, it'll generate a fixup and be
989     // handled later.
990     if (!CE) return true;
991     int64_t Value = CE->getValue();
992     return Value >= 256 && Value < 65536;
993   }
994   bool isImm0_65535Expr() const {
995     if (!isImm()) return false;
996     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
997     // If it's not a constant expression, it'll generate a fixup and be
998     // handled later.
999     if (!CE) return true;
1000     int64_t Value = CE->getValue();
1001     return Value >= 0 && Value < 65536;
1002   }
1003   bool isImm24bit() const {
1004     return isImmediate<0, 0xffffff + 1>();
1005   }
1006   bool isImmThumbSR() const {
1007     return isImmediate<1, 33>();
1008   }
1009   bool isPKHLSLImm() const {
1010     return isImmediate<0, 32>();
1011   }
1012   bool isPKHASRImm() const {
1013     return isImmediate<0, 33>();
1014   }
1015   bool isAdrLabel() const {
1016     // If we have an immediate that's not a constant, treat it as a label
1017     // reference needing a fixup.
1018     if (isImm() && !isa<MCConstantExpr>(getImm()))
1019       return true;
1020 
1021     // If it is a constant, it must fit into a modified immediate encoding.
1022     if (!isImm()) return false;
1023     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1024     if (!CE) return false;
1025     int64_t Value = CE->getValue();
1026     return (ARM_AM::getSOImmVal(Value) != -1 ||
1027             ARM_AM::getSOImmVal(-Value) != -1);
1028   }
1029   bool isT2SOImm() const {
1030     // If we have an immediate that's not a constant, treat it as an expression
1031     // needing a fixup.
1032     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1033       // We want to avoid matching :upper16: and :lower16: as we want these
1034       // expressions to match in isImm0_65535Expr()
1035       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1036       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1037                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1038     }
1039     if (!isImm()) return false;
1040     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1041     if (!CE) return false;
1042     int64_t Value = CE->getValue();
1043     return ARM_AM::getT2SOImmVal(Value) != -1;
1044   }
1045   bool isT2SOImmNot() const {
1046     if (!isImm()) return false;
1047     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1048     if (!CE) return false;
1049     int64_t Value = CE->getValue();
1050     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1051       ARM_AM::getT2SOImmVal(~Value) != -1;
1052   }
1053   bool isT2SOImmNeg() const {
1054     if (!isImm()) return false;
1055     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1056     if (!CE) return false;
1057     int64_t Value = CE->getValue();
1058     // Only use this when not representable as a plain so_imm.
1059     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1060       ARM_AM::getT2SOImmVal(-Value) != -1;
1061   }
1062   bool isSetEndImm() const {
1063     if (!isImm()) return false;
1064     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1065     if (!CE) return false;
1066     int64_t Value = CE->getValue();
1067     return Value == 1 || Value == 0;
1068   }
1069   bool isReg() const override { return Kind == k_Register; }
1070   bool isRegList() const { return Kind == k_RegisterList; }
1071   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1072   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1073   bool isToken() const override { return Kind == k_Token; }
1074   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1075   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1076   bool isMem() const override { return Kind == k_Memory; }
1077   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1078   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1079   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1080   bool isRotImm() const { return Kind == k_RotateImmediate; }
1081   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1082   bool isModImmNot() const {
1083     if (!isImm()) return false;
1084     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1085     if (!CE) return false;
1086     int64_t Value = CE->getValue();
1087     return ARM_AM::getSOImmVal(~Value) != -1;
1088   }
1089   bool isModImmNeg() const {
1090     if (!isImm()) return false;
1091     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1092     if (!CE) return false;
1093     int64_t Value = CE->getValue();
1094     return ARM_AM::getSOImmVal(Value) == -1 &&
1095       ARM_AM::getSOImmVal(-Value) != -1;
1096   }
1097   bool isThumbModImmNeg1_7() const {
1098     if (!isImm()) return false;
1099     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1100     if (!CE) return false;
1101     int32_t Value = -(int32_t)CE->getValue();
1102     return 0 < Value && Value < 8;
1103   }
1104   bool isThumbModImmNeg8_255() const {
1105     if (!isImm()) return false;
1106     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1107     if (!CE) return false;
1108     int32_t Value = -(int32_t)CE->getValue();
1109     return 7 < Value && Value < 256;
1110   }
1111   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1112   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1113   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1114   bool isPostIdxReg() const {
1115     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1116   }
1117   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1118     if (!isMem())
1119       return false;
1120     // No offset of any kind.
1121     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1122      (alignOK || Memory.Alignment == Alignment);
1123   }
1124   bool isMemPCRelImm12() const {
1125     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1126       return false;
1127     // Base register must be PC.
1128     if (Memory.BaseRegNum != ARM::PC)
1129       return false;
1130     // Immediate offset in range [-4095, 4095].
1131     if (!Memory.OffsetImm) return true;
1132     int64_t Val = Memory.OffsetImm->getValue();
1133     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1134   }
1135   bool isAlignedMemory() const {
1136     return isMemNoOffset(true);
1137   }
1138   bool isAlignedMemoryNone() const {
1139     return isMemNoOffset(false, 0);
1140   }
1141   bool isDupAlignedMemoryNone() const {
1142     return isMemNoOffset(false, 0);
1143   }
1144   bool isAlignedMemory16() const {
1145     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1146       return true;
1147     return isMemNoOffset(false, 0);
1148   }
1149   bool isDupAlignedMemory16() const {
1150     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1151       return true;
1152     return isMemNoOffset(false, 0);
1153   }
1154   bool isAlignedMemory32() const {
1155     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1156       return true;
1157     return isMemNoOffset(false, 0);
1158   }
1159   bool isDupAlignedMemory32() const {
1160     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1161       return true;
1162     return isMemNoOffset(false, 0);
1163   }
1164   bool isAlignedMemory64() const {
1165     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1166       return true;
1167     return isMemNoOffset(false, 0);
1168   }
1169   bool isDupAlignedMemory64() const {
1170     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1171       return true;
1172     return isMemNoOffset(false, 0);
1173   }
1174   bool isAlignedMemory64or128() const {
1175     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1176       return true;
1177     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1178       return true;
1179     return isMemNoOffset(false, 0);
1180   }
1181   bool isDupAlignedMemory64or128() const {
1182     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1183       return true;
1184     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1185       return true;
1186     return isMemNoOffset(false, 0);
1187   }
1188   bool isAlignedMemory64or128or256() const {
1189     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1190       return true;
1191     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1192       return true;
1193     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1194       return true;
1195     return isMemNoOffset(false, 0);
1196   }
1197   bool isAddrMode2() const {
1198     if (!isMem() || Memory.Alignment != 0) return false;
1199     // Check for register offset.
1200     if (Memory.OffsetRegNum) return true;
1201     // Immediate offset in range [-4095, 4095].
1202     if (!Memory.OffsetImm) return true;
1203     int64_t Val = Memory.OffsetImm->getValue();
1204     return Val > -4096 && Val < 4096;
1205   }
1206   bool isAM2OffsetImm() const {
1207     if (!isImm()) return false;
1208     // Immediate offset in range [-4095, 4095].
1209     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1210     if (!CE) return false;
1211     int64_t Val = CE->getValue();
1212     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1213   }
1214   bool isAddrMode3() const {
1215     // If we have an immediate that's not a constant, treat it as a label
1216     // reference needing a fixup. If it is a constant, it's something else
1217     // and we reject it.
1218     if (isImm() && !isa<MCConstantExpr>(getImm()))
1219       return true;
1220     if (!isMem() || Memory.Alignment != 0) return false;
1221     // No shifts are legal for AM3.
1222     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1223     // Check for register offset.
1224     if (Memory.OffsetRegNum) return true;
1225     // Immediate offset in range [-255, 255].
1226     if (!Memory.OffsetImm) return true;
1227     int64_t Val = Memory.OffsetImm->getValue();
1228     // The #-0 offset is encoded as INT32_MIN, and we have to check
1229     // for this too.
1230     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1231   }
1232   bool isAM3Offset() const {
1233     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1234       return false;
1235     if (Kind == k_PostIndexRegister)
1236       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1237     // Immediate offset in range [-255, 255].
1238     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1239     if (!CE) return false;
1240     int64_t Val = CE->getValue();
1241     // Special case, #-0 is INT32_MIN.
1242     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1243   }
1244   bool isAddrMode5() const {
1245     // If we have an immediate that's not a constant, treat it as a label
1246     // reference needing a fixup. If it is a constant, it's something else
1247     // and we reject it.
1248     if (isImm() && !isa<MCConstantExpr>(getImm()))
1249       return true;
1250     if (!isMem() || Memory.Alignment != 0) return false;
1251     // Check for register offset.
1252     if (Memory.OffsetRegNum) return false;
1253     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1254     if (!Memory.OffsetImm) return true;
1255     int64_t Val = Memory.OffsetImm->getValue();
1256     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1257       Val == INT32_MIN;
1258   }
1259   bool isAddrMode5FP16() const {
1260     // If we have an immediate that's not a constant, treat it as a label
1261     // reference needing a fixup. If it is a constant, it's something else
1262     // and we reject it.
1263     if (isImm() && !isa<MCConstantExpr>(getImm()))
1264       return true;
1265     if (!isMem() || Memory.Alignment != 0) return false;
1266     // Check for register offset.
1267     if (Memory.OffsetRegNum) return false;
1268     // Immediate offset in range [-510, 510] and a multiple of 2.
1269     if (!Memory.OffsetImm) return true;
1270     int64_t Val = Memory.OffsetImm->getValue();
1271     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) || Val == INT32_MIN;
1272   }
1273   bool isMemTBB() const {
1274     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1275         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1276       return false;
1277     return true;
1278   }
1279   bool isMemTBH() const {
1280     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1281         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1282         Memory.Alignment != 0 )
1283       return false;
1284     return true;
1285   }
1286   bool isMemRegOffset() const {
1287     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1288       return false;
1289     return true;
1290   }
1291   bool isT2MemRegOffset() const {
1292     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1293         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1294       return false;
1295     // Only lsl #{0, 1, 2, 3} allowed.
1296     if (Memory.ShiftType == ARM_AM::no_shift)
1297       return true;
1298     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1299       return false;
1300     return true;
1301   }
1302   bool isMemThumbRR() const {
1303     // Thumb reg+reg addressing is simple. Just two registers, a base and
1304     // an offset. No shifts, negations or any other complicating factors.
1305     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1306         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1307       return false;
1308     return isARMLowRegister(Memory.BaseRegNum) &&
1309       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1310   }
1311   bool isMemThumbRIs4() const {
1312     if (!isMem() || Memory.OffsetRegNum != 0 ||
1313         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1314       return false;
1315     // Immediate offset, multiple of 4 in range [0, 124].
1316     if (!Memory.OffsetImm) return true;
1317     int64_t Val = Memory.OffsetImm->getValue();
1318     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1319   }
1320   bool isMemThumbRIs2() const {
1321     if (!isMem() || Memory.OffsetRegNum != 0 ||
1322         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1323       return false;
1324     // Immediate offset, multiple of 4 in range [0, 62].
1325     if (!Memory.OffsetImm) return true;
1326     int64_t Val = Memory.OffsetImm->getValue();
1327     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1328   }
1329   bool isMemThumbRIs1() const {
1330     if (!isMem() || Memory.OffsetRegNum != 0 ||
1331         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1332       return false;
1333     // Immediate offset in range [0, 31].
1334     if (!Memory.OffsetImm) return true;
1335     int64_t Val = Memory.OffsetImm->getValue();
1336     return Val >= 0 && Val <= 31;
1337   }
1338   bool isMemThumbSPI() const {
1339     if (!isMem() || Memory.OffsetRegNum != 0 ||
1340         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1341       return false;
1342     // Immediate offset, multiple of 4 in range [0, 1020].
1343     if (!Memory.OffsetImm) return true;
1344     int64_t Val = Memory.OffsetImm->getValue();
1345     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1346   }
1347   bool isMemImm8s4Offset() const {
1348     // If we have an immediate that's not a constant, treat it as a label
1349     // reference needing a fixup. If it is a constant, it's something else
1350     // and we reject it.
1351     if (isImm() && !isa<MCConstantExpr>(getImm()))
1352       return true;
1353     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1354       return false;
1355     // Immediate offset a multiple of 4 in range [-1020, 1020].
1356     if (!Memory.OffsetImm) return true;
1357     int64_t Val = Memory.OffsetImm->getValue();
1358     // Special case, #-0 is INT32_MIN.
1359     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1360   }
1361   bool isMemImm0_1020s4Offset() const {
1362     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1363       return false;
1364     // Immediate offset a multiple of 4 in range [0, 1020].
1365     if (!Memory.OffsetImm) return true;
1366     int64_t Val = Memory.OffsetImm->getValue();
1367     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1368   }
1369   bool isMemImm8Offset() const {
1370     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1371       return false;
1372     // Base reg of PC isn't allowed for these encodings.
1373     if (Memory.BaseRegNum == ARM::PC) return false;
1374     // Immediate offset in range [-255, 255].
1375     if (!Memory.OffsetImm) return true;
1376     int64_t Val = Memory.OffsetImm->getValue();
1377     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1378   }
1379   bool isMemPosImm8Offset() const {
1380     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1381       return false;
1382     // Immediate offset in range [0, 255].
1383     if (!Memory.OffsetImm) return true;
1384     int64_t Val = Memory.OffsetImm->getValue();
1385     return Val >= 0 && Val < 256;
1386   }
1387   bool isMemNegImm8Offset() const {
1388     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1389       return false;
1390     // Base reg of PC isn't allowed for these encodings.
1391     if (Memory.BaseRegNum == ARM::PC) return false;
1392     // Immediate offset in range [-255, -1].
1393     if (!Memory.OffsetImm) return false;
1394     int64_t Val = Memory.OffsetImm->getValue();
1395     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1396   }
1397   bool isMemUImm12Offset() const {
1398     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1399       return false;
1400     // Immediate offset in range [0, 4095].
1401     if (!Memory.OffsetImm) return true;
1402     int64_t Val = Memory.OffsetImm->getValue();
1403     return (Val >= 0 && Val < 4096);
1404   }
1405   bool isMemImm12Offset() const {
1406     // If we have an immediate that's not a constant, treat it as a label
1407     // reference needing a fixup. If it is a constant, it's something else
1408     // and we reject it.
1409 
1410     if (isImm() && !isa<MCConstantExpr>(getImm()))
1411       return true;
1412 
1413     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1414       return false;
1415     // Immediate offset in range [-4095, 4095].
1416     if (!Memory.OffsetImm) return true;
1417     int64_t Val = Memory.OffsetImm->getValue();
1418     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1419   }
1420   bool isConstPoolAsmImm() const {
1421     // Delay processing of Constant Pool Immediate, this will turn into
1422     // a constant. Match no other operand
1423     return (isConstantPoolImm());
1424   }
1425   bool isPostIdxImm8() const {
1426     if (!isImm()) return false;
1427     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1428     if (!CE) return false;
1429     int64_t Val = CE->getValue();
1430     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1431   }
1432   bool isPostIdxImm8s4() const {
1433     if (!isImm()) return false;
1434     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1435     if (!CE) return false;
1436     int64_t Val = CE->getValue();
1437     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1438       (Val == INT32_MIN);
1439   }
1440 
1441   bool isMSRMask() const { return Kind == k_MSRMask; }
1442   bool isBankedReg() const { return Kind == k_BankedReg; }
1443   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1444 
1445   // NEON operands.
1446   bool isSingleSpacedVectorList() const {
1447     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1448   }
1449   bool isDoubleSpacedVectorList() const {
1450     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1451   }
1452   bool isVecListOneD() const {
1453     if (!isSingleSpacedVectorList()) return false;
1454     return VectorList.Count == 1;
1455   }
1456 
1457   bool isVecListDPair() const {
1458     if (!isSingleSpacedVectorList()) return false;
1459     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1460               .contains(VectorList.RegNum));
1461   }
1462 
1463   bool isVecListThreeD() const {
1464     if (!isSingleSpacedVectorList()) return false;
1465     return VectorList.Count == 3;
1466   }
1467 
1468   bool isVecListFourD() const {
1469     if (!isSingleSpacedVectorList()) return false;
1470     return VectorList.Count == 4;
1471   }
1472 
1473   bool isVecListDPairSpaced() const {
1474     if (Kind != k_VectorList) return false;
1475     if (isSingleSpacedVectorList()) return false;
1476     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1477               .contains(VectorList.RegNum));
1478   }
1479 
1480   bool isVecListThreeQ() const {
1481     if (!isDoubleSpacedVectorList()) return false;
1482     return VectorList.Count == 3;
1483   }
1484 
1485   bool isVecListFourQ() const {
1486     if (!isDoubleSpacedVectorList()) return false;
1487     return VectorList.Count == 4;
1488   }
1489 
1490   bool isSingleSpacedVectorAllLanes() const {
1491     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1492   }
1493   bool isDoubleSpacedVectorAllLanes() const {
1494     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1495   }
1496   bool isVecListOneDAllLanes() const {
1497     if (!isSingleSpacedVectorAllLanes()) return false;
1498     return VectorList.Count == 1;
1499   }
1500 
1501   bool isVecListDPairAllLanes() const {
1502     if (!isSingleSpacedVectorAllLanes()) return false;
1503     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1504               .contains(VectorList.RegNum));
1505   }
1506 
1507   bool isVecListDPairSpacedAllLanes() const {
1508     if (!isDoubleSpacedVectorAllLanes()) return false;
1509     return VectorList.Count == 2;
1510   }
1511 
1512   bool isVecListThreeDAllLanes() const {
1513     if (!isSingleSpacedVectorAllLanes()) return false;
1514     return VectorList.Count == 3;
1515   }
1516 
1517   bool isVecListThreeQAllLanes() const {
1518     if (!isDoubleSpacedVectorAllLanes()) return false;
1519     return VectorList.Count == 3;
1520   }
1521 
1522   bool isVecListFourDAllLanes() const {
1523     if (!isSingleSpacedVectorAllLanes()) return false;
1524     return VectorList.Count == 4;
1525   }
1526 
1527   bool isVecListFourQAllLanes() const {
1528     if (!isDoubleSpacedVectorAllLanes()) return false;
1529     return VectorList.Count == 4;
1530   }
1531 
1532   bool isSingleSpacedVectorIndexed() const {
1533     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1534   }
1535   bool isDoubleSpacedVectorIndexed() const {
1536     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1537   }
1538   bool isVecListOneDByteIndexed() const {
1539     if (!isSingleSpacedVectorIndexed()) return false;
1540     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1541   }
1542 
1543   bool isVecListOneDHWordIndexed() const {
1544     if (!isSingleSpacedVectorIndexed()) return false;
1545     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1546   }
1547 
1548   bool isVecListOneDWordIndexed() const {
1549     if (!isSingleSpacedVectorIndexed()) return false;
1550     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1551   }
1552 
1553   bool isVecListTwoDByteIndexed() const {
1554     if (!isSingleSpacedVectorIndexed()) return false;
1555     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1556   }
1557 
1558   bool isVecListTwoDHWordIndexed() const {
1559     if (!isSingleSpacedVectorIndexed()) return false;
1560     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1561   }
1562 
1563   bool isVecListTwoQWordIndexed() const {
1564     if (!isDoubleSpacedVectorIndexed()) return false;
1565     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1566   }
1567 
1568   bool isVecListTwoQHWordIndexed() const {
1569     if (!isDoubleSpacedVectorIndexed()) return false;
1570     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1571   }
1572 
1573   bool isVecListTwoDWordIndexed() const {
1574     if (!isSingleSpacedVectorIndexed()) return false;
1575     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1576   }
1577 
1578   bool isVecListThreeDByteIndexed() const {
1579     if (!isSingleSpacedVectorIndexed()) return false;
1580     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1581   }
1582 
1583   bool isVecListThreeDHWordIndexed() const {
1584     if (!isSingleSpacedVectorIndexed()) return false;
1585     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1586   }
1587 
1588   bool isVecListThreeQWordIndexed() const {
1589     if (!isDoubleSpacedVectorIndexed()) return false;
1590     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1591   }
1592 
1593   bool isVecListThreeQHWordIndexed() const {
1594     if (!isDoubleSpacedVectorIndexed()) return false;
1595     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1596   }
1597 
1598   bool isVecListThreeDWordIndexed() const {
1599     if (!isSingleSpacedVectorIndexed()) return false;
1600     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1601   }
1602 
1603   bool isVecListFourDByteIndexed() const {
1604     if (!isSingleSpacedVectorIndexed()) return false;
1605     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1606   }
1607 
1608   bool isVecListFourDHWordIndexed() const {
1609     if (!isSingleSpacedVectorIndexed()) return false;
1610     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1611   }
1612 
1613   bool isVecListFourQWordIndexed() const {
1614     if (!isDoubleSpacedVectorIndexed()) return false;
1615     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1616   }
1617 
1618   bool isVecListFourQHWordIndexed() const {
1619     if (!isDoubleSpacedVectorIndexed()) return false;
1620     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1621   }
1622 
1623   bool isVecListFourDWordIndexed() const {
1624     if (!isSingleSpacedVectorIndexed()) return false;
1625     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1626   }
1627 
1628   bool isVectorIndex8() const {
1629     if (Kind != k_VectorIndex) return false;
1630     return VectorIndex.Val < 8;
1631   }
1632   bool isVectorIndex16() const {
1633     if (Kind != k_VectorIndex) return false;
1634     return VectorIndex.Val < 4;
1635   }
1636   bool isVectorIndex32() const {
1637     if (Kind != k_VectorIndex) return false;
1638     return VectorIndex.Val < 2;
1639   }
1640 
1641   bool isNEONi8splat() const {
1642     if (!isImm()) return false;
1643     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1644     // Must be a constant.
1645     if (!CE) return false;
1646     int64_t Value = CE->getValue();
1647     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1648     // value.
1649     return Value >= 0 && Value < 256;
1650   }
1651 
1652   bool isNEONi16splat() const {
1653     if (isNEONByteReplicate(2))
1654       return false; // Leave that for bytes replication and forbid by default.
1655     if (!isImm())
1656       return false;
1657     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1658     // Must be a constant.
1659     if (!CE) return false;
1660     unsigned Value = CE->getValue();
1661     return ARM_AM::isNEONi16splat(Value);
1662   }
1663 
1664   bool isNEONi16splatNot() const {
1665     if (!isImm())
1666       return false;
1667     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1668     // Must be a constant.
1669     if (!CE) return false;
1670     unsigned Value = CE->getValue();
1671     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1672   }
1673 
1674   bool isNEONi32splat() const {
1675     if (isNEONByteReplicate(4))
1676       return false; // Leave that for bytes replication and forbid by default.
1677     if (!isImm())
1678       return false;
1679     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1680     // Must be a constant.
1681     if (!CE) return false;
1682     unsigned Value = CE->getValue();
1683     return ARM_AM::isNEONi32splat(Value);
1684   }
1685 
1686   bool isNEONi32splatNot() const {
1687     if (!isImm())
1688       return false;
1689     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1690     // Must be a constant.
1691     if (!CE) return false;
1692     unsigned Value = CE->getValue();
1693     return ARM_AM::isNEONi32splat(~Value);
1694   }
1695 
1696   bool isNEONByteReplicate(unsigned NumBytes) const {
1697     if (!isImm())
1698       return false;
1699     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1700     // Must be a constant.
1701     if (!CE)
1702       return false;
1703     int64_t Value = CE->getValue();
1704     if (!Value)
1705       return false; // Don't bother with zero.
1706 
1707     unsigned char B = Value & 0xff;
1708     for (unsigned i = 1; i < NumBytes; ++i) {
1709       Value >>= 8;
1710       if ((Value & 0xff) != B)
1711         return false;
1712     }
1713     return true;
1714   }
1715   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1716   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1717   bool isNEONi32vmov() const {
1718     if (isNEONByteReplicate(4))
1719       return false; // Let it to be classified as byte-replicate case.
1720     if (!isImm())
1721       return false;
1722     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1723     // Must be a constant.
1724     if (!CE)
1725       return false;
1726     int64_t Value = CE->getValue();
1727     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1728     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1729     // FIXME: This is probably wrong and a copy and paste from previous example
1730     return (Value >= 0 && Value < 256) ||
1731       (Value >= 0x0100 && Value <= 0xff00) ||
1732       (Value >= 0x010000 && Value <= 0xff0000) ||
1733       (Value >= 0x01000000 && Value <= 0xff000000) ||
1734       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1735       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1736   }
1737   bool isNEONi32vmovNeg() const {
1738     if (!isImm()) return false;
1739     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1740     // Must be a constant.
1741     if (!CE) return false;
1742     int64_t Value = ~CE->getValue();
1743     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1744     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1745     // FIXME: This is probably wrong and a copy and paste from previous example
1746     return (Value >= 0 && Value < 256) ||
1747       (Value >= 0x0100 && Value <= 0xff00) ||
1748       (Value >= 0x010000 && Value <= 0xff0000) ||
1749       (Value >= 0x01000000 && Value <= 0xff000000) ||
1750       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1751       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1752   }
1753 
1754   bool isNEONi64splat() const {
1755     if (!isImm()) return false;
1756     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1757     // Must be a constant.
1758     if (!CE) return false;
1759     uint64_t Value = CE->getValue();
1760     // i64 value with each byte being either 0 or 0xff.
1761     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1762       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1763     return true;
1764   }
1765 
1766   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1767     // Add as immediates when possible.  Null MCExpr = 0.
1768     if (!Expr)
1769       Inst.addOperand(MCOperand::createImm(0));
1770     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1771       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1772     else
1773       Inst.addOperand(MCOperand::createExpr(Expr));
1774   }
1775 
1776   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
1777     assert(N == 1 && "Invalid number of operands!");
1778     addExpr(Inst, getImm());
1779   }
1780 
1781   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
1782     assert(N == 1 && "Invalid number of operands!");
1783     addExpr(Inst, getImm());
1784   }
1785 
1786   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1787     assert(N == 2 && "Invalid number of operands!");
1788     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1789     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1790     Inst.addOperand(MCOperand::createReg(RegNum));
1791   }
1792 
1793   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1794     assert(N == 1 && "Invalid number of operands!");
1795     Inst.addOperand(MCOperand::createImm(getCoproc()));
1796   }
1797 
1798   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1799     assert(N == 1 && "Invalid number of operands!");
1800     Inst.addOperand(MCOperand::createImm(getCoproc()));
1801   }
1802 
1803   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1804     assert(N == 1 && "Invalid number of operands!");
1805     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1806   }
1807 
1808   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1809     assert(N == 1 && "Invalid number of operands!");
1810     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1811   }
1812 
1813   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1814     assert(N == 1 && "Invalid number of operands!");
1815     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1816   }
1817 
1818   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1819     assert(N == 1 && "Invalid number of operands!");
1820     Inst.addOperand(MCOperand::createReg(getReg()));
1821   }
1822 
1823   void addRegOperands(MCInst &Inst, unsigned N) const {
1824     assert(N == 1 && "Invalid number of operands!");
1825     Inst.addOperand(MCOperand::createReg(getReg()));
1826   }
1827 
1828   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1829     assert(N == 3 && "Invalid number of operands!");
1830     assert(isRegShiftedReg() &&
1831            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1832     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1833     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1834     Inst.addOperand(MCOperand::createImm(
1835       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1836   }
1837 
1838   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1839     assert(N == 2 && "Invalid number of operands!");
1840     assert(isRegShiftedImm() &&
1841            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1842     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1843     // Shift of #32 is encoded as 0 where permitted
1844     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1845     Inst.addOperand(MCOperand::createImm(
1846       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1847   }
1848 
1849   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1850     assert(N == 1 && "Invalid number of operands!");
1851     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1852                                          ShifterImm.Imm));
1853   }
1854 
1855   void addRegListOperands(MCInst &Inst, unsigned N) const {
1856     assert(N == 1 && "Invalid number of operands!");
1857     const SmallVectorImpl<unsigned> &RegList = getRegList();
1858     for (SmallVectorImpl<unsigned>::const_iterator
1859            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1860       Inst.addOperand(MCOperand::createReg(*I));
1861   }
1862 
1863   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1864     addRegListOperands(Inst, N);
1865   }
1866 
1867   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1868     addRegListOperands(Inst, N);
1869   }
1870 
1871   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1872     assert(N == 1 && "Invalid number of operands!");
1873     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1874     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1875   }
1876 
1877   void addModImmOperands(MCInst &Inst, unsigned N) const {
1878     assert(N == 1 && "Invalid number of operands!");
1879 
1880     // Support for fixups (MCFixup)
1881     if (isImm())
1882       return addImmOperands(Inst, N);
1883 
1884     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
1885   }
1886 
1887   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1888     assert(N == 1 && "Invalid number of operands!");
1889     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1890     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1891     Inst.addOperand(MCOperand::createImm(Enc));
1892   }
1893 
1894   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1895     assert(N == 1 && "Invalid number of operands!");
1896     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1897     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1898     Inst.addOperand(MCOperand::createImm(Enc));
1899   }
1900 
1901   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
1902     assert(N == 1 && "Invalid number of operands!");
1903     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1904     uint32_t Val = -CE->getValue();
1905     Inst.addOperand(MCOperand::createImm(Val));
1906   }
1907 
1908   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
1909     assert(N == 1 && "Invalid number of operands!");
1910     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1911     uint32_t Val = -CE->getValue();
1912     Inst.addOperand(MCOperand::createImm(Val));
1913   }
1914 
1915   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1916     assert(N == 1 && "Invalid number of operands!");
1917     // Munge the lsb/width into a bitfield mask.
1918     unsigned lsb = Bitfield.LSB;
1919     unsigned width = Bitfield.Width;
1920     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1921     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1922                       (32 - (lsb + width)));
1923     Inst.addOperand(MCOperand::createImm(Mask));
1924   }
1925 
1926   void addImmOperands(MCInst &Inst, unsigned N) const {
1927     assert(N == 1 && "Invalid number of operands!");
1928     addExpr(Inst, getImm());
1929   }
1930 
1931   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1932     assert(N == 1 && "Invalid number of operands!");
1933     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1934     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
1935   }
1936 
1937   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1938     assert(N == 1 && "Invalid number of operands!");
1939     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1940     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
1941   }
1942 
1943   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1944     assert(N == 1 && "Invalid number of operands!");
1945     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1946     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1947     Inst.addOperand(MCOperand::createImm(Val));
1948   }
1949 
1950   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1951     assert(N == 1 && "Invalid number of operands!");
1952     // FIXME: We really want to scale the value here, but the LDRD/STRD
1953     // instruction don't encode operands that way yet.
1954     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1955     Inst.addOperand(MCOperand::createImm(CE->getValue()));
1956   }
1957 
1958   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1959     assert(N == 1 && "Invalid number of operands!");
1960     // The immediate is scaled by four in the encoding and is stored
1961     // in the MCInst as such. Lop off the low two bits here.
1962     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1963     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1964   }
1965 
1966   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1967     assert(N == 1 && "Invalid number of operands!");
1968     // The immediate is scaled by four in the encoding and is stored
1969     // in the MCInst as such. Lop off the low two bits here.
1970     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1971     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
1972   }
1973 
1974   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1975     assert(N == 1 && "Invalid number of operands!");
1976     // The immediate is scaled by four in the encoding and is stored
1977     // in the MCInst as such. Lop off the low two bits here.
1978     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1979     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1980   }
1981 
1982   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1983     assert(N == 1 && "Invalid number of operands!");
1984     // The constant encodes as the immediate-1, and we store in the instruction
1985     // the bits as encoded, so subtract off one here.
1986     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1987     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1988   }
1989 
1990   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1991     assert(N == 1 && "Invalid number of operands!");
1992     // The constant encodes as the immediate-1, and we store in the instruction
1993     // the bits as encoded, so subtract off one here.
1994     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1995     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1996   }
1997 
1998   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1999     assert(N == 1 && "Invalid number of operands!");
2000     // The constant encodes as the immediate, except for 32, which encodes as
2001     // zero.
2002     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2003     unsigned Imm = CE->getValue();
2004     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2005   }
2006 
2007   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2008     assert(N == 1 && "Invalid number of operands!");
2009     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2010     // the instruction as well.
2011     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2012     int Val = CE->getValue();
2013     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2014   }
2015 
2016   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2017     assert(N == 1 && "Invalid number of operands!");
2018     // The operand is actually a t2_so_imm, but we have its bitwise
2019     // negation in the assembly source, so twiddle it here.
2020     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2021     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2022   }
2023 
2024   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2025     assert(N == 1 && "Invalid number of operands!");
2026     // The operand is actually a t2_so_imm, but we have its
2027     // negation in the assembly source, so twiddle it here.
2028     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2029     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2030   }
2031 
2032   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2033     assert(N == 1 && "Invalid number of operands!");
2034     // The operand is actually an imm0_4095, but we have its
2035     // negation in the assembly source, so twiddle it here.
2036     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2037     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2038   }
2039 
2040   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2041     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2042       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2043       return;
2044     }
2045 
2046     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2047     assert(SR && "Unknown value type!");
2048     Inst.addOperand(MCOperand::createExpr(SR));
2049   }
2050 
2051   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2052     assert(N == 1 && "Invalid number of operands!");
2053     if (isImm()) {
2054       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2055       if (CE) {
2056         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2057         return;
2058       }
2059 
2060       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2061 
2062       assert(SR && "Unknown value type!");
2063       Inst.addOperand(MCOperand::createExpr(SR));
2064       return;
2065     }
2066 
2067     assert(isMem()  && "Unknown value type!");
2068     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2069     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2070   }
2071 
2072   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2073     assert(N == 1 && "Invalid number of operands!");
2074     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2075   }
2076 
2077   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2078     assert(N == 1 && "Invalid number of operands!");
2079     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2080   }
2081 
2082   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2083     assert(N == 1 && "Invalid number of operands!");
2084     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2085   }
2086 
2087   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2088     assert(N == 1 && "Invalid number of operands!");
2089     int32_t Imm = Memory.OffsetImm->getValue();
2090     Inst.addOperand(MCOperand::createImm(Imm));
2091   }
2092 
2093   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2094     assert(N == 1 && "Invalid number of operands!");
2095     assert(isImm() && "Not an immediate!");
2096 
2097     // If we have an immediate that's not a constant, treat it as a label
2098     // reference needing a fixup.
2099     if (!isa<MCConstantExpr>(getImm())) {
2100       Inst.addOperand(MCOperand::createExpr(getImm()));
2101       return;
2102     }
2103 
2104     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2105     int Val = CE->getValue();
2106     Inst.addOperand(MCOperand::createImm(Val));
2107   }
2108 
2109   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2110     assert(N == 2 && "Invalid number of operands!");
2111     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2112     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2113   }
2114 
2115   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2116     addAlignedMemoryOperands(Inst, N);
2117   }
2118 
2119   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2120     addAlignedMemoryOperands(Inst, N);
2121   }
2122 
2123   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2124     addAlignedMemoryOperands(Inst, N);
2125   }
2126 
2127   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2128     addAlignedMemoryOperands(Inst, N);
2129   }
2130 
2131   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2132     addAlignedMemoryOperands(Inst, N);
2133   }
2134 
2135   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2136     addAlignedMemoryOperands(Inst, N);
2137   }
2138 
2139   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2140     addAlignedMemoryOperands(Inst, N);
2141   }
2142 
2143   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2144     addAlignedMemoryOperands(Inst, N);
2145   }
2146 
2147   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2148     addAlignedMemoryOperands(Inst, N);
2149   }
2150 
2151   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2152     addAlignedMemoryOperands(Inst, N);
2153   }
2154 
2155   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2156     addAlignedMemoryOperands(Inst, N);
2157   }
2158 
2159   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2160     assert(N == 3 && "Invalid number of operands!");
2161     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2162     if (!Memory.OffsetRegNum) {
2163       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2164       // Special case for #-0
2165       if (Val == INT32_MIN) Val = 0;
2166       if (Val < 0) Val = -Val;
2167       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2168     } else {
2169       // For register offset, we encode the shift type and negation flag
2170       // here.
2171       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2172                               Memory.ShiftImm, Memory.ShiftType);
2173     }
2174     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2175     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2176     Inst.addOperand(MCOperand::createImm(Val));
2177   }
2178 
2179   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2180     assert(N == 2 && "Invalid number of operands!");
2181     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2182     assert(CE && "non-constant AM2OffsetImm operand!");
2183     int32_t Val = CE->getValue();
2184     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2185     // Special case for #-0
2186     if (Val == INT32_MIN) Val = 0;
2187     if (Val < 0) Val = -Val;
2188     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2189     Inst.addOperand(MCOperand::createReg(0));
2190     Inst.addOperand(MCOperand::createImm(Val));
2191   }
2192 
2193   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2194     assert(N == 3 && "Invalid number of operands!");
2195     // If we have an immediate that's not a constant, treat it as a label
2196     // reference needing a fixup. If it is a constant, it's something else
2197     // and we reject it.
2198     if (isImm()) {
2199       Inst.addOperand(MCOperand::createExpr(getImm()));
2200       Inst.addOperand(MCOperand::createReg(0));
2201       Inst.addOperand(MCOperand::createImm(0));
2202       return;
2203     }
2204 
2205     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2206     if (!Memory.OffsetRegNum) {
2207       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2208       // Special case for #-0
2209       if (Val == INT32_MIN) Val = 0;
2210       if (Val < 0) Val = -Val;
2211       Val = ARM_AM::getAM3Opc(AddSub, Val);
2212     } else {
2213       // For register offset, we encode the shift type and negation flag
2214       // here.
2215       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2216     }
2217     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2218     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2219     Inst.addOperand(MCOperand::createImm(Val));
2220   }
2221 
2222   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2223     assert(N == 2 && "Invalid number of operands!");
2224     if (Kind == k_PostIndexRegister) {
2225       int32_t Val =
2226         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2227       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2228       Inst.addOperand(MCOperand::createImm(Val));
2229       return;
2230     }
2231 
2232     // Constant offset.
2233     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2234     int32_t Val = CE->getValue();
2235     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2236     // Special case for #-0
2237     if (Val == INT32_MIN) Val = 0;
2238     if (Val < 0) Val = -Val;
2239     Val = ARM_AM::getAM3Opc(AddSub, Val);
2240     Inst.addOperand(MCOperand::createReg(0));
2241     Inst.addOperand(MCOperand::createImm(Val));
2242   }
2243 
2244   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2245     assert(N == 2 && "Invalid number of operands!");
2246     // If we have an immediate that's not a constant, treat it as a label
2247     // reference needing a fixup. If it is a constant, it's something else
2248     // and we reject it.
2249     if (isImm()) {
2250       Inst.addOperand(MCOperand::createExpr(getImm()));
2251       Inst.addOperand(MCOperand::createImm(0));
2252       return;
2253     }
2254 
2255     // The lower two bits are always zero and as such are not encoded.
2256     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2257     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2258     // Special case for #-0
2259     if (Val == INT32_MIN) Val = 0;
2260     if (Val < 0) Val = -Val;
2261     Val = ARM_AM::getAM5Opc(AddSub, Val);
2262     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2263     Inst.addOperand(MCOperand::createImm(Val));
2264   }
2265 
2266   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2267     assert(N == 2 && "Invalid number of operands!");
2268     // If we have an immediate that's not a constant, treat it as a label
2269     // reference needing a fixup. If it is a constant, it's something else
2270     // and we reject it.
2271     if (isImm()) {
2272       Inst.addOperand(MCOperand::createExpr(getImm()));
2273       Inst.addOperand(MCOperand::createImm(0));
2274       return;
2275     }
2276 
2277     // The lower bit is always zero and as such is not encoded.
2278     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2279     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2280     // Special case for #-0
2281     if (Val == INT32_MIN) Val = 0;
2282     if (Val < 0) Val = -Val;
2283     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2284     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2285     Inst.addOperand(MCOperand::createImm(Val));
2286   }
2287 
2288   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2289     assert(N == 2 && "Invalid number of operands!");
2290     // If we have an immediate that's not a constant, treat it as a label
2291     // reference needing a fixup. If it is a constant, it's something else
2292     // and we reject it.
2293     if (isImm()) {
2294       Inst.addOperand(MCOperand::createExpr(getImm()));
2295       Inst.addOperand(MCOperand::createImm(0));
2296       return;
2297     }
2298 
2299     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2300     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2301     Inst.addOperand(MCOperand::createImm(Val));
2302   }
2303 
2304   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2305     assert(N == 2 && "Invalid number of operands!");
2306     // The lower two bits are always zero and as such are not encoded.
2307     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2308     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2309     Inst.addOperand(MCOperand::createImm(Val));
2310   }
2311 
2312   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2313     assert(N == 2 && "Invalid number of operands!");
2314     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2315     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2316     Inst.addOperand(MCOperand::createImm(Val));
2317   }
2318 
2319   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2320     addMemImm8OffsetOperands(Inst, N);
2321   }
2322 
2323   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2324     addMemImm8OffsetOperands(Inst, N);
2325   }
2326 
2327   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2328     assert(N == 2 && "Invalid number of operands!");
2329     // If this is an immediate, it's a label reference.
2330     if (isImm()) {
2331       addExpr(Inst, getImm());
2332       Inst.addOperand(MCOperand::createImm(0));
2333       return;
2334     }
2335 
2336     // Otherwise, it's a normal memory reg+offset.
2337     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2338     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2339     Inst.addOperand(MCOperand::createImm(Val));
2340   }
2341 
2342   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2343     assert(N == 2 && "Invalid number of operands!");
2344     // If this is an immediate, it's a label reference.
2345     if (isImm()) {
2346       addExpr(Inst, getImm());
2347       Inst.addOperand(MCOperand::createImm(0));
2348       return;
2349     }
2350 
2351     // Otherwise, it's a normal memory reg+offset.
2352     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2353     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2354     Inst.addOperand(MCOperand::createImm(Val));
2355   }
2356 
2357   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2358     assert(N == 1 && "Invalid number of operands!");
2359     // This is container for the immediate that we will create the constant
2360     // pool from
2361     addExpr(Inst, getConstantPoolImm());
2362     return;
2363   }
2364 
2365   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2366     assert(N == 2 && "Invalid number of operands!");
2367     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2368     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2369   }
2370 
2371   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2372     assert(N == 2 && "Invalid number of operands!");
2373     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2374     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2375   }
2376 
2377   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2378     assert(N == 3 && "Invalid number of operands!");
2379     unsigned Val =
2380       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2381                         Memory.ShiftImm, Memory.ShiftType);
2382     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2383     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2384     Inst.addOperand(MCOperand::createImm(Val));
2385   }
2386 
2387   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2388     assert(N == 3 && "Invalid number of operands!");
2389     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2390     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2391     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2392   }
2393 
2394   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2395     assert(N == 2 && "Invalid number of operands!");
2396     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2397     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2398   }
2399 
2400   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2401     assert(N == 2 && "Invalid number of operands!");
2402     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2403     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2404     Inst.addOperand(MCOperand::createImm(Val));
2405   }
2406 
2407   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2408     assert(N == 2 && "Invalid number of operands!");
2409     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2410     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2411     Inst.addOperand(MCOperand::createImm(Val));
2412   }
2413 
2414   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2415     assert(N == 2 && "Invalid number of operands!");
2416     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2417     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2418     Inst.addOperand(MCOperand::createImm(Val));
2419   }
2420 
2421   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2422     assert(N == 2 && "Invalid number of operands!");
2423     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2424     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2425     Inst.addOperand(MCOperand::createImm(Val));
2426   }
2427 
2428   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2429     assert(N == 1 && "Invalid number of operands!");
2430     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2431     assert(CE && "non-constant post-idx-imm8 operand!");
2432     int Imm = CE->getValue();
2433     bool isAdd = Imm >= 0;
2434     if (Imm == INT32_MIN) Imm = 0;
2435     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2436     Inst.addOperand(MCOperand::createImm(Imm));
2437   }
2438 
2439   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2440     assert(N == 1 && "Invalid number of operands!");
2441     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2442     assert(CE && "non-constant post-idx-imm8s4 operand!");
2443     int Imm = CE->getValue();
2444     bool isAdd = Imm >= 0;
2445     if (Imm == INT32_MIN) Imm = 0;
2446     // Immediate is scaled by 4.
2447     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2448     Inst.addOperand(MCOperand::createImm(Imm));
2449   }
2450 
2451   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2452     assert(N == 2 && "Invalid number of operands!");
2453     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2454     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2455   }
2456 
2457   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2458     assert(N == 2 && "Invalid number of operands!");
2459     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2460     // The sign, shift type, and shift amount are encoded in a single operand
2461     // using the AM2 encoding helpers.
2462     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2463     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2464                                      PostIdxReg.ShiftTy);
2465     Inst.addOperand(MCOperand::createImm(Imm));
2466   }
2467 
2468   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2469     assert(N == 1 && "Invalid number of operands!");
2470     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2471   }
2472 
2473   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2474     assert(N == 1 && "Invalid number of operands!");
2475     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2476   }
2477 
2478   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2479     assert(N == 1 && "Invalid number of operands!");
2480     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2481   }
2482 
2483   void addVecListOperands(MCInst &Inst, unsigned N) const {
2484     assert(N == 1 && "Invalid number of operands!");
2485     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2486   }
2487 
2488   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2489     assert(N == 2 && "Invalid number of operands!");
2490     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2491     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2492   }
2493 
2494   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2495     assert(N == 1 && "Invalid number of operands!");
2496     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2497   }
2498 
2499   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2500     assert(N == 1 && "Invalid number of operands!");
2501     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2502   }
2503 
2504   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2505     assert(N == 1 && "Invalid number of operands!");
2506     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2507   }
2508 
2509   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2510     assert(N == 1 && "Invalid number of operands!");
2511     // The immediate encodes the type of constant as well as the value.
2512     // Mask in that this is an i8 splat.
2513     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2514     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2515   }
2516 
2517   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2518     assert(N == 1 && "Invalid number of operands!");
2519     // The immediate encodes the type of constant as well as the value.
2520     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2521     unsigned Value = CE->getValue();
2522     Value = ARM_AM::encodeNEONi16splat(Value);
2523     Inst.addOperand(MCOperand::createImm(Value));
2524   }
2525 
2526   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2527     assert(N == 1 && "Invalid number of operands!");
2528     // The immediate encodes the type of constant as well as the value.
2529     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2530     unsigned Value = CE->getValue();
2531     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2532     Inst.addOperand(MCOperand::createImm(Value));
2533   }
2534 
2535   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2536     assert(N == 1 && "Invalid number of operands!");
2537     // The immediate encodes the type of constant as well as the value.
2538     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2539     unsigned Value = CE->getValue();
2540     Value = ARM_AM::encodeNEONi32splat(Value);
2541     Inst.addOperand(MCOperand::createImm(Value));
2542   }
2543 
2544   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2545     assert(N == 1 && "Invalid number of operands!");
2546     // The immediate encodes the type of constant as well as the value.
2547     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2548     unsigned Value = CE->getValue();
2549     Value = ARM_AM::encodeNEONi32splat(~Value);
2550     Inst.addOperand(MCOperand::createImm(Value));
2551   }
2552 
2553   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2554     assert(N == 1 && "Invalid number of operands!");
2555     // The immediate encodes the type of constant as well as the value.
2556     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2557     unsigned Value = CE->getValue();
2558     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2559             Inst.getOpcode() == ARM::VMOVv16i8) &&
2560            "All vmvn instructions that wants to replicate non-zero byte "
2561            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2562     unsigned B = ((~Value) & 0xff);
2563     B |= 0xe00; // cmode = 0b1110
2564     Inst.addOperand(MCOperand::createImm(B));
2565   }
2566   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2567     assert(N == 1 && "Invalid number of operands!");
2568     // The immediate encodes the type of constant as well as the value.
2569     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2570     unsigned Value = CE->getValue();
2571     if (Value >= 256 && Value <= 0xffff)
2572       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2573     else if (Value > 0xffff && Value <= 0xffffff)
2574       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2575     else if (Value > 0xffffff)
2576       Value = (Value >> 24) | 0x600;
2577     Inst.addOperand(MCOperand::createImm(Value));
2578   }
2579 
2580   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2581     assert(N == 1 && "Invalid number of operands!");
2582     // The immediate encodes the type of constant as well as the value.
2583     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2584     unsigned Value = CE->getValue();
2585     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2586             Inst.getOpcode() == ARM::VMOVv16i8) &&
2587            "All instructions that wants to replicate non-zero byte "
2588            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2589     unsigned B = Value & 0xff;
2590     B |= 0xe00; // cmode = 0b1110
2591     Inst.addOperand(MCOperand::createImm(B));
2592   }
2593   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2594     assert(N == 1 && "Invalid number of operands!");
2595     // The immediate encodes the type of constant as well as the value.
2596     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2597     unsigned Value = ~CE->getValue();
2598     if (Value >= 256 && Value <= 0xffff)
2599       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2600     else if (Value > 0xffff && Value <= 0xffffff)
2601       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2602     else if (Value > 0xffffff)
2603       Value = (Value >> 24) | 0x600;
2604     Inst.addOperand(MCOperand::createImm(Value));
2605   }
2606 
2607   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2608     assert(N == 1 && "Invalid number of operands!");
2609     // The immediate encodes the type of constant as well as the value.
2610     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2611     uint64_t Value = CE->getValue();
2612     unsigned Imm = 0;
2613     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2614       Imm |= (Value & 1) << i;
2615     }
2616     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2617   }
2618 
2619   void print(raw_ostream &OS) const override;
2620 
2621   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2622     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2623     Op->ITMask.Mask = Mask;
2624     Op->StartLoc = S;
2625     Op->EndLoc = S;
2626     return Op;
2627   }
2628 
2629   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2630                                                     SMLoc S) {
2631     auto Op = make_unique<ARMOperand>(k_CondCode);
2632     Op->CC.Val = CC;
2633     Op->StartLoc = S;
2634     Op->EndLoc = S;
2635     return Op;
2636   }
2637 
2638   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2639     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2640     Op->Cop.Val = CopVal;
2641     Op->StartLoc = S;
2642     Op->EndLoc = S;
2643     return Op;
2644   }
2645 
2646   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2647     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2648     Op->Cop.Val = CopVal;
2649     Op->StartLoc = S;
2650     Op->EndLoc = S;
2651     return Op;
2652   }
2653 
2654   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2655                                                         SMLoc E) {
2656     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2657     Op->Cop.Val = Val;
2658     Op->StartLoc = S;
2659     Op->EndLoc = E;
2660     return Op;
2661   }
2662 
2663   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2664     auto Op = make_unique<ARMOperand>(k_CCOut);
2665     Op->Reg.RegNum = RegNum;
2666     Op->StartLoc = S;
2667     Op->EndLoc = S;
2668     return Op;
2669   }
2670 
2671   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2672     auto Op = make_unique<ARMOperand>(k_Token);
2673     Op->Tok.Data = Str.data();
2674     Op->Tok.Length = Str.size();
2675     Op->StartLoc = S;
2676     Op->EndLoc = S;
2677     return Op;
2678   }
2679 
2680   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2681                                                SMLoc E) {
2682     auto Op = make_unique<ARMOperand>(k_Register);
2683     Op->Reg.RegNum = RegNum;
2684     Op->StartLoc = S;
2685     Op->EndLoc = E;
2686     return Op;
2687   }
2688 
2689   static std::unique_ptr<ARMOperand>
2690   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2691                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2692                         SMLoc E) {
2693     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2694     Op->RegShiftedReg.ShiftTy = ShTy;
2695     Op->RegShiftedReg.SrcReg = SrcReg;
2696     Op->RegShiftedReg.ShiftReg = ShiftReg;
2697     Op->RegShiftedReg.ShiftImm = ShiftImm;
2698     Op->StartLoc = S;
2699     Op->EndLoc = E;
2700     return Op;
2701   }
2702 
2703   static std::unique_ptr<ARMOperand>
2704   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2705                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2706     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2707     Op->RegShiftedImm.ShiftTy = ShTy;
2708     Op->RegShiftedImm.SrcReg = SrcReg;
2709     Op->RegShiftedImm.ShiftImm = ShiftImm;
2710     Op->StartLoc = S;
2711     Op->EndLoc = E;
2712     return Op;
2713   }
2714 
2715   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2716                                                       SMLoc S, SMLoc E) {
2717     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2718     Op->ShifterImm.isASR = isASR;
2719     Op->ShifterImm.Imm = Imm;
2720     Op->StartLoc = S;
2721     Op->EndLoc = E;
2722     return Op;
2723   }
2724 
2725   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2726                                                   SMLoc E) {
2727     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2728     Op->RotImm.Imm = Imm;
2729     Op->StartLoc = S;
2730     Op->EndLoc = E;
2731     return Op;
2732   }
2733 
2734   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2735                                                   SMLoc S, SMLoc E) {
2736     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2737     Op->ModImm.Bits = Bits;
2738     Op->ModImm.Rot = Rot;
2739     Op->StartLoc = S;
2740     Op->EndLoc = E;
2741     return Op;
2742   }
2743 
2744   static std::unique_ptr<ARMOperand>
2745   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2746     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
2747     Op->Imm.Val = Val;
2748     Op->StartLoc = S;
2749     Op->EndLoc = E;
2750     return Op;
2751   }
2752 
2753   static std::unique_ptr<ARMOperand>
2754   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2755     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2756     Op->Bitfield.LSB = LSB;
2757     Op->Bitfield.Width = Width;
2758     Op->StartLoc = S;
2759     Op->EndLoc = E;
2760     return Op;
2761   }
2762 
2763   static std::unique_ptr<ARMOperand>
2764   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2765                 SMLoc StartLoc, SMLoc EndLoc) {
2766     assert (Regs.size() > 0 && "RegList contains no registers?");
2767     KindTy Kind = k_RegisterList;
2768 
2769     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2770       Kind = k_DPRRegisterList;
2771     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2772              contains(Regs.front().second))
2773       Kind = k_SPRRegisterList;
2774 
2775     // Sort based on the register encoding values.
2776     array_pod_sort(Regs.begin(), Regs.end());
2777 
2778     auto Op = make_unique<ARMOperand>(Kind);
2779     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2780            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2781       Op->Registers.push_back(I->second);
2782     Op->StartLoc = StartLoc;
2783     Op->EndLoc = EndLoc;
2784     return Op;
2785   }
2786 
2787   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2788                                                       unsigned Count,
2789                                                       bool isDoubleSpaced,
2790                                                       SMLoc S, SMLoc E) {
2791     auto Op = make_unique<ARMOperand>(k_VectorList);
2792     Op->VectorList.RegNum = RegNum;
2793     Op->VectorList.Count = Count;
2794     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2795     Op->StartLoc = S;
2796     Op->EndLoc = E;
2797     return Op;
2798   }
2799 
2800   static std::unique_ptr<ARMOperand>
2801   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2802                            SMLoc S, SMLoc E) {
2803     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2804     Op->VectorList.RegNum = RegNum;
2805     Op->VectorList.Count = Count;
2806     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2807     Op->StartLoc = S;
2808     Op->EndLoc = E;
2809     return Op;
2810   }
2811 
2812   static std::unique_ptr<ARMOperand>
2813   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2814                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2815     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2816     Op->VectorList.RegNum = RegNum;
2817     Op->VectorList.Count = Count;
2818     Op->VectorList.LaneIndex = Index;
2819     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2820     Op->StartLoc = S;
2821     Op->EndLoc = E;
2822     return Op;
2823   }
2824 
2825   static std::unique_ptr<ARMOperand>
2826   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2827     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2828     Op->VectorIndex.Val = Idx;
2829     Op->StartLoc = S;
2830     Op->EndLoc = E;
2831     return Op;
2832   }
2833 
2834   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2835                                                SMLoc E) {
2836     auto Op = make_unique<ARMOperand>(k_Immediate);
2837     Op->Imm.Val = Val;
2838     Op->StartLoc = S;
2839     Op->EndLoc = E;
2840     return Op;
2841   }
2842 
2843   static std::unique_ptr<ARMOperand>
2844   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2845             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2846             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2847             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2848     auto Op = make_unique<ARMOperand>(k_Memory);
2849     Op->Memory.BaseRegNum = BaseRegNum;
2850     Op->Memory.OffsetImm = OffsetImm;
2851     Op->Memory.OffsetRegNum = OffsetRegNum;
2852     Op->Memory.ShiftType = ShiftType;
2853     Op->Memory.ShiftImm = ShiftImm;
2854     Op->Memory.Alignment = Alignment;
2855     Op->Memory.isNegative = isNegative;
2856     Op->StartLoc = S;
2857     Op->EndLoc = E;
2858     Op->AlignmentLoc = AlignmentLoc;
2859     return Op;
2860   }
2861 
2862   static std::unique_ptr<ARMOperand>
2863   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2864                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2865     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2866     Op->PostIdxReg.RegNum = RegNum;
2867     Op->PostIdxReg.isAdd = isAdd;
2868     Op->PostIdxReg.ShiftTy = ShiftTy;
2869     Op->PostIdxReg.ShiftImm = ShiftImm;
2870     Op->StartLoc = S;
2871     Op->EndLoc = E;
2872     return Op;
2873   }
2874 
2875   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2876                                                          SMLoc S) {
2877     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2878     Op->MBOpt.Val = Opt;
2879     Op->StartLoc = S;
2880     Op->EndLoc = S;
2881     return Op;
2882   }
2883 
2884   static std::unique_ptr<ARMOperand>
2885   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2886     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2887     Op->ISBOpt.Val = Opt;
2888     Op->StartLoc = S;
2889     Op->EndLoc = S;
2890     return Op;
2891   }
2892 
2893   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2894                                                       SMLoc S) {
2895     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2896     Op->IFlags.Val = IFlags;
2897     Op->StartLoc = S;
2898     Op->EndLoc = S;
2899     return Op;
2900   }
2901 
2902   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2903     auto Op = make_unique<ARMOperand>(k_MSRMask);
2904     Op->MMask.Val = MMask;
2905     Op->StartLoc = S;
2906     Op->EndLoc = S;
2907     return Op;
2908   }
2909 
2910   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2911     auto Op = make_unique<ARMOperand>(k_BankedReg);
2912     Op->BankedReg.Val = Reg;
2913     Op->StartLoc = S;
2914     Op->EndLoc = S;
2915     return Op;
2916   }
2917 };
2918 
2919 } // end anonymous namespace.
2920 
2921 void ARMOperand::print(raw_ostream &OS) const {
2922   switch (Kind) {
2923   case k_CondCode:
2924     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2925     break;
2926   case k_CCOut:
2927     OS << "<ccout " << getReg() << ">";
2928     break;
2929   case k_ITCondMask: {
2930     static const char *const MaskStr[] = {
2931       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2932       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2933     };
2934     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2935     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2936     break;
2937   }
2938   case k_CoprocNum:
2939     OS << "<coprocessor number: " << getCoproc() << ">";
2940     break;
2941   case k_CoprocReg:
2942     OS << "<coprocessor register: " << getCoproc() << ">";
2943     break;
2944   case k_CoprocOption:
2945     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2946     break;
2947   case k_MSRMask:
2948     OS << "<mask: " << getMSRMask() << ">";
2949     break;
2950   case k_BankedReg:
2951     OS << "<banked reg: " << getBankedReg() << ">";
2952     break;
2953   case k_Immediate:
2954     OS << *getImm();
2955     break;
2956   case k_MemBarrierOpt:
2957     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2958     break;
2959   case k_InstSyncBarrierOpt:
2960     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2961     break;
2962   case k_Memory:
2963     OS << "<memory "
2964        << " base:" << Memory.BaseRegNum;
2965     OS << ">";
2966     break;
2967   case k_PostIndexRegister:
2968     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2969        << PostIdxReg.RegNum;
2970     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2971       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2972          << PostIdxReg.ShiftImm;
2973     OS << ">";
2974     break;
2975   case k_ProcIFlags: {
2976     OS << "<ARM_PROC::";
2977     unsigned IFlags = getProcIFlags();
2978     for (int i=2; i >= 0; --i)
2979       if (IFlags & (1 << i))
2980         OS << ARM_PROC::IFlagsToString(1 << i);
2981     OS << ">";
2982     break;
2983   }
2984   case k_Register:
2985     OS << "<register " << getReg() << ">";
2986     break;
2987   case k_ShifterImmediate:
2988     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2989        << " #" << ShifterImm.Imm << ">";
2990     break;
2991   case k_ShiftedRegister:
2992     OS << "<so_reg_reg "
2993        << RegShiftedReg.SrcReg << " "
2994        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2995        << " " << RegShiftedReg.ShiftReg << ">";
2996     break;
2997   case k_ShiftedImmediate:
2998     OS << "<so_reg_imm "
2999        << RegShiftedImm.SrcReg << " "
3000        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
3001        << " #" << RegShiftedImm.ShiftImm << ">";
3002     break;
3003   case k_RotateImmediate:
3004     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3005     break;
3006   case k_ModifiedImmediate:
3007     OS << "<mod_imm #" << ModImm.Bits << ", #"
3008        <<  ModImm.Rot << ")>";
3009     break;
3010   case k_ConstantPoolImmediate:
3011     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3012     break;
3013   case k_BitfieldDescriptor:
3014     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3015        << ", width: " << Bitfield.Width << ">";
3016     break;
3017   case k_RegisterList:
3018   case k_DPRRegisterList:
3019   case k_SPRRegisterList: {
3020     OS << "<register_list ";
3021 
3022     const SmallVectorImpl<unsigned> &RegList = getRegList();
3023     for (SmallVectorImpl<unsigned>::const_iterator
3024            I = RegList.begin(), E = RegList.end(); I != E; ) {
3025       OS << *I;
3026       if (++I < E) OS << ", ";
3027     }
3028 
3029     OS << ">";
3030     break;
3031   }
3032   case k_VectorList:
3033     OS << "<vector_list " << VectorList.Count << " * "
3034        << VectorList.RegNum << ">";
3035     break;
3036   case k_VectorListAllLanes:
3037     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3038        << VectorList.RegNum << ">";
3039     break;
3040   case k_VectorListIndexed:
3041     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3042        << VectorList.Count << " * " << VectorList.RegNum << ">";
3043     break;
3044   case k_Token:
3045     OS << "'" << getToken() << "'";
3046     break;
3047   case k_VectorIndex:
3048     OS << "<vectorindex " << getVectorIndex() << ">";
3049     break;
3050   }
3051 }
3052 
3053 /// @name Auto-generated Match Functions
3054 /// {
3055 
3056 static unsigned MatchRegisterName(StringRef Name);
3057 
3058 /// }
3059 
3060 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3061                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3062   const AsmToken &Tok = getParser().getTok();
3063   StartLoc = Tok.getLoc();
3064   EndLoc = Tok.getEndLoc();
3065   RegNo = tryParseRegister();
3066 
3067   return (RegNo == (unsigned)-1);
3068 }
3069 
3070 /// Try to parse a register name.  The token must be an Identifier when called,
3071 /// and if it is a register name the token is eaten and the register number is
3072 /// returned.  Otherwise return -1.
3073 ///
3074 int ARMAsmParser::tryParseRegister() {
3075   MCAsmParser &Parser = getParser();
3076   const AsmToken &Tok = Parser.getTok();
3077   if (Tok.isNot(AsmToken::Identifier)) return -1;
3078 
3079   std::string lowerCase = Tok.getString().lower();
3080   unsigned RegNum = MatchRegisterName(lowerCase);
3081   if (!RegNum) {
3082     RegNum = StringSwitch<unsigned>(lowerCase)
3083       .Case("r13", ARM::SP)
3084       .Case("r14", ARM::LR)
3085       .Case("r15", ARM::PC)
3086       .Case("ip", ARM::R12)
3087       // Additional register name aliases for 'gas' compatibility.
3088       .Case("a1", ARM::R0)
3089       .Case("a2", ARM::R1)
3090       .Case("a3", ARM::R2)
3091       .Case("a4", ARM::R3)
3092       .Case("v1", ARM::R4)
3093       .Case("v2", ARM::R5)
3094       .Case("v3", ARM::R6)
3095       .Case("v4", ARM::R7)
3096       .Case("v5", ARM::R8)
3097       .Case("v6", ARM::R9)
3098       .Case("v7", ARM::R10)
3099       .Case("v8", ARM::R11)
3100       .Case("sb", ARM::R9)
3101       .Case("sl", ARM::R10)
3102       .Case("fp", ARM::R11)
3103       .Default(0);
3104   }
3105   if (!RegNum) {
3106     // Check for aliases registered via .req. Canonicalize to lower case.
3107     // That's more consistent since register names are case insensitive, and
3108     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3109     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3110     // If no match, return failure.
3111     if (Entry == RegisterReqs.end())
3112       return -1;
3113     Parser.Lex(); // Eat identifier token.
3114     return Entry->getValue();
3115   }
3116 
3117   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3118   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3119     return -1;
3120 
3121   Parser.Lex(); // Eat identifier token.
3122 
3123   return RegNum;
3124 }
3125 
3126 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3127 // If a recoverable error occurs, return 1. If an irrecoverable error
3128 // occurs, return -1. An irrecoverable error is one where tokens have been
3129 // consumed in the process of trying to parse the shifter (i.e., when it is
3130 // indeed a shifter operand, but malformed).
3131 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3132   MCAsmParser &Parser = getParser();
3133   SMLoc S = Parser.getTok().getLoc();
3134   const AsmToken &Tok = Parser.getTok();
3135   if (Tok.isNot(AsmToken::Identifier))
3136     return -1;
3137 
3138   std::string lowerCase = Tok.getString().lower();
3139   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3140       .Case("asl", ARM_AM::lsl)
3141       .Case("lsl", ARM_AM::lsl)
3142       .Case("lsr", ARM_AM::lsr)
3143       .Case("asr", ARM_AM::asr)
3144       .Case("ror", ARM_AM::ror)
3145       .Case("rrx", ARM_AM::rrx)
3146       .Default(ARM_AM::no_shift);
3147 
3148   if (ShiftTy == ARM_AM::no_shift)
3149     return 1;
3150 
3151   Parser.Lex(); // Eat the operator.
3152 
3153   // The source register for the shift has already been added to the
3154   // operand list, so we need to pop it off and combine it into the shifted
3155   // register operand instead.
3156   std::unique_ptr<ARMOperand> PrevOp(
3157       (ARMOperand *)Operands.pop_back_val().release());
3158   if (!PrevOp->isReg())
3159     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3160   int SrcReg = PrevOp->getReg();
3161 
3162   SMLoc EndLoc;
3163   int64_t Imm = 0;
3164   int ShiftReg = 0;
3165   if (ShiftTy == ARM_AM::rrx) {
3166     // RRX Doesn't have an explicit shift amount. The encoder expects
3167     // the shift register to be the same as the source register. Seems odd,
3168     // but OK.
3169     ShiftReg = SrcReg;
3170   } else {
3171     // Figure out if this is shifted by a constant or a register (for non-RRX).
3172     if (Parser.getTok().is(AsmToken::Hash) ||
3173         Parser.getTok().is(AsmToken::Dollar)) {
3174       Parser.Lex(); // Eat hash.
3175       SMLoc ImmLoc = Parser.getTok().getLoc();
3176       const MCExpr *ShiftExpr = nullptr;
3177       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3178         Error(ImmLoc, "invalid immediate shift value");
3179         return -1;
3180       }
3181       // The expression must be evaluatable as an immediate.
3182       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3183       if (!CE) {
3184         Error(ImmLoc, "invalid immediate shift value");
3185         return -1;
3186       }
3187       // Range check the immediate.
3188       // lsl, ror: 0 <= imm <= 31
3189       // lsr, asr: 0 <= imm <= 32
3190       Imm = CE->getValue();
3191       if (Imm < 0 ||
3192           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3193           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3194         Error(ImmLoc, "immediate shift value out of range");
3195         return -1;
3196       }
3197       // shift by zero is a nop. Always send it through as lsl.
3198       // ('as' compatibility)
3199       if (Imm == 0)
3200         ShiftTy = ARM_AM::lsl;
3201     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3202       SMLoc L = Parser.getTok().getLoc();
3203       EndLoc = Parser.getTok().getEndLoc();
3204       ShiftReg = tryParseRegister();
3205       if (ShiftReg == -1) {
3206         Error(L, "expected immediate or register in shift operand");
3207         return -1;
3208       }
3209     } else {
3210       Error(Parser.getTok().getLoc(),
3211             "expected immediate or register in shift operand");
3212       return -1;
3213     }
3214   }
3215 
3216   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3217     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3218                                                          ShiftReg, Imm,
3219                                                          S, EndLoc));
3220   else
3221     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3222                                                           S, EndLoc));
3223 
3224   return 0;
3225 }
3226 
3227 
3228 /// Try to parse a register name.  The token must be an Identifier when called.
3229 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3230 /// if there is a "writeback". 'true' if it's not a register.
3231 ///
3232 /// TODO this is likely to change to allow different register types and or to
3233 /// parse for a specific register type.
3234 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3235   MCAsmParser &Parser = getParser();
3236   const AsmToken &RegTok = Parser.getTok();
3237   int RegNo = tryParseRegister();
3238   if (RegNo == -1)
3239     return true;
3240 
3241   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3242                                            RegTok.getEndLoc()));
3243 
3244   const AsmToken &ExclaimTok = Parser.getTok();
3245   if (ExclaimTok.is(AsmToken::Exclaim)) {
3246     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3247                                                ExclaimTok.getLoc()));
3248     Parser.Lex(); // Eat exclaim token
3249     return false;
3250   }
3251 
3252   // Also check for an index operand. This is only legal for vector registers,
3253   // but that'll get caught OK in operand matching, so we don't need to
3254   // explicitly filter everything else out here.
3255   if (Parser.getTok().is(AsmToken::LBrac)) {
3256     SMLoc SIdx = Parser.getTok().getLoc();
3257     Parser.Lex(); // Eat left bracket token.
3258 
3259     const MCExpr *ImmVal;
3260     if (getParser().parseExpression(ImmVal))
3261       return true;
3262     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3263     if (!MCE)
3264       return TokError("immediate value expected for vector index");
3265 
3266     if (Parser.getTok().isNot(AsmToken::RBrac))
3267       return Error(Parser.getTok().getLoc(), "']' expected");
3268 
3269     SMLoc E = Parser.getTok().getEndLoc();
3270     Parser.Lex(); // Eat right bracket token.
3271 
3272     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3273                                                      SIdx, E,
3274                                                      getContext()));
3275   }
3276 
3277   return false;
3278 }
3279 
3280 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3281 /// instruction with a symbolic operand name.
3282 /// We accept "crN" syntax for GAS compatibility.
3283 /// <operand-name> ::= <prefix><number>
3284 /// If CoprocOp is 'c', then:
3285 ///   <prefix> ::= c | cr
3286 /// If CoprocOp is 'p', then :
3287 ///   <prefix> ::= p
3288 /// <number> ::= integer in range [0, 15]
3289 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3290   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3291   // but efficient.
3292   if (Name.size() < 2 || Name[0] != CoprocOp)
3293     return -1;
3294   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3295 
3296   switch (Name.size()) {
3297   default: return -1;
3298   case 1:
3299     switch (Name[0]) {
3300     default:  return -1;
3301     case '0': return 0;
3302     case '1': return 1;
3303     case '2': return 2;
3304     case '3': return 3;
3305     case '4': return 4;
3306     case '5': return 5;
3307     case '6': return 6;
3308     case '7': return 7;
3309     case '8': return 8;
3310     case '9': return 9;
3311     }
3312   case 2:
3313     if (Name[0] != '1')
3314       return -1;
3315     switch (Name[1]) {
3316     default:  return -1;
3317     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3318     // However, old cores (v5/v6) did use them in that way.
3319     case '0': return 10;
3320     case '1': return 11;
3321     case '2': return 12;
3322     case '3': return 13;
3323     case '4': return 14;
3324     case '5': return 15;
3325     }
3326   }
3327 }
3328 
3329 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3330 OperandMatchResultTy
3331 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3332   MCAsmParser &Parser = getParser();
3333   SMLoc S = Parser.getTok().getLoc();
3334   const AsmToken &Tok = Parser.getTok();
3335   if (!Tok.is(AsmToken::Identifier))
3336     return MatchOperand_NoMatch;
3337   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3338     .Case("eq", ARMCC::EQ)
3339     .Case("ne", ARMCC::NE)
3340     .Case("hs", ARMCC::HS)
3341     .Case("cs", ARMCC::HS)
3342     .Case("lo", ARMCC::LO)
3343     .Case("cc", ARMCC::LO)
3344     .Case("mi", ARMCC::MI)
3345     .Case("pl", ARMCC::PL)
3346     .Case("vs", ARMCC::VS)
3347     .Case("vc", ARMCC::VC)
3348     .Case("hi", ARMCC::HI)
3349     .Case("ls", ARMCC::LS)
3350     .Case("ge", ARMCC::GE)
3351     .Case("lt", ARMCC::LT)
3352     .Case("gt", ARMCC::GT)
3353     .Case("le", ARMCC::LE)
3354     .Case("al", ARMCC::AL)
3355     .Default(~0U);
3356   if (CC == ~0U)
3357     return MatchOperand_NoMatch;
3358   Parser.Lex(); // Eat the token.
3359 
3360   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3361 
3362   return MatchOperand_Success;
3363 }
3364 
3365 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3366 /// token must be an Identifier when called, and if it is a coprocessor
3367 /// number, the token is eaten and the operand is added to the operand list.
3368 OperandMatchResultTy
3369 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3370   MCAsmParser &Parser = getParser();
3371   SMLoc S = Parser.getTok().getLoc();
3372   const AsmToken &Tok = Parser.getTok();
3373   if (Tok.isNot(AsmToken::Identifier))
3374     return MatchOperand_NoMatch;
3375 
3376   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3377   if (Num == -1)
3378     return MatchOperand_NoMatch;
3379   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3380   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3381     return MatchOperand_NoMatch;
3382 
3383   Parser.Lex(); // Eat identifier token.
3384   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3385   return MatchOperand_Success;
3386 }
3387 
3388 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3389 /// token must be an Identifier when called, and if it is a coprocessor
3390 /// number, the token is eaten and the operand is added to the operand list.
3391 OperandMatchResultTy
3392 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3393   MCAsmParser &Parser = getParser();
3394   SMLoc S = Parser.getTok().getLoc();
3395   const AsmToken &Tok = Parser.getTok();
3396   if (Tok.isNot(AsmToken::Identifier))
3397     return MatchOperand_NoMatch;
3398 
3399   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3400   if (Reg == -1)
3401     return MatchOperand_NoMatch;
3402 
3403   Parser.Lex(); // Eat identifier token.
3404   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3405   return MatchOperand_Success;
3406 }
3407 
3408 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3409 /// coproc_option : '{' imm0_255 '}'
3410 OperandMatchResultTy
3411 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3412   MCAsmParser &Parser = getParser();
3413   SMLoc S = Parser.getTok().getLoc();
3414 
3415   // If this isn't a '{', this isn't a coprocessor immediate operand.
3416   if (Parser.getTok().isNot(AsmToken::LCurly))
3417     return MatchOperand_NoMatch;
3418   Parser.Lex(); // Eat the '{'
3419 
3420   const MCExpr *Expr;
3421   SMLoc Loc = Parser.getTok().getLoc();
3422   if (getParser().parseExpression(Expr)) {
3423     Error(Loc, "illegal expression");
3424     return MatchOperand_ParseFail;
3425   }
3426   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3427   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3428     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3429     return MatchOperand_ParseFail;
3430   }
3431   int Val = CE->getValue();
3432 
3433   // Check for and consume the closing '}'
3434   if (Parser.getTok().isNot(AsmToken::RCurly))
3435     return MatchOperand_ParseFail;
3436   SMLoc E = Parser.getTok().getEndLoc();
3437   Parser.Lex(); // Eat the '}'
3438 
3439   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3440   return MatchOperand_Success;
3441 }
3442 
3443 // For register list parsing, we need to map from raw GPR register numbering
3444 // to the enumeration values. The enumeration values aren't sorted by
3445 // register number due to our using "sp", "lr" and "pc" as canonical names.
3446 static unsigned getNextRegister(unsigned Reg) {
3447   // If this is a GPR, we need to do it manually, otherwise we can rely
3448   // on the sort ordering of the enumeration since the other reg-classes
3449   // are sane.
3450   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3451     return Reg + 1;
3452   switch(Reg) {
3453   default: llvm_unreachable("Invalid GPR number!");
3454   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3455   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3456   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3457   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3458   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3459   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3460   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3461   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3462   }
3463 }
3464 
3465 // Return the low-subreg of a given Q register.
3466 static unsigned getDRegFromQReg(unsigned QReg) {
3467   switch (QReg) {
3468   default: llvm_unreachable("expected a Q register!");
3469   case ARM::Q0:  return ARM::D0;
3470   case ARM::Q1:  return ARM::D2;
3471   case ARM::Q2:  return ARM::D4;
3472   case ARM::Q3:  return ARM::D6;
3473   case ARM::Q4:  return ARM::D8;
3474   case ARM::Q5:  return ARM::D10;
3475   case ARM::Q6:  return ARM::D12;
3476   case ARM::Q7:  return ARM::D14;
3477   case ARM::Q8:  return ARM::D16;
3478   case ARM::Q9:  return ARM::D18;
3479   case ARM::Q10: return ARM::D20;
3480   case ARM::Q11: return ARM::D22;
3481   case ARM::Q12: return ARM::D24;
3482   case ARM::Q13: return ARM::D26;
3483   case ARM::Q14: return ARM::D28;
3484   case ARM::Q15: return ARM::D30;
3485   }
3486 }
3487 
3488 /// Parse a register list.
3489 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3490   MCAsmParser &Parser = getParser();
3491   if (Parser.getTok().isNot(AsmToken::LCurly))
3492     return TokError("Token is not a Left Curly Brace");
3493   SMLoc S = Parser.getTok().getLoc();
3494   Parser.Lex(); // Eat '{' token.
3495   SMLoc RegLoc = Parser.getTok().getLoc();
3496 
3497   // Check the first register in the list to see what register class
3498   // this is a list of.
3499   int Reg = tryParseRegister();
3500   if (Reg == -1)
3501     return Error(RegLoc, "register expected");
3502 
3503   // The reglist instructions have at most 16 registers, so reserve
3504   // space for that many.
3505   int EReg = 0;
3506   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3507 
3508   // Allow Q regs and just interpret them as the two D sub-registers.
3509   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3510     Reg = getDRegFromQReg(Reg);
3511     EReg = MRI->getEncodingValue(Reg);
3512     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3513     ++Reg;
3514   }
3515   const MCRegisterClass *RC;
3516   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3517     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3518   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3519     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3520   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3521     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3522   else
3523     return Error(RegLoc, "invalid register in register list");
3524 
3525   // Store the register.
3526   EReg = MRI->getEncodingValue(Reg);
3527   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3528 
3529   // This starts immediately after the first register token in the list,
3530   // so we can see either a comma or a minus (range separator) as a legal
3531   // next token.
3532   while (Parser.getTok().is(AsmToken::Comma) ||
3533          Parser.getTok().is(AsmToken::Minus)) {
3534     if (Parser.getTok().is(AsmToken::Minus)) {
3535       Parser.Lex(); // Eat the minus.
3536       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3537       int EndReg = tryParseRegister();
3538       if (EndReg == -1)
3539         return Error(AfterMinusLoc, "register expected");
3540       // Allow Q regs and just interpret them as the two D sub-registers.
3541       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3542         EndReg = getDRegFromQReg(EndReg) + 1;
3543       // If the register is the same as the start reg, there's nothing
3544       // more to do.
3545       if (Reg == EndReg)
3546         continue;
3547       // The register must be in the same register class as the first.
3548       if (!RC->contains(EndReg))
3549         return Error(AfterMinusLoc, "invalid register in register list");
3550       // Ranges must go from low to high.
3551       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3552         return Error(AfterMinusLoc, "bad range in register list");
3553 
3554       // Add all the registers in the range to the register list.
3555       while (Reg != EndReg) {
3556         Reg = getNextRegister(Reg);
3557         EReg = MRI->getEncodingValue(Reg);
3558         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3559       }
3560       continue;
3561     }
3562     Parser.Lex(); // Eat the comma.
3563     RegLoc = Parser.getTok().getLoc();
3564     int OldReg = Reg;
3565     const AsmToken RegTok = Parser.getTok();
3566     Reg = tryParseRegister();
3567     if (Reg == -1)
3568       return Error(RegLoc, "register expected");
3569     // Allow Q regs and just interpret them as the two D sub-registers.
3570     bool isQReg = false;
3571     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3572       Reg = getDRegFromQReg(Reg);
3573       isQReg = true;
3574     }
3575     // The register must be in the same register class as the first.
3576     if (!RC->contains(Reg))
3577       return Error(RegLoc, "invalid register in register list");
3578     // List must be monotonically increasing.
3579     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3580       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3581         Warning(RegLoc, "register list not in ascending order");
3582       else
3583         return Error(RegLoc, "register list not in ascending order");
3584     }
3585     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3586       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3587               ") in register list");
3588       continue;
3589     }
3590     // VFP register lists must also be contiguous.
3591     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3592         Reg != OldReg + 1)
3593       return Error(RegLoc, "non-contiguous register range");
3594     EReg = MRI->getEncodingValue(Reg);
3595     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3596     if (isQReg) {
3597       EReg = MRI->getEncodingValue(++Reg);
3598       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3599     }
3600   }
3601 
3602   if (Parser.getTok().isNot(AsmToken::RCurly))
3603     return Error(Parser.getTok().getLoc(), "'}' expected");
3604   SMLoc E = Parser.getTok().getEndLoc();
3605   Parser.Lex(); // Eat '}' token.
3606 
3607   // Push the register list operand.
3608   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3609 
3610   // The ARM system instruction variants for LDM/STM have a '^' token here.
3611   if (Parser.getTok().is(AsmToken::Caret)) {
3612     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3613     Parser.Lex(); // Eat '^' token.
3614   }
3615 
3616   return false;
3617 }
3618 
3619 // Helper function to parse the lane index for vector lists.
3620 OperandMatchResultTy ARMAsmParser::
3621 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3622   MCAsmParser &Parser = getParser();
3623   Index = 0; // Always return a defined index value.
3624   if (Parser.getTok().is(AsmToken::LBrac)) {
3625     Parser.Lex(); // Eat the '['.
3626     if (Parser.getTok().is(AsmToken::RBrac)) {
3627       // "Dn[]" is the 'all lanes' syntax.
3628       LaneKind = AllLanes;
3629       EndLoc = Parser.getTok().getEndLoc();
3630       Parser.Lex(); // Eat the ']'.
3631       return MatchOperand_Success;
3632     }
3633 
3634     // There's an optional '#' token here. Normally there wouldn't be, but
3635     // inline assemble puts one in, and it's friendly to accept that.
3636     if (Parser.getTok().is(AsmToken::Hash))
3637       Parser.Lex(); // Eat '#' or '$'.
3638 
3639     const MCExpr *LaneIndex;
3640     SMLoc Loc = Parser.getTok().getLoc();
3641     if (getParser().parseExpression(LaneIndex)) {
3642       Error(Loc, "illegal expression");
3643       return MatchOperand_ParseFail;
3644     }
3645     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3646     if (!CE) {
3647       Error(Loc, "lane index must be empty or an integer");
3648       return MatchOperand_ParseFail;
3649     }
3650     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3651       Error(Parser.getTok().getLoc(), "']' expected");
3652       return MatchOperand_ParseFail;
3653     }
3654     EndLoc = Parser.getTok().getEndLoc();
3655     Parser.Lex(); // Eat the ']'.
3656     int64_t Val = CE->getValue();
3657 
3658     // FIXME: Make this range check context sensitive for .8, .16, .32.
3659     if (Val < 0 || Val > 7) {
3660       Error(Parser.getTok().getLoc(), "lane index out of range");
3661       return MatchOperand_ParseFail;
3662     }
3663     Index = Val;
3664     LaneKind = IndexedLane;
3665     return MatchOperand_Success;
3666   }
3667   LaneKind = NoLanes;
3668   return MatchOperand_Success;
3669 }
3670 
3671 // parse a vector register list
3672 OperandMatchResultTy
3673 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3674   MCAsmParser &Parser = getParser();
3675   VectorLaneTy LaneKind;
3676   unsigned LaneIndex;
3677   SMLoc S = Parser.getTok().getLoc();
3678   // As an extension (to match gas), support a plain D register or Q register
3679   // (without encosing curly braces) as a single or double entry list,
3680   // respectively.
3681   if (Parser.getTok().is(AsmToken::Identifier)) {
3682     SMLoc E = Parser.getTok().getEndLoc();
3683     int Reg = tryParseRegister();
3684     if (Reg == -1)
3685       return MatchOperand_NoMatch;
3686     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3687       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3688       if (Res != MatchOperand_Success)
3689         return Res;
3690       switch (LaneKind) {
3691       case NoLanes:
3692         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3693         break;
3694       case AllLanes:
3695         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3696                                                                 S, E));
3697         break;
3698       case IndexedLane:
3699         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3700                                                                LaneIndex,
3701                                                                false, S, E));
3702         break;
3703       }
3704       return MatchOperand_Success;
3705     }
3706     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3707       Reg = getDRegFromQReg(Reg);
3708       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3709       if (Res != MatchOperand_Success)
3710         return Res;
3711       switch (LaneKind) {
3712       case NoLanes:
3713         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3714                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3715         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3716         break;
3717       case AllLanes:
3718         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3719                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3720         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3721                                                                 S, E));
3722         break;
3723       case IndexedLane:
3724         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3725                                                                LaneIndex,
3726                                                                false, S, E));
3727         break;
3728       }
3729       return MatchOperand_Success;
3730     }
3731     Error(S, "vector register expected");
3732     return MatchOperand_ParseFail;
3733   }
3734 
3735   if (Parser.getTok().isNot(AsmToken::LCurly))
3736     return MatchOperand_NoMatch;
3737 
3738   Parser.Lex(); // Eat '{' token.
3739   SMLoc RegLoc = Parser.getTok().getLoc();
3740 
3741   int Reg = tryParseRegister();
3742   if (Reg == -1) {
3743     Error(RegLoc, "register expected");
3744     return MatchOperand_ParseFail;
3745   }
3746   unsigned Count = 1;
3747   int Spacing = 0;
3748   unsigned FirstReg = Reg;
3749   // The list is of D registers, but we also allow Q regs and just interpret
3750   // them as the two D sub-registers.
3751   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3752     FirstReg = Reg = getDRegFromQReg(Reg);
3753     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3754                  // it's ambiguous with four-register single spaced.
3755     ++Reg;
3756     ++Count;
3757   }
3758 
3759   SMLoc E;
3760   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3761     return MatchOperand_ParseFail;
3762 
3763   while (Parser.getTok().is(AsmToken::Comma) ||
3764          Parser.getTok().is(AsmToken::Minus)) {
3765     if (Parser.getTok().is(AsmToken::Minus)) {
3766       if (!Spacing)
3767         Spacing = 1; // Register range implies a single spaced list.
3768       else if (Spacing == 2) {
3769         Error(Parser.getTok().getLoc(),
3770               "sequential registers in double spaced list");
3771         return MatchOperand_ParseFail;
3772       }
3773       Parser.Lex(); // Eat the minus.
3774       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3775       int EndReg = tryParseRegister();
3776       if (EndReg == -1) {
3777         Error(AfterMinusLoc, "register expected");
3778         return MatchOperand_ParseFail;
3779       }
3780       // Allow Q regs and just interpret them as the two D sub-registers.
3781       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3782         EndReg = getDRegFromQReg(EndReg) + 1;
3783       // If the register is the same as the start reg, there's nothing
3784       // more to do.
3785       if (Reg == EndReg)
3786         continue;
3787       // The register must be in the same register class as the first.
3788       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3789         Error(AfterMinusLoc, "invalid register in register list");
3790         return MatchOperand_ParseFail;
3791       }
3792       // Ranges must go from low to high.
3793       if (Reg > EndReg) {
3794         Error(AfterMinusLoc, "bad range in register list");
3795         return MatchOperand_ParseFail;
3796       }
3797       // Parse the lane specifier if present.
3798       VectorLaneTy NextLaneKind;
3799       unsigned NextLaneIndex;
3800       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3801           MatchOperand_Success)
3802         return MatchOperand_ParseFail;
3803       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3804         Error(AfterMinusLoc, "mismatched lane index in register list");
3805         return MatchOperand_ParseFail;
3806       }
3807 
3808       // Add all the registers in the range to the register list.
3809       Count += EndReg - Reg;
3810       Reg = EndReg;
3811       continue;
3812     }
3813     Parser.Lex(); // Eat the comma.
3814     RegLoc = Parser.getTok().getLoc();
3815     int OldReg = Reg;
3816     Reg = tryParseRegister();
3817     if (Reg == -1) {
3818       Error(RegLoc, "register expected");
3819       return MatchOperand_ParseFail;
3820     }
3821     // vector register lists must be contiguous.
3822     // It's OK to use the enumeration values directly here rather, as the
3823     // VFP register classes have the enum sorted properly.
3824     //
3825     // The list is of D registers, but we also allow Q regs and just interpret
3826     // them as the two D sub-registers.
3827     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3828       if (!Spacing)
3829         Spacing = 1; // Register range implies a single spaced list.
3830       else if (Spacing == 2) {
3831         Error(RegLoc,
3832               "invalid register in double-spaced list (must be 'D' register')");
3833         return MatchOperand_ParseFail;
3834       }
3835       Reg = getDRegFromQReg(Reg);
3836       if (Reg != OldReg + 1) {
3837         Error(RegLoc, "non-contiguous register range");
3838         return MatchOperand_ParseFail;
3839       }
3840       ++Reg;
3841       Count += 2;
3842       // Parse the lane specifier if present.
3843       VectorLaneTy NextLaneKind;
3844       unsigned NextLaneIndex;
3845       SMLoc LaneLoc = Parser.getTok().getLoc();
3846       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3847           MatchOperand_Success)
3848         return MatchOperand_ParseFail;
3849       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3850         Error(LaneLoc, "mismatched lane index in register list");
3851         return MatchOperand_ParseFail;
3852       }
3853       continue;
3854     }
3855     // Normal D register.
3856     // Figure out the register spacing (single or double) of the list if
3857     // we don't know it already.
3858     if (!Spacing)
3859       Spacing = 1 + (Reg == OldReg + 2);
3860 
3861     // Just check that it's contiguous and keep going.
3862     if (Reg != OldReg + Spacing) {
3863       Error(RegLoc, "non-contiguous register range");
3864       return MatchOperand_ParseFail;
3865     }
3866     ++Count;
3867     // Parse the lane specifier if present.
3868     VectorLaneTy NextLaneKind;
3869     unsigned NextLaneIndex;
3870     SMLoc EndLoc = Parser.getTok().getLoc();
3871     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3872       return MatchOperand_ParseFail;
3873     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3874       Error(EndLoc, "mismatched lane index in register list");
3875       return MatchOperand_ParseFail;
3876     }
3877   }
3878 
3879   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3880     Error(Parser.getTok().getLoc(), "'}' expected");
3881     return MatchOperand_ParseFail;
3882   }
3883   E = Parser.getTok().getEndLoc();
3884   Parser.Lex(); // Eat '}' token.
3885 
3886   switch (LaneKind) {
3887   case NoLanes:
3888     // Two-register operands have been converted to the
3889     // composite register classes.
3890     if (Count == 2) {
3891       const MCRegisterClass *RC = (Spacing == 1) ?
3892         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3893         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3894       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3895     }
3896 
3897     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3898                                                     (Spacing == 2), S, E));
3899     break;
3900   case AllLanes:
3901     // Two-register operands have been converted to the
3902     // composite register classes.
3903     if (Count == 2) {
3904       const MCRegisterClass *RC = (Spacing == 1) ?
3905         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3906         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3907       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3908     }
3909     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3910                                                             (Spacing == 2),
3911                                                             S, E));
3912     break;
3913   case IndexedLane:
3914     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3915                                                            LaneIndex,
3916                                                            (Spacing == 2),
3917                                                            S, E));
3918     break;
3919   }
3920   return MatchOperand_Success;
3921 }
3922 
3923 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3924 OperandMatchResultTy
3925 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3926   MCAsmParser &Parser = getParser();
3927   SMLoc S = Parser.getTok().getLoc();
3928   const AsmToken &Tok = Parser.getTok();
3929   unsigned Opt;
3930 
3931   if (Tok.is(AsmToken::Identifier)) {
3932     StringRef OptStr = Tok.getString();
3933 
3934     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3935       .Case("sy",    ARM_MB::SY)
3936       .Case("st",    ARM_MB::ST)
3937       .Case("ld",    ARM_MB::LD)
3938       .Case("sh",    ARM_MB::ISH)
3939       .Case("ish",   ARM_MB::ISH)
3940       .Case("shst",  ARM_MB::ISHST)
3941       .Case("ishst", ARM_MB::ISHST)
3942       .Case("ishld", ARM_MB::ISHLD)
3943       .Case("nsh",   ARM_MB::NSH)
3944       .Case("un",    ARM_MB::NSH)
3945       .Case("nshst", ARM_MB::NSHST)
3946       .Case("nshld", ARM_MB::NSHLD)
3947       .Case("unst",  ARM_MB::NSHST)
3948       .Case("osh",   ARM_MB::OSH)
3949       .Case("oshst", ARM_MB::OSHST)
3950       .Case("oshld", ARM_MB::OSHLD)
3951       .Default(~0U);
3952 
3953     // ishld, oshld, nshld and ld are only available from ARMv8.
3954     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3955                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3956       Opt = ~0U;
3957 
3958     if (Opt == ~0U)
3959       return MatchOperand_NoMatch;
3960 
3961     Parser.Lex(); // Eat identifier token.
3962   } else if (Tok.is(AsmToken::Hash) ||
3963              Tok.is(AsmToken::Dollar) ||
3964              Tok.is(AsmToken::Integer)) {
3965     if (Parser.getTok().isNot(AsmToken::Integer))
3966       Parser.Lex(); // Eat '#' or '$'.
3967     SMLoc Loc = Parser.getTok().getLoc();
3968 
3969     const MCExpr *MemBarrierID;
3970     if (getParser().parseExpression(MemBarrierID)) {
3971       Error(Loc, "illegal expression");
3972       return MatchOperand_ParseFail;
3973     }
3974 
3975     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3976     if (!CE) {
3977       Error(Loc, "constant expression expected");
3978       return MatchOperand_ParseFail;
3979     }
3980 
3981     int Val = CE->getValue();
3982     if (Val & ~0xf) {
3983       Error(Loc, "immediate value out of range");
3984       return MatchOperand_ParseFail;
3985     }
3986 
3987     Opt = ARM_MB::RESERVED_0 + Val;
3988   } else
3989     return MatchOperand_ParseFail;
3990 
3991   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3992   return MatchOperand_Success;
3993 }
3994 
3995 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3996 OperandMatchResultTy
3997 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3998   MCAsmParser &Parser = getParser();
3999   SMLoc S = Parser.getTok().getLoc();
4000   const AsmToken &Tok = Parser.getTok();
4001   unsigned Opt;
4002 
4003   if (Tok.is(AsmToken::Identifier)) {
4004     StringRef OptStr = Tok.getString();
4005 
4006     if (OptStr.equals_lower("sy"))
4007       Opt = ARM_ISB::SY;
4008     else
4009       return MatchOperand_NoMatch;
4010 
4011     Parser.Lex(); // Eat identifier token.
4012   } else if (Tok.is(AsmToken::Hash) ||
4013              Tok.is(AsmToken::Dollar) ||
4014              Tok.is(AsmToken::Integer)) {
4015     if (Parser.getTok().isNot(AsmToken::Integer))
4016       Parser.Lex(); // Eat '#' or '$'.
4017     SMLoc Loc = Parser.getTok().getLoc();
4018 
4019     const MCExpr *ISBarrierID;
4020     if (getParser().parseExpression(ISBarrierID)) {
4021       Error(Loc, "illegal expression");
4022       return MatchOperand_ParseFail;
4023     }
4024 
4025     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4026     if (!CE) {
4027       Error(Loc, "constant expression expected");
4028       return MatchOperand_ParseFail;
4029     }
4030 
4031     int Val = CE->getValue();
4032     if (Val & ~0xf) {
4033       Error(Loc, "immediate value out of range");
4034       return MatchOperand_ParseFail;
4035     }
4036 
4037     Opt = ARM_ISB::RESERVED_0 + Val;
4038   } else
4039     return MatchOperand_ParseFail;
4040 
4041   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4042           (ARM_ISB::InstSyncBOpt)Opt, S));
4043   return MatchOperand_Success;
4044 }
4045 
4046 
4047 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4048 OperandMatchResultTy
4049 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4050   MCAsmParser &Parser = getParser();
4051   SMLoc S = Parser.getTok().getLoc();
4052   const AsmToken &Tok = Parser.getTok();
4053   if (!Tok.is(AsmToken::Identifier))
4054     return MatchOperand_NoMatch;
4055   StringRef IFlagsStr = Tok.getString();
4056 
4057   // An iflags string of "none" is interpreted to mean that none of the AIF
4058   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4059   unsigned IFlags = 0;
4060   if (IFlagsStr != "none") {
4061         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4062       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
4063         .Case("a", ARM_PROC::A)
4064         .Case("i", ARM_PROC::I)
4065         .Case("f", ARM_PROC::F)
4066         .Default(~0U);
4067 
4068       // If some specific iflag is already set, it means that some letter is
4069       // present more than once, this is not acceptable.
4070       if (Flag == ~0U || (IFlags & Flag))
4071         return MatchOperand_NoMatch;
4072 
4073       IFlags |= Flag;
4074     }
4075   }
4076 
4077   Parser.Lex(); // Eat identifier token.
4078   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4079   return MatchOperand_Success;
4080 }
4081 
4082 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4083 OperandMatchResultTy
4084 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4085   MCAsmParser &Parser = getParser();
4086   SMLoc S = Parser.getTok().getLoc();
4087   const AsmToken &Tok = Parser.getTok();
4088   if (!Tok.is(AsmToken::Identifier))
4089     return MatchOperand_NoMatch;
4090   StringRef Mask = Tok.getString();
4091 
4092   if (isMClass()) {
4093     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4094     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4095       return MatchOperand_NoMatch;
4096 
4097     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4098 
4099     Parser.Lex(); // Eat identifier token.
4100     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4101     return MatchOperand_Success;
4102   }
4103 
4104   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4105   size_t Start = 0, Next = Mask.find('_');
4106   StringRef Flags = "";
4107   std::string SpecReg = Mask.slice(Start, Next).lower();
4108   if (Next != StringRef::npos)
4109     Flags = Mask.slice(Next+1, Mask.size());
4110 
4111   // FlagsVal contains the complete mask:
4112   // 3-0: Mask
4113   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4114   unsigned FlagsVal = 0;
4115 
4116   if (SpecReg == "apsr") {
4117     FlagsVal = StringSwitch<unsigned>(Flags)
4118     .Case("nzcvq",  0x8) // same as CPSR_f
4119     .Case("g",      0x4) // same as CPSR_s
4120     .Case("nzcvqg", 0xc) // same as CPSR_fs
4121     .Default(~0U);
4122 
4123     if (FlagsVal == ~0U) {
4124       if (!Flags.empty())
4125         return MatchOperand_NoMatch;
4126       else
4127         FlagsVal = 8; // No flag
4128     }
4129   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4130     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4131     if (Flags == "all" || Flags == "")
4132       Flags = "fc";
4133     for (int i = 0, e = Flags.size(); i != e; ++i) {
4134       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4135       .Case("c", 1)
4136       .Case("x", 2)
4137       .Case("s", 4)
4138       .Case("f", 8)
4139       .Default(~0U);
4140 
4141       // If some specific flag is already set, it means that some letter is
4142       // present more than once, this is not acceptable.
4143       if (Flag == ~0U || (FlagsVal & Flag))
4144         return MatchOperand_NoMatch;
4145       FlagsVal |= Flag;
4146     }
4147   } else // No match for special register.
4148     return MatchOperand_NoMatch;
4149 
4150   // Special register without flags is NOT equivalent to "fc" flags.
4151   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4152   // two lines would enable gas compatibility at the expense of breaking
4153   // round-tripping.
4154   //
4155   // if (!FlagsVal)
4156   //  FlagsVal = 0x9;
4157 
4158   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4159   if (SpecReg == "spsr")
4160     FlagsVal |= 16;
4161 
4162   Parser.Lex(); // Eat identifier token.
4163   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4164   return MatchOperand_Success;
4165 }
4166 
4167 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4168 /// use in the MRS/MSR instructions added to support virtualization.
4169 OperandMatchResultTy
4170 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4171   MCAsmParser &Parser = getParser();
4172   SMLoc S = Parser.getTok().getLoc();
4173   const AsmToken &Tok = Parser.getTok();
4174   if (!Tok.is(AsmToken::Identifier))
4175     return MatchOperand_NoMatch;
4176   StringRef RegName = Tok.getString();
4177 
4178   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4179   // and bit 5 is R.
4180   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4181                           .Case("r8_usr", 0x00)
4182                           .Case("r9_usr", 0x01)
4183                           .Case("r10_usr", 0x02)
4184                           .Case("r11_usr", 0x03)
4185                           .Case("r12_usr", 0x04)
4186                           .Case("sp_usr", 0x05)
4187                           .Case("lr_usr", 0x06)
4188                           .Case("r8_fiq", 0x08)
4189                           .Case("r9_fiq", 0x09)
4190                           .Case("r10_fiq", 0x0a)
4191                           .Case("r11_fiq", 0x0b)
4192                           .Case("r12_fiq", 0x0c)
4193                           .Case("sp_fiq", 0x0d)
4194                           .Case("lr_fiq", 0x0e)
4195                           .Case("lr_irq", 0x10)
4196                           .Case("sp_irq", 0x11)
4197                           .Case("lr_svc", 0x12)
4198                           .Case("sp_svc", 0x13)
4199                           .Case("lr_abt", 0x14)
4200                           .Case("sp_abt", 0x15)
4201                           .Case("lr_und", 0x16)
4202                           .Case("sp_und", 0x17)
4203                           .Case("lr_mon", 0x1c)
4204                           .Case("sp_mon", 0x1d)
4205                           .Case("elr_hyp", 0x1e)
4206                           .Case("sp_hyp", 0x1f)
4207                           .Case("spsr_fiq", 0x2e)
4208                           .Case("spsr_irq", 0x30)
4209                           .Case("spsr_svc", 0x32)
4210                           .Case("spsr_abt", 0x34)
4211                           .Case("spsr_und", 0x36)
4212                           .Case("spsr_mon", 0x3c)
4213                           .Case("spsr_hyp", 0x3e)
4214                           .Default(~0U);
4215 
4216   if (Encoding == ~0U)
4217     return MatchOperand_NoMatch;
4218 
4219   Parser.Lex(); // Eat identifier token.
4220   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4221   return MatchOperand_Success;
4222 }
4223 
4224 OperandMatchResultTy
4225 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4226                           int High) {
4227   MCAsmParser &Parser = getParser();
4228   const AsmToken &Tok = Parser.getTok();
4229   if (Tok.isNot(AsmToken::Identifier)) {
4230     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4231     return MatchOperand_ParseFail;
4232   }
4233   StringRef ShiftName = Tok.getString();
4234   std::string LowerOp = Op.lower();
4235   std::string UpperOp = Op.upper();
4236   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4237     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4238     return MatchOperand_ParseFail;
4239   }
4240   Parser.Lex(); // Eat shift type token.
4241 
4242   // There must be a '#' and a shift amount.
4243   if (Parser.getTok().isNot(AsmToken::Hash) &&
4244       Parser.getTok().isNot(AsmToken::Dollar)) {
4245     Error(Parser.getTok().getLoc(), "'#' expected");
4246     return MatchOperand_ParseFail;
4247   }
4248   Parser.Lex(); // Eat hash token.
4249 
4250   const MCExpr *ShiftAmount;
4251   SMLoc Loc = Parser.getTok().getLoc();
4252   SMLoc EndLoc;
4253   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4254     Error(Loc, "illegal expression");
4255     return MatchOperand_ParseFail;
4256   }
4257   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4258   if (!CE) {
4259     Error(Loc, "constant expression expected");
4260     return MatchOperand_ParseFail;
4261   }
4262   int Val = CE->getValue();
4263   if (Val < Low || Val > High) {
4264     Error(Loc, "immediate value out of range");
4265     return MatchOperand_ParseFail;
4266   }
4267 
4268   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4269 
4270   return MatchOperand_Success;
4271 }
4272 
4273 OperandMatchResultTy
4274 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4275   MCAsmParser &Parser = getParser();
4276   const AsmToken &Tok = Parser.getTok();
4277   SMLoc S = Tok.getLoc();
4278   if (Tok.isNot(AsmToken::Identifier)) {
4279     Error(S, "'be' or 'le' operand expected");
4280     return MatchOperand_ParseFail;
4281   }
4282   int Val = StringSwitch<int>(Tok.getString().lower())
4283     .Case("be", 1)
4284     .Case("le", 0)
4285     .Default(-1);
4286   Parser.Lex(); // Eat the token.
4287 
4288   if (Val == -1) {
4289     Error(S, "'be' or 'le' operand expected");
4290     return MatchOperand_ParseFail;
4291   }
4292   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4293                                                                   getContext()),
4294                                            S, Tok.getEndLoc()));
4295   return MatchOperand_Success;
4296 }
4297 
4298 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4299 /// instructions. Legal values are:
4300 ///     lsl #n  'n' in [0,31]
4301 ///     asr #n  'n' in [1,32]
4302 ///             n == 32 encoded as n == 0.
4303 OperandMatchResultTy
4304 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4305   MCAsmParser &Parser = getParser();
4306   const AsmToken &Tok = Parser.getTok();
4307   SMLoc S = Tok.getLoc();
4308   if (Tok.isNot(AsmToken::Identifier)) {
4309     Error(S, "shift operator 'asr' or 'lsl' expected");
4310     return MatchOperand_ParseFail;
4311   }
4312   StringRef ShiftName = Tok.getString();
4313   bool isASR;
4314   if (ShiftName == "lsl" || ShiftName == "LSL")
4315     isASR = false;
4316   else if (ShiftName == "asr" || ShiftName == "ASR")
4317     isASR = true;
4318   else {
4319     Error(S, "shift operator 'asr' or 'lsl' expected");
4320     return MatchOperand_ParseFail;
4321   }
4322   Parser.Lex(); // Eat the operator.
4323 
4324   // A '#' and a shift amount.
4325   if (Parser.getTok().isNot(AsmToken::Hash) &&
4326       Parser.getTok().isNot(AsmToken::Dollar)) {
4327     Error(Parser.getTok().getLoc(), "'#' expected");
4328     return MatchOperand_ParseFail;
4329   }
4330   Parser.Lex(); // Eat hash token.
4331   SMLoc ExLoc = Parser.getTok().getLoc();
4332 
4333   const MCExpr *ShiftAmount;
4334   SMLoc EndLoc;
4335   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4336     Error(ExLoc, "malformed shift expression");
4337     return MatchOperand_ParseFail;
4338   }
4339   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4340   if (!CE) {
4341     Error(ExLoc, "shift amount must be an immediate");
4342     return MatchOperand_ParseFail;
4343   }
4344 
4345   int64_t Val = CE->getValue();
4346   if (isASR) {
4347     // Shift amount must be in [1,32]
4348     if (Val < 1 || Val > 32) {
4349       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4350       return MatchOperand_ParseFail;
4351     }
4352     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4353     if (isThumb() && Val == 32) {
4354       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4355       return MatchOperand_ParseFail;
4356     }
4357     if (Val == 32) Val = 0;
4358   } else {
4359     // Shift amount must be in [1,32]
4360     if (Val < 0 || Val > 31) {
4361       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4362       return MatchOperand_ParseFail;
4363     }
4364   }
4365 
4366   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4367 
4368   return MatchOperand_Success;
4369 }
4370 
4371 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4372 /// of instructions. Legal values are:
4373 ///     ror #n  'n' in {0, 8, 16, 24}
4374 OperandMatchResultTy
4375 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4376   MCAsmParser &Parser = getParser();
4377   const AsmToken &Tok = Parser.getTok();
4378   SMLoc S = Tok.getLoc();
4379   if (Tok.isNot(AsmToken::Identifier))
4380     return MatchOperand_NoMatch;
4381   StringRef ShiftName = Tok.getString();
4382   if (ShiftName != "ror" && ShiftName != "ROR")
4383     return MatchOperand_NoMatch;
4384   Parser.Lex(); // Eat the operator.
4385 
4386   // A '#' and a rotate amount.
4387   if (Parser.getTok().isNot(AsmToken::Hash) &&
4388       Parser.getTok().isNot(AsmToken::Dollar)) {
4389     Error(Parser.getTok().getLoc(), "'#' expected");
4390     return MatchOperand_ParseFail;
4391   }
4392   Parser.Lex(); // Eat hash token.
4393   SMLoc ExLoc = Parser.getTok().getLoc();
4394 
4395   const MCExpr *ShiftAmount;
4396   SMLoc EndLoc;
4397   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4398     Error(ExLoc, "malformed rotate expression");
4399     return MatchOperand_ParseFail;
4400   }
4401   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4402   if (!CE) {
4403     Error(ExLoc, "rotate amount must be an immediate");
4404     return MatchOperand_ParseFail;
4405   }
4406 
4407   int64_t Val = CE->getValue();
4408   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4409   // normally, zero is represented in asm by omitting the rotate operand
4410   // entirely.
4411   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4412     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4413     return MatchOperand_ParseFail;
4414   }
4415 
4416   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4417 
4418   return MatchOperand_Success;
4419 }
4420 
4421 OperandMatchResultTy
4422 ARMAsmParser::parseModImm(OperandVector &Operands) {
4423   MCAsmParser &Parser = getParser();
4424   MCAsmLexer &Lexer = getLexer();
4425   int64_t Imm1, Imm2;
4426 
4427   SMLoc S = Parser.getTok().getLoc();
4428 
4429   // 1) A mod_imm operand can appear in the place of a register name:
4430   //   add r0, #mod_imm
4431   //   add r0, r0, #mod_imm
4432   // to correctly handle the latter, we bail out as soon as we see an
4433   // identifier.
4434   //
4435   // 2) Similarly, we do not want to parse into complex operands:
4436   //   mov r0, #mod_imm
4437   //   mov r0, :lower16:(_foo)
4438   if (Parser.getTok().is(AsmToken::Identifier) ||
4439       Parser.getTok().is(AsmToken::Colon))
4440     return MatchOperand_NoMatch;
4441 
4442   // Hash (dollar) is optional as per the ARMARM
4443   if (Parser.getTok().is(AsmToken::Hash) ||
4444       Parser.getTok().is(AsmToken::Dollar)) {
4445     // Avoid parsing into complex operands (#:)
4446     if (Lexer.peekTok().is(AsmToken::Colon))
4447       return MatchOperand_NoMatch;
4448 
4449     // Eat the hash (dollar)
4450     Parser.Lex();
4451   }
4452 
4453   SMLoc Sx1, Ex1;
4454   Sx1 = Parser.getTok().getLoc();
4455   const MCExpr *Imm1Exp;
4456   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4457     Error(Sx1, "malformed expression");
4458     return MatchOperand_ParseFail;
4459   }
4460 
4461   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4462 
4463   if (CE) {
4464     // Immediate must fit within 32-bits
4465     Imm1 = CE->getValue();
4466     int Enc = ARM_AM::getSOImmVal(Imm1);
4467     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4468       // We have a match!
4469       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4470                                                   (Enc & 0xF00) >> 7,
4471                                                   Sx1, Ex1));
4472       return MatchOperand_Success;
4473     }
4474 
4475     // We have parsed an immediate which is not for us, fallback to a plain
4476     // immediate. This can happen for instruction aliases. For an example,
4477     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4478     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4479     // instruction with a mod_imm operand. The alias is defined such that the
4480     // parser method is shared, that's why we have to do this here.
4481     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4482       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4483       return MatchOperand_Success;
4484     }
4485   } else {
4486     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4487     // MCFixup). Fallback to a plain immediate.
4488     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4489     return MatchOperand_Success;
4490   }
4491 
4492   // From this point onward, we expect the input to be a (#bits, #rot) pair
4493   if (Parser.getTok().isNot(AsmToken::Comma)) {
4494     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4495     return MatchOperand_ParseFail;
4496   }
4497 
4498   if (Imm1 & ~0xFF) {
4499     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4500     return MatchOperand_ParseFail;
4501   }
4502 
4503   // Eat the comma
4504   Parser.Lex();
4505 
4506   // Repeat for #rot
4507   SMLoc Sx2, Ex2;
4508   Sx2 = Parser.getTok().getLoc();
4509 
4510   // Eat the optional hash (dollar)
4511   if (Parser.getTok().is(AsmToken::Hash) ||
4512       Parser.getTok().is(AsmToken::Dollar))
4513     Parser.Lex();
4514 
4515   const MCExpr *Imm2Exp;
4516   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4517     Error(Sx2, "malformed expression");
4518     return MatchOperand_ParseFail;
4519   }
4520 
4521   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4522 
4523   if (CE) {
4524     Imm2 = CE->getValue();
4525     if (!(Imm2 & ~0x1E)) {
4526       // We have a match!
4527       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4528       return MatchOperand_Success;
4529     }
4530     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4531     return MatchOperand_ParseFail;
4532   } else {
4533     Error(Sx2, "constant expression expected");
4534     return MatchOperand_ParseFail;
4535   }
4536 }
4537 
4538 OperandMatchResultTy
4539 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4540   MCAsmParser &Parser = getParser();
4541   SMLoc S = Parser.getTok().getLoc();
4542   // The bitfield descriptor is really two operands, the LSB and the width.
4543   if (Parser.getTok().isNot(AsmToken::Hash) &&
4544       Parser.getTok().isNot(AsmToken::Dollar)) {
4545     Error(Parser.getTok().getLoc(), "'#' expected");
4546     return MatchOperand_ParseFail;
4547   }
4548   Parser.Lex(); // Eat hash token.
4549 
4550   const MCExpr *LSBExpr;
4551   SMLoc E = Parser.getTok().getLoc();
4552   if (getParser().parseExpression(LSBExpr)) {
4553     Error(E, "malformed immediate expression");
4554     return MatchOperand_ParseFail;
4555   }
4556   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4557   if (!CE) {
4558     Error(E, "'lsb' operand must be an immediate");
4559     return MatchOperand_ParseFail;
4560   }
4561 
4562   int64_t LSB = CE->getValue();
4563   // The LSB must be in the range [0,31]
4564   if (LSB < 0 || LSB > 31) {
4565     Error(E, "'lsb' operand must be in the range [0,31]");
4566     return MatchOperand_ParseFail;
4567   }
4568   E = Parser.getTok().getLoc();
4569 
4570   // Expect another immediate operand.
4571   if (Parser.getTok().isNot(AsmToken::Comma)) {
4572     Error(Parser.getTok().getLoc(), "too few operands");
4573     return MatchOperand_ParseFail;
4574   }
4575   Parser.Lex(); // Eat hash token.
4576   if (Parser.getTok().isNot(AsmToken::Hash) &&
4577       Parser.getTok().isNot(AsmToken::Dollar)) {
4578     Error(Parser.getTok().getLoc(), "'#' expected");
4579     return MatchOperand_ParseFail;
4580   }
4581   Parser.Lex(); // Eat hash token.
4582 
4583   const MCExpr *WidthExpr;
4584   SMLoc EndLoc;
4585   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4586     Error(E, "malformed immediate expression");
4587     return MatchOperand_ParseFail;
4588   }
4589   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4590   if (!CE) {
4591     Error(E, "'width' operand must be an immediate");
4592     return MatchOperand_ParseFail;
4593   }
4594 
4595   int64_t Width = CE->getValue();
4596   // The LSB must be in the range [1,32-lsb]
4597   if (Width < 1 || Width > 32 - LSB) {
4598     Error(E, "'width' operand must be in the range [1,32-lsb]");
4599     return MatchOperand_ParseFail;
4600   }
4601 
4602   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4603 
4604   return MatchOperand_Success;
4605 }
4606 
4607 OperandMatchResultTy
4608 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4609   // Check for a post-index addressing register operand. Specifically:
4610   // postidx_reg := '+' register {, shift}
4611   //              | '-' register {, shift}
4612   //              | register {, shift}
4613 
4614   // This method must return MatchOperand_NoMatch without consuming any tokens
4615   // in the case where there is no match, as other alternatives take other
4616   // parse methods.
4617   MCAsmParser &Parser = getParser();
4618   AsmToken Tok = Parser.getTok();
4619   SMLoc S = Tok.getLoc();
4620   bool haveEaten = false;
4621   bool isAdd = true;
4622   if (Tok.is(AsmToken::Plus)) {
4623     Parser.Lex(); // Eat the '+' token.
4624     haveEaten = true;
4625   } else if (Tok.is(AsmToken::Minus)) {
4626     Parser.Lex(); // Eat the '-' token.
4627     isAdd = false;
4628     haveEaten = true;
4629   }
4630 
4631   SMLoc E = Parser.getTok().getEndLoc();
4632   int Reg = tryParseRegister();
4633   if (Reg == -1) {
4634     if (!haveEaten)
4635       return MatchOperand_NoMatch;
4636     Error(Parser.getTok().getLoc(), "register expected");
4637     return MatchOperand_ParseFail;
4638   }
4639 
4640   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4641   unsigned ShiftImm = 0;
4642   if (Parser.getTok().is(AsmToken::Comma)) {
4643     Parser.Lex(); // Eat the ','.
4644     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4645       return MatchOperand_ParseFail;
4646 
4647     // FIXME: Only approximates end...may include intervening whitespace.
4648     E = Parser.getTok().getLoc();
4649   }
4650 
4651   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4652                                                   ShiftImm, S, E));
4653 
4654   return MatchOperand_Success;
4655 }
4656 
4657 OperandMatchResultTy
4658 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4659   // Check for a post-index addressing register operand. Specifically:
4660   // am3offset := '+' register
4661   //              | '-' register
4662   //              | register
4663   //              | # imm
4664   //              | # + imm
4665   //              | # - imm
4666 
4667   // This method must return MatchOperand_NoMatch without consuming any tokens
4668   // in the case where there is no match, as other alternatives take other
4669   // parse methods.
4670   MCAsmParser &Parser = getParser();
4671   AsmToken Tok = Parser.getTok();
4672   SMLoc S = Tok.getLoc();
4673 
4674   // Do immediates first, as we always parse those if we have a '#'.
4675   if (Parser.getTok().is(AsmToken::Hash) ||
4676       Parser.getTok().is(AsmToken::Dollar)) {
4677     Parser.Lex(); // Eat '#' or '$'.
4678     // Explicitly look for a '-', as we need to encode negative zero
4679     // differently.
4680     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4681     const MCExpr *Offset;
4682     SMLoc E;
4683     if (getParser().parseExpression(Offset, E))
4684       return MatchOperand_ParseFail;
4685     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4686     if (!CE) {
4687       Error(S, "constant expression expected");
4688       return MatchOperand_ParseFail;
4689     }
4690     // Negative zero is encoded as the flag value INT32_MIN.
4691     int32_t Val = CE->getValue();
4692     if (isNegative && Val == 0)
4693       Val = INT32_MIN;
4694 
4695     Operands.push_back(
4696       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4697 
4698     return MatchOperand_Success;
4699   }
4700 
4701 
4702   bool haveEaten = false;
4703   bool isAdd = true;
4704   if (Tok.is(AsmToken::Plus)) {
4705     Parser.Lex(); // Eat the '+' token.
4706     haveEaten = true;
4707   } else if (Tok.is(AsmToken::Minus)) {
4708     Parser.Lex(); // Eat the '-' token.
4709     isAdd = false;
4710     haveEaten = true;
4711   }
4712 
4713   Tok = Parser.getTok();
4714   int Reg = tryParseRegister();
4715   if (Reg == -1) {
4716     if (!haveEaten)
4717       return MatchOperand_NoMatch;
4718     Error(Tok.getLoc(), "register expected");
4719     return MatchOperand_ParseFail;
4720   }
4721 
4722   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4723                                                   0, S, Tok.getEndLoc()));
4724 
4725   return MatchOperand_Success;
4726 }
4727 
4728 /// Convert parsed operands to MCInst.  Needed here because this instruction
4729 /// only has two register operands, but multiplication is commutative so
4730 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4731 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4732                                     const OperandVector &Operands) {
4733   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4734   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4735   // If we have a three-operand form, make sure to set Rn to be the operand
4736   // that isn't the same as Rd.
4737   unsigned RegOp = 4;
4738   if (Operands.size() == 6 &&
4739       ((ARMOperand &)*Operands[4]).getReg() ==
4740           ((ARMOperand &)*Operands[3]).getReg())
4741     RegOp = 5;
4742   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4743   Inst.addOperand(Inst.getOperand(0));
4744   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4745 }
4746 
4747 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4748                                     const OperandVector &Operands) {
4749   int CondOp = -1, ImmOp = -1;
4750   switch(Inst.getOpcode()) {
4751     case ARM::tB:
4752     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4753 
4754     case ARM::t2B:
4755     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4756 
4757     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4758   }
4759   // first decide whether or not the branch should be conditional
4760   // by looking at it's location relative to an IT block
4761   if(inITBlock()) {
4762     // inside an IT block we cannot have any conditional branches. any
4763     // such instructions needs to be converted to unconditional form
4764     switch(Inst.getOpcode()) {
4765       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4766       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4767     }
4768   } else {
4769     // outside IT blocks we can only have unconditional branches with AL
4770     // condition code or conditional branches with non-AL condition code
4771     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4772     switch(Inst.getOpcode()) {
4773       case ARM::tB:
4774       case ARM::tBcc:
4775         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4776         break;
4777       case ARM::t2B:
4778       case ARM::t2Bcc:
4779         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4780         break;
4781     }
4782   }
4783 
4784   // now decide on encoding size based on branch target range
4785   switch(Inst.getOpcode()) {
4786     // classify tB as either t2B or t1B based on range of immediate operand
4787     case ARM::tB: {
4788       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4789       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4790         Inst.setOpcode(ARM::t2B);
4791       break;
4792     }
4793     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4794     case ARM::tBcc: {
4795       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4796       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4797         Inst.setOpcode(ARM::t2Bcc);
4798       break;
4799     }
4800   }
4801   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4802   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4803 }
4804 
4805 /// Parse an ARM memory expression, return false if successful else return true
4806 /// or an error.  The first token must be a '[' when called.
4807 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4808   MCAsmParser &Parser = getParser();
4809   SMLoc S, E;
4810   if (Parser.getTok().isNot(AsmToken::LBrac))
4811     return TokError("Token is not a Left Bracket");
4812   S = Parser.getTok().getLoc();
4813   Parser.Lex(); // Eat left bracket token.
4814 
4815   const AsmToken &BaseRegTok = Parser.getTok();
4816   int BaseRegNum = tryParseRegister();
4817   if (BaseRegNum == -1)
4818     return Error(BaseRegTok.getLoc(), "register expected");
4819 
4820   // The next token must either be a comma, a colon or a closing bracket.
4821   const AsmToken &Tok = Parser.getTok();
4822   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4823       !Tok.is(AsmToken::RBrac))
4824     return Error(Tok.getLoc(), "malformed memory operand");
4825 
4826   if (Tok.is(AsmToken::RBrac)) {
4827     E = Tok.getEndLoc();
4828     Parser.Lex(); // Eat right bracket token.
4829 
4830     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4831                                              ARM_AM::no_shift, 0, 0, false,
4832                                              S, E));
4833 
4834     // If there's a pre-indexing writeback marker, '!', just add it as a token
4835     // operand. It's rather odd, but syntactically valid.
4836     if (Parser.getTok().is(AsmToken::Exclaim)) {
4837       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4838       Parser.Lex(); // Eat the '!'.
4839     }
4840 
4841     return false;
4842   }
4843 
4844   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4845          "Lost colon or comma in memory operand?!");
4846   if (Tok.is(AsmToken::Comma)) {
4847     Parser.Lex(); // Eat the comma.
4848   }
4849 
4850   // If we have a ':', it's an alignment specifier.
4851   if (Parser.getTok().is(AsmToken::Colon)) {
4852     Parser.Lex(); // Eat the ':'.
4853     E = Parser.getTok().getLoc();
4854     SMLoc AlignmentLoc = Tok.getLoc();
4855 
4856     const MCExpr *Expr;
4857     if (getParser().parseExpression(Expr))
4858      return true;
4859 
4860     // The expression has to be a constant. Memory references with relocations
4861     // don't come through here, as they use the <label> forms of the relevant
4862     // instructions.
4863     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4864     if (!CE)
4865       return Error (E, "constant expression expected");
4866 
4867     unsigned Align = 0;
4868     switch (CE->getValue()) {
4869     default:
4870       return Error(E,
4871                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4872     case 16:  Align = 2; break;
4873     case 32:  Align = 4; break;
4874     case 64:  Align = 8; break;
4875     case 128: Align = 16; break;
4876     case 256: Align = 32; break;
4877     }
4878 
4879     // Now we should have the closing ']'
4880     if (Parser.getTok().isNot(AsmToken::RBrac))
4881       return Error(Parser.getTok().getLoc(), "']' expected");
4882     E = Parser.getTok().getEndLoc();
4883     Parser.Lex(); // Eat right bracket token.
4884 
4885     // Don't worry about range checking the value here. That's handled by
4886     // the is*() predicates.
4887     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4888                                              ARM_AM::no_shift, 0, Align,
4889                                              false, S, E, AlignmentLoc));
4890 
4891     // If there's a pre-indexing writeback marker, '!', just add it as a token
4892     // operand.
4893     if (Parser.getTok().is(AsmToken::Exclaim)) {
4894       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4895       Parser.Lex(); // Eat the '!'.
4896     }
4897 
4898     return false;
4899   }
4900 
4901   // If we have a '#', it's an immediate offset, else assume it's a register
4902   // offset. Be friendly and also accept a plain integer (without a leading
4903   // hash) for gas compatibility.
4904   if (Parser.getTok().is(AsmToken::Hash) ||
4905       Parser.getTok().is(AsmToken::Dollar) ||
4906       Parser.getTok().is(AsmToken::Integer)) {
4907     if (Parser.getTok().isNot(AsmToken::Integer))
4908       Parser.Lex(); // Eat '#' or '$'.
4909     E = Parser.getTok().getLoc();
4910 
4911     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4912     const MCExpr *Offset;
4913     if (getParser().parseExpression(Offset))
4914      return true;
4915 
4916     // The expression has to be a constant. Memory references with relocations
4917     // don't come through here, as they use the <label> forms of the relevant
4918     // instructions.
4919     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4920     if (!CE)
4921       return Error (E, "constant expression expected");
4922 
4923     // If the constant was #-0, represent it as INT32_MIN.
4924     int32_t Val = CE->getValue();
4925     if (isNegative && Val == 0)
4926       CE = MCConstantExpr::create(INT32_MIN, getContext());
4927 
4928     // Now we should have the closing ']'
4929     if (Parser.getTok().isNot(AsmToken::RBrac))
4930       return Error(Parser.getTok().getLoc(), "']' expected");
4931     E = Parser.getTok().getEndLoc();
4932     Parser.Lex(); // Eat right bracket token.
4933 
4934     // Don't worry about range checking the value here. That's handled by
4935     // the is*() predicates.
4936     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4937                                              ARM_AM::no_shift, 0, 0,
4938                                              false, S, E));
4939 
4940     // If there's a pre-indexing writeback marker, '!', just add it as a token
4941     // operand.
4942     if (Parser.getTok().is(AsmToken::Exclaim)) {
4943       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4944       Parser.Lex(); // Eat the '!'.
4945     }
4946 
4947     return false;
4948   }
4949 
4950   // The register offset is optionally preceded by a '+' or '-'
4951   bool isNegative = false;
4952   if (Parser.getTok().is(AsmToken::Minus)) {
4953     isNegative = true;
4954     Parser.Lex(); // Eat the '-'.
4955   } else if (Parser.getTok().is(AsmToken::Plus)) {
4956     // Nothing to do.
4957     Parser.Lex(); // Eat the '+'.
4958   }
4959 
4960   E = Parser.getTok().getLoc();
4961   int OffsetRegNum = tryParseRegister();
4962   if (OffsetRegNum == -1)
4963     return Error(E, "register expected");
4964 
4965   // If there's a shift operator, handle it.
4966   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4967   unsigned ShiftImm = 0;
4968   if (Parser.getTok().is(AsmToken::Comma)) {
4969     Parser.Lex(); // Eat the ','.
4970     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4971       return true;
4972   }
4973 
4974   // Now we should have the closing ']'
4975   if (Parser.getTok().isNot(AsmToken::RBrac))
4976     return Error(Parser.getTok().getLoc(), "']' expected");
4977   E = Parser.getTok().getEndLoc();
4978   Parser.Lex(); // Eat right bracket token.
4979 
4980   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
4981                                            ShiftType, ShiftImm, 0, isNegative,
4982                                            S, E));
4983 
4984   // If there's a pre-indexing writeback marker, '!', just add it as a token
4985   // operand.
4986   if (Parser.getTok().is(AsmToken::Exclaim)) {
4987     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4988     Parser.Lex(); // Eat the '!'.
4989   }
4990 
4991   return false;
4992 }
4993 
4994 /// parseMemRegOffsetShift - one of these two:
4995 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4996 ///   rrx
4997 /// return true if it parses a shift otherwise it returns false.
4998 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4999                                           unsigned &Amount) {
5000   MCAsmParser &Parser = getParser();
5001   SMLoc Loc = Parser.getTok().getLoc();
5002   const AsmToken &Tok = Parser.getTok();
5003   if (Tok.isNot(AsmToken::Identifier))
5004     return true;
5005   StringRef ShiftName = Tok.getString();
5006   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5007       ShiftName == "asl" || ShiftName == "ASL")
5008     St = ARM_AM::lsl;
5009   else if (ShiftName == "lsr" || ShiftName == "LSR")
5010     St = ARM_AM::lsr;
5011   else if (ShiftName == "asr" || ShiftName == "ASR")
5012     St = ARM_AM::asr;
5013   else if (ShiftName == "ror" || ShiftName == "ROR")
5014     St = ARM_AM::ror;
5015   else if (ShiftName == "rrx" || ShiftName == "RRX")
5016     St = ARM_AM::rrx;
5017   else
5018     return Error(Loc, "illegal shift operator");
5019   Parser.Lex(); // Eat shift type token.
5020 
5021   // rrx stands alone.
5022   Amount = 0;
5023   if (St != ARM_AM::rrx) {
5024     Loc = Parser.getTok().getLoc();
5025     // A '#' and a shift amount.
5026     const AsmToken &HashTok = Parser.getTok();
5027     if (HashTok.isNot(AsmToken::Hash) &&
5028         HashTok.isNot(AsmToken::Dollar))
5029       return Error(HashTok.getLoc(), "'#' expected");
5030     Parser.Lex(); // Eat hash token.
5031 
5032     const MCExpr *Expr;
5033     if (getParser().parseExpression(Expr))
5034       return true;
5035     // Range check the immediate.
5036     // lsl, ror: 0 <= imm <= 31
5037     // lsr, asr: 0 <= imm <= 32
5038     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5039     if (!CE)
5040       return Error(Loc, "shift amount must be an immediate");
5041     int64_t Imm = CE->getValue();
5042     if (Imm < 0 ||
5043         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5044         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5045       return Error(Loc, "immediate shift value out of range");
5046     // If <ShiftTy> #0, turn it into a no_shift.
5047     if (Imm == 0)
5048       St = ARM_AM::lsl;
5049     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5050     if (Imm == 32)
5051       Imm = 0;
5052     Amount = Imm;
5053   }
5054 
5055   return false;
5056 }
5057 
5058 /// parseFPImm - A floating point immediate expression operand.
5059 OperandMatchResultTy
5060 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5061   MCAsmParser &Parser = getParser();
5062   // Anything that can accept a floating point constant as an operand
5063   // needs to go through here, as the regular parseExpression is
5064   // integer only.
5065   //
5066   // This routine still creates a generic Immediate operand, containing
5067   // a bitcast of the 64-bit floating point value. The various operands
5068   // that accept floats can check whether the value is valid for them
5069   // via the standard is*() predicates.
5070 
5071   SMLoc S = Parser.getTok().getLoc();
5072 
5073   if (Parser.getTok().isNot(AsmToken::Hash) &&
5074       Parser.getTok().isNot(AsmToken::Dollar))
5075     return MatchOperand_NoMatch;
5076 
5077   // Disambiguate the VMOV forms that can accept an FP immediate.
5078   // vmov.f32 <sreg>, #imm
5079   // vmov.f64 <dreg>, #imm
5080   // vmov.f32 <dreg>, #imm  @ vector f32x2
5081   // vmov.f32 <qreg>, #imm  @ vector f32x4
5082   //
5083   // There are also the NEON VMOV instructions which expect an
5084   // integer constant. Make sure we don't try to parse an FPImm
5085   // for these:
5086   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5087   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5088   bool isVmovf = TyOp.isToken() &&
5089                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5090                   TyOp.getToken() == ".f16");
5091   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5092   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5093                                          Mnemonic.getToken() == "fconsts");
5094   if (!(isVmovf || isFconst))
5095     return MatchOperand_NoMatch;
5096 
5097   Parser.Lex(); // Eat '#' or '$'.
5098 
5099   // Handle negation, as that still comes through as a separate token.
5100   bool isNegative = false;
5101   if (Parser.getTok().is(AsmToken::Minus)) {
5102     isNegative = true;
5103     Parser.Lex();
5104   }
5105   const AsmToken &Tok = Parser.getTok();
5106   SMLoc Loc = Tok.getLoc();
5107   if (Tok.is(AsmToken::Real) && isVmovf) {
5108     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5109     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5110     // If we had a '-' in front, toggle the sign bit.
5111     IntVal ^= (uint64_t)isNegative << 31;
5112     Parser.Lex(); // Eat the token.
5113     Operands.push_back(ARMOperand::CreateImm(
5114           MCConstantExpr::create(IntVal, getContext()),
5115           S, Parser.getTok().getLoc()));
5116     return MatchOperand_Success;
5117   }
5118   // Also handle plain integers. Instructions which allow floating point
5119   // immediates also allow a raw encoded 8-bit value.
5120   if (Tok.is(AsmToken::Integer) && isFconst) {
5121     int64_t Val = Tok.getIntVal();
5122     Parser.Lex(); // Eat the token.
5123     if (Val > 255 || Val < 0) {
5124       Error(Loc, "encoded floating point value out of range");
5125       return MatchOperand_ParseFail;
5126     }
5127     float RealVal = ARM_AM::getFPImmFloat(Val);
5128     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5129 
5130     Operands.push_back(ARMOperand::CreateImm(
5131         MCConstantExpr::create(Val, getContext()), S,
5132         Parser.getTok().getLoc()));
5133     return MatchOperand_Success;
5134   }
5135 
5136   Error(Loc, "invalid floating point immediate");
5137   return MatchOperand_ParseFail;
5138 }
5139 
5140 /// Parse a arm instruction operand.  For now this parses the operand regardless
5141 /// of the mnemonic.
5142 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5143   MCAsmParser &Parser = getParser();
5144   SMLoc S, E;
5145 
5146   // Check if the current operand has a custom associated parser, if so, try to
5147   // custom parse the operand, or fallback to the general approach.
5148   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5149   if (ResTy == MatchOperand_Success)
5150     return false;
5151   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5152   // there was a match, but an error occurred, in which case, just return that
5153   // the operand parsing failed.
5154   if (ResTy == MatchOperand_ParseFail)
5155     return true;
5156 
5157   switch (getLexer().getKind()) {
5158   default:
5159     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5160     return true;
5161   case AsmToken::Identifier: {
5162     // If we've seen a branch mnemonic, the next operand must be a label.  This
5163     // is true even if the label is a register name.  So "br r1" means branch to
5164     // label "r1".
5165     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5166     if (!ExpectLabel) {
5167       if (!tryParseRegisterWithWriteBack(Operands))
5168         return false;
5169       int Res = tryParseShiftRegister(Operands);
5170       if (Res == 0) // success
5171         return false;
5172       else if (Res == -1) // irrecoverable error
5173         return true;
5174       // If this is VMRS, check for the apsr_nzcv operand.
5175       if (Mnemonic == "vmrs" &&
5176           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5177         S = Parser.getTok().getLoc();
5178         Parser.Lex();
5179         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5180         return false;
5181       }
5182     }
5183 
5184     // Fall though for the Identifier case that is not a register or a
5185     // special name.
5186     LLVM_FALLTHROUGH;
5187   }
5188   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5189   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5190   case AsmToken::String:  // quoted label names.
5191   case AsmToken::Dot: {   // . as a branch target
5192     // This was not a register so parse other operands that start with an
5193     // identifier (like labels) as expressions and create them as immediates.
5194     const MCExpr *IdVal;
5195     S = Parser.getTok().getLoc();
5196     if (getParser().parseExpression(IdVal))
5197       return true;
5198     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5199     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5200     return false;
5201   }
5202   case AsmToken::LBrac:
5203     return parseMemory(Operands);
5204   case AsmToken::LCurly:
5205     return parseRegisterList(Operands);
5206   case AsmToken::Dollar:
5207   case AsmToken::Hash: {
5208     // #42 -> immediate.
5209     S = Parser.getTok().getLoc();
5210     Parser.Lex();
5211 
5212     if (Parser.getTok().isNot(AsmToken::Colon)) {
5213       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5214       const MCExpr *ImmVal;
5215       if (getParser().parseExpression(ImmVal))
5216         return true;
5217       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5218       if (CE) {
5219         int32_t Val = CE->getValue();
5220         if (isNegative && Val == 0)
5221           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5222       }
5223       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5224       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5225 
5226       // There can be a trailing '!' on operands that we want as a separate
5227       // '!' Token operand. Handle that here. For example, the compatibility
5228       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5229       if (Parser.getTok().is(AsmToken::Exclaim)) {
5230         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5231                                                    Parser.getTok().getLoc()));
5232         Parser.Lex(); // Eat exclaim token
5233       }
5234       return false;
5235     }
5236     // w/ a ':' after the '#', it's just like a plain ':'.
5237     LLVM_FALLTHROUGH;
5238   }
5239   case AsmToken::Colon: {
5240     S = Parser.getTok().getLoc();
5241     // ":lower16:" and ":upper16:" expression prefixes
5242     // FIXME: Check it's an expression prefix,
5243     // e.g. (FOO - :lower16:BAR) isn't legal.
5244     ARMMCExpr::VariantKind RefKind;
5245     if (parsePrefix(RefKind))
5246       return true;
5247 
5248     const MCExpr *SubExprVal;
5249     if (getParser().parseExpression(SubExprVal))
5250       return true;
5251 
5252     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5253                                               getContext());
5254     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5255     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5256     return false;
5257   }
5258   case AsmToken::Equal: {
5259     S = Parser.getTok().getLoc();
5260     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5261       return Error(S, "unexpected token in operand");
5262     Parser.Lex(); // Eat '='
5263     const MCExpr *SubExprVal;
5264     if (getParser().parseExpression(SubExprVal))
5265       return true;
5266     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5267 
5268     // execute-only: we assume that assembly programmers know what they are
5269     // doing and allow literal pool creation here
5270     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5271     return false;
5272   }
5273   }
5274 }
5275 
5276 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5277 //  :lower16: and :upper16:.
5278 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5279   MCAsmParser &Parser = getParser();
5280   RefKind = ARMMCExpr::VK_ARM_None;
5281 
5282   // consume an optional '#' (GNU compatibility)
5283   if (getLexer().is(AsmToken::Hash))
5284     Parser.Lex();
5285 
5286   // :lower16: and :upper16: modifiers
5287   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5288   Parser.Lex(); // Eat ':'
5289 
5290   if (getLexer().isNot(AsmToken::Identifier)) {
5291     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5292     return true;
5293   }
5294 
5295   enum {
5296     COFF = (1 << MCObjectFileInfo::IsCOFF),
5297     ELF = (1 << MCObjectFileInfo::IsELF),
5298     MACHO = (1 << MCObjectFileInfo::IsMachO),
5299     WASM = (1 << MCObjectFileInfo::IsWasm),
5300   };
5301   static const struct PrefixEntry {
5302     const char *Spelling;
5303     ARMMCExpr::VariantKind VariantKind;
5304     uint8_t SupportedFormats;
5305   } PrefixEntries[] = {
5306     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5307     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5308   };
5309 
5310   StringRef IDVal = Parser.getTok().getIdentifier();
5311 
5312   const auto &Prefix =
5313       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5314                    [&IDVal](const PrefixEntry &PE) {
5315                       return PE.Spelling == IDVal;
5316                    });
5317   if (Prefix == std::end(PrefixEntries)) {
5318     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5319     return true;
5320   }
5321 
5322   uint8_t CurrentFormat;
5323   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5324   case MCObjectFileInfo::IsMachO:
5325     CurrentFormat = MACHO;
5326     break;
5327   case MCObjectFileInfo::IsELF:
5328     CurrentFormat = ELF;
5329     break;
5330   case MCObjectFileInfo::IsCOFF:
5331     CurrentFormat = COFF;
5332     break;
5333   case MCObjectFileInfo::IsWasm:
5334     CurrentFormat = WASM;
5335     break;
5336   }
5337 
5338   if (~Prefix->SupportedFormats & CurrentFormat) {
5339     Error(Parser.getTok().getLoc(),
5340           "cannot represent relocation in the current file format");
5341     return true;
5342   }
5343 
5344   RefKind = Prefix->VariantKind;
5345   Parser.Lex();
5346 
5347   if (getLexer().isNot(AsmToken::Colon)) {
5348     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5349     return true;
5350   }
5351   Parser.Lex(); // Eat the last ':'
5352 
5353   return false;
5354 }
5355 
5356 /// \brief Given a mnemonic, split out possible predication code and carry
5357 /// setting letters to form a canonical mnemonic and flags.
5358 //
5359 // FIXME: Would be nice to autogen this.
5360 // FIXME: This is a bit of a maze of special cases.
5361 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5362                                       unsigned &PredicationCode,
5363                                       bool &CarrySetting,
5364                                       unsigned &ProcessorIMod,
5365                                       StringRef &ITMask) {
5366   PredicationCode = ARMCC::AL;
5367   CarrySetting = false;
5368   ProcessorIMod = 0;
5369 
5370   // Ignore some mnemonics we know aren't predicated forms.
5371   //
5372   // FIXME: Would be nice to autogen this.
5373   if ((Mnemonic == "movs" && isThumb()) ||
5374       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5375       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5376       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5377       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5378       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5379       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5380       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5381       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5382       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5383       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5384       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5385       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5386       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5387       Mnemonic == "bxns"  || Mnemonic == "blxns")
5388     return Mnemonic;
5389 
5390   // First, split out any predication code. Ignore mnemonics we know aren't
5391   // predicated but do have a carry-set and so weren't caught above.
5392   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5393       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5394       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5395       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5396     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5397       .Case("eq", ARMCC::EQ)
5398       .Case("ne", ARMCC::NE)
5399       .Case("hs", ARMCC::HS)
5400       .Case("cs", ARMCC::HS)
5401       .Case("lo", ARMCC::LO)
5402       .Case("cc", ARMCC::LO)
5403       .Case("mi", ARMCC::MI)
5404       .Case("pl", ARMCC::PL)
5405       .Case("vs", ARMCC::VS)
5406       .Case("vc", ARMCC::VC)
5407       .Case("hi", ARMCC::HI)
5408       .Case("ls", ARMCC::LS)
5409       .Case("ge", ARMCC::GE)
5410       .Case("lt", ARMCC::LT)
5411       .Case("gt", ARMCC::GT)
5412       .Case("le", ARMCC::LE)
5413       .Case("al", ARMCC::AL)
5414       .Default(~0U);
5415     if (CC != ~0U) {
5416       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5417       PredicationCode = CC;
5418     }
5419   }
5420 
5421   // Next, determine if we have a carry setting bit. We explicitly ignore all
5422   // the instructions we know end in 's'.
5423   if (Mnemonic.endswith("s") &&
5424       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5425         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5426         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5427         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5428         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5429         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5430         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5431         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5432         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5433         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5434         (Mnemonic == "movs" && isThumb()))) {
5435     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5436     CarrySetting = true;
5437   }
5438 
5439   // The "cps" instruction can have a interrupt mode operand which is glued into
5440   // the mnemonic. Check if this is the case, split it and parse the imod op
5441   if (Mnemonic.startswith("cps")) {
5442     // Split out any imod code.
5443     unsigned IMod =
5444       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5445       .Case("ie", ARM_PROC::IE)
5446       .Case("id", ARM_PROC::ID)
5447       .Default(~0U);
5448     if (IMod != ~0U) {
5449       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5450       ProcessorIMod = IMod;
5451     }
5452   }
5453 
5454   // The "it" instruction has the condition mask on the end of the mnemonic.
5455   if (Mnemonic.startswith("it")) {
5456     ITMask = Mnemonic.slice(2, Mnemonic.size());
5457     Mnemonic = Mnemonic.slice(0, 2);
5458   }
5459 
5460   return Mnemonic;
5461 }
5462 
5463 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5464 /// inclusion of carry set or predication code operands.
5465 //
5466 // FIXME: It would be nice to autogen this.
5467 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5468                                          bool &CanAcceptCarrySet,
5469                                          bool &CanAcceptPredicationCode) {
5470   CanAcceptCarrySet =
5471       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5472       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5473       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5474       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5475       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5476       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5477       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5478       (!isThumb() &&
5479        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5480         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5481 
5482   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5483       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5484       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5485       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5486       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5487       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5488       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5489       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5490       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5491       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5492       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5493       Mnemonic == "vmovx" || Mnemonic == "vins") {
5494     // These mnemonics are never predicable
5495     CanAcceptPredicationCode = false;
5496   } else if (!isThumb()) {
5497     // Some instructions are only predicable in Thumb mode
5498     CanAcceptPredicationCode =
5499         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5500         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5501         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5502         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5503         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5504         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5505         !Mnemonic.startswith("srs");
5506   } else if (isThumbOne()) {
5507     if (hasV6MOps())
5508       CanAcceptPredicationCode = Mnemonic != "movs";
5509     else
5510       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5511   } else
5512     CanAcceptPredicationCode = true;
5513 }
5514 
5515 // \brief Some Thumb instructions have two operand forms that are not
5516 // available as three operand, convert to two operand form if possible.
5517 //
5518 // FIXME: We would really like to be able to tablegen'erate this.
5519 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5520                                                  bool CarrySetting,
5521                                                  OperandVector &Operands) {
5522   if (Operands.size() != 6)
5523     return;
5524 
5525   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5526         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5527   if (!Op3.isReg() || !Op4.isReg())
5528     return;
5529 
5530   auto Op3Reg = Op3.getReg();
5531   auto Op4Reg = Op4.getReg();
5532 
5533   // For most Thumb2 cases we just generate the 3 operand form and reduce
5534   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5535   // won't accept SP or PC so we do the transformation here taking care
5536   // with immediate range in the 'add sp, sp #imm' case.
5537   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5538   if (isThumbTwo()) {
5539     if (Mnemonic != "add")
5540       return;
5541     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5542                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5543     if (!TryTransform) {
5544       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5545                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5546                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5547                        Op5.isImm() && !Op5.isImm0_508s4());
5548     }
5549     if (!TryTransform)
5550       return;
5551   } else if (!isThumbOne())
5552     return;
5553 
5554   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5555         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5556         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5557         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5558     return;
5559 
5560   // If first 2 operands of a 3 operand instruction are the same
5561   // then transform to 2 operand version of the same instruction
5562   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5563   bool Transform = Op3Reg == Op4Reg;
5564 
5565   // For communtative operations, we might be able to transform if we swap
5566   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5567   // as tADDrsp.
5568   const ARMOperand *LastOp = &Op5;
5569   bool Swap = false;
5570   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5571       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5572        Mnemonic == "and" || Mnemonic == "eor" ||
5573        Mnemonic == "adc" || Mnemonic == "orr")) {
5574     Swap = true;
5575     LastOp = &Op4;
5576     Transform = true;
5577   }
5578 
5579   // If both registers are the same then remove one of them from
5580   // the operand list, with certain exceptions.
5581   if (Transform) {
5582     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5583     // 2 operand forms don't exist.
5584     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5585         LastOp->isReg())
5586       Transform = false;
5587 
5588     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5589     // 3-bits because the ARMARM says not to.
5590     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5591       Transform = false;
5592   }
5593 
5594   if (Transform) {
5595     if (Swap)
5596       std::swap(Op4, Op5);
5597     Operands.erase(Operands.begin() + 3);
5598   }
5599 }
5600 
5601 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5602                                           OperandVector &Operands) {
5603   // FIXME: This is all horribly hacky. We really need a better way to deal
5604   // with optional operands like this in the matcher table.
5605 
5606   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5607   // another does not. Specifically, the MOVW instruction does not. So we
5608   // special case it here and remove the defaulted (non-setting) cc_out
5609   // operand if that's the instruction we're trying to match.
5610   //
5611   // We do this as post-processing of the explicit operands rather than just
5612   // conditionally adding the cc_out in the first place because we need
5613   // to check the type of the parsed immediate operand.
5614   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5615       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5616       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5617       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5618     return true;
5619 
5620   // Register-register 'add' for thumb does not have a cc_out operand
5621   // when there are only two register operands.
5622   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5623       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5624       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5625       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5626     return true;
5627   // Register-register 'add' for thumb does not have a cc_out operand
5628   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5629   // have to check the immediate range here since Thumb2 has a variant
5630   // that can handle a different range and has a cc_out operand.
5631   if (((isThumb() && Mnemonic == "add") ||
5632        (isThumbTwo() && Mnemonic == "sub")) &&
5633       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5634       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5635       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5636       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5637       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5638        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5639     return true;
5640   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5641   // imm0_4095 variant. That's the least-preferred variant when
5642   // selecting via the generic "add" mnemonic, so to know that we
5643   // should remove the cc_out operand, we have to explicitly check that
5644   // it's not one of the other variants. Ugh.
5645   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5646       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5647       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5648       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5649     // Nest conditions rather than one big 'if' statement for readability.
5650     //
5651     // If both registers are low, we're in an IT block, and the immediate is
5652     // in range, we should use encoding T1 instead, which has a cc_out.
5653     if (inITBlock() &&
5654         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5655         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5656         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5657       return false;
5658     // Check against T3. If the second register is the PC, this is an
5659     // alternate form of ADR, which uses encoding T4, so check for that too.
5660     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5661         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5662       return false;
5663 
5664     // Otherwise, we use encoding T4, which does not have a cc_out
5665     // operand.
5666     return true;
5667   }
5668 
5669   // The thumb2 multiply instruction doesn't have a CCOut register, so
5670   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5671   // use the 16-bit encoding or not.
5672   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5673       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5674       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5675       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5676       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5677       // If the registers aren't low regs, the destination reg isn't the
5678       // same as one of the source regs, or the cc_out operand is zero
5679       // outside of an IT block, we have to use the 32-bit encoding, so
5680       // remove the cc_out operand.
5681       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5682        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5683        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5684        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5685                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5686                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5687                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5688     return true;
5689 
5690   // Also check the 'mul' syntax variant that doesn't specify an explicit
5691   // destination register.
5692   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5693       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5694       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5695       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5696       // If the registers aren't low regs  or the cc_out operand is zero
5697       // outside of an IT block, we have to use the 32-bit encoding, so
5698       // remove the cc_out operand.
5699       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5700        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5701        !inITBlock()))
5702     return true;
5703 
5704 
5705 
5706   // Register-register 'add/sub' for thumb does not have a cc_out operand
5707   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5708   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5709   // right, this will result in better diagnostics (which operand is off)
5710   // anyway.
5711   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5712       (Operands.size() == 5 || Operands.size() == 6) &&
5713       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5714       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5715       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5716       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5717        (Operands.size() == 6 &&
5718         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5719     return true;
5720 
5721   return false;
5722 }
5723 
5724 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5725                                               OperandVector &Operands) {
5726   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5727   unsigned RegIdx = 3;
5728   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5729       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5730        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5731     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5732         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5733          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5734       RegIdx = 4;
5735 
5736     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5737         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5738              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5739          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5740              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5741       return true;
5742   }
5743   return false;
5744 }
5745 
5746 static bool isDataTypeToken(StringRef Tok) {
5747   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5748     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5749     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5750     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5751     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5752     Tok == ".f" || Tok == ".d";
5753 }
5754 
5755 // FIXME: This bit should probably be handled via an explicit match class
5756 // in the .td files that matches the suffix instead of having it be
5757 // a literal string token the way it is now.
5758 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5759   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5760 }
5761 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5762                                  unsigned VariantID);
5763 
5764 static bool RequiresVFPRegListValidation(StringRef Inst,
5765                                          bool &AcceptSinglePrecisionOnly,
5766                                          bool &AcceptDoublePrecisionOnly) {
5767   if (Inst.size() < 7)
5768     return false;
5769 
5770   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5771     StringRef AddressingMode = Inst.substr(4, 2);
5772     if (AddressingMode == "ia" || AddressingMode == "db" ||
5773         AddressingMode == "ea" || AddressingMode == "fd") {
5774       AcceptSinglePrecisionOnly = Inst[6] == 's';
5775       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5776       return true;
5777     }
5778   }
5779 
5780   return false;
5781 }
5782 
5783 /// Parse an arm instruction mnemonic followed by its operands.
5784 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5785                                     SMLoc NameLoc, OperandVector &Operands) {
5786   MCAsmParser &Parser = getParser();
5787   // FIXME: Can this be done via tablegen in some fashion?
5788   bool RequireVFPRegisterListCheck;
5789   bool AcceptSinglePrecisionOnly;
5790   bool AcceptDoublePrecisionOnly;
5791   RequireVFPRegisterListCheck =
5792     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5793                                  AcceptDoublePrecisionOnly);
5794 
5795   // Apply mnemonic aliases before doing anything else, as the destination
5796   // mnemonic may include suffices and we want to handle them normally.
5797   // The generic tblgen'erated code does this later, at the start of
5798   // MatchInstructionImpl(), but that's too late for aliases that include
5799   // any sort of suffix.
5800   uint64_t AvailableFeatures = getAvailableFeatures();
5801   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5802   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5803 
5804   // First check for the ARM-specific .req directive.
5805   if (Parser.getTok().is(AsmToken::Identifier) &&
5806       Parser.getTok().getIdentifier() == ".req") {
5807     parseDirectiveReq(Name, NameLoc);
5808     // We always return 'error' for this, as we're done with this
5809     // statement and don't need to match the 'instruction."
5810     return true;
5811   }
5812 
5813   // Create the leading tokens for the mnemonic, split by '.' characters.
5814   size_t Start = 0, Next = Name.find('.');
5815   StringRef Mnemonic = Name.slice(Start, Next);
5816 
5817   // Split out the predication code and carry setting flag from the mnemonic.
5818   unsigned PredicationCode;
5819   unsigned ProcessorIMod;
5820   bool CarrySetting;
5821   StringRef ITMask;
5822   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5823                            ProcessorIMod, ITMask);
5824 
5825   // In Thumb1, only the branch (B) instruction can be predicated.
5826   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5827     return Error(NameLoc, "conditional execution not supported in Thumb1");
5828   }
5829 
5830   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5831 
5832   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5833   // is the mask as it will be for the IT encoding if the conditional
5834   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5835   // where the conditional bit0 is zero, the instruction post-processing
5836   // will adjust the mask accordingly.
5837   if (Mnemonic == "it") {
5838     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5839     if (ITMask.size() > 3) {
5840       return Error(Loc, "too many conditions on IT instruction");
5841     }
5842     unsigned Mask = 8;
5843     for (unsigned i = ITMask.size(); i != 0; --i) {
5844       char pos = ITMask[i - 1];
5845       if (pos != 't' && pos != 'e') {
5846         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5847       }
5848       Mask >>= 1;
5849       if (ITMask[i - 1] == 't')
5850         Mask |= 8;
5851     }
5852     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5853   }
5854 
5855   // FIXME: This is all a pretty gross hack. We should automatically handle
5856   // optional operands like this via tblgen.
5857 
5858   // Next, add the CCOut and ConditionCode operands, if needed.
5859   //
5860   // For mnemonics which can ever incorporate a carry setting bit or predication
5861   // code, our matching model involves us always generating CCOut and
5862   // ConditionCode operands to match the mnemonic "as written" and then we let
5863   // the matcher deal with finding the right instruction or generating an
5864   // appropriate error.
5865   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5866   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5867 
5868   // If we had a carry-set on an instruction that can't do that, issue an
5869   // error.
5870   if (!CanAcceptCarrySet && CarrySetting) {
5871     return Error(NameLoc, "instruction '" + Mnemonic +
5872                  "' can not set flags, but 's' suffix specified");
5873   }
5874   // If we had a predication code on an instruction that can't do that, issue an
5875   // error.
5876   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5877     return Error(NameLoc, "instruction '" + Mnemonic +
5878                  "' is not predicable, but condition code specified");
5879   }
5880 
5881   // Add the carry setting operand, if necessary.
5882   if (CanAcceptCarrySet) {
5883     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5884     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5885                                                Loc));
5886   }
5887 
5888   // Add the predication code operand, if necessary.
5889   if (CanAcceptPredicationCode) {
5890     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5891                                       CarrySetting);
5892     Operands.push_back(ARMOperand::CreateCondCode(
5893                          ARMCC::CondCodes(PredicationCode), Loc));
5894   }
5895 
5896   // Add the processor imod operand, if necessary.
5897   if (ProcessorIMod) {
5898     Operands.push_back(ARMOperand::CreateImm(
5899           MCConstantExpr::create(ProcessorIMod, getContext()),
5900                                  NameLoc, NameLoc));
5901   } else if (Mnemonic == "cps" && isMClass()) {
5902     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5903   }
5904 
5905   // Add the remaining tokens in the mnemonic.
5906   while (Next != StringRef::npos) {
5907     Start = Next;
5908     Next = Name.find('.', Start + 1);
5909     StringRef ExtraToken = Name.slice(Start, Next);
5910 
5911     // Some NEON instructions have an optional datatype suffix that is
5912     // completely ignored. Check for that.
5913     if (isDataTypeToken(ExtraToken) &&
5914         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5915       continue;
5916 
5917     // For for ARM mode generate an error if the .n qualifier is used.
5918     if (ExtraToken == ".n" && !isThumb()) {
5919       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5920       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5921                    "arm mode");
5922     }
5923 
5924     // The .n qualifier is always discarded as that is what the tables
5925     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5926     // so discard it to avoid errors that can be caused by the matcher.
5927     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5928       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5929       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5930     }
5931   }
5932 
5933   // Read the remaining operands.
5934   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5935     // Read the first operand.
5936     if (parseOperand(Operands, Mnemonic)) {
5937       return true;
5938     }
5939 
5940     while (parseOptionalToken(AsmToken::Comma)) {
5941       // Parse and remember the operand.
5942       if (parseOperand(Operands, Mnemonic)) {
5943         return true;
5944       }
5945     }
5946   }
5947 
5948   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
5949     return true;
5950 
5951   if (RequireVFPRegisterListCheck) {
5952     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5953     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5954       return Error(Op.getStartLoc(),
5955                    "VFP/Neon single precision register expected");
5956     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5957       return Error(Op.getStartLoc(),
5958                    "VFP/Neon double precision register expected");
5959   }
5960 
5961   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
5962 
5963   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5964   // do and don't have a cc_out optional-def operand. With some spot-checks
5965   // of the operand list, we can figure out which variant we're trying to
5966   // parse and adjust accordingly before actually matching. We shouldn't ever
5967   // try to remove a cc_out operand that was explicitly set on the
5968   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5969   // table driven matcher doesn't fit well with the ARM instruction set.
5970   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
5971     Operands.erase(Operands.begin() + 1);
5972 
5973   // Some instructions have the same mnemonic, but don't always
5974   // have a predicate. Distinguish them here and delete the
5975   // predicate if needed.
5976   if (shouldOmitPredicateOperand(Mnemonic, Operands))
5977     Operands.erase(Operands.begin() + 1);
5978 
5979   // ARM mode 'blx' need special handling, as the register operand version
5980   // is predicable, but the label operand version is not. So, we can't rely
5981   // on the Mnemonic based checking to correctly figure out when to put
5982   // a k_CondCode operand in the list. If we're trying to match the label
5983   // version, remove the k_CondCode operand here.
5984   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
5985       static_cast<ARMOperand &>(*Operands[2]).isImm())
5986     Operands.erase(Operands.begin() + 1);
5987 
5988   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
5989   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
5990   // a single GPRPair reg operand is used in the .td file to replace the two
5991   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
5992   // expressed as a GPRPair, so we have to manually merge them.
5993   // FIXME: We would really like to be able to tablegen'erate this.
5994   if (!isThumb() && Operands.size() > 4 &&
5995       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
5996        Mnemonic == "stlexd")) {
5997     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
5998     unsigned Idx = isLoad ? 2 : 3;
5999     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6000     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6001 
6002     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6003     // Adjust only if Op1 and Op2 are GPRs.
6004     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6005         MRC.contains(Op2.getReg())) {
6006       unsigned Reg1 = Op1.getReg();
6007       unsigned Reg2 = Op2.getReg();
6008       unsigned Rt = MRI->getEncodingValue(Reg1);
6009       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6010 
6011       // Rt2 must be Rt + 1 and Rt must be even.
6012       if (Rt + 1 != Rt2 || (Rt & 1)) {
6013         return Error(Op2.getStartLoc(),
6014                      isLoad ? "destination operands must be sequential"
6015                             : "source operands must be sequential");
6016       }
6017       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6018           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6019       Operands[Idx] =
6020           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6021       Operands.erase(Operands.begin() + Idx + 1);
6022     }
6023   }
6024 
6025   // GNU Assembler extension (compatibility)
6026   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
6027     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6028     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6029     if (Op3.isMem()) {
6030       assert(Op2.isReg() && "expected register argument");
6031 
6032       unsigned SuperReg = MRI->getMatchingSuperReg(
6033           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
6034 
6035       assert(SuperReg && "expected register pair");
6036 
6037       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
6038 
6039       Operands.insert(
6040           Operands.begin() + 3,
6041           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6042     }
6043   }
6044 
6045   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6046   // does not fit with other "subs" and tblgen.
6047   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6048   // so the Mnemonic is the original name "subs" and delete the predicate
6049   // operand so it will match the table entry.
6050   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6051       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6052       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6053       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6054       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6055       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6056     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6057     Operands.erase(Operands.begin() + 1);
6058   }
6059   return false;
6060 }
6061 
6062 // Validate context-sensitive operand constraints.
6063 
6064 // return 'true' if register list contains non-low GPR registers,
6065 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6066 // 'containsReg' to true.
6067 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6068                                  unsigned Reg, unsigned HiReg,
6069                                  bool &containsReg) {
6070   containsReg = false;
6071   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6072     unsigned OpReg = Inst.getOperand(i).getReg();
6073     if (OpReg == Reg)
6074       containsReg = true;
6075     // Anything other than a low register isn't legal here.
6076     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6077       return true;
6078   }
6079   return false;
6080 }
6081 
6082 // Check if the specified regisgter is in the register list of the inst,
6083 // starting at the indicated operand number.
6084 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6085   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6086     unsigned OpReg = Inst.getOperand(i).getReg();
6087     if (OpReg == Reg)
6088       return true;
6089   }
6090   return false;
6091 }
6092 
6093 // Return true if instruction has the interesting property of being
6094 // allowed in IT blocks, but not being predicable.
6095 static bool instIsBreakpoint(const MCInst &Inst) {
6096     return Inst.getOpcode() == ARM::tBKPT ||
6097            Inst.getOpcode() == ARM::BKPT ||
6098            Inst.getOpcode() == ARM::tHLT ||
6099            Inst.getOpcode() == ARM::HLT;
6100 
6101 }
6102 
6103 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6104                                        const OperandVector &Operands,
6105                                        unsigned ListNo, bool IsARPop) {
6106   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6107   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6108 
6109   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6110   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6111   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6112 
6113   if (!IsARPop && ListContainsSP)
6114     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6115                  "SP may not be in the register list");
6116   else if (ListContainsPC && ListContainsLR)
6117     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6118                  "PC and LR may not be in the register list simultaneously");
6119   return false;
6120 }
6121 
6122 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6123                                        const OperandVector &Operands,
6124                                        unsigned ListNo) {
6125   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6126   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6127 
6128   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6129   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6130 
6131   if (ListContainsSP && ListContainsPC)
6132     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6133                  "SP and PC may not be in the register list");
6134   else if (ListContainsSP)
6135     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6136                  "SP may not be in the register list");
6137   else if (ListContainsPC)
6138     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6139                  "PC may not be in the register list");
6140   return false;
6141 }
6142 
6143 // FIXME: We would really like to be able to tablegen'erate this.
6144 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6145                                        const OperandVector &Operands) {
6146   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6147   SMLoc Loc = Operands[0]->getStartLoc();
6148 
6149   // Check the IT block state first.
6150   // NOTE: BKPT and HLT instructions have the interesting property of being
6151   // allowed in IT blocks, but not being predicable. They just always execute.
6152   if (inITBlock() && !instIsBreakpoint(Inst)) {
6153     // The instruction must be predicable.
6154     if (!MCID.isPredicable())
6155       return Error(Loc, "instructions in IT block must be predicable");
6156     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6157     if (Cond != currentITCond()) {
6158       // Find the condition code Operand to get its SMLoc information.
6159       SMLoc CondLoc;
6160       for (unsigned I = 1; I < Operands.size(); ++I)
6161         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6162           CondLoc = Operands[I]->getStartLoc();
6163       return Error(CondLoc, "incorrect condition in IT block; got '" +
6164                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6165                    "', but expected '" +
6166                    ARMCondCodeToString(ARMCC::CondCodes(currentITCond())) + "'");
6167     }
6168   // Check for non-'al' condition codes outside of the IT block.
6169   } else if (isThumbTwo() && MCID.isPredicable() &&
6170              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6171              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6172              Inst.getOpcode() != ARM::t2Bcc) {
6173     return Error(Loc, "predicated instructions must be in IT block");
6174   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6175              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6176                  ARMCC::AL) {
6177     return Warning(Loc, "predicated instructions should be in IT block");
6178   }
6179 
6180   // PC-setting instructions in an IT block, but not the last instruction of
6181   // the block, are UNPREDICTABLE.
6182   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6183     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6184   }
6185 
6186   const unsigned Opcode = Inst.getOpcode();
6187   switch (Opcode) {
6188   case ARM::LDRD:
6189   case ARM::LDRD_PRE:
6190   case ARM::LDRD_POST: {
6191     const unsigned RtReg = Inst.getOperand(0).getReg();
6192 
6193     // Rt can't be R14.
6194     if (RtReg == ARM::LR)
6195       return Error(Operands[3]->getStartLoc(),
6196                    "Rt can't be R14");
6197 
6198     const unsigned Rt = MRI->getEncodingValue(RtReg);
6199     // Rt must be even-numbered.
6200     if ((Rt & 1) == 1)
6201       return Error(Operands[3]->getStartLoc(),
6202                    "Rt must be even-numbered");
6203 
6204     // Rt2 must be Rt + 1.
6205     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6206     if (Rt2 != Rt + 1)
6207       return Error(Operands[3]->getStartLoc(),
6208                    "destination operands must be sequential");
6209 
6210     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6211       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6212       // For addressing modes with writeback, the base register needs to be
6213       // different from the destination registers.
6214       if (Rn == Rt || Rn == Rt2)
6215         return Error(Operands[3]->getStartLoc(),
6216                      "base register needs to be different from destination "
6217                      "registers");
6218     }
6219 
6220     return false;
6221   }
6222   case ARM::t2LDRDi8:
6223   case ARM::t2LDRD_PRE:
6224   case ARM::t2LDRD_POST: {
6225     // Rt2 must be different from Rt.
6226     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6227     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6228     if (Rt2 == Rt)
6229       return Error(Operands[3]->getStartLoc(),
6230                    "destination operands can't be identical");
6231     return false;
6232   }
6233   case ARM::t2BXJ: {
6234     const unsigned RmReg = Inst.getOperand(0).getReg();
6235     // Rm = SP is no longer unpredictable in v8-A
6236     if (RmReg == ARM::SP && !hasV8Ops())
6237       return Error(Operands[2]->getStartLoc(),
6238                    "r13 (SP) is an unpredictable operand to BXJ");
6239     return false;
6240   }
6241   case ARM::STRD: {
6242     // Rt2 must be Rt + 1.
6243     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6244     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6245     if (Rt2 != Rt + 1)
6246       return Error(Operands[3]->getStartLoc(),
6247                    "source operands must be sequential");
6248     return false;
6249   }
6250   case ARM::STRD_PRE:
6251   case ARM::STRD_POST: {
6252     // Rt2 must be Rt + 1.
6253     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6254     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6255     if (Rt2 != Rt + 1)
6256       return Error(Operands[3]->getStartLoc(),
6257                    "source operands must be sequential");
6258     return false;
6259   }
6260   case ARM::STR_PRE_IMM:
6261   case ARM::STR_PRE_REG:
6262   case ARM::STR_POST_IMM:
6263   case ARM::STR_POST_REG:
6264   case ARM::STRH_PRE:
6265   case ARM::STRH_POST:
6266   case ARM::STRB_PRE_IMM:
6267   case ARM::STRB_PRE_REG:
6268   case ARM::STRB_POST_IMM:
6269   case ARM::STRB_POST_REG: {
6270     // Rt must be different from Rn.
6271     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6272     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6273 
6274     if (Rt == Rn)
6275       return Error(Operands[3]->getStartLoc(),
6276                    "source register and base register can't be identical");
6277     return false;
6278   }
6279   case ARM::LDR_PRE_IMM:
6280   case ARM::LDR_PRE_REG:
6281   case ARM::LDR_POST_IMM:
6282   case ARM::LDR_POST_REG:
6283   case ARM::LDRH_PRE:
6284   case ARM::LDRH_POST:
6285   case ARM::LDRSH_PRE:
6286   case ARM::LDRSH_POST:
6287   case ARM::LDRB_PRE_IMM:
6288   case ARM::LDRB_PRE_REG:
6289   case ARM::LDRB_POST_IMM:
6290   case ARM::LDRB_POST_REG:
6291   case ARM::LDRSB_PRE:
6292   case ARM::LDRSB_POST: {
6293     // Rt must be different from Rn.
6294     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6295     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6296 
6297     if (Rt == Rn)
6298       return Error(Operands[3]->getStartLoc(),
6299                    "destination register and base register can't be identical");
6300     return false;
6301   }
6302   case ARM::SBFX:
6303   case ARM::UBFX: {
6304     // Width must be in range [1, 32-lsb].
6305     unsigned LSB = Inst.getOperand(2).getImm();
6306     unsigned Widthm1 = Inst.getOperand(3).getImm();
6307     if (Widthm1 >= 32 - LSB)
6308       return Error(Operands[5]->getStartLoc(),
6309                    "bitfield width must be in range [1,32-lsb]");
6310     return false;
6311   }
6312   // Notionally handles ARM::tLDMIA_UPD too.
6313   case ARM::tLDMIA: {
6314     // If we're parsing Thumb2, the .w variant is available and handles
6315     // most cases that are normally illegal for a Thumb1 LDM instruction.
6316     // We'll make the transformation in processInstruction() if necessary.
6317     //
6318     // Thumb LDM instructions are writeback iff the base register is not
6319     // in the register list.
6320     unsigned Rn = Inst.getOperand(0).getReg();
6321     bool HasWritebackToken =
6322         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6323          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6324     bool ListContainsBase;
6325     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6326       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6327                    "registers must be in range r0-r7");
6328     // If we should have writeback, then there should be a '!' token.
6329     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6330       return Error(Operands[2]->getStartLoc(),
6331                    "writeback operator '!' expected");
6332     // If we should not have writeback, there must not be a '!'. This is
6333     // true even for the 32-bit wide encodings.
6334     if (ListContainsBase && HasWritebackToken)
6335       return Error(Operands[3]->getStartLoc(),
6336                    "writeback operator '!' not allowed when base register "
6337                    "in register list");
6338 
6339     if (validatetLDMRegList(Inst, Operands, 3))
6340       return true;
6341     break;
6342   }
6343   case ARM::LDMIA_UPD:
6344   case ARM::LDMDB_UPD:
6345   case ARM::LDMIB_UPD:
6346   case ARM::LDMDA_UPD:
6347     // ARM variants loading and updating the same register are only officially
6348     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6349     if (!hasV7Ops())
6350       break;
6351     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6352       return Error(Operands.back()->getStartLoc(),
6353                    "writeback register not allowed in register list");
6354     break;
6355   case ARM::t2LDMIA:
6356   case ARM::t2LDMDB:
6357     if (validatetLDMRegList(Inst, Operands, 3))
6358       return true;
6359     break;
6360   case ARM::t2STMIA:
6361   case ARM::t2STMDB:
6362     if (validatetSTMRegList(Inst, Operands, 3))
6363       return true;
6364     break;
6365   case ARM::t2LDMIA_UPD:
6366   case ARM::t2LDMDB_UPD:
6367   case ARM::t2STMIA_UPD:
6368   case ARM::t2STMDB_UPD: {
6369     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6370       return Error(Operands.back()->getStartLoc(),
6371                    "writeback register not allowed in register list");
6372 
6373     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6374       if (validatetLDMRegList(Inst, Operands, 3))
6375         return true;
6376     } else {
6377       if (validatetSTMRegList(Inst, Operands, 3))
6378         return true;
6379     }
6380     break;
6381   }
6382   case ARM::sysLDMIA_UPD:
6383   case ARM::sysLDMDA_UPD:
6384   case ARM::sysLDMDB_UPD:
6385   case ARM::sysLDMIB_UPD:
6386     if (!listContainsReg(Inst, 3, ARM::PC))
6387       return Error(Operands[4]->getStartLoc(),
6388                    "writeback register only allowed on system LDM "
6389                    "if PC in register-list");
6390     break;
6391   case ARM::sysSTMIA_UPD:
6392   case ARM::sysSTMDA_UPD:
6393   case ARM::sysSTMDB_UPD:
6394   case ARM::sysSTMIB_UPD:
6395     return Error(Operands[2]->getStartLoc(),
6396                  "system STM cannot have writeback register");
6397   case ARM::tMUL: {
6398     // The second source operand must be the same register as the destination
6399     // operand.
6400     //
6401     // In this case, we must directly check the parsed operands because the
6402     // cvtThumbMultiply() function is written in such a way that it guarantees
6403     // this first statement is always true for the new Inst.  Essentially, the
6404     // destination is unconditionally copied into the second source operand
6405     // without checking to see if it matches what we actually parsed.
6406     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6407                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6408         (((ARMOperand &)*Operands[3]).getReg() !=
6409          ((ARMOperand &)*Operands[4]).getReg())) {
6410       return Error(Operands[3]->getStartLoc(),
6411                    "destination register must match source register");
6412     }
6413     break;
6414   }
6415   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6416   // so only issue a diagnostic for thumb1. The instructions will be
6417   // switched to the t2 encodings in processInstruction() if necessary.
6418   case ARM::tPOP: {
6419     bool ListContainsBase;
6420     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6421         !isThumbTwo())
6422       return Error(Operands[2]->getStartLoc(),
6423                    "registers must be in range r0-r7 or pc");
6424     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6425       return true;
6426     break;
6427   }
6428   case ARM::tPUSH: {
6429     bool ListContainsBase;
6430     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6431         !isThumbTwo())
6432       return Error(Operands[2]->getStartLoc(),
6433                    "registers must be in range r0-r7 or lr");
6434     if (validatetSTMRegList(Inst, Operands, 2))
6435       return true;
6436     break;
6437   }
6438   case ARM::tSTMIA_UPD: {
6439     bool ListContainsBase, InvalidLowList;
6440     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6441                                           0, ListContainsBase);
6442     if (InvalidLowList && !isThumbTwo())
6443       return Error(Operands[4]->getStartLoc(),
6444                    "registers must be in range r0-r7");
6445 
6446     // This would be converted to a 32-bit stm, but that's not valid if the
6447     // writeback register is in the list.
6448     if (InvalidLowList && ListContainsBase)
6449       return Error(Operands[4]->getStartLoc(),
6450                    "writeback operator '!' not allowed when base register "
6451                    "in register list");
6452 
6453     if (validatetSTMRegList(Inst, Operands, 4))
6454       return true;
6455     break;
6456   }
6457   case ARM::tADDrSP: {
6458     // If the non-SP source operand and the destination operand are not the
6459     // same, we need thumb2 (for the wide encoding), or we have an error.
6460     if (!isThumbTwo() &&
6461         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6462       return Error(Operands[4]->getStartLoc(),
6463                    "source register must be the same as destination");
6464     }
6465     break;
6466   }
6467   // Final range checking for Thumb unconditional branch instructions.
6468   case ARM::tB:
6469     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6470       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6471     break;
6472   case ARM::t2B: {
6473     int op = (Operands[2]->isImm()) ? 2 : 3;
6474     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6475       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6476     break;
6477   }
6478   // Final range checking for Thumb conditional branch instructions.
6479   case ARM::tBcc:
6480     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6481       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6482     break;
6483   case ARM::t2Bcc: {
6484     int Op = (Operands[2]->isImm()) ? 2 : 3;
6485     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6486       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6487     break;
6488   }
6489   case ARM::tCBZ:
6490   case ARM::tCBNZ: {
6491     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6492       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6493     break;
6494   }
6495   case ARM::MOVi16:
6496   case ARM::MOVTi16:
6497   case ARM::t2MOVi16:
6498   case ARM::t2MOVTi16:
6499     {
6500     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6501     // especially when we turn it into a movw and the expression <symbol> does
6502     // not have a :lower16: or :upper16 as part of the expression.  We don't
6503     // want the behavior of silently truncating, which can be unexpected and
6504     // lead to bugs that are difficult to find since this is an easy mistake
6505     // to make.
6506     int i = (Operands[3]->isImm()) ? 3 : 4;
6507     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6508     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6509     if (CE) break;
6510     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6511     if (!E) break;
6512     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6513     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6514                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6515       return Error(
6516           Op.getStartLoc(),
6517           "immediate expression for mov requires :lower16: or :upper16");
6518     break;
6519   }
6520   case ARM::HINT:
6521   case ARM::t2HINT: {
6522     if (hasRAS()) {
6523       // ESB is not predicable (pred must be AL)
6524       unsigned Imm8 = Inst.getOperand(0).getImm();
6525       unsigned Pred = Inst.getOperand(1).getImm();
6526       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6527         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6528                                                  "predicable, but condition "
6529                                                  "code specified");
6530     }
6531     // Without the RAS extension, this behaves as any other unallocated hint.
6532     break;
6533   }
6534   }
6535 
6536   return false;
6537 }
6538 
6539 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6540   switch(Opc) {
6541   default: llvm_unreachable("unexpected opcode!");
6542   // VST1LN
6543   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6544   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6545   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6546   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6547   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6548   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6549   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6550   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6551   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6552 
6553   // VST2LN
6554   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6555   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6556   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6557   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6558   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6559 
6560   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6561   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6562   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6563   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6564   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6565 
6566   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6567   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6568   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6569   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6570   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6571 
6572   // VST3LN
6573   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6574   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6575   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6576   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6577   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6578   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6579   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6580   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6581   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6582   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6583   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6584   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6585   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6586   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6587   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6588 
6589   // VST3
6590   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6591   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6592   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6593   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6594   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6595   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6596   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6597   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6598   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6599   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6600   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6601   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6602   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6603   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6604   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6605   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6606   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6607   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6608 
6609   // VST4LN
6610   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6611   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6612   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6613   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6614   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6615   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6616   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6617   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6618   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6619   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6620   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6621   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6622   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6623   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6624   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6625 
6626   // VST4
6627   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6628   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6629   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6630   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6631   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6632   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6633   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6634   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6635   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6636   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6637   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6638   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6639   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6640   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6641   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6642   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6643   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6644   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6645   }
6646 }
6647 
6648 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6649   switch(Opc) {
6650   default: llvm_unreachable("unexpected opcode!");
6651   // VLD1LN
6652   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6653   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6654   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6655   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6656   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6657   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6658   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6659   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6660   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6661 
6662   // VLD2LN
6663   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6664   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6665   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6666   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6667   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6668   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6669   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6670   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6671   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6672   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6673   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6674   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6675   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6676   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6677   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6678 
6679   // VLD3DUP
6680   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6681   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6682   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6683   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6684   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6685   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6686   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6687   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6688   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6689   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6690   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6691   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6692   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6693   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6694   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6695   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6696   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6697   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6698 
6699   // VLD3LN
6700   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6701   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6702   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6703   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6704   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6705   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6706   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6707   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6708   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6709   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6710   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6711   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6712   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6713   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6714   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6715 
6716   // VLD3
6717   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6718   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6719   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6720   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6721   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6722   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6723   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6724   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6725   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6726   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6727   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6728   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6729   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6730   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6731   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6732   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6733   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6734   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6735 
6736   // VLD4LN
6737   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6738   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6739   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6740   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6741   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6742   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6743   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6744   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6745   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6746   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6747   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6748   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6749   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6750   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6751   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6752 
6753   // VLD4DUP
6754   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6755   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6756   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6757   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6758   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6759   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6760   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6761   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6762   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6763   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6764   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6765   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6766   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6767   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6768   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6769   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6770   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6771   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6772 
6773   // VLD4
6774   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6775   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6776   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6777   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6778   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6779   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6780   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6781   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6782   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6783   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6784   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6785   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6786   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6787   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6788   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6789   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6790   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6791   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6792   }
6793 }
6794 
6795 bool ARMAsmParser::processInstruction(MCInst &Inst,
6796                                       const OperandVector &Operands,
6797                                       MCStreamer &Out) {
6798   // Check if we have the wide qualifier, because if it's present we
6799   // must avoid selecting a 16-bit thumb instruction.
6800   bool HasWideQualifier = false;
6801   for (auto &Op : Operands) {
6802     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
6803     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
6804       HasWideQualifier = true;
6805       break;
6806     }
6807   }
6808 
6809   switch (Inst.getOpcode()) {
6810   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6811   case ARM::LDRT_POST:
6812   case ARM::LDRBT_POST: {
6813     const unsigned Opcode =
6814       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6815                                            : ARM::LDRBT_POST_IMM;
6816     MCInst TmpInst;
6817     TmpInst.setOpcode(Opcode);
6818     TmpInst.addOperand(Inst.getOperand(0));
6819     TmpInst.addOperand(Inst.getOperand(1));
6820     TmpInst.addOperand(Inst.getOperand(1));
6821     TmpInst.addOperand(MCOperand::createReg(0));
6822     TmpInst.addOperand(MCOperand::createImm(0));
6823     TmpInst.addOperand(Inst.getOperand(2));
6824     TmpInst.addOperand(Inst.getOperand(3));
6825     Inst = TmpInst;
6826     return true;
6827   }
6828   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6829   case ARM::STRT_POST:
6830   case ARM::STRBT_POST: {
6831     const unsigned Opcode =
6832       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6833                                            : ARM::STRBT_POST_IMM;
6834     MCInst TmpInst;
6835     TmpInst.setOpcode(Opcode);
6836     TmpInst.addOperand(Inst.getOperand(1));
6837     TmpInst.addOperand(Inst.getOperand(0));
6838     TmpInst.addOperand(Inst.getOperand(1));
6839     TmpInst.addOperand(MCOperand::createReg(0));
6840     TmpInst.addOperand(MCOperand::createImm(0));
6841     TmpInst.addOperand(Inst.getOperand(2));
6842     TmpInst.addOperand(Inst.getOperand(3));
6843     Inst = TmpInst;
6844     return true;
6845   }
6846   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6847   case ARM::ADDri: {
6848     if (Inst.getOperand(1).getReg() != ARM::PC ||
6849         Inst.getOperand(5).getReg() != 0 ||
6850         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6851       return false;
6852     MCInst TmpInst;
6853     TmpInst.setOpcode(ARM::ADR);
6854     TmpInst.addOperand(Inst.getOperand(0));
6855     if (Inst.getOperand(2).isImm()) {
6856       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6857       // before passing it to the ADR instruction.
6858       unsigned Enc = Inst.getOperand(2).getImm();
6859       TmpInst.addOperand(MCOperand::createImm(
6860         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6861     } else {
6862       // Turn PC-relative expression into absolute expression.
6863       // Reading PC provides the start of the current instruction + 8 and
6864       // the transform to adr is biased by that.
6865       MCSymbol *Dot = getContext().createTempSymbol();
6866       Out.EmitLabel(Dot);
6867       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6868       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6869                                                      MCSymbolRefExpr::VK_None,
6870                                                      getContext());
6871       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6872       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6873                                                      getContext());
6874       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6875                                                         getContext());
6876       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6877     }
6878     TmpInst.addOperand(Inst.getOperand(3));
6879     TmpInst.addOperand(Inst.getOperand(4));
6880     Inst = TmpInst;
6881     return true;
6882   }
6883   // Aliases for alternate PC+imm syntax of LDR instructions.
6884   case ARM::t2LDRpcrel:
6885     // Select the narrow version if the immediate will fit.
6886     if (Inst.getOperand(1).getImm() > 0 &&
6887         Inst.getOperand(1).getImm() <= 0xff &&
6888         !HasWideQualifier)
6889       Inst.setOpcode(ARM::tLDRpci);
6890     else
6891       Inst.setOpcode(ARM::t2LDRpci);
6892     return true;
6893   case ARM::t2LDRBpcrel:
6894     Inst.setOpcode(ARM::t2LDRBpci);
6895     return true;
6896   case ARM::t2LDRHpcrel:
6897     Inst.setOpcode(ARM::t2LDRHpci);
6898     return true;
6899   case ARM::t2LDRSBpcrel:
6900     Inst.setOpcode(ARM::t2LDRSBpci);
6901     return true;
6902   case ARM::t2LDRSHpcrel:
6903     Inst.setOpcode(ARM::t2LDRSHpci);
6904     return true;
6905   case ARM::LDRConstPool:
6906   case ARM::tLDRConstPool:
6907   case ARM::t2LDRConstPool: {
6908     // Pseudo instruction ldr rt, =immediate is converted to a
6909     // MOV rt, immediate if immediate is known and representable
6910     // otherwise we create a constant pool entry that we load from.
6911     MCInst TmpInst;
6912     if (Inst.getOpcode() == ARM::LDRConstPool)
6913       TmpInst.setOpcode(ARM::LDRi12);
6914     else if (Inst.getOpcode() == ARM::tLDRConstPool)
6915       TmpInst.setOpcode(ARM::tLDRpci);
6916     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
6917       TmpInst.setOpcode(ARM::t2LDRpci);
6918     const ARMOperand &PoolOperand =
6919       (HasWideQualifier ?
6920        static_cast<ARMOperand &>(*Operands[4]) :
6921        static_cast<ARMOperand &>(*Operands[3]));
6922     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
6923     // If SubExprVal is a constant we may be able to use a MOV
6924     if (isa<MCConstantExpr>(SubExprVal) &&
6925         Inst.getOperand(0).getReg() != ARM::PC &&
6926         Inst.getOperand(0).getReg() != ARM::SP) {
6927       int64_t Value =
6928         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
6929       bool UseMov  = true;
6930       bool MovHasS = true;
6931       if (Inst.getOpcode() == ARM::LDRConstPool) {
6932         // ARM Constant
6933         if (ARM_AM::getSOImmVal(Value) != -1) {
6934           Value = ARM_AM::getSOImmVal(Value);
6935           TmpInst.setOpcode(ARM::MOVi);
6936         }
6937         else if (ARM_AM::getSOImmVal(~Value) != -1) {
6938           Value = ARM_AM::getSOImmVal(~Value);
6939           TmpInst.setOpcode(ARM::MVNi);
6940         }
6941         else if (hasV6T2Ops() &&
6942                  Value >=0 && Value < 65536) {
6943           TmpInst.setOpcode(ARM::MOVi16);
6944           MovHasS = false;
6945         }
6946         else
6947           UseMov = false;
6948       }
6949       else {
6950         // Thumb/Thumb2 Constant
6951         if (hasThumb2() &&
6952             ARM_AM::getT2SOImmVal(Value) != -1)
6953           TmpInst.setOpcode(ARM::t2MOVi);
6954         else if (hasThumb2() &&
6955                  ARM_AM::getT2SOImmVal(~Value) != -1) {
6956           TmpInst.setOpcode(ARM::t2MVNi);
6957           Value = ~Value;
6958         }
6959         else if (hasV8MBaseline() &&
6960                  Value >=0 && Value < 65536) {
6961           TmpInst.setOpcode(ARM::t2MOVi16);
6962           MovHasS = false;
6963         }
6964         else
6965           UseMov = false;
6966       }
6967       if (UseMov) {
6968         TmpInst.addOperand(Inst.getOperand(0));           // Rt
6969         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
6970         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
6971         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
6972         if (MovHasS)
6973           TmpInst.addOperand(MCOperand::createReg(0));    // S
6974         Inst = TmpInst;
6975         return true;
6976       }
6977     }
6978     // No opportunity to use MOV/MVN create constant pool
6979     const MCExpr *CPLoc =
6980       getTargetStreamer().addConstantPoolEntry(SubExprVal,
6981                                                PoolOperand.getStartLoc());
6982     TmpInst.addOperand(Inst.getOperand(0));           // Rt
6983     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
6984     if (TmpInst.getOpcode() == ARM::LDRi12)
6985       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
6986     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
6987     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
6988     Inst = TmpInst;
6989     return true;
6990   }
6991   // Handle NEON VST complex aliases.
6992   case ARM::VST1LNdWB_register_Asm_8:
6993   case ARM::VST1LNdWB_register_Asm_16:
6994   case ARM::VST1LNdWB_register_Asm_32: {
6995     MCInst TmpInst;
6996     // Shuffle the operands around so the lane index operand is in the
6997     // right place.
6998     unsigned Spacing;
6999     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7000     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7001     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7002     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7003     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7004     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7005     TmpInst.addOperand(Inst.getOperand(1)); // lane
7006     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7007     TmpInst.addOperand(Inst.getOperand(6));
7008     Inst = TmpInst;
7009     return true;
7010   }
7011 
7012   case ARM::VST2LNdWB_register_Asm_8:
7013   case ARM::VST2LNdWB_register_Asm_16:
7014   case ARM::VST2LNdWB_register_Asm_32:
7015   case ARM::VST2LNqWB_register_Asm_16:
7016   case ARM::VST2LNqWB_register_Asm_32: {
7017     MCInst TmpInst;
7018     // Shuffle the operands around so the lane index operand is in the
7019     // right place.
7020     unsigned Spacing;
7021     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7022     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7023     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7024     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7025     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7026     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7027     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7028                                             Spacing));
7029     TmpInst.addOperand(Inst.getOperand(1)); // lane
7030     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7031     TmpInst.addOperand(Inst.getOperand(6));
7032     Inst = TmpInst;
7033     return true;
7034   }
7035 
7036   case ARM::VST3LNdWB_register_Asm_8:
7037   case ARM::VST3LNdWB_register_Asm_16:
7038   case ARM::VST3LNdWB_register_Asm_32:
7039   case ARM::VST3LNqWB_register_Asm_16:
7040   case ARM::VST3LNqWB_register_Asm_32: {
7041     MCInst TmpInst;
7042     // Shuffle the operands around so the lane index operand is in the
7043     // right place.
7044     unsigned Spacing;
7045     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7046     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7047     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7048     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7049     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7050     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7051     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7052                                             Spacing));
7053     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7054                                             Spacing * 2));
7055     TmpInst.addOperand(Inst.getOperand(1)); // lane
7056     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7057     TmpInst.addOperand(Inst.getOperand(6));
7058     Inst = TmpInst;
7059     return true;
7060   }
7061 
7062   case ARM::VST4LNdWB_register_Asm_8:
7063   case ARM::VST4LNdWB_register_Asm_16:
7064   case ARM::VST4LNdWB_register_Asm_32:
7065   case ARM::VST4LNqWB_register_Asm_16:
7066   case ARM::VST4LNqWB_register_Asm_32: {
7067     MCInst TmpInst;
7068     // Shuffle the operands around so the lane index operand is in the
7069     // right place.
7070     unsigned Spacing;
7071     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7072     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7073     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7074     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7075     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7076     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7077     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7078                                             Spacing));
7079     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7080                                             Spacing * 2));
7081     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7082                                             Spacing * 3));
7083     TmpInst.addOperand(Inst.getOperand(1)); // lane
7084     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7085     TmpInst.addOperand(Inst.getOperand(6));
7086     Inst = TmpInst;
7087     return true;
7088   }
7089 
7090   case ARM::VST1LNdWB_fixed_Asm_8:
7091   case ARM::VST1LNdWB_fixed_Asm_16:
7092   case ARM::VST1LNdWB_fixed_Asm_32: {
7093     MCInst TmpInst;
7094     // Shuffle the operands around so the lane index operand is in the
7095     // right place.
7096     unsigned Spacing;
7097     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7098     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7099     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7100     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7101     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7102     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7103     TmpInst.addOperand(Inst.getOperand(1)); // lane
7104     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7105     TmpInst.addOperand(Inst.getOperand(5));
7106     Inst = TmpInst;
7107     return true;
7108   }
7109 
7110   case ARM::VST2LNdWB_fixed_Asm_8:
7111   case ARM::VST2LNdWB_fixed_Asm_16:
7112   case ARM::VST2LNdWB_fixed_Asm_32:
7113   case ARM::VST2LNqWB_fixed_Asm_16:
7114   case ARM::VST2LNqWB_fixed_Asm_32: {
7115     MCInst TmpInst;
7116     // Shuffle the operands around so the lane index operand is in the
7117     // right place.
7118     unsigned Spacing;
7119     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7120     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7121     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7122     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7123     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7124     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7125     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7126                                             Spacing));
7127     TmpInst.addOperand(Inst.getOperand(1)); // lane
7128     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7129     TmpInst.addOperand(Inst.getOperand(5));
7130     Inst = TmpInst;
7131     return true;
7132   }
7133 
7134   case ARM::VST3LNdWB_fixed_Asm_8:
7135   case ARM::VST3LNdWB_fixed_Asm_16:
7136   case ARM::VST3LNdWB_fixed_Asm_32:
7137   case ARM::VST3LNqWB_fixed_Asm_16:
7138   case ARM::VST3LNqWB_fixed_Asm_32: {
7139     MCInst TmpInst;
7140     // Shuffle the operands around so the lane index operand is in the
7141     // right place.
7142     unsigned Spacing;
7143     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7144     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7145     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7146     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7147     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7148     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7149     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7150                                             Spacing));
7151     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7152                                             Spacing * 2));
7153     TmpInst.addOperand(Inst.getOperand(1)); // lane
7154     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7155     TmpInst.addOperand(Inst.getOperand(5));
7156     Inst = TmpInst;
7157     return true;
7158   }
7159 
7160   case ARM::VST4LNdWB_fixed_Asm_8:
7161   case ARM::VST4LNdWB_fixed_Asm_16:
7162   case ARM::VST4LNdWB_fixed_Asm_32:
7163   case ARM::VST4LNqWB_fixed_Asm_16:
7164   case ARM::VST4LNqWB_fixed_Asm_32: {
7165     MCInst TmpInst;
7166     // Shuffle the operands around so the lane index operand is in the
7167     // right place.
7168     unsigned Spacing;
7169     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7170     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7171     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7172     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7173     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7174     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7175     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7176                                             Spacing));
7177     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7178                                             Spacing * 2));
7179     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7180                                             Spacing * 3));
7181     TmpInst.addOperand(Inst.getOperand(1)); // lane
7182     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7183     TmpInst.addOperand(Inst.getOperand(5));
7184     Inst = TmpInst;
7185     return true;
7186   }
7187 
7188   case ARM::VST1LNdAsm_8:
7189   case ARM::VST1LNdAsm_16:
7190   case ARM::VST1LNdAsm_32: {
7191     MCInst TmpInst;
7192     // Shuffle the operands around so the lane index operand is in the
7193     // right place.
7194     unsigned Spacing;
7195     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7196     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7197     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7198     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7199     TmpInst.addOperand(Inst.getOperand(1)); // lane
7200     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7201     TmpInst.addOperand(Inst.getOperand(5));
7202     Inst = TmpInst;
7203     return true;
7204   }
7205 
7206   case ARM::VST2LNdAsm_8:
7207   case ARM::VST2LNdAsm_16:
7208   case ARM::VST2LNdAsm_32:
7209   case ARM::VST2LNqAsm_16:
7210   case ARM::VST2LNqAsm_32: {
7211     MCInst TmpInst;
7212     // Shuffle the operands around so the lane index operand is in the
7213     // right place.
7214     unsigned Spacing;
7215     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7216     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7217     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7218     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7219     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7220                                             Spacing));
7221     TmpInst.addOperand(Inst.getOperand(1)); // lane
7222     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7223     TmpInst.addOperand(Inst.getOperand(5));
7224     Inst = TmpInst;
7225     return true;
7226   }
7227 
7228   case ARM::VST3LNdAsm_8:
7229   case ARM::VST3LNdAsm_16:
7230   case ARM::VST3LNdAsm_32:
7231   case ARM::VST3LNqAsm_16:
7232   case ARM::VST3LNqAsm_32: {
7233     MCInst TmpInst;
7234     // Shuffle the operands around so the lane index operand is in the
7235     // right place.
7236     unsigned Spacing;
7237     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7238     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7239     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7240     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7241     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7242                                             Spacing));
7243     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7244                                             Spacing * 2));
7245     TmpInst.addOperand(Inst.getOperand(1)); // lane
7246     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7247     TmpInst.addOperand(Inst.getOperand(5));
7248     Inst = TmpInst;
7249     return true;
7250   }
7251 
7252   case ARM::VST4LNdAsm_8:
7253   case ARM::VST4LNdAsm_16:
7254   case ARM::VST4LNdAsm_32:
7255   case ARM::VST4LNqAsm_16:
7256   case ARM::VST4LNqAsm_32: {
7257     MCInst TmpInst;
7258     // Shuffle the operands around so the lane index operand is in the
7259     // right place.
7260     unsigned Spacing;
7261     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7262     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7263     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7264     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7265     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7266                                             Spacing));
7267     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7268                                             Spacing * 2));
7269     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7270                                             Spacing * 3));
7271     TmpInst.addOperand(Inst.getOperand(1)); // lane
7272     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7273     TmpInst.addOperand(Inst.getOperand(5));
7274     Inst = TmpInst;
7275     return true;
7276   }
7277 
7278   // Handle NEON VLD complex aliases.
7279   case ARM::VLD1LNdWB_register_Asm_8:
7280   case ARM::VLD1LNdWB_register_Asm_16:
7281   case ARM::VLD1LNdWB_register_Asm_32: {
7282     MCInst TmpInst;
7283     // Shuffle the operands around so the lane index operand is in the
7284     // right place.
7285     unsigned Spacing;
7286     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7287     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7288     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7289     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7290     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7291     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7292     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7293     TmpInst.addOperand(Inst.getOperand(1)); // lane
7294     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7295     TmpInst.addOperand(Inst.getOperand(6));
7296     Inst = TmpInst;
7297     return true;
7298   }
7299 
7300   case ARM::VLD2LNdWB_register_Asm_8:
7301   case ARM::VLD2LNdWB_register_Asm_16:
7302   case ARM::VLD2LNdWB_register_Asm_32:
7303   case ARM::VLD2LNqWB_register_Asm_16:
7304   case ARM::VLD2LNqWB_register_Asm_32: {
7305     MCInst TmpInst;
7306     // Shuffle the operands around so the lane index operand is in the
7307     // right place.
7308     unsigned Spacing;
7309     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7310     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7311     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7312                                             Spacing));
7313     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7314     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7315     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7316     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7317     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7318     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7319                                             Spacing));
7320     TmpInst.addOperand(Inst.getOperand(1)); // lane
7321     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7322     TmpInst.addOperand(Inst.getOperand(6));
7323     Inst = TmpInst;
7324     return true;
7325   }
7326 
7327   case ARM::VLD3LNdWB_register_Asm_8:
7328   case ARM::VLD3LNdWB_register_Asm_16:
7329   case ARM::VLD3LNdWB_register_Asm_32:
7330   case ARM::VLD3LNqWB_register_Asm_16:
7331   case ARM::VLD3LNqWB_register_Asm_32: {
7332     MCInst TmpInst;
7333     // Shuffle the operands around so the lane index operand is in the
7334     // right place.
7335     unsigned Spacing;
7336     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7337     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7338     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7339                                             Spacing));
7340     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7341                                             Spacing * 2));
7342     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7343     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7344     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7345     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7346     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7347     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7348                                             Spacing));
7349     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7350                                             Spacing * 2));
7351     TmpInst.addOperand(Inst.getOperand(1)); // lane
7352     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7353     TmpInst.addOperand(Inst.getOperand(6));
7354     Inst = TmpInst;
7355     return true;
7356   }
7357 
7358   case ARM::VLD4LNdWB_register_Asm_8:
7359   case ARM::VLD4LNdWB_register_Asm_16:
7360   case ARM::VLD4LNdWB_register_Asm_32:
7361   case ARM::VLD4LNqWB_register_Asm_16:
7362   case ARM::VLD4LNqWB_register_Asm_32: {
7363     MCInst TmpInst;
7364     // Shuffle the operands around so the lane index operand is in the
7365     // right place.
7366     unsigned Spacing;
7367     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7368     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7369     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7370                                             Spacing));
7371     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7372                                             Spacing * 2));
7373     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7374                                             Spacing * 3));
7375     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7376     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7377     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7378     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7379     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7380     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7381                                             Spacing));
7382     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7383                                             Spacing * 2));
7384     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7385                                             Spacing * 3));
7386     TmpInst.addOperand(Inst.getOperand(1)); // lane
7387     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7388     TmpInst.addOperand(Inst.getOperand(6));
7389     Inst = TmpInst;
7390     return true;
7391   }
7392 
7393   case ARM::VLD1LNdWB_fixed_Asm_8:
7394   case ARM::VLD1LNdWB_fixed_Asm_16:
7395   case ARM::VLD1LNdWB_fixed_Asm_32: {
7396     MCInst TmpInst;
7397     // Shuffle the operands around so the lane index operand is in the
7398     // right place.
7399     unsigned Spacing;
7400     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7401     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7402     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7403     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7404     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7405     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7406     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7407     TmpInst.addOperand(Inst.getOperand(1)); // lane
7408     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7409     TmpInst.addOperand(Inst.getOperand(5));
7410     Inst = TmpInst;
7411     return true;
7412   }
7413 
7414   case ARM::VLD2LNdWB_fixed_Asm_8:
7415   case ARM::VLD2LNdWB_fixed_Asm_16:
7416   case ARM::VLD2LNdWB_fixed_Asm_32:
7417   case ARM::VLD2LNqWB_fixed_Asm_16:
7418   case ARM::VLD2LNqWB_fixed_Asm_32: {
7419     MCInst TmpInst;
7420     // Shuffle the operands around so the lane index operand is in the
7421     // right place.
7422     unsigned Spacing;
7423     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7424     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7425     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7426                                             Spacing));
7427     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7428     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7429     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7430     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7431     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7432     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7433                                             Spacing));
7434     TmpInst.addOperand(Inst.getOperand(1)); // lane
7435     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7436     TmpInst.addOperand(Inst.getOperand(5));
7437     Inst = TmpInst;
7438     return true;
7439   }
7440 
7441   case ARM::VLD3LNdWB_fixed_Asm_8:
7442   case ARM::VLD3LNdWB_fixed_Asm_16:
7443   case ARM::VLD3LNdWB_fixed_Asm_32:
7444   case ARM::VLD3LNqWB_fixed_Asm_16:
7445   case ARM::VLD3LNqWB_fixed_Asm_32: {
7446     MCInst TmpInst;
7447     // Shuffle the operands around so the lane index operand is in the
7448     // right place.
7449     unsigned Spacing;
7450     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7451     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7452     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7453                                             Spacing));
7454     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7455                                             Spacing * 2));
7456     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7457     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7458     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7459     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7460     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7461     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7462                                             Spacing));
7463     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7464                                             Spacing * 2));
7465     TmpInst.addOperand(Inst.getOperand(1)); // lane
7466     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7467     TmpInst.addOperand(Inst.getOperand(5));
7468     Inst = TmpInst;
7469     return true;
7470   }
7471 
7472   case ARM::VLD4LNdWB_fixed_Asm_8:
7473   case ARM::VLD4LNdWB_fixed_Asm_16:
7474   case ARM::VLD4LNdWB_fixed_Asm_32:
7475   case ARM::VLD4LNqWB_fixed_Asm_16:
7476   case ARM::VLD4LNqWB_fixed_Asm_32: {
7477     MCInst TmpInst;
7478     // Shuffle the operands around so the lane index operand is in the
7479     // right place.
7480     unsigned Spacing;
7481     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
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(2)); // Rn_wb
7490     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7491     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7492     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7493     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7494     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7495                                             Spacing));
7496     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7497                                             Spacing * 2));
7498     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7499                                             Spacing * 3));
7500     TmpInst.addOperand(Inst.getOperand(1)); // lane
7501     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7502     TmpInst.addOperand(Inst.getOperand(5));
7503     Inst = TmpInst;
7504     return true;
7505   }
7506 
7507   case ARM::VLD1LNdAsm_8:
7508   case ARM::VLD1LNdAsm_16:
7509   case ARM::VLD1LNdAsm_32: {
7510     MCInst TmpInst;
7511     // Shuffle the operands around so the lane index operand is in the
7512     // right place.
7513     unsigned Spacing;
7514     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7515     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7516     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7517     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7518     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7519     TmpInst.addOperand(Inst.getOperand(1)); // lane
7520     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7521     TmpInst.addOperand(Inst.getOperand(5));
7522     Inst = TmpInst;
7523     return true;
7524   }
7525 
7526   case ARM::VLD2LNdAsm_8:
7527   case ARM::VLD2LNdAsm_16:
7528   case ARM::VLD2LNdAsm_32:
7529   case ARM::VLD2LNqAsm_16:
7530   case ARM::VLD2LNqAsm_32: {
7531     MCInst TmpInst;
7532     // Shuffle the operands around so the lane index operand is in the
7533     // right place.
7534     unsigned Spacing;
7535     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7536     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7537     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7538                                             Spacing));
7539     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7540     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7541     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7542     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7543                                             Spacing));
7544     TmpInst.addOperand(Inst.getOperand(1)); // lane
7545     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7546     TmpInst.addOperand(Inst.getOperand(5));
7547     Inst = TmpInst;
7548     return true;
7549   }
7550 
7551   case ARM::VLD3LNdAsm_8:
7552   case ARM::VLD3LNdAsm_16:
7553   case ARM::VLD3LNdAsm_32:
7554   case ARM::VLD3LNqAsm_16:
7555   case ARM::VLD3LNqAsm_32: {
7556     MCInst TmpInst;
7557     // Shuffle the operands around so the lane index operand is in the
7558     // right place.
7559     unsigned Spacing;
7560     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7561     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7562     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7563                                             Spacing));
7564     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7565                                             Spacing * 2));
7566     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7567     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7568     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7569     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7570                                             Spacing));
7571     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7572                                             Spacing * 2));
7573     TmpInst.addOperand(Inst.getOperand(1)); // lane
7574     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7575     TmpInst.addOperand(Inst.getOperand(5));
7576     Inst = TmpInst;
7577     return true;
7578   }
7579 
7580   case ARM::VLD4LNdAsm_8:
7581   case ARM::VLD4LNdAsm_16:
7582   case ARM::VLD4LNdAsm_32:
7583   case ARM::VLD4LNqAsm_16:
7584   case ARM::VLD4LNqAsm_32: {
7585     MCInst TmpInst;
7586     // Shuffle the operands around so the lane index operand is in the
7587     // right place.
7588     unsigned Spacing;
7589     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7590     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7591     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7592                                             Spacing));
7593     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7594                                             Spacing * 2));
7595     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7596                                             Spacing * 3));
7597     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7598     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7599     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7600     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7601                                             Spacing));
7602     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7603                                             Spacing * 2));
7604     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7605                                             Spacing * 3));
7606     TmpInst.addOperand(Inst.getOperand(1)); // lane
7607     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7608     TmpInst.addOperand(Inst.getOperand(5));
7609     Inst = TmpInst;
7610     return true;
7611   }
7612 
7613   // VLD3DUP single 3-element structure to all lanes instructions.
7614   case ARM::VLD3DUPdAsm_8:
7615   case ARM::VLD3DUPdAsm_16:
7616   case ARM::VLD3DUPdAsm_32:
7617   case ARM::VLD3DUPqAsm_8:
7618   case ARM::VLD3DUPqAsm_16:
7619   case ARM::VLD3DUPqAsm_32: {
7620     MCInst TmpInst;
7621     unsigned Spacing;
7622     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7623     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7624     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7625                                             Spacing));
7626     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7627                                             Spacing * 2));
7628     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7629     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7630     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7631     TmpInst.addOperand(Inst.getOperand(4));
7632     Inst = TmpInst;
7633     return true;
7634   }
7635 
7636   case ARM::VLD3DUPdWB_fixed_Asm_8:
7637   case ARM::VLD3DUPdWB_fixed_Asm_16:
7638   case ARM::VLD3DUPdWB_fixed_Asm_32:
7639   case ARM::VLD3DUPqWB_fixed_Asm_8:
7640   case ARM::VLD3DUPqWB_fixed_Asm_16:
7641   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7642     MCInst TmpInst;
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(1)); // Rn
7651     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7652     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7653     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7654     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7655     TmpInst.addOperand(Inst.getOperand(4));
7656     Inst = TmpInst;
7657     return true;
7658   }
7659 
7660   case ARM::VLD3DUPdWB_register_Asm_8:
7661   case ARM::VLD3DUPdWB_register_Asm_16:
7662   case ARM::VLD3DUPdWB_register_Asm_32:
7663   case ARM::VLD3DUPqWB_register_Asm_8:
7664   case ARM::VLD3DUPqWB_register_Asm_16:
7665   case ARM::VLD3DUPqWB_register_Asm_32: {
7666     MCInst TmpInst;
7667     unsigned Spacing;
7668     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7669     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7670     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7671                                             Spacing));
7672     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7673                                             Spacing * 2));
7674     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7675     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7676     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7677     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7678     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7679     TmpInst.addOperand(Inst.getOperand(5));
7680     Inst = TmpInst;
7681     return true;
7682   }
7683 
7684   // VLD3 multiple 3-element structure instructions.
7685   case ARM::VLD3dAsm_8:
7686   case ARM::VLD3dAsm_16:
7687   case ARM::VLD3dAsm_32:
7688   case ARM::VLD3qAsm_8:
7689   case ARM::VLD3qAsm_16:
7690   case ARM::VLD3qAsm_32: {
7691     MCInst TmpInst;
7692     unsigned Spacing;
7693     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7694     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7695     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7696                                             Spacing));
7697     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7698                                             Spacing * 2));
7699     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7700     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7701     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7702     TmpInst.addOperand(Inst.getOperand(4));
7703     Inst = TmpInst;
7704     return true;
7705   }
7706 
7707   case ARM::VLD3dWB_fixed_Asm_8:
7708   case ARM::VLD3dWB_fixed_Asm_16:
7709   case ARM::VLD3dWB_fixed_Asm_32:
7710   case ARM::VLD3qWB_fixed_Asm_8:
7711   case ARM::VLD3qWB_fixed_Asm_16:
7712   case ARM::VLD3qWB_fixed_Asm_32: {
7713     MCInst TmpInst;
7714     unsigned Spacing;
7715     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7716     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7717     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7718                                             Spacing));
7719     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7720                                             Spacing * 2));
7721     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7722     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7723     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7724     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7725     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7726     TmpInst.addOperand(Inst.getOperand(4));
7727     Inst = TmpInst;
7728     return true;
7729   }
7730 
7731   case ARM::VLD3dWB_register_Asm_8:
7732   case ARM::VLD3dWB_register_Asm_16:
7733   case ARM::VLD3dWB_register_Asm_32:
7734   case ARM::VLD3qWB_register_Asm_8:
7735   case ARM::VLD3qWB_register_Asm_16:
7736   case ARM::VLD3qWB_register_Asm_32: {
7737     MCInst TmpInst;
7738     unsigned Spacing;
7739     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7740     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7741     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7742                                             Spacing));
7743     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7744                                             Spacing * 2));
7745     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7746     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7747     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7748     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7749     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7750     TmpInst.addOperand(Inst.getOperand(5));
7751     Inst = TmpInst;
7752     return true;
7753   }
7754 
7755   // VLD4DUP single 3-element structure to all lanes instructions.
7756   case ARM::VLD4DUPdAsm_8:
7757   case ARM::VLD4DUPdAsm_16:
7758   case ARM::VLD4DUPdAsm_32:
7759   case ARM::VLD4DUPqAsm_8:
7760   case ARM::VLD4DUPqAsm_16:
7761   case ARM::VLD4DUPqAsm_32: {
7762     MCInst TmpInst;
7763     unsigned Spacing;
7764     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7765     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7766     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7767                                             Spacing));
7768     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7769                                             Spacing * 2));
7770     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7771                                             Spacing * 3));
7772     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7773     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7774     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7775     TmpInst.addOperand(Inst.getOperand(4));
7776     Inst = TmpInst;
7777     return true;
7778   }
7779 
7780   case ARM::VLD4DUPdWB_fixed_Asm_8:
7781   case ARM::VLD4DUPdWB_fixed_Asm_16:
7782   case ARM::VLD4DUPdWB_fixed_Asm_32:
7783   case ARM::VLD4DUPqWB_fixed_Asm_8:
7784   case ARM::VLD4DUPqWB_fixed_Asm_16:
7785   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7786     MCInst TmpInst;
7787     unsigned Spacing;
7788     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7789     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7790     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7791                                             Spacing));
7792     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7793                                             Spacing * 2));
7794     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7795                                             Spacing * 3));
7796     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7797     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7798     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7799     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7800     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7801     TmpInst.addOperand(Inst.getOperand(4));
7802     Inst = TmpInst;
7803     return true;
7804   }
7805 
7806   case ARM::VLD4DUPdWB_register_Asm_8:
7807   case ARM::VLD4DUPdWB_register_Asm_16:
7808   case ARM::VLD4DUPdWB_register_Asm_32:
7809   case ARM::VLD4DUPqWB_register_Asm_8:
7810   case ARM::VLD4DUPqWB_register_Asm_16:
7811   case ARM::VLD4DUPqWB_register_Asm_32: {
7812     MCInst TmpInst;
7813     unsigned Spacing;
7814     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7815     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7816     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7817                                             Spacing));
7818     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7819                                             Spacing * 2));
7820     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7821                                             Spacing * 3));
7822     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7823     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7824     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7825     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7826     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7827     TmpInst.addOperand(Inst.getOperand(5));
7828     Inst = TmpInst;
7829     return true;
7830   }
7831 
7832   // VLD4 multiple 4-element structure instructions.
7833   case ARM::VLD4dAsm_8:
7834   case ARM::VLD4dAsm_16:
7835   case ARM::VLD4dAsm_32:
7836   case ARM::VLD4qAsm_8:
7837   case ARM::VLD4qAsm_16:
7838   case ARM::VLD4qAsm_32: {
7839     MCInst TmpInst;
7840     unsigned Spacing;
7841     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7842     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7843     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7844                                             Spacing));
7845     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7846                                             Spacing * 2));
7847     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7848                                             Spacing * 3));
7849     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7850     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7851     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7852     TmpInst.addOperand(Inst.getOperand(4));
7853     Inst = TmpInst;
7854     return true;
7855   }
7856 
7857   case ARM::VLD4dWB_fixed_Asm_8:
7858   case ARM::VLD4dWB_fixed_Asm_16:
7859   case ARM::VLD4dWB_fixed_Asm_32:
7860   case ARM::VLD4qWB_fixed_Asm_8:
7861   case ARM::VLD4qWB_fixed_Asm_16:
7862   case ARM::VLD4qWB_fixed_Asm_32: {
7863     MCInst TmpInst;
7864     unsigned Spacing;
7865     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7866     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7867     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7868                                             Spacing));
7869     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7870                                             Spacing * 2));
7871     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7872                                             Spacing * 3));
7873     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7874     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7875     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7876     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7877     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7878     TmpInst.addOperand(Inst.getOperand(4));
7879     Inst = TmpInst;
7880     return true;
7881   }
7882 
7883   case ARM::VLD4dWB_register_Asm_8:
7884   case ARM::VLD4dWB_register_Asm_16:
7885   case ARM::VLD4dWB_register_Asm_32:
7886   case ARM::VLD4qWB_register_Asm_8:
7887   case ARM::VLD4qWB_register_Asm_16:
7888   case ARM::VLD4qWB_register_Asm_32: {
7889     MCInst TmpInst;
7890     unsigned Spacing;
7891     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7892     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7893     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7894                                             Spacing));
7895     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7896                                             Spacing * 2));
7897     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7898                                             Spacing * 3));
7899     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7900     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7901     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7902     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7903     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7904     TmpInst.addOperand(Inst.getOperand(5));
7905     Inst = TmpInst;
7906     return true;
7907   }
7908 
7909   // VST3 multiple 3-element structure instructions.
7910   case ARM::VST3dAsm_8:
7911   case ARM::VST3dAsm_16:
7912   case ARM::VST3dAsm_32:
7913   case ARM::VST3qAsm_8:
7914   case ARM::VST3qAsm_16:
7915   case ARM::VST3qAsm_32: {
7916     MCInst TmpInst;
7917     unsigned Spacing;
7918     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7919     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7920     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7921     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7922     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7923                                             Spacing));
7924     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7925                                             Spacing * 2));
7926     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7927     TmpInst.addOperand(Inst.getOperand(4));
7928     Inst = TmpInst;
7929     return true;
7930   }
7931 
7932   case ARM::VST3dWB_fixed_Asm_8:
7933   case ARM::VST3dWB_fixed_Asm_16:
7934   case ARM::VST3dWB_fixed_Asm_32:
7935   case ARM::VST3qWB_fixed_Asm_8:
7936   case ARM::VST3qWB_fixed_Asm_16:
7937   case ARM::VST3qWB_fixed_Asm_32: {
7938     MCInst TmpInst;
7939     unsigned Spacing;
7940     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7941     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7942     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7943     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7944     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7945     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7946     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7947                                             Spacing));
7948     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7949                                             Spacing * 2));
7950     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7951     TmpInst.addOperand(Inst.getOperand(4));
7952     Inst = TmpInst;
7953     return true;
7954   }
7955 
7956   case ARM::VST3dWB_register_Asm_8:
7957   case ARM::VST3dWB_register_Asm_16:
7958   case ARM::VST3dWB_register_Asm_32:
7959   case ARM::VST3qWB_register_Asm_8:
7960   case ARM::VST3qWB_register_Asm_16:
7961   case ARM::VST3qWB_register_Asm_32: {
7962     MCInst TmpInst;
7963     unsigned Spacing;
7964     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7965     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7966     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7967     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7968     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7969     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7970     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7971                                             Spacing));
7972     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7973                                             Spacing * 2));
7974     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7975     TmpInst.addOperand(Inst.getOperand(5));
7976     Inst = TmpInst;
7977     return true;
7978   }
7979 
7980   // VST4 multiple 3-element structure instructions.
7981   case ARM::VST4dAsm_8:
7982   case ARM::VST4dAsm_16:
7983   case ARM::VST4dAsm_32:
7984   case ARM::VST4qAsm_8:
7985   case ARM::VST4qAsm_16:
7986   case ARM::VST4qAsm_32: {
7987     MCInst TmpInst;
7988     unsigned Spacing;
7989     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7990     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7991     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7992     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7993     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7994                                             Spacing));
7995     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7996                                             Spacing * 2));
7997     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7998                                             Spacing * 3));
7999     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8000     TmpInst.addOperand(Inst.getOperand(4));
8001     Inst = TmpInst;
8002     return true;
8003   }
8004 
8005   case ARM::VST4dWB_fixed_Asm_8:
8006   case ARM::VST4dWB_fixed_Asm_16:
8007   case ARM::VST4dWB_fixed_Asm_32:
8008   case ARM::VST4qWB_fixed_Asm_8:
8009   case ARM::VST4qWB_fixed_Asm_16:
8010   case ARM::VST4qWB_fixed_Asm_32: {
8011     MCInst TmpInst;
8012     unsigned Spacing;
8013     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8014     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8015     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8016     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8017     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8018     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8019     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8020                                             Spacing));
8021     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8022                                             Spacing * 2));
8023     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8024                                             Spacing * 3));
8025     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8026     TmpInst.addOperand(Inst.getOperand(4));
8027     Inst = TmpInst;
8028     return true;
8029   }
8030 
8031   case ARM::VST4dWB_register_Asm_8:
8032   case ARM::VST4dWB_register_Asm_16:
8033   case ARM::VST4dWB_register_Asm_32:
8034   case ARM::VST4qWB_register_Asm_8:
8035   case ARM::VST4qWB_register_Asm_16:
8036   case ARM::VST4qWB_register_Asm_32: {
8037     MCInst TmpInst;
8038     unsigned Spacing;
8039     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8040     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8041     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8042     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8043     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8044     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8045     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8046                                             Spacing));
8047     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8048                                             Spacing * 2));
8049     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8050                                             Spacing * 3));
8051     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8052     TmpInst.addOperand(Inst.getOperand(5));
8053     Inst = TmpInst;
8054     return true;
8055   }
8056 
8057   // Handle encoding choice for the shift-immediate instructions.
8058   case ARM::t2LSLri:
8059   case ARM::t2LSRri:
8060   case ARM::t2ASRri: {
8061     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8062         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8063         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8064         !HasWideQualifier) {
8065       unsigned NewOpc;
8066       switch (Inst.getOpcode()) {
8067       default: llvm_unreachable("unexpected opcode");
8068       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8069       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8070       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8071       }
8072       // The Thumb1 operands aren't in the same order. Awesome, eh?
8073       MCInst TmpInst;
8074       TmpInst.setOpcode(NewOpc);
8075       TmpInst.addOperand(Inst.getOperand(0));
8076       TmpInst.addOperand(Inst.getOperand(5));
8077       TmpInst.addOperand(Inst.getOperand(1));
8078       TmpInst.addOperand(Inst.getOperand(2));
8079       TmpInst.addOperand(Inst.getOperand(3));
8080       TmpInst.addOperand(Inst.getOperand(4));
8081       Inst = TmpInst;
8082       return true;
8083     }
8084     return false;
8085   }
8086 
8087   // Handle the Thumb2 mode MOV complex aliases.
8088   case ARM::t2MOVsr:
8089   case ARM::t2MOVSsr: {
8090     // Which instruction to expand to depends on the CCOut operand and
8091     // whether we're in an IT block if the register operands are low
8092     // registers.
8093     bool isNarrow = false;
8094     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8095         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8096         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8097         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8098         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8099         !HasWideQualifier)
8100       isNarrow = true;
8101     MCInst TmpInst;
8102     unsigned newOpc;
8103     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8104     default: llvm_unreachable("unexpected opcode!");
8105     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8106     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8107     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8108     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8109     }
8110     TmpInst.setOpcode(newOpc);
8111     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8112     if (isNarrow)
8113       TmpInst.addOperand(MCOperand::createReg(
8114           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8115     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8116     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8117     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8118     TmpInst.addOperand(Inst.getOperand(5));
8119     if (!isNarrow)
8120       TmpInst.addOperand(MCOperand::createReg(
8121           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8122     Inst = TmpInst;
8123     return true;
8124   }
8125   case ARM::t2MOVsi:
8126   case ARM::t2MOVSsi: {
8127     // Which instruction to expand to depends on the CCOut operand and
8128     // whether we're in an IT block if the register operands are low
8129     // registers.
8130     bool isNarrow = false;
8131     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8132         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8133         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8134         !HasWideQualifier)
8135       isNarrow = true;
8136     MCInst TmpInst;
8137     unsigned newOpc;
8138     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8139     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8140     bool isMov = false;
8141     // MOV rd, rm, LSL #0 is actually a MOV instruction
8142     if (Shift == ARM_AM::lsl && Amount == 0) {
8143       isMov = true;
8144       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8145       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8146       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8147       // instead.
8148       if (inITBlock()) {
8149         isNarrow = false;
8150       }
8151       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8152     } else {
8153       switch(Shift) {
8154       default: llvm_unreachable("unexpected opcode!");
8155       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8156       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8157       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8158       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8159       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8160       }
8161     }
8162     if (Amount == 32) Amount = 0;
8163     TmpInst.setOpcode(newOpc);
8164     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8165     if (isNarrow && !isMov)
8166       TmpInst.addOperand(MCOperand::createReg(
8167           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8168     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8169     if (newOpc != ARM::t2RRX && !isMov)
8170       TmpInst.addOperand(MCOperand::createImm(Amount));
8171     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8172     TmpInst.addOperand(Inst.getOperand(4));
8173     if (!isNarrow)
8174       TmpInst.addOperand(MCOperand::createReg(
8175           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8176     Inst = TmpInst;
8177     return true;
8178   }
8179   // Handle the ARM mode MOV complex aliases.
8180   case ARM::ASRr:
8181   case ARM::LSRr:
8182   case ARM::LSLr:
8183   case ARM::RORr: {
8184     ARM_AM::ShiftOpc ShiftTy;
8185     switch(Inst.getOpcode()) {
8186     default: llvm_unreachable("unexpected opcode!");
8187     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8188     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8189     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8190     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8191     }
8192     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8193     MCInst TmpInst;
8194     TmpInst.setOpcode(ARM::MOVsr);
8195     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8196     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8197     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8198     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8199     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8200     TmpInst.addOperand(Inst.getOperand(4));
8201     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8202     Inst = TmpInst;
8203     return true;
8204   }
8205   case ARM::ASRi:
8206   case ARM::LSRi:
8207   case ARM::LSLi:
8208   case ARM::RORi: {
8209     ARM_AM::ShiftOpc ShiftTy;
8210     switch(Inst.getOpcode()) {
8211     default: llvm_unreachable("unexpected opcode!");
8212     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8213     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8214     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8215     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8216     }
8217     // A shift by zero is a plain MOVr, not a MOVsi.
8218     unsigned Amt = Inst.getOperand(2).getImm();
8219     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8220     // A shift by 32 should be encoded as 0 when permitted
8221     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8222       Amt = 0;
8223     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8224     MCInst TmpInst;
8225     TmpInst.setOpcode(Opc);
8226     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8227     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8228     if (Opc == ARM::MOVsi)
8229       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8230     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8231     TmpInst.addOperand(Inst.getOperand(4));
8232     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8233     Inst = TmpInst;
8234     return true;
8235   }
8236   case ARM::RRXi: {
8237     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8238     MCInst TmpInst;
8239     TmpInst.setOpcode(ARM::MOVsi);
8240     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8241     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8242     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8243     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8244     TmpInst.addOperand(Inst.getOperand(3));
8245     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8246     Inst = TmpInst;
8247     return true;
8248   }
8249   case ARM::t2LDMIA_UPD: {
8250     // If this is a load of a single register, then we should use
8251     // a post-indexed LDR instruction instead, per the ARM ARM.
8252     if (Inst.getNumOperands() != 5)
8253       return false;
8254     MCInst TmpInst;
8255     TmpInst.setOpcode(ARM::t2LDR_POST);
8256     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8257     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8258     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8259     TmpInst.addOperand(MCOperand::createImm(4));
8260     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8261     TmpInst.addOperand(Inst.getOperand(3));
8262     Inst = TmpInst;
8263     return true;
8264   }
8265   case ARM::t2STMDB_UPD: {
8266     // If this is a store of a single register, then we should use
8267     // a pre-indexed STR instruction instead, per the ARM ARM.
8268     if (Inst.getNumOperands() != 5)
8269       return false;
8270     MCInst TmpInst;
8271     TmpInst.setOpcode(ARM::t2STR_PRE);
8272     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8273     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8274     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8275     TmpInst.addOperand(MCOperand::createImm(-4));
8276     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8277     TmpInst.addOperand(Inst.getOperand(3));
8278     Inst = TmpInst;
8279     return true;
8280   }
8281   case ARM::LDMIA_UPD:
8282     // If this is a load of a single register via a 'pop', then we should use
8283     // a post-indexed LDR instruction instead, per the ARM ARM.
8284     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8285         Inst.getNumOperands() == 5) {
8286       MCInst TmpInst;
8287       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8288       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8289       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8290       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8291       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8292       TmpInst.addOperand(MCOperand::createImm(4));
8293       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8294       TmpInst.addOperand(Inst.getOperand(3));
8295       Inst = TmpInst;
8296       return true;
8297     }
8298     break;
8299   case ARM::STMDB_UPD:
8300     // If this is a store of a single register via a 'push', then we should use
8301     // a pre-indexed STR instruction instead, per the ARM ARM.
8302     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8303         Inst.getNumOperands() == 5) {
8304       MCInst TmpInst;
8305       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8306       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8307       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8308       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8309       TmpInst.addOperand(MCOperand::createImm(-4));
8310       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8311       TmpInst.addOperand(Inst.getOperand(3));
8312       Inst = TmpInst;
8313     }
8314     break;
8315   case ARM::t2ADDri12:
8316     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8317     // mnemonic was used (not "addw"), encoding T3 is preferred.
8318     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8319         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8320       break;
8321     Inst.setOpcode(ARM::t2ADDri);
8322     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8323     break;
8324   case ARM::t2SUBri12:
8325     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8326     // mnemonic was used (not "subw"), encoding T3 is preferred.
8327     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8328         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8329       break;
8330     Inst.setOpcode(ARM::t2SUBri);
8331     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8332     break;
8333   case ARM::tADDi8:
8334     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8335     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8336     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8337     // to encoding T1 if <Rd> is omitted."
8338     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8339       Inst.setOpcode(ARM::tADDi3);
8340       return true;
8341     }
8342     break;
8343   case ARM::tSUBi8:
8344     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8345     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8346     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8347     // to encoding T1 if <Rd> is omitted."
8348     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8349       Inst.setOpcode(ARM::tSUBi3);
8350       return true;
8351     }
8352     break;
8353   case ARM::t2ADDri:
8354   case ARM::t2SUBri: {
8355     // If the destination and first source operand are the same, and
8356     // the flags are compatible with the current IT status, use encoding T2
8357     // instead of T3. For compatibility with the system 'as'. Make sure the
8358     // wide encoding wasn't explicit.
8359     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8360         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8361         (Inst.getOperand(2).isImm() &&
8362          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8363         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8364         HasWideQualifier)
8365       break;
8366     MCInst TmpInst;
8367     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8368                       ARM::tADDi8 : ARM::tSUBi8);
8369     TmpInst.addOperand(Inst.getOperand(0));
8370     TmpInst.addOperand(Inst.getOperand(5));
8371     TmpInst.addOperand(Inst.getOperand(0));
8372     TmpInst.addOperand(Inst.getOperand(2));
8373     TmpInst.addOperand(Inst.getOperand(3));
8374     TmpInst.addOperand(Inst.getOperand(4));
8375     Inst = TmpInst;
8376     return true;
8377   }
8378   case ARM::t2ADDrr: {
8379     // If the destination and first source operand are the same, and
8380     // there's no setting of the flags, use encoding T2 instead of T3.
8381     // Note that this is only for ADD, not SUB. This mirrors the system
8382     // 'as' behaviour.  Also take advantage of ADD being commutative.
8383     // Make sure the wide encoding wasn't explicit.
8384     bool Swap = false;
8385     auto DestReg = Inst.getOperand(0).getReg();
8386     bool Transform = DestReg == Inst.getOperand(1).getReg();
8387     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8388       Transform = true;
8389       Swap = true;
8390     }
8391     if (!Transform ||
8392         Inst.getOperand(5).getReg() != 0 ||
8393         HasWideQualifier)
8394       break;
8395     MCInst TmpInst;
8396     TmpInst.setOpcode(ARM::tADDhirr);
8397     TmpInst.addOperand(Inst.getOperand(0));
8398     TmpInst.addOperand(Inst.getOperand(0));
8399     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8400     TmpInst.addOperand(Inst.getOperand(3));
8401     TmpInst.addOperand(Inst.getOperand(4));
8402     Inst = TmpInst;
8403     return true;
8404   }
8405   case ARM::tADDrSP: {
8406     // If the non-SP source operand and the destination operand are not the
8407     // same, we need to use the 32-bit encoding if it's available.
8408     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8409       Inst.setOpcode(ARM::t2ADDrr);
8410       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8411       return true;
8412     }
8413     break;
8414   }
8415   case ARM::tB:
8416     // A Thumb conditional branch outside of an IT block is a tBcc.
8417     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8418       Inst.setOpcode(ARM::tBcc);
8419       return true;
8420     }
8421     break;
8422   case ARM::t2B:
8423     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8424     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8425       Inst.setOpcode(ARM::t2Bcc);
8426       return true;
8427     }
8428     break;
8429   case ARM::t2Bcc:
8430     // If the conditional is AL or we're in an IT block, we really want t2B.
8431     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8432       Inst.setOpcode(ARM::t2B);
8433       return true;
8434     }
8435     break;
8436   case ARM::tBcc:
8437     // If the conditional is AL, we really want tB.
8438     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8439       Inst.setOpcode(ARM::tB);
8440       return true;
8441     }
8442     break;
8443   case ARM::tLDMIA: {
8444     // If the register list contains any high registers, or if the writeback
8445     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8446     // instead if we're in Thumb2. Otherwise, this should have generated
8447     // an error in validateInstruction().
8448     unsigned Rn = Inst.getOperand(0).getReg();
8449     bool hasWritebackToken =
8450         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8451          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8452     bool listContainsBase;
8453     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8454         (!listContainsBase && !hasWritebackToken) ||
8455         (listContainsBase && hasWritebackToken)) {
8456       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8457       assert (isThumbTwo());
8458       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8459       // If we're switching to the updating version, we need to insert
8460       // the writeback tied operand.
8461       if (hasWritebackToken)
8462         Inst.insert(Inst.begin(),
8463                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8464       return true;
8465     }
8466     break;
8467   }
8468   case ARM::tSTMIA_UPD: {
8469     // If the register list contains any high registers, we need to use
8470     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8471     // should have generated an error in validateInstruction().
8472     unsigned Rn = Inst.getOperand(0).getReg();
8473     bool listContainsBase;
8474     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8475       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8476       assert (isThumbTwo());
8477       Inst.setOpcode(ARM::t2STMIA_UPD);
8478       return true;
8479     }
8480     break;
8481   }
8482   case ARM::tPOP: {
8483     bool listContainsBase;
8484     // If the register list contains any high registers, we need to use
8485     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8486     // should have generated an error in validateInstruction().
8487     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8488       return false;
8489     assert (isThumbTwo());
8490     Inst.setOpcode(ARM::t2LDMIA_UPD);
8491     // Add the base register and writeback operands.
8492     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8493     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8494     return true;
8495   }
8496   case ARM::tPUSH: {
8497     bool listContainsBase;
8498     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8499       return false;
8500     assert (isThumbTwo());
8501     Inst.setOpcode(ARM::t2STMDB_UPD);
8502     // Add the base register and writeback operands.
8503     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8504     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8505     return true;
8506   }
8507   case ARM::t2MOVi: {
8508     // If we can use the 16-bit encoding and the user didn't explicitly
8509     // request the 32-bit variant, transform it here.
8510     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8511         (Inst.getOperand(1).isImm() &&
8512          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8513         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8514         !HasWideQualifier) {
8515       // The operands aren't in the same order for tMOVi8...
8516       MCInst TmpInst;
8517       TmpInst.setOpcode(ARM::tMOVi8);
8518       TmpInst.addOperand(Inst.getOperand(0));
8519       TmpInst.addOperand(Inst.getOperand(4));
8520       TmpInst.addOperand(Inst.getOperand(1));
8521       TmpInst.addOperand(Inst.getOperand(2));
8522       TmpInst.addOperand(Inst.getOperand(3));
8523       Inst = TmpInst;
8524       return true;
8525     }
8526     break;
8527   }
8528   case ARM::t2MOVr: {
8529     // If we can use the 16-bit encoding and the user didn't explicitly
8530     // request the 32-bit variant, transform it here.
8531     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8532         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8533         Inst.getOperand(2).getImm() == ARMCC::AL &&
8534         Inst.getOperand(4).getReg() == ARM::CPSR &&
8535         !HasWideQualifier) {
8536       // The operands aren't the same for tMOV[S]r... (no cc_out)
8537       MCInst TmpInst;
8538       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8539       TmpInst.addOperand(Inst.getOperand(0));
8540       TmpInst.addOperand(Inst.getOperand(1));
8541       TmpInst.addOperand(Inst.getOperand(2));
8542       TmpInst.addOperand(Inst.getOperand(3));
8543       Inst = TmpInst;
8544       return true;
8545     }
8546     break;
8547   }
8548   case ARM::t2SXTH:
8549   case ARM::t2SXTB:
8550   case ARM::t2UXTH:
8551   case ARM::t2UXTB: {
8552     // If we can use the 16-bit encoding and the user didn't explicitly
8553     // request the 32-bit variant, transform it here.
8554     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8555         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8556         Inst.getOperand(2).getImm() == 0 &&
8557         !HasWideQualifier) {
8558       unsigned NewOpc;
8559       switch (Inst.getOpcode()) {
8560       default: llvm_unreachable("Illegal opcode!");
8561       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8562       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8563       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8564       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8565       }
8566       // The operands aren't the same for thumb1 (no rotate operand).
8567       MCInst TmpInst;
8568       TmpInst.setOpcode(NewOpc);
8569       TmpInst.addOperand(Inst.getOperand(0));
8570       TmpInst.addOperand(Inst.getOperand(1));
8571       TmpInst.addOperand(Inst.getOperand(3));
8572       TmpInst.addOperand(Inst.getOperand(4));
8573       Inst = TmpInst;
8574       return true;
8575     }
8576     break;
8577   }
8578   case ARM::MOVsi: {
8579     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8580     // rrx shifts and asr/lsr of #32 is encoded as 0
8581     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8582       return false;
8583     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8584       // Shifting by zero is accepted as a vanilla 'MOVr'
8585       MCInst TmpInst;
8586       TmpInst.setOpcode(ARM::MOVr);
8587       TmpInst.addOperand(Inst.getOperand(0));
8588       TmpInst.addOperand(Inst.getOperand(1));
8589       TmpInst.addOperand(Inst.getOperand(3));
8590       TmpInst.addOperand(Inst.getOperand(4));
8591       TmpInst.addOperand(Inst.getOperand(5));
8592       Inst = TmpInst;
8593       return true;
8594     }
8595     return false;
8596   }
8597   case ARM::ANDrsi:
8598   case ARM::ORRrsi:
8599   case ARM::EORrsi:
8600   case ARM::BICrsi:
8601   case ARM::SUBrsi:
8602   case ARM::ADDrsi: {
8603     unsigned newOpc;
8604     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8605     if (SOpc == ARM_AM::rrx) return false;
8606     switch (Inst.getOpcode()) {
8607     default: llvm_unreachable("unexpected opcode!");
8608     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8609     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8610     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8611     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8612     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8613     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8614     }
8615     // If the shift is by zero, use the non-shifted instruction definition.
8616     // The exception is for right shifts, where 0 == 32
8617     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8618         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8619       MCInst TmpInst;
8620       TmpInst.setOpcode(newOpc);
8621       TmpInst.addOperand(Inst.getOperand(0));
8622       TmpInst.addOperand(Inst.getOperand(1));
8623       TmpInst.addOperand(Inst.getOperand(2));
8624       TmpInst.addOperand(Inst.getOperand(4));
8625       TmpInst.addOperand(Inst.getOperand(5));
8626       TmpInst.addOperand(Inst.getOperand(6));
8627       Inst = TmpInst;
8628       return true;
8629     }
8630     return false;
8631   }
8632   case ARM::ITasm:
8633   case ARM::t2IT: {
8634     MCOperand &MO = Inst.getOperand(1);
8635     unsigned Mask = MO.getImm();
8636     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8637 
8638     // Set up the IT block state according to the IT instruction we just
8639     // matched.
8640     assert(!inITBlock() && "nested IT blocks?!");
8641     startExplicitITBlock(Cond, Mask);
8642     MO.setImm(getITMaskEncoding());
8643     break;
8644   }
8645   case ARM::t2LSLrr:
8646   case ARM::t2LSRrr:
8647   case ARM::t2ASRrr:
8648   case ARM::t2SBCrr:
8649   case ARM::t2RORrr:
8650   case ARM::t2BICrr:
8651   {
8652     // Assemblers should use the narrow encodings of these instructions when permissible.
8653     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8654          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8655         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8656         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8657         !HasWideQualifier) {
8658       unsigned NewOpc;
8659       switch (Inst.getOpcode()) {
8660         default: llvm_unreachable("unexpected opcode");
8661         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8662         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8663         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8664         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8665         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8666         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8667       }
8668       MCInst TmpInst;
8669       TmpInst.setOpcode(NewOpc);
8670       TmpInst.addOperand(Inst.getOperand(0));
8671       TmpInst.addOperand(Inst.getOperand(5));
8672       TmpInst.addOperand(Inst.getOperand(1));
8673       TmpInst.addOperand(Inst.getOperand(2));
8674       TmpInst.addOperand(Inst.getOperand(3));
8675       TmpInst.addOperand(Inst.getOperand(4));
8676       Inst = TmpInst;
8677       return true;
8678     }
8679     return false;
8680   }
8681   case ARM::t2ANDrr:
8682   case ARM::t2EORrr:
8683   case ARM::t2ADCrr:
8684   case ARM::t2ORRrr:
8685   {
8686     // Assemblers should use the narrow encodings of these instructions when permissible.
8687     // These instructions are special in that they are commutable, so shorter encodings
8688     // are available more often.
8689     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8690          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8691         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8692          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8693         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8694         !HasWideQualifier) {
8695       unsigned NewOpc;
8696       switch (Inst.getOpcode()) {
8697         default: llvm_unreachable("unexpected opcode");
8698         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8699         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8700         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8701         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8702       }
8703       MCInst TmpInst;
8704       TmpInst.setOpcode(NewOpc);
8705       TmpInst.addOperand(Inst.getOperand(0));
8706       TmpInst.addOperand(Inst.getOperand(5));
8707       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8708         TmpInst.addOperand(Inst.getOperand(1));
8709         TmpInst.addOperand(Inst.getOperand(2));
8710       } else {
8711         TmpInst.addOperand(Inst.getOperand(2));
8712         TmpInst.addOperand(Inst.getOperand(1));
8713       }
8714       TmpInst.addOperand(Inst.getOperand(3));
8715       TmpInst.addOperand(Inst.getOperand(4));
8716       Inst = TmpInst;
8717       return true;
8718     }
8719     return false;
8720   }
8721   }
8722   return false;
8723 }
8724 
8725 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8726   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8727   // suffix depending on whether they're in an IT block or not.
8728   unsigned Opc = Inst.getOpcode();
8729   const MCInstrDesc &MCID = MII.get(Opc);
8730   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8731     assert(MCID.hasOptionalDef() &&
8732            "optionally flag setting instruction missing optional def operand");
8733     assert(MCID.NumOperands == Inst.getNumOperands() &&
8734            "operand count mismatch!");
8735     // Find the optional-def operand (cc_out).
8736     unsigned OpNo;
8737     for (OpNo = 0;
8738          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8739          ++OpNo)
8740       ;
8741     // If we're parsing Thumb1, reject it completely.
8742     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8743       return Match_RequiresFlagSetting;
8744     // If we're parsing Thumb2, which form is legal depends on whether we're
8745     // in an IT block.
8746     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8747         !inITBlock())
8748       return Match_RequiresITBlock;
8749     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8750         inITBlock())
8751       return Match_RequiresNotITBlock;
8752     // LSL with zero immediate is not allowed in an IT block
8753     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8754       return Match_RequiresNotITBlock;
8755   } else if (isThumbOne()) {
8756     // Some high-register supporting Thumb1 encodings only allow both registers
8757     // to be from r0-r7 when in Thumb2.
8758     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8759         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8760         isARMLowRegister(Inst.getOperand(2).getReg()))
8761       return Match_RequiresThumb2;
8762     // Others only require ARMv6 or later.
8763     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8764              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8765              isARMLowRegister(Inst.getOperand(1).getReg()))
8766       return Match_RequiresV6;
8767   }
8768 
8769   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8770   // than the loop below can handle, so it uses the GPRnopc register class and
8771   // we do SP handling here.
8772   if (Opc == ARM::t2MOVr && !hasV8Ops())
8773   {
8774     // SP as both source and destination is not allowed
8775     if (Inst.getOperand(0).getReg() == ARM::SP &&
8776         Inst.getOperand(1).getReg() == ARM::SP)
8777       return Match_RequiresV8;
8778     // When flags-setting SP as either source or destination is not allowed
8779     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8780         (Inst.getOperand(0).getReg() == ARM::SP ||
8781          Inst.getOperand(1).getReg() == ARM::SP))
8782       return Match_RequiresV8;
8783   }
8784 
8785   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8786     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8787       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8788       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8789         return Match_RequiresV8;
8790       else if (Inst.getOperand(I).getReg() == ARM::PC)
8791         return Match_InvalidOperand;
8792     }
8793 
8794   return Match_Success;
8795 }
8796 
8797 namespace llvm {
8798 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8799   return true; // In an assembly source, no need to second-guess
8800 }
8801 }
8802 
8803 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8804 // the last instruction in the block.
8805 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8806   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8807 
8808   // All branch & call instructions terminate IT blocks.
8809   if (MCID.isTerminator() || MCID.isCall() || MCID.isReturn() ||
8810       MCID.isBranch() || MCID.isIndirectBranch())
8811     return true;
8812 
8813   // Any arithmetic instruction which writes to the PC also terminates the IT
8814   // block.
8815   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8816     MCOperand &Op = Inst.getOperand(OpIdx);
8817     if (Op.isReg() && Op.getReg() == ARM::PC)
8818       return true;
8819   }
8820 
8821   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8822     return true;
8823 
8824   // Instructions with variable operand lists, which write to the variable
8825   // operands. We only care about Thumb instructions here, as ARM instructions
8826   // obviously can't be in an IT block.
8827   switch (Inst.getOpcode()) {
8828   case ARM::tLDMIA:
8829   case ARM::t2LDMIA:
8830   case ARM::t2LDMIA_UPD:
8831   case ARM::t2LDMDB:
8832   case ARM::t2LDMDB_UPD:
8833     if (listContainsReg(Inst, 3, ARM::PC))
8834       return true;
8835     break;
8836   case ARM::tPOP:
8837     if (listContainsReg(Inst, 2, ARM::PC))
8838       return true;
8839     break;
8840   }
8841 
8842   return false;
8843 }
8844 
8845 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8846                                           uint64_t &ErrorInfo,
8847                                           bool MatchingInlineAsm,
8848                                           bool &EmitInITBlock,
8849                                           MCStreamer &Out) {
8850   // If we can't use an implicit IT block here, just match as normal.
8851   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8852     return MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8853 
8854   // Try to match the instruction in an extension of the current IT block (if
8855   // there is one).
8856   if (inImplicitITBlock()) {
8857     extendImplicitITBlock(ITState.Cond);
8858     if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8859             Match_Success) {
8860       // The match succeded, but we still have to check that the instruction is
8861       // valid in this implicit IT block.
8862       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8863       if (MCID.isPredicable()) {
8864         ARMCC::CondCodes InstCond =
8865             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8866                 .getImm();
8867         ARMCC::CondCodes ITCond = currentITCond();
8868         if (InstCond == ITCond) {
8869           EmitInITBlock = true;
8870           return Match_Success;
8871         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
8872           invertCurrentITCondition();
8873           EmitInITBlock = true;
8874           return Match_Success;
8875         }
8876       }
8877     }
8878     rewindImplicitITPosition();
8879   }
8880 
8881   // Finish the current IT block, and try to match outside any IT block.
8882   flushPendingInstructions(Out);
8883   unsigned PlainMatchResult =
8884       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8885   if (PlainMatchResult == Match_Success) {
8886     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8887     if (MCID.isPredicable()) {
8888       ARMCC::CondCodes InstCond =
8889           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8890               .getImm();
8891       // Some forms of the branch instruction have their own condition code
8892       // fields, so can be conditionally executed without an IT block.
8893       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
8894         EmitInITBlock = false;
8895         return Match_Success;
8896       }
8897       if (InstCond == ARMCC::AL) {
8898         EmitInITBlock = false;
8899         return Match_Success;
8900       }
8901     } else {
8902       EmitInITBlock = false;
8903       return Match_Success;
8904     }
8905   }
8906 
8907   // Try to match in a new IT block. The matcher doesn't check the actual
8908   // condition, so we create an IT block with a dummy condition, and fix it up
8909   // once we know the actual condition.
8910   startImplicitITBlock();
8911   if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8912       Match_Success) {
8913     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8914     if (MCID.isPredicable()) {
8915       ITState.Cond =
8916           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8917               .getImm();
8918       EmitInITBlock = true;
8919       return Match_Success;
8920     }
8921   }
8922   discardImplicitITBlock();
8923 
8924   // If none of these succeed, return the error we got when trying to match
8925   // outside any IT blocks.
8926   EmitInITBlock = false;
8927   return PlainMatchResult;
8928 }
8929 
8930 std::string ARMMnemonicSpellCheck(StringRef S, uint64_t FBS);
8931 
8932 static const char *getSubtargetFeatureName(uint64_t Val);
8933 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8934                                            OperandVector &Operands,
8935                                            MCStreamer &Out, uint64_t &ErrorInfo,
8936                                            bool MatchingInlineAsm) {
8937   MCInst Inst;
8938   unsigned MatchResult;
8939   bool PendConditionalInstruction = false;
8940 
8941   MatchResult = MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm,
8942                                  PendConditionalInstruction, Out);
8943 
8944   SMLoc ErrorLoc;
8945   if (ErrorInfo < Operands.size()) {
8946     ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8947     if (ErrorLoc == SMLoc())
8948       ErrorLoc = IDLoc;
8949   }
8950 
8951   switch (MatchResult) {
8952   case Match_Success:
8953     // Context sensitive operand constraints aren't handled by the matcher,
8954     // so check them here.
8955     if (validateInstruction(Inst, Operands)) {
8956       // Still progress the IT block, otherwise one wrong condition causes
8957       // nasty cascading errors.
8958       forwardITPosition();
8959       return true;
8960     }
8961 
8962     { // processInstruction() updates inITBlock state, we need to save it away
8963       bool wasInITBlock = inITBlock();
8964 
8965       // Some instructions need post-processing to, for example, tweak which
8966       // encoding is selected. Loop on it while changes happen so the
8967       // individual transformations can chain off each other. E.g.,
8968       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
8969       while (processInstruction(Inst, Operands, Out))
8970         ;
8971 
8972       // Only after the instruction is fully processed, we can validate it
8973       if (wasInITBlock && hasV8Ops() && isThumb() &&
8974           !isV8EligibleForIT(&Inst)) {
8975         Warning(IDLoc, "deprecated instruction in IT block");
8976       }
8977     }
8978 
8979     // Only move forward at the very end so that everything in validate
8980     // and process gets a consistent answer about whether we're in an IT
8981     // block.
8982     forwardITPosition();
8983 
8984     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
8985     // doesn't actually encode.
8986     if (Inst.getOpcode() == ARM::ITasm)
8987       return false;
8988 
8989     Inst.setLoc(IDLoc);
8990     if (PendConditionalInstruction) {
8991       PendingConditionalInsts.push_back(Inst);
8992       if (isITBlockFull() || isITBlockTerminator(Inst))
8993         flushPendingInstructions(Out);
8994     } else {
8995       Out.EmitInstruction(Inst, getSTI());
8996     }
8997     return false;
8998   case Match_MissingFeature: {
8999     assert(ErrorInfo && "Unknown missing feature!");
9000     // Special case the error message for the very common case where only
9001     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
9002     std::string Msg = "instruction requires:";
9003     uint64_t Mask = 1;
9004     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
9005       if (ErrorInfo & Mask) {
9006         Msg += " ";
9007         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
9008       }
9009       Mask <<= 1;
9010     }
9011     return Error(IDLoc, Msg);
9012   }
9013   case Match_InvalidOperand: {
9014     SMLoc ErrorLoc = IDLoc;
9015     if (ErrorInfo != ~0ULL) {
9016       if (ErrorInfo >= Operands.size())
9017         return Error(IDLoc, "too few operands for instruction");
9018 
9019       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9020       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9021     }
9022 
9023     return Error(ErrorLoc, "invalid operand for instruction");
9024   }
9025   case Match_MnemonicFail: {
9026     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
9027     std::string Suggestion = ARMMnemonicSpellCheck(
9028       ((ARMOperand &)*Operands[0]).getToken(), FBS);
9029     return Error(IDLoc, "invalid instruction" + Suggestion,
9030                  ((ARMOperand &)*Operands[0]).getLocRange());
9031   }
9032   case Match_RequiresNotITBlock:
9033     return Error(IDLoc, "flag setting instruction only valid outside IT block");
9034   case Match_RequiresITBlock:
9035     return Error(IDLoc, "instruction only valid inside IT block");
9036   case Match_RequiresV6:
9037     return Error(IDLoc, "instruction variant requires ARMv6 or later");
9038   case Match_RequiresThumb2:
9039     return Error(IDLoc, "instruction variant requires Thumb2");
9040   case Match_RequiresV8:
9041     return Error(IDLoc, "instruction variant requires ARMv8 or later");
9042   case Match_RequiresFlagSetting:
9043     return Error(IDLoc, "no flag-preserving variant of this instruction available");
9044   case Match_ImmRange0_1:
9045     return Error(ErrorLoc, "immediate operand must be in the range [0,1]");
9046   case Match_ImmRange0_3:
9047     return Error(ErrorLoc, "immediate operand must be in the range [0,3]");
9048   case Match_ImmRange0_7:
9049     return Error(ErrorLoc, "immediate operand must be in the range [0,7]");
9050   case Match_ImmRange0_15:
9051     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
9052   case Match_ImmRange0_31:
9053     return Error(ErrorLoc, "immediate operand must be in the range [0,31]");
9054   case Match_ImmRange0_32:
9055     return Error(ErrorLoc, "immediate operand must be in the range [0,32]");
9056   case Match_ImmRange0_63:
9057     return Error(ErrorLoc, "immediate operand must be in the range [0,63]");
9058   case Match_ImmRange0_239:
9059     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
9060   case Match_ImmRange0_255:
9061     return Error(ErrorLoc, "immediate operand must be in the range [0,255]");
9062   case Match_ImmRange0_4095:
9063     return Error(ErrorLoc, "immediate operand must be in the range [0,4095]");
9064   case Match_ImmRange0_65535:
9065     return Error(ErrorLoc, "immediate operand must be in the range [0,65535]");
9066   case Match_ImmRange1_7:
9067     return Error(ErrorLoc, "immediate operand must be in the range [1,7]");
9068   case Match_ImmRange1_8:
9069     return Error(ErrorLoc, "immediate operand must be in the range [1,8]");
9070   case Match_ImmRange1_15:
9071     return Error(ErrorLoc, "immediate operand must be in the range [1,15]");
9072   case Match_ImmRange1_16:
9073     return Error(ErrorLoc, "immediate operand must be in the range [1,16]");
9074   case Match_ImmRange1_31:
9075     return Error(ErrorLoc, "immediate operand must be in the range [1,31]");
9076   case Match_ImmRange1_32:
9077     return Error(ErrorLoc, "immediate operand must be in the range [1,32]");
9078   case Match_ImmRange1_64:
9079     return Error(ErrorLoc, "immediate operand must be in the range [1,64]");
9080   case Match_ImmRange8_8:
9081     return Error(ErrorLoc, "immediate operand must be 8.");
9082   case Match_ImmRange16_16:
9083     return Error(ErrorLoc, "immediate operand must be 16.");
9084   case Match_ImmRange32_32:
9085     return Error(ErrorLoc, "immediate operand must be 32.");
9086   case Match_ImmRange256_65535:
9087     return Error(ErrorLoc, "immediate operand must be in the range [255,65535]");
9088   case Match_ImmRange0_16777215:
9089     return Error(ErrorLoc, "immediate operand must be in the range [0,0xffffff]");
9090   case Match_AlignedMemoryRequiresNone:
9091   case Match_DupAlignedMemoryRequiresNone:
9092   case Match_AlignedMemoryRequires16:
9093   case Match_DupAlignedMemoryRequires16:
9094   case Match_AlignedMemoryRequires32:
9095   case Match_DupAlignedMemoryRequires32:
9096   case Match_AlignedMemoryRequires64:
9097   case Match_DupAlignedMemoryRequires64:
9098   case Match_AlignedMemoryRequires64or128:
9099   case Match_DupAlignedMemoryRequires64or128:
9100   case Match_AlignedMemoryRequires64or128or256:
9101   {
9102     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
9103     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9104     switch (MatchResult) {
9105       default:
9106         llvm_unreachable("Missing Match_Aligned type");
9107       case Match_AlignedMemoryRequiresNone:
9108       case Match_DupAlignedMemoryRequiresNone:
9109         return Error(ErrorLoc, "alignment must be omitted");
9110       case Match_AlignedMemoryRequires16:
9111       case Match_DupAlignedMemoryRequires16:
9112         return Error(ErrorLoc, "alignment must be 16 or omitted");
9113       case Match_AlignedMemoryRequires32:
9114       case Match_DupAlignedMemoryRequires32:
9115         return Error(ErrorLoc, "alignment must be 32 or omitted");
9116       case Match_AlignedMemoryRequires64:
9117       case Match_DupAlignedMemoryRequires64:
9118         return Error(ErrorLoc, "alignment must be 64 or omitted");
9119       case Match_AlignedMemoryRequires64or128:
9120       case Match_DupAlignedMemoryRequires64or128:
9121         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
9122       case Match_AlignedMemoryRequires64or128or256:
9123         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
9124     }
9125   }
9126   }
9127 
9128   llvm_unreachable("Implement any new match types added!");
9129 }
9130 
9131 /// parseDirective parses the arm specific directives
9132 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9133   const MCObjectFileInfo::Environment Format =
9134     getContext().getObjectFileInfo()->getObjectFileType();
9135   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9136   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9137 
9138   StringRef IDVal = DirectiveID.getIdentifier();
9139   if (IDVal == ".word")
9140     parseLiteralValues(4, DirectiveID.getLoc());
9141   else if (IDVal == ".short" || IDVal == ".hword")
9142     parseLiteralValues(2, DirectiveID.getLoc());
9143   else if (IDVal == ".thumb")
9144     parseDirectiveThumb(DirectiveID.getLoc());
9145   else if (IDVal == ".arm")
9146     parseDirectiveARM(DirectiveID.getLoc());
9147   else if (IDVal == ".thumb_func")
9148     parseDirectiveThumbFunc(DirectiveID.getLoc());
9149   else if (IDVal == ".code")
9150     parseDirectiveCode(DirectiveID.getLoc());
9151   else if (IDVal == ".syntax")
9152     parseDirectiveSyntax(DirectiveID.getLoc());
9153   else if (IDVal == ".unreq")
9154     parseDirectiveUnreq(DirectiveID.getLoc());
9155   else if (IDVal == ".fnend")
9156     parseDirectiveFnEnd(DirectiveID.getLoc());
9157   else if (IDVal == ".cantunwind")
9158     parseDirectiveCantUnwind(DirectiveID.getLoc());
9159   else if (IDVal == ".personality")
9160     parseDirectivePersonality(DirectiveID.getLoc());
9161   else if (IDVal == ".handlerdata")
9162     parseDirectiveHandlerData(DirectiveID.getLoc());
9163   else if (IDVal == ".setfp")
9164     parseDirectiveSetFP(DirectiveID.getLoc());
9165   else if (IDVal == ".pad")
9166     parseDirectivePad(DirectiveID.getLoc());
9167   else if (IDVal == ".save")
9168     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9169   else if (IDVal == ".vsave")
9170     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9171   else if (IDVal == ".ltorg" || IDVal == ".pool")
9172     parseDirectiveLtorg(DirectiveID.getLoc());
9173   else if (IDVal == ".even")
9174     parseDirectiveEven(DirectiveID.getLoc());
9175   else if (IDVal == ".personalityindex")
9176     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9177   else if (IDVal == ".unwind_raw")
9178     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9179   else if (IDVal == ".movsp")
9180     parseDirectiveMovSP(DirectiveID.getLoc());
9181   else if (IDVal == ".arch_extension")
9182     parseDirectiveArchExtension(DirectiveID.getLoc());
9183   else if (IDVal == ".align")
9184     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9185   else if (IDVal == ".thumb_set")
9186     parseDirectiveThumbSet(DirectiveID.getLoc());
9187   else if (!IsMachO && !IsCOFF) {
9188     if (IDVal == ".arch")
9189       parseDirectiveArch(DirectiveID.getLoc());
9190     else if (IDVal == ".cpu")
9191       parseDirectiveCPU(DirectiveID.getLoc());
9192     else if (IDVal == ".eabi_attribute")
9193       parseDirectiveEabiAttr(DirectiveID.getLoc());
9194     else if (IDVal == ".fpu")
9195       parseDirectiveFPU(DirectiveID.getLoc());
9196     else if (IDVal == ".fnstart")
9197       parseDirectiveFnStart(DirectiveID.getLoc());
9198     else if (IDVal == ".inst")
9199       parseDirectiveInst(DirectiveID.getLoc());
9200     else if (IDVal == ".inst.n")
9201       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9202     else if (IDVal == ".inst.w")
9203       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9204     else if (IDVal == ".object_arch")
9205       parseDirectiveObjectArch(DirectiveID.getLoc());
9206     else if (IDVal == ".tlsdescseq")
9207       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9208     else
9209       return true;
9210   } else
9211     return true;
9212   return false;
9213 }
9214 
9215 /// parseLiteralValues
9216 ///  ::= .hword expression [, expression]*
9217 ///  ::= .short expression [, expression]*
9218 ///  ::= .word expression [, expression]*
9219 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9220   auto parseOne = [&]() -> bool {
9221     const MCExpr *Value;
9222     if (getParser().parseExpression(Value))
9223       return true;
9224     getParser().getStreamer().EmitValue(Value, Size, L);
9225     return false;
9226   };
9227   return (parseMany(parseOne));
9228 }
9229 
9230 /// parseDirectiveThumb
9231 ///  ::= .thumb
9232 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9233   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9234       check(!hasThumb(), L, "target does not support Thumb mode"))
9235     return true;
9236 
9237   if (!isThumb())
9238     SwitchMode();
9239 
9240   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9241   return false;
9242 }
9243 
9244 /// parseDirectiveARM
9245 ///  ::= .arm
9246 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9247   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9248       check(!hasARM(), L, "target does not support ARM mode"))
9249     return true;
9250 
9251   if (isThumb())
9252     SwitchMode();
9253   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9254   return false;
9255 }
9256 
9257 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9258   // We need to flush the current implicit IT block on a label, because it is
9259   // not legal to branch into an IT block.
9260   flushPendingInstructions(getStreamer());
9261   if (NextSymbolIsThumb) {
9262     getParser().getStreamer().EmitThumbFunc(Symbol);
9263     NextSymbolIsThumb = false;
9264   }
9265 }
9266 
9267 /// parseDirectiveThumbFunc
9268 ///  ::= .thumbfunc symbol_name
9269 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9270   MCAsmParser &Parser = getParser();
9271   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9272   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9273 
9274   // Darwin asm has (optionally) function name after .thumb_func direction
9275   // ELF doesn't
9276 
9277   if (IsMachO) {
9278     if (Parser.getTok().is(AsmToken::Identifier) ||
9279         Parser.getTok().is(AsmToken::String)) {
9280       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9281           Parser.getTok().getIdentifier());
9282       getParser().getStreamer().EmitThumbFunc(Func);
9283       Parser.Lex();
9284       if (parseToken(AsmToken::EndOfStatement,
9285                      "unexpected token in '.thumb_func' directive"))
9286         return true;
9287       return false;
9288     }
9289   }
9290 
9291   if (parseToken(AsmToken::EndOfStatement,
9292                  "unexpected token in '.thumb_func' directive"))
9293     return true;
9294 
9295   NextSymbolIsThumb = true;
9296   return false;
9297 }
9298 
9299 /// parseDirectiveSyntax
9300 ///  ::= .syntax unified | divided
9301 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9302   MCAsmParser &Parser = getParser();
9303   const AsmToken &Tok = Parser.getTok();
9304   if (Tok.isNot(AsmToken::Identifier)) {
9305     Error(L, "unexpected token in .syntax directive");
9306     return false;
9307   }
9308 
9309   StringRef Mode = Tok.getString();
9310   Parser.Lex();
9311   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9312             "'.syntax divided' arm assembly not supported") ||
9313       check(Mode != "unified" && Mode != "UNIFIED", L,
9314             "unrecognized syntax mode in .syntax directive") ||
9315       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9316     return true;
9317 
9318   // TODO tell the MC streamer the mode
9319   // getParser().getStreamer().Emit???();
9320   return false;
9321 }
9322 
9323 /// parseDirectiveCode
9324 ///  ::= .code 16 | 32
9325 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9326   MCAsmParser &Parser = getParser();
9327   const AsmToken &Tok = Parser.getTok();
9328   if (Tok.isNot(AsmToken::Integer))
9329     return Error(L, "unexpected token in .code directive");
9330   int64_t Val = Parser.getTok().getIntVal();
9331   if (Val != 16 && Val != 32) {
9332     Error(L, "invalid operand to .code directive");
9333     return false;
9334   }
9335   Parser.Lex();
9336 
9337   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9338     return true;
9339 
9340   if (Val == 16) {
9341     if (!hasThumb())
9342       return Error(L, "target does not support Thumb mode");
9343 
9344     if (!isThumb())
9345       SwitchMode();
9346     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9347   } else {
9348     if (!hasARM())
9349       return Error(L, "target does not support ARM mode");
9350 
9351     if (isThumb())
9352       SwitchMode();
9353     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9354   }
9355 
9356   return false;
9357 }
9358 
9359 /// parseDirectiveReq
9360 ///  ::= name .req registername
9361 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9362   MCAsmParser &Parser = getParser();
9363   Parser.Lex(); // Eat the '.req' token.
9364   unsigned Reg;
9365   SMLoc SRegLoc, ERegLoc;
9366   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9367             "register name expected") ||
9368       parseToken(AsmToken::EndOfStatement,
9369                  "unexpected input in .req directive."))
9370     return true;
9371 
9372   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9373     return Error(SRegLoc,
9374                  "redefinition of '" + Name + "' does not match original.");
9375 
9376   return false;
9377 }
9378 
9379 /// parseDirectiveUneq
9380 ///  ::= .unreq registername
9381 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9382   MCAsmParser &Parser = getParser();
9383   if (Parser.getTok().isNot(AsmToken::Identifier))
9384     return Error(L, "unexpected input in .unreq directive.");
9385   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9386   Parser.Lex(); // Eat the identifier.
9387   if (parseToken(AsmToken::EndOfStatement,
9388                  "unexpected input in '.unreq' directive"))
9389     return true;
9390   return false;
9391 }
9392 
9393 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9394 // before, if supported by the new target, or emit mapping symbols for the mode
9395 // switch.
9396 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9397   if (WasThumb != isThumb()) {
9398     if (WasThumb && hasThumb()) {
9399       // Stay in Thumb mode
9400       SwitchMode();
9401     } else if (!WasThumb && hasARM()) {
9402       // Stay in ARM mode
9403       SwitchMode();
9404     } else {
9405       // Mode switch forced, because the new arch doesn't support the old mode.
9406       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9407                                                             : MCAF_Code32);
9408       // Warn about the implcit mode switch. GAS does not switch modes here,
9409       // but instead stays in the old mode, reporting an error on any following
9410       // instructions as the mode does not exist on the target.
9411       Warning(Loc, Twine("new target does not support ") +
9412                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9413                        (!WasThumb ? "thumb" : "arm") + " mode");
9414     }
9415   }
9416 }
9417 
9418 /// parseDirectiveArch
9419 ///  ::= .arch token
9420 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9421   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9422   ARM::ArchKind ID = ARM::parseArch(Arch);
9423 
9424   if (ID == ARM::ArchKind::INVALID)
9425     return Error(L, "Unknown arch name");
9426 
9427   bool WasThumb = isThumb();
9428   Triple T;
9429   MCSubtargetInfo &STI = copySTI();
9430   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9431   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9432   FixModeAfterArchChange(WasThumb, L);
9433 
9434   getTargetStreamer().emitArch(ID);
9435   return false;
9436 }
9437 
9438 /// parseDirectiveEabiAttr
9439 ///  ::= .eabi_attribute int, int [, "str"]
9440 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9441 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9442   MCAsmParser &Parser = getParser();
9443   int64_t Tag;
9444   SMLoc TagLoc;
9445   TagLoc = Parser.getTok().getLoc();
9446   if (Parser.getTok().is(AsmToken::Identifier)) {
9447     StringRef Name = Parser.getTok().getIdentifier();
9448     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9449     if (Tag == -1) {
9450       Error(TagLoc, "attribute name not recognised: " + Name);
9451       return false;
9452     }
9453     Parser.Lex();
9454   } else {
9455     const MCExpr *AttrExpr;
9456 
9457     TagLoc = Parser.getTok().getLoc();
9458     if (Parser.parseExpression(AttrExpr))
9459       return true;
9460 
9461     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9462     if (check(!CE, TagLoc, "expected numeric constant"))
9463       return true;
9464 
9465     Tag = CE->getValue();
9466   }
9467 
9468   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9469     return true;
9470 
9471   StringRef StringValue = "";
9472   bool IsStringValue = false;
9473 
9474   int64_t IntegerValue = 0;
9475   bool IsIntegerValue = false;
9476 
9477   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9478     IsStringValue = true;
9479   else if (Tag == ARMBuildAttrs::compatibility) {
9480     IsStringValue = true;
9481     IsIntegerValue = true;
9482   } else if (Tag < 32 || Tag % 2 == 0)
9483     IsIntegerValue = true;
9484   else if (Tag % 2 == 1)
9485     IsStringValue = true;
9486   else
9487     llvm_unreachable("invalid tag type");
9488 
9489   if (IsIntegerValue) {
9490     const MCExpr *ValueExpr;
9491     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9492     if (Parser.parseExpression(ValueExpr))
9493       return true;
9494 
9495     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9496     if (!CE)
9497       return Error(ValueExprLoc, "expected numeric constant");
9498     IntegerValue = CE->getValue();
9499   }
9500 
9501   if (Tag == ARMBuildAttrs::compatibility) {
9502     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9503       return true;
9504   }
9505 
9506   if (IsStringValue) {
9507     if (Parser.getTok().isNot(AsmToken::String))
9508       return Error(Parser.getTok().getLoc(), "bad string constant");
9509 
9510     StringValue = Parser.getTok().getStringContents();
9511     Parser.Lex();
9512   }
9513 
9514   if (Parser.parseToken(AsmToken::EndOfStatement,
9515                         "unexpected token in '.eabi_attribute' directive"))
9516     return true;
9517 
9518   if (IsIntegerValue && IsStringValue) {
9519     assert(Tag == ARMBuildAttrs::compatibility);
9520     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9521   } else if (IsIntegerValue)
9522     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9523   else if (IsStringValue)
9524     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9525   return false;
9526 }
9527 
9528 /// parseDirectiveCPU
9529 ///  ::= .cpu str
9530 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9531   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9532   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9533 
9534   // FIXME: This is using table-gen data, but should be moved to
9535   // ARMTargetParser once that is table-gen'd.
9536   if (!getSTI().isCPUStringValid(CPU))
9537     return Error(L, "Unknown CPU name");
9538 
9539   bool WasThumb = isThumb();
9540   MCSubtargetInfo &STI = copySTI();
9541   STI.setDefaultFeatures(CPU, "");
9542   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9543   FixModeAfterArchChange(WasThumb, L);
9544 
9545   return false;
9546 }
9547 /// parseDirectiveFPU
9548 ///  ::= .fpu str
9549 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9550   SMLoc FPUNameLoc = getTok().getLoc();
9551   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9552 
9553   unsigned ID = ARM::parseFPU(FPU);
9554   std::vector<StringRef> Features;
9555   if (!ARM::getFPUFeatures(ID, Features))
9556     return Error(FPUNameLoc, "Unknown FPU name");
9557 
9558   MCSubtargetInfo &STI = copySTI();
9559   for (auto Feature : Features)
9560     STI.ApplyFeatureFlag(Feature);
9561   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9562 
9563   getTargetStreamer().emitFPU(ID);
9564   return false;
9565 }
9566 
9567 /// parseDirectiveFnStart
9568 ///  ::= .fnstart
9569 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9570   if (parseToken(AsmToken::EndOfStatement,
9571                  "unexpected token in '.fnstart' directive"))
9572     return true;
9573 
9574   if (UC.hasFnStart()) {
9575     Error(L, ".fnstart starts before the end of previous one");
9576     UC.emitFnStartLocNotes();
9577     return true;
9578   }
9579 
9580   // Reset the unwind directives parser state
9581   UC.reset();
9582 
9583   getTargetStreamer().emitFnStart();
9584 
9585   UC.recordFnStart(L);
9586   return false;
9587 }
9588 
9589 /// parseDirectiveFnEnd
9590 ///  ::= .fnend
9591 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9592   if (parseToken(AsmToken::EndOfStatement,
9593                  "unexpected token in '.fnend' directive"))
9594     return true;
9595   // Check the ordering of unwind directives
9596   if (!UC.hasFnStart())
9597     return Error(L, ".fnstart must precede .fnend directive");
9598 
9599   // Reset the unwind directives parser state
9600   getTargetStreamer().emitFnEnd();
9601 
9602   UC.reset();
9603   return false;
9604 }
9605 
9606 /// parseDirectiveCantUnwind
9607 ///  ::= .cantunwind
9608 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9609   if (parseToken(AsmToken::EndOfStatement,
9610                  "unexpected token in '.cantunwind' directive"))
9611     return true;
9612 
9613   UC.recordCantUnwind(L);
9614   // Check the ordering of unwind directives
9615   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9616     return true;
9617 
9618   if (UC.hasHandlerData()) {
9619     Error(L, ".cantunwind can't be used with .handlerdata directive");
9620     UC.emitHandlerDataLocNotes();
9621     return true;
9622   }
9623   if (UC.hasPersonality()) {
9624     Error(L, ".cantunwind can't be used with .personality directive");
9625     UC.emitPersonalityLocNotes();
9626     return true;
9627   }
9628 
9629   getTargetStreamer().emitCantUnwind();
9630   return false;
9631 }
9632 
9633 /// parseDirectivePersonality
9634 ///  ::= .personality name
9635 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9636   MCAsmParser &Parser = getParser();
9637   bool HasExistingPersonality = UC.hasPersonality();
9638 
9639   // Parse the name of the personality routine
9640   if (Parser.getTok().isNot(AsmToken::Identifier))
9641     return Error(L, "unexpected input in .personality directive.");
9642   StringRef Name(Parser.getTok().getIdentifier());
9643   Parser.Lex();
9644 
9645   if (parseToken(AsmToken::EndOfStatement,
9646                  "unexpected token in '.personality' directive"))
9647     return true;
9648 
9649   UC.recordPersonality(L);
9650 
9651   // Check the ordering of unwind directives
9652   if (!UC.hasFnStart())
9653     return Error(L, ".fnstart must precede .personality directive");
9654   if (UC.cantUnwind()) {
9655     Error(L, ".personality can't be used with .cantunwind directive");
9656     UC.emitCantUnwindLocNotes();
9657     return true;
9658   }
9659   if (UC.hasHandlerData()) {
9660     Error(L, ".personality must precede .handlerdata directive");
9661     UC.emitHandlerDataLocNotes();
9662     return true;
9663   }
9664   if (HasExistingPersonality) {
9665     Error(L, "multiple personality directives");
9666     UC.emitPersonalityLocNotes();
9667     return true;
9668   }
9669 
9670   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9671   getTargetStreamer().emitPersonality(PR);
9672   return false;
9673 }
9674 
9675 /// parseDirectiveHandlerData
9676 ///  ::= .handlerdata
9677 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9678   if (parseToken(AsmToken::EndOfStatement,
9679                  "unexpected token in '.handlerdata' directive"))
9680     return true;
9681 
9682   UC.recordHandlerData(L);
9683   // Check the ordering of unwind directives
9684   if (!UC.hasFnStart())
9685     return Error(L, ".fnstart must precede .personality directive");
9686   if (UC.cantUnwind()) {
9687     Error(L, ".handlerdata can't be used with .cantunwind directive");
9688     UC.emitCantUnwindLocNotes();
9689     return true;
9690   }
9691 
9692   getTargetStreamer().emitHandlerData();
9693   return false;
9694 }
9695 
9696 /// parseDirectiveSetFP
9697 ///  ::= .setfp fpreg, spreg [, offset]
9698 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9699   MCAsmParser &Parser = getParser();
9700   // Check the ordering of unwind directives
9701   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9702       check(UC.hasHandlerData(), L,
9703             ".setfp must precede .handlerdata directive"))
9704     return true;
9705 
9706   // Parse fpreg
9707   SMLoc FPRegLoc = Parser.getTok().getLoc();
9708   int FPReg = tryParseRegister();
9709 
9710   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9711       Parser.parseToken(AsmToken::Comma, "comma expected"))
9712     return true;
9713 
9714   // Parse spreg
9715   SMLoc SPRegLoc = Parser.getTok().getLoc();
9716   int SPReg = tryParseRegister();
9717   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9718       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9719             "register should be either $sp or the latest fp register"))
9720     return true;
9721 
9722   // Update the frame pointer register
9723   UC.saveFPReg(FPReg);
9724 
9725   // Parse offset
9726   int64_t Offset = 0;
9727   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9728     if (Parser.getTok().isNot(AsmToken::Hash) &&
9729         Parser.getTok().isNot(AsmToken::Dollar))
9730       return Error(Parser.getTok().getLoc(), "'#' expected");
9731     Parser.Lex(); // skip hash token.
9732 
9733     const MCExpr *OffsetExpr;
9734     SMLoc ExLoc = Parser.getTok().getLoc();
9735     SMLoc EndLoc;
9736     if (getParser().parseExpression(OffsetExpr, EndLoc))
9737       return Error(ExLoc, "malformed setfp offset");
9738     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9739     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9740       return true;
9741     Offset = CE->getValue();
9742   }
9743 
9744   if (Parser.parseToken(AsmToken::EndOfStatement))
9745     return true;
9746 
9747   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9748                                 static_cast<unsigned>(SPReg), Offset);
9749   return false;
9750 }
9751 
9752 /// parseDirective
9753 ///  ::= .pad offset
9754 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9755   MCAsmParser &Parser = getParser();
9756   // Check the ordering of unwind directives
9757   if (!UC.hasFnStart())
9758     return Error(L, ".fnstart must precede .pad directive");
9759   if (UC.hasHandlerData())
9760     return Error(L, ".pad must precede .handlerdata directive");
9761 
9762   // Parse the offset
9763   if (Parser.getTok().isNot(AsmToken::Hash) &&
9764       Parser.getTok().isNot(AsmToken::Dollar))
9765     return Error(Parser.getTok().getLoc(), "'#' expected");
9766   Parser.Lex(); // skip hash token.
9767 
9768   const MCExpr *OffsetExpr;
9769   SMLoc ExLoc = Parser.getTok().getLoc();
9770   SMLoc EndLoc;
9771   if (getParser().parseExpression(OffsetExpr, EndLoc))
9772     return Error(ExLoc, "malformed pad offset");
9773   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9774   if (!CE)
9775     return Error(ExLoc, "pad offset must be an immediate");
9776 
9777   if (parseToken(AsmToken::EndOfStatement,
9778                  "unexpected token in '.pad' directive"))
9779     return true;
9780 
9781   getTargetStreamer().emitPad(CE->getValue());
9782   return false;
9783 }
9784 
9785 /// parseDirectiveRegSave
9786 ///  ::= .save  { registers }
9787 ///  ::= .vsave { registers }
9788 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9789   // Check the ordering of unwind directives
9790   if (!UC.hasFnStart())
9791     return Error(L, ".fnstart must precede .save or .vsave directives");
9792   if (UC.hasHandlerData())
9793     return Error(L, ".save or .vsave must precede .handlerdata directive");
9794 
9795   // RAII object to make sure parsed operands are deleted.
9796   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9797 
9798   // Parse the register list
9799   if (parseRegisterList(Operands) ||
9800       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9801     return true;
9802   ARMOperand &Op = (ARMOperand &)*Operands[0];
9803   if (!IsVector && !Op.isRegList())
9804     return Error(L, ".save expects GPR registers");
9805   if (IsVector && !Op.isDPRRegList())
9806     return Error(L, ".vsave expects DPR registers");
9807 
9808   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9809   return false;
9810 }
9811 
9812 /// parseDirectiveInst
9813 ///  ::= .inst opcode [, ...]
9814 ///  ::= .inst.n opcode [, ...]
9815 ///  ::= .inst.w opcode [, ...]
9816 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9817   int Width = 4;
9818 
9819   if (isThumb()) {
9820     switch (Suffix) {
9821     case 'n':
9822       Width = 2;
9823       break;
9824     case 'w':
9825       break;
9826     default:
9827       return Error(Loc, "cannot determine Thumb instruction size, "
9828                         "use inst.n/inst.w instead");
9829     }
9830   } else {
9831     if (Suffix)
9832       return Error(Loc, "width suffixes are invalid in ARM mode");
9833   }
9834 
9835   auto parseOne = [&]() -> bool {
9836     const MCExpr *Expr;
9837     if (getParser().parseExpression(Expr))
9838       return true;
9839     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9840     if (!Value) {
9841       return Error(Loc, "expected constant expression");
9842     }
9843 
9844     switch (Width) {
9845     case 2:
9846       if (Value->getValue() > 0xffff)
9847         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9848       break;
9849     case 4:
9850       if (Value->getValue() > 0xffffffff)
9851         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9852                               " operand is too big");
9853       break;
9854     default:
9855       llvm_unreachable("only supported widths are 2 and 4");
9856     }
9857 
9858     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9859     return false;
9860   };
9861 
9862   if (parseOptionalToken(AsmToken::EndOfStatement))
9863     return Error(Loc, "expected expression following directive");
9864   if (parseMany(parseOne))
9865     return true;
9866   return false;
9867 }
9868 
9869 /// parseDirectiveLtorg
9870 ///  ::= .ltorg | .pool
9871 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9872   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9873     return true;
9874   getTargetStreamer().emitCurrentConstantPool();
9875   return false;
9876 }
9877 
9878 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9879   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9880 
9881   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9882     return true;
9883 
9884   if (!Section) {
9885     getStreamer().InitSections(false);
9886     Section = getStreamer().getCurrentSectionOnly();
9887   }
9888 
9889   assert(Section && "must have section to emit alignment");
9890   if (Section->UseCodeAlign())
9891     getStreamer().EmitCodeAlignment(2);
9892   else
9893     getStreamer().EmitValueToAlignment(2);
9894 
9895   return false;
9896 }
9897 
9898 /// parseDirectivePersonalityIndex
9899 ///   ::= .personalityindex index
9900 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9901   MCAsmParser &Parser = getParser();
9902   bool HasExistingPersonality = UC.hasPersonality();
9903 
9904   const MCExpr *IndexExpression;
9905   SMLoc IndexLoc = Parser.getTok().getLoc();
9906   if (Parser.parseExpression(IndexExpression) ||
9907       parseToken(AsmToken::EndOfStatement,
9908                  "unexpected token in '.personalityindex' directive")) {
9909     return true;
9910   }
9911 
9912   UC.recordPersonalityIndex(L);
9913 
9914   if (!UC.hasFnStart()) {
9915     return Error(L, ".fnstart must precede .personalityindex directive");
9916   }
9917   if (UC.cantUnwind()) {
9918     Error(L, ".personalityindex cannot be used with .cantunwind");
9919     UC.emitCantUnwindLocNotes();
9920     return true;
9921   }
9922   if (UC.hasHandlerData()) {
9923     Error(L, ".personalityindex must precede .handlerdata directive");
9924     UC.emitHandlerDataLocNotes();
9925     return true;
9926   }
9927   if (HasExistingPersonality) {
9928     Error(L, "multiple personality directives");
9929     UC.emitPersonalityLocNotes();
9930     return true;
9931   }
9932 
9933   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9934   if (!CE)
9935     return Error(IndexLoc, "index must be a constant number");
9936   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9937     return Error(IndexLoc,
9938                  "personality routine index should be in range [0-3]");
9939 
9940   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9941   return false;
9942 }
9943 
9944 /// parseDirectiveUnwindRaw
9945 ///   ::= .unwind_raw offset, opcode [, opcode...]
9946 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9947   MCAsmParser &Parser = getParser();
9948   int64_t StackOffset;
9949   const MCExpr *OffsetExpr;
9950   SMLoc OffsetLoc = getLexer().getLoc();
9951 
9952   if (!UC.hasFnStart())
9953     return Error(L, ".fnstart must precede .unwind_raw directives");
9954   if (getParser().parseExpression(OffsetExpr))
9955     return Error(OffsetLoc, "expected expression");
9956 
9957   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9958   if (!CE)
9959     return Error(OffsetLoc, "offset must be a constant");
9960 
9961   StackOffset = CE->getValue();
9962 
9963   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
9964     return true;
9965 
9966   SmallVector<uint8_t, 16> Opcodes;
9967 
9968   auto parseOne = [&]() -> bool {
9969     const MCExpr *OE;
9970     SMLoc OpcodeLoc = getLexer().getLoc();
9971     if (check(getLexer().is(AsmToken::EndOfStatement) ||
9972                   Parser.parseExpression(OE),
9973               OpcodeLoc, "expected opcode expression"))
9974       return true;
9975     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9976     if (!OC)
9977       return Error(OpcodeLoc, "opcode value must be a constant");
9978     const int64_t Opcode = OC->getValue();
9979     if (Opcode & ~0xff)
9980       return Error(OpcodeLoc, "invalid opcode");
9981     Opcodes.push_back(uint8_t(Opcode));
9982     return false;
9983   };
9984 
9985   // Must have at least 1 element
9986   SMLoc OpcodeLoc = getLexer().getLoc();
9987   if (parseOptionalToken(AsmToken::EndOfStatement))
9988     return Error(OpcodeLoc, "expected opcode expression");
9989   if (parseMany(parseOne))
9990     return true;
9991 
9992   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9993   return false;
9994 }
9995 
9996 /// parseDirectiveTLSDescSeq
9997 ///   ::= .tlsdescseq tls-variable
9998 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9999   MCAsmParser &Parser = getParser();
10000 
10001   if (getLexer().isNot(AsmToken::Identifier))
10002     return TokError("expected variable after '.tlsdescseq' directive");
10003 
10004   const MCSymbolRefExpr *SRE =
10005     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10006                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10007   Lex();
10008 
10009   if (parseToken(AsmToken::EndOfStatement,
10010                  "unexpected token in '.tlsdescseq' directive"))
10011     return true;
10012 
10013   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10014   return false;
10015 }
10016 
10017 /// parseDirectiveMovSP
10018 ///  ::= .movsp reg [, #offset]
10019 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10020   MCAsmParser &Parser = getParser();
10021   if (!UC.hasFnStart())
10022     return Error(L, ".fnstart must precede .movsp directives");
10023   if (UC.getFPReg() != ARM::SP)
10024     return Error(L, "unexpected .movsp directive");
10025 
10026   SMLoc SPRegLoc = Parser.getTok().getLoc();
10027   int SPReg = tryParseRegister();
10028   if (SPReg == -1)
10029     return Error(SPRegLoc, "register expected");
10030   if (SPReg == ARM::SP || SPReg == ARM::PC)
10031     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10032 
10033   int64_t Offset = 0;
10034   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10035     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10036       return true;
10037 
10038     const MCExpr *OffsetExpr;
10039     SMLoc OffsetLoc = Parser.getTok().getLoc();
10040 
10041     if (Parser.parseExpression(OffsetExpr))
10042       return Error(OffsetLoc, "malformed offset expression");
10043 
10044     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10045     if (!CE)
10046       return Error(OffsetLoc, "offset must be an immediate constant");
10047 
10048     Offset = CE->getValue();
10049   }
10050 
10051   if (parseToken(AsmToken::EndOfStatement,
10052                  "unexpected token in '.movsp' directive"))
10053     return true;
10054 
10055   getTargetStreamer().emitMovSP(SPReg, Offset);
10056   UC.saveFPReg(SPReg);
10057 
10058   return false;
10059 }
10060 
10061 /// parseDirectiveObjectArch
10062 ///   ::= .object_arch name
10063 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10064   MCAsmParser &Parser = getParser();
10065   if (getLexer().isNot(AsmToken::Identifier))
10066     return Error(getLexer().getLoc(), "unexpected token");
10067 
10068   StringRef Arch = Parser.getTok().getString();
10069   SMLoc ArchLoc = Parser.getTok().getLoc();
10070   Lex();
10071 
10072   ARM::ArchKind ID = ARM::parseArch(Arch);
10073 
10074   if (ID == ARM::ArchKind::INVALID)
10075     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10076   if (parseToken(AsmToken::EndOfStatement))
10077     return true;
10078 
10079   getTargetStreamer().emitObjectArch(ID);
10080   return false;
10081 }
10082 
10083 /// parseDirectiveAlign
10084 ///   ::= .align
10085 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10086   // NOTE: if this is not the end of the statement, fall back to the target
10087   // agnostic handling for this directive which will correctly handle this.
10088   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10089     // '.align' is target specifically handled to mean 2**2 byte alignment.
10090     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10091     assert(Section && "must have section to emit alignment");
10092     if (Section->UseCodeAlign())
10093       getStreamer().EmitCodeAlignment(4, 0);
10094     else
10095       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10096     return false;
10097   }
10098   return true;
10099 }
10100 
10101 /// parseDirectiveThumbSet
10102 ///  ::= .thumb_set name, value
10103 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10104   MCAsmParser &Parser = getParser();
10105 
10106   StringRef Name;
10107   if (check(Parser.parseIdentifier(Name),
10108             "expected identifier after '.thumb_set'") ||
10109       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10110     return true;
10111 
10112   MCSymbol *Sym;
10113   const MCExpr *Value;
10114   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10115                                                Parser, Sym, Value))
10116     return true;
10117 
10118   getTargetStreamer().emitThumbSet(Sym, Value);
10119   return false;
10120 }
10121 
10122 /// Force static initialization.
10123 extern "C" void LLVMInitializeARMAsmParser() {
10124   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10125   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10126   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10127   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10128 }
10129 
10130 #define GET_REGISTER_MATCHER
10131 #define GET_SUBTARGET_FEATURE_NAME
10132 #define GET_MATCHER_IMPLEMENTATION
10133 #include "ARMGenAsmMatcher.inc"
10134 
10135 // FIXME: This structure should be moved inside ARMTargetParser
10136 // when we start to table-generate them, and we can use the ARM
10137 // flags below, that were generated by table-gen.
10138 static const struct {
10139   const unsigned Kind;
10140   const uint64_t ArchCheck;
10141   const FeatureBitset Features;
10142 } Extensions[] = {
10143   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10144   { ARM::AEK_CRYPTO,  Feature_HasV8,
10145     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10146   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10147   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10148     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10149   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10150   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10151   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10152   // FIXME: Only available in A-class, isel not predicated
10153   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10154   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10155   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10156   // FIXME: Unsupported extensions.
10157   { ARM::AEK_OS, Feature_None, {} },
10158   { ARM::AEK_IWMMXT, Feature_None, {} },
10159   { ARM::AEK_IWMMXT2, Feature_None, {} },
10160   { ARM::AEK_MAVERICK, Feature_None, {} },
10161   { ARM::AEK_XSCALE, Feature_None, {} },
10162 };
10163 
10164 /// parseDirectiveArchExtension
10165 ///   ::= .arch_extension [no]feature
10166 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10167   MCAsmParser &Parser = getParser();
10168 
10169   if (getLexer().isNot(AsmToken::Identifier))
10170     return Error(getLexer().getLoc(), "expected architecture extension name");
10171 
10172   StringRef Name = Parser.getTok().getString();
10173   SMLoc ExtLoc = Parser.getTok().getLoc();
10174   Lex();
10175 
10176   if (parseToken(AsmToken::EndOfStatement,
10177                  "unexpected token in '.arch_extension' directive"))
10178     return true;
10179 
10180   bool EnableFeature = true;
10181   if (Name.startswith_lower("no")) {
10182     EnableFeature = false;
10183     Name = Name.substr(2);
10184   }
10185   unsigned FeatureKind = ARM::parseArchExt(Name);
10186   if (FeatureKind == ARM::AEK_INVALID)
10187     return Error(ExtLoc, "unknown architectural extension: " + Name);
10188 
10189   for (const auto &Extension : Extensions) {
10190     if (Extension.Kind != FeatureKind)
10191       continue;
10192 
10193     if (Extension.Features.none())
10194       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10195 
10196     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10197       return Error(ExtLoc, "architectural extension '" + Name +
10198                                "' is not "
10199                                "allowed for the current base architecture");
10200 
10201     MCSubtargetInfo &STI = copySTI();
10202     FeatureBitset ToggleFeatures = EnableFeature
10203       ? (~STI.getFeatureBits() & Extension.Features)
10204       : ( STI.getFeatureBits() & Extension.Features);
10205 
10206     uint64_t Features =
10207         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10208     setAvailableFeatures(Features);
10209     return false;
10210   }
10211 
10212   return Error(ExtLoc, "unknown architectural extension: " + Name);
10213 }
10214 
10215 // Define this matcher function after the auto-generated include so we
10216 // have the match class enum definitions.
10217 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10218                                                   unsigned Kind) {
10219   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10220   // If the kind is a token for a literal immediate, check if our asm
10221   // operand matches. This is for InstAliases which have a fixed-value
10222   // immediate in the syntax.
10223   switch (Kind) {
10224   default: break;
10225   case MCK__35_0:
10226     if (Op.isImm())
10227       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10228         if (CE->getValue() == 0)
10229           return Match_Success;
10230     break;
10231   case MCK_ModImm:
10232     if (Op.isImm()) {
10233       const MCExpr *SOExpr = Op.getImm();
10234       int64_t Value;
10235       if (!SOExpr->evaluateAsAbsolute(Value))
10236         return Match_Success;
10237       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
10238              "expression value must be representable in 32 bits");
10239     }
10240     break;
10241   case MCK_rGPR:
10242     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10243       return Match_Success;
10244     break;
10245   case MCK_GPRPair:
10246     if (Op.isReg() &&
10247         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10248       return Match_Success;
10249     break;
10250   }
10251   return Match_InvalidOperand;
10252 }
10253