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   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4179   if (!TheReg)
4180     return MatchOperand_NoMatch;
4181   unsigned Encoding = TheReg->Encoding;
4182 
4183   Parser.Lex(); // Eat identifier token.
4184   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4185   return MatchOperand_Success;
4186 }
4187 
4188 OperandMatchResultTy
4189 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4190                           int High) {
4191   MCAsmParser &Parser = getParser();
4192   const AsmToken &Tok = Parser.getTok();
4193   if (Tok.isNot(AsmToken::Identifier)) {
4194     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4195     return MatchOperand_ParseFail;
4196   }
4197   StringRef ShiftName = Tok.getString();
4198   std::string LowerOp = Op.lower();
4199   std::string UpperOp = Op.upper();
4200   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4201     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4202     return MatchOperand_ParseFail;
4203   }
4204   Parser.Lex(); // Eat shift type token.
4205 
4206   // There must be a '#' and a shift amount.
4207   if (Parser.getTok().isNot(AsmToken::Hash) &&
4208       Parser.getTok().isNot(AsmToken::Dollar)) {
4209     Error(Parser.getTok().getLoc(), "'#' expected");
4210     return MatchOperand_ParseFail;
4211   }
4212   Parser.Lex(); // Eat hash token.
4213 
4214   const MCExpr *ShiftAmount;
4215   SMLoc Loc = Parser.getTok().getLoc();
4216   SMLoc EndLoc;
4217   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4218     Error(Loc, "illegal expression");
4219     return MatchOperand_ParseFail;
4220   }
4221   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4222   if (!CE) {
4223     Error(Loc, "constant expression expected");
4224     return MatchOperand_ParseFail;
4225   }
4226   int Val = CE->getValue();
4227   if (Val < Low || Val > High) {
4228     Error(Loc, "immediate value out of range");
4229     return MatchOperand_ParseFail;
4230   }
4231 
4232   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4233 
4234   return MatchOperand_Success;
4235 }
4236 
4237 OperandMatchResultTy
4238 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4239   MCAsmParser &Parser = getParser();
4240   const AsmToken &Tok = Parser.getTok();
4241   SMLoc S = Tok.getLoc();
4242   if (Tok.isNot(AsmToken::Identifier)) {
4243     Error(S, "'be' or 'le' operand expected");
4244     return MatchOperand_ParseFail;
4245   }
4246   int Val = StringSwitch<int>(Tok.getString().lower())
4247     .Case("be", 1)
4248     .Case("le", 0)
4249     .Default(-1);
4250   Parser.Lex(); // Eat the token.
4251 
4252   if (Val == -1) {
4253     Error(S, "'be' or 'le' operand expected");
4254     return MatchOperand_ParseFail;
4255   }
4256   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4257                                                                   getContext()),
4258                                            S, Tok.getEndLoc()));
4259   return MatchOperand_Success;
4260 }
4261 
4262 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4263 /// instructions. Legal values are:
4264 ///     lsl #n  'n' in [0,31]
4265 ///     asr #n  'n' in [1,32]
4266 ///             n == 32 encoded as n == 0.
4267 OperandMatchResultTy
4268 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4269   MCAsmParser &Parser = getParser();
4270   const AsmToken &Tok = Parser.getTok();
4271   SMLoc S = Tok.getLoc();
4272   if (Tok.isNot(AsmToken::Identifier)) {
4273     Error(S, "shift operator 'asr' or 'lsl' expected");
4274     return MatchOperand_ParseFail;
4275   }
4276   StringRef ShiftName = Tok.getString();
4277   bool isASR;
4278   if (ShiftName == "lsl" || ShiftName == "LSL")
4279     isASR = false;
4280   else if (ShiftName == "asr" || ShiftName == "ASR")
4281     isASR = true;
4282   else {
4283     Error(S, "shift operator 'asr' or 'lsl' expected");
4284     return MatchOperand_ParseFail;
4285   }
4286   Parser.Lex(); // Eat the operator.
4287 
4288   // A '#' and a shift amount.
4289   if (Parser.getTok().isNot(AsmToken::Hash) &&
4290       Parser.getTok().isNot(AsmToken::Dollar)) {
4291     Error(Parser.getTok().getLoc(), "'#' expected");
4292     return MatchOperand_ParseFail;
4293   }
4294   Parser.Lex(); // Eat hash token.
4295   SMLoc ExLoc = Parser.getTok().getLoc();
4296 
4297   const MCExpr *ShiftAmount;
4298   SMLoc EndLoc;
4299   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4300     Error(ExLoc, "malformed shift expression");
4301     return MatchOperand_ParseFail;
4302   }
4303   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4304   if (!CE) {
4305     Error(ExLoc, "shift amount must be an immediate");
4306     return MatchOperand_ParseFail;
4307   }
4308 
4309   int64_t Val = CE->getValue();
4310   if (isASR) {
4311     // Shift amount must be in [1,32]
4312     if (Val < 1 || Val > 32) {
4313       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4314       return MatchOperand_ParseFail;
4315     }
4316     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4317     if (isThumb() && Val == 32) {
4318       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4319       return MatchOperand_ParseFail;
4320     }
4321     if (Val == 32) Val = 0;
4322   } else {
4323     // Shift amount must be in [1,32]
4324     if (Val < 0 || Val > 31) {
4325       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4326       return MatchOperand_ParseFail;
4327     }
4328   }
4329 
4330   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4331 
4332   return MatchOperand_Success;
4333 }
4334 
4335 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4336 /// of instructions. Legal values are:
4337 ///     ror #n  'n' in {0, 8, 16, 24}
4338 OperandMatchResultTy
4339 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4340   MCAsmParser &Parser = getParser();
4341   const AsmToken &Tok = Parser.getTok();
4342   SMLoc S = Tok.getLoc();
4343   if (Tok.isNot(AsmToken::Identifier))
4344     return MatchOperand_NoMatch;
4345   StringRef ShiftName = Tok.getString();
4346   if (ShiftName != "ror" && ShiftName != "ROR")
4347     return MatchOperand_NoMatch;
4348   Parser.Lex(); // Eat the operator.
4349 
4350   // A '#' and a rotate amount.
4351   if (Parser.getTok().isNot(AsmToken::Hash) &&
4352       Parser.getTok().isNot(AsmToken::Dollar)) {
4353     Error(Parser.getTok().getLoc(), "'#' expected");
4354     return MatchOperand_ParseFail;
4355   }
4356   Parser.Lex(); // Eat hash token.
4357   SMLoc ExLoc = Parser.getTok().getLoc();
4358 
4359   const MCExpr *ShiftAmount;
4360   SMLoc EndLoc;
4361   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4362     Error(ExLoc, "malformed rotate expression");
4363     return MatchOperand_ParseFail;
4364   }
4365   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4366   if (!CE) {
4367     Error(ExLoc, "rotate amount must be an immediate");
4368     return MatchOperand_ParseFail;
4369   }
4370 
4371   int64_t Val = CE->getValue();
4372   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4373   // normally, zero is represented in asm by omitting the rotate operand
4374   // entirely.
4375   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4376     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4377     return MatchOperand_ParseFail;
4378   }
4379 
4380   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4381 
4382   return MatchOperand_Success;
4383 }
4384 
4385 OperandMatchResultTy
4386 ARMAsmParser::parseModImm(OperandVector &Operands) {
4387   MCAsmParser &Parser = getParser();
4388   MCAsmLexer &Lexer = getLexer();
4389   int64_t Imm1, Imm2;
4390 
4391   SMLoc S = Parser.getTok().getLoc();
4392 
4393   // 1) A mod_imm operand can appear in the place of a register name:
4394   //   add r0, #mod_imm
4395   //   add r0, r0, #mod_imm
4396   // to correctly handle the latter, we bail out as soon as we see an
4397   // identifier.
4398   //
4399   // 2) Similarly, we do not want to parse into complex operands:
4400   //   mov r0, #mod_imm
4401   //   mov r0, :lower16:(_foo)
4402   if (Parser.getTok().is(AsmToken::Identifier) ||
4403       Parser.getTok().is(AsmToken::Colon))
4404     return MatchOperand_NoMatch;
4405 
4406   // Hash (dollar) is optional as per the ARMARM
4407   if (Parser.getTok().is(AsmToken::Hash) ||
4408       Parser.getTok().is(AsmToken::Dollar)) {
4409     // Avoid parsing into complex operands (#:)
4410     if (Lexer.peekTok().is(AsmToken::Colon))
4411       return MatchOperand_NoMatch;
4412 
4413     // Eat the hash (dollar)
4414     Parser.Lex();
4415   }
4416 
4417   SMLoc Sx1, Ex1;
4418   Sx1 = Parser.getTok().getLoc();
4419   const MCExpr *Imm1Exp;
4420   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4421     Error(Sx1, "malformed expression");
4422     return MatchOperand_ParseFail;
4423   }
4424 
4425   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4426 
4427   if (CE) {
4428     // Immediate must fit within 32-bits
4429     Imm1 = CE->getValue();
4430     int Enc = ARM_AM::getSOImmVal(Imm1);
4431     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4432       // We have a match!
4433       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4434                                                   (Enc & 0xF00) >> 7,
4435                                                   Sx1, Ex1));
4436       return MatchOperand_Success;
4437     }
4438 
4439     // We have parsed an immediate which is not for us, fallback to a plain
4440     // immediate. This can happen for instruction aliases. For an example,
4441     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4442     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4443     // instruction with a mod_imm operand. The alias is defined such that the
4444     // parser method is shared, that's why we have to do this here.
4445     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4446       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4447       return MatchOperand_Success;
4448     }
4449   } else {
4450     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4451     // MCFixup). Fallback to a plain immediate.
4452     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4453     return MatchOperand_Success;
4454   }
4455 
4456   // From this point onward, we expect the input to be a (#bits, #rot) pair
4457   if (Parser.getTok().isNot(AsmToken::Comma)) {
4458     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4459     return MatchOperand_ParseFail;
4460   }
4461 
4462   if (Imm1 & ~0xFF) {
4463     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4464     return MatchOperand_ParseFail;
4465   }
4466 
4467   // Eat the comma
4468   Parser.Lex();
4469 
4470   // Repeat for #rot
4471   SMLoc Sx2, Ex2;
4472   Sx2 = Parser.getTok().getLoc();
4473 
4474   // Eat the optional hash (dollar)
4475   if (Parser.getTok().is(AsmToken::Hash) ||
4476       Parser.getTok().is(AsmToken::Dollar))
4477     Parser.Lex();
4478 
4479   const MCExpr *Imm2Exp;
4480   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4481     Error(Sx2, "malformed expression");
4482     return MatchOperand_ParseFail;
4483   }
4484 
4485   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4486 
4487   if (CE) {
4488     Imm2 = CE->getValue();
4489     if (!(Imm2 & ~0x1E)) {
4490       // We have a match!
4491       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4492       return MatchOperand_Success;
4493     }
4494     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4495     return MatchOperand_ParseFail;
4496   } else {
4497     Error(Sx2, "constant expression expected");
4498     return MatchOperand_ParseFail;
4499   }
4500 }
4501 
4502 OperandMatchResultTy
4503 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4504   MCAsmParser &Parser = getParser();
4505   SMLoc S = Parser.getTok().getLoc();
4506   // The bitfield descriptor is really two operands, the LSB and the width.
4507   if (Parser.getTok().isNot(AsmToken::Hash) &&
4508       Parser.getTok().isNot(AsmToken::Dollar)) {
4509     Error(Parser.getTok().getLoc(), "'#' expected");
4510     return MatchOperand_ParseFail;
4511   }
4512   Parser.Lex(); // Eat hash token.
4513 
4514   const MCExpr *LSBExpr;
4515   SMLoc E = Parser.getTok().getLoc();
4516   if (getParser().parseExpression(LSBExpr)) {
4517     Error(E, "malformed immediate expression");
4518     return MatchOperand_ParseFail;
4519   }
4520   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4521   if (!CE) {
4522     Error(E, "'lsb' operand must be an immediate");
4523     return MatchOperand_ParseFail;
4524   }
4525 
4526   int64_t LSB = CE->getValue();
4527   // The LSB must be in the range [0,31]
4528   if (LSB < 0 || LSB > 31) {
4529     Error(E, "'lsb' operand must be in the range [0,31]");
4530     return MatchOperand_ParseFail;
4531   }
4532   E = Parser.getTok().getLoc();
4533 
4534   // Expect another immediate operand.
4535   if (Parser.getTok().isNot(AsmToken::Comma)) {
4536     Error(Parser.getTok().getLoc(), "too few operands");
4537     return MatchOperand_ParseFail;
4538   }
4539   Parser.Lex(); // Eat hash token.
4540   if (Parser.getTok().isNot(AsmToken::Hash) &&
4541       Parser.getTok().isNot(AsmToken::Dollar)) {
4542     Error(Parser.getTok().getLoc(), "'#' expected");
4543     return MatchOperand_ParseFail;
4544   }
4545   Parser.Lex(); // Eat hash token.
4546 
4547   const MCExpr *WidthExpr;
4548   SMLoc EndLoc;
4549   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4550     Error(E, "malformed immediate expression");
4551     return MatchOperand_ParseFail;
4552   }
4553   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4554   if (!CE) {
4555     Error(E, "'width' operand must be an immediate");
4556     return MatchOperand_ParseFail;
4557   }
4558 
4559   int64_t Width = CE->getValue();
4560   // The LSB must be in the range [1,32-lsb]
4561   if (Width < 1 || Width > 32 - LSB) {
4562     Error(E, "'width' operand must be in the range [1,32-lsb]");
4563     return MatchOperand_ParseFail;
4564   }
4565 
4566   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4567 
4568   return MatchOperand_Success;
4569 }
4570 
4571 OperandMatchResultTy
4572 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4573   // Check for a post-index addressing register operand. Specifically:
4574   // postidx_reg := '+' register {, shift}
4575   //              | '-' register {, shift}
4576   //              | register {, shift}
4577 
4578   // This method must return MatchOperand_NoMatch without consuming any tokens
4579   // in the case where there is no match, as other alternatives take other
4580   // parse methods.
4581   MCAsmParser &Parser = getParser();
4582   AsmToken Tok = Parser.getTok();
4583   SMLoc S = Tok.getLoc();
4584   bool haveEaten = false;
4585   bool isAdd = true;
4586   if (Tok.is(AsmToken::Plus)) {
4587     Parser.Lex(); // Eat the '+' token.
4588     haveEaten = true;
4589   } else if (Tok.is(AsmToken::Minus)) {
4590     Parser.Lex(); // Eat the '-' token.
4591     isAdd = false;
4592     haveEaten = true;
4593   }
4594 
4595   SMLoc E = Parser.getTok().getEndLoc();
4596   int Reg = tryParseRegister();
4597   if (Reg == -1) {
4598     if (!haveEaten)
4599       return MatchOperand_NoMatch;
4600     Error(Parser.getTok().getLoc(), "register expected");
4601     return MatchOperand_ParseFail;
4602   }
4603 
4604   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4605   unsigned ShiftImm = 0;
4606   if (Parser.getTok().is(AsmToken::Comma)) {
4607     Parser.Lex(); // Eat the ','.
4608     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4609       return MatchOperand_ParseFail;
4610 
4611     // FIXME: Only approximates end...may include intervening whitespace.
4612     E = Parser.getTok().getLoc();
4613   }
4614 
4615   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4616                                                   ShiftImm, S, E));
4617 
4618   return MatchOperand_Success;
4619 }
4620 
4621 OperandMatchResultTy
4622 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4623   // Check for a post-index addressing register operand. Specifically:
4624   // am3offset := '+' register
4625   //              | '-' register
4626   //              | register
4627   //              | # imm
4628   //              | # + imm
4629   //              | # - imm
4630 
4631   // This method must return MatchOperand_NoMatch without consuming any tokens
4632   // in the case where there is no match, as other alternatives take other
4633   // parse methods.
4634   MCAsmParser &Parser = getParser();
4635   AsmToken Tok = Parser.getTok();
4636   SMLoc S = Tok.getLoc();
4637 
4638   // Do immediates first, as we always parse those if we have a '#'.
4639   if (Parser.getTok().is(AsmToken::Hash) ||
4640       Parser.getTok().is(AsmToken::Dollar)) {
4641     Parser.Lex(); // Eat '#' or '$'.
4642     // Explicitly look for a '-', as we need to encode negative zero
4643     // differently.
4644     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4645     const MCExpr *Offset;
4646     SMLoc E;
4647     if (getParser().parseExpression(Offset, E))
4648       return MatchOperand_ParseFail;
4649     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4650     if (!CE) {
4651       Error(S, "constant expression expected");
4652       return MatchOperand_ParseFail;
4653     }
4654     // Negative zero is encoded as the flag value INT32_MIN.
4655     int32_t Val = CE->getValue();
4656     if (isNegative && Val == 0)
4657       Val = INT32_MIN;
4658 
4659     Operands.push_back(
4660       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4661 
4662     return MatchOperand_Success;
4663   }
4664 
4665 
4666   bool haveEaten = false;
4667   bool isAdd = true;
4668   if (Tok.is(AsmToken::Plus)) {
4669     Parser.Lex(); // Eat the '+' token.
4670     haveEaten = true;
4671   } else if (Tok.is(AsmToken::Minus)) {
4672     Parser.Lex(); // Eat the '-' token.
4673     isAdd = false;
4674     haveEaten = true;
4675   }
4676 
4677   Tok = Parser.getTok();
4678   int Reg = tryParseRegister();
4679   if (Reg == -1) {
4680     if (!haveEaten)
4681       return MatchOperand_NoMatch;
4682     Error(Tok.getLoc(), "register expected");
4683     return MatchOperand_ParseFail;
4684   }
4685 
4686   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4687                                                   0, S, Tok.getEndLoc()));
4688 
4689   return MatchOperand_Success;
4690 }
4691 
4692 /// Convert parsed operands to MCInst.  Needed here because this instruction
4693 /// only has two register operands, but multiplication is commutative so
4694 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4695 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4696                                     const OperandVector &Operands) {
4697   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4698   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4699   // If we have a three-operand form, make sure to set Rn to be the operand
4700   // that isn't the same as Rd.
4701   unsigned RegOp = 4;
4702   if (Operands.size() == 6 &&
4703       ((ARMOperand &)*Operands[4]).getReg() ==
4704           ((ARMOperand &)*Operands[3]).getReg())
4705     RegOp = 5;
4706   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4707   Inst.addOperand(Inst.getOperand(0));
4708   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4709 }
4710 
4711 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4712                                     const OperandVector &Operands) {
4713   int CondOp = -1, ImmOp = -1;
4714   switch(Inst.getOpcode()) {
4715     case ARM::tB:
4716     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4717 
4718     case ARM::t2B:
4719     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4720 
4721     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4722   }
4723   // first decide whether or not the branch should be conditional
4724   // by looking at it's location relative to an IT block
4725   if(inITBlock()) {
4726     // inside an IT block we cannot have any conditional branches. any
4727     // such instructions needs to be converted to unconditional form
4728     switch(Inst.getOpcode()) {
4729       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4730       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4731     }
4732   } else {
4733     // outside IT blocks we can only have unconditional branches with AL
4734     // condition code or conditional branches with non-AL condition code
4735     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4736     switch(Inst.getOpcode()) {
4737       case ARM::tB:
4738       case ARM::tBcc:
4739         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4740         break;
4741       case ARM::t2B:
4742       case ARM::t2Bcc:
4743         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4744         break;
4745     }
4746   }
4747 
4748   // now decide on encoding size based on branch target range
4749   switch(Inst.getOpcode()) {
4750     // classify tB as either t2B or t1B based on range of immediate operand
4751     case ARM::tB: {
4752       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4753       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4754         Inst.setOpcode(ARM::t2B);
4755       break;
4756     }
4757     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4758     case ARM::tBcc: {
4759       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4760       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4761         Inst.setOpcode(ARM::t2Bcc);
4762       break;
4763     }
4764   }
4765   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4766   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4767 }
4768 
4769 /// Parse an ARM memory expression, return false if successful else return true
4770 /// or an error.  The first token must be a '[' when called.
4771 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4772   MCAsmParser &Parser = getParser();
4773   SMLoc S, E;
4774   if (Parser.getTok().isNot(AsmToken::LBrac))
4775     return TokError("Token is not a Left Bracket");
4776   S = Parser.getTok().getLoc();
4777   Parser.Lex(); // Eat left bracket token.
4778 
4779   const AsmToken &BaseRegTok = Parser.getTok();
4780   int BaseRegNum = tryParseRegister();
4781   if (BaseRegNum == -1)
4782     return Error(BaseRegTok.getLoc(), "register expected");
4783 
4784   // The next token must either be a comma, a colon or a closing bracket.
4785   const AsmToken &Tok = Parser.getTok();
4786   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4787       !Tok.is(AsmToken::RBrac))
4788     return Error(Tok.getLoc(), "malformed memory operand");
4789 
4790   if (Tok.is(AsmToken::RBrac)) {
4791     E = Tok.getEndLoc();
4792     Parser.Lex(); // Eat right bracket token.
4793 
4794     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4795                                              ARM_AM::no_shift, 0, 0, false,
4796                                              S, E));
4797 
4798     // If there's a pre-indexing writeback marker, '!', just add it as a token
4799     // operand. It's rather odd, but syntactically valid.
4800     if (Parser.getTok().is(AsmToken::Exclaim)) {
4801       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4802       Parser.Lex(); // Eat the '!'.
4803     }
4804 
4805     return false;
4806   }
4807 
4808   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4809          "Lost colon or comma in memory operand?!");
4810   if (Tok.is(AsmToken::Comma)) {
4811     Parser.Lex(); // Eat the comma.
4812   }
4813 
4814   // If we have a ':', it's an alignment specifier.
4815   if (Parser.getTok().is(AsmToken::Colon)) {
4816     Parser.Lex(); // Eat the ':'.
4817     E = Parser.getTok().getLoc();
4818     SMLoc AlignmentLoc = Tok.getLoc();
4819 
4820     const MCExpr *Expr;
4821     if (getParser().parseExpression(Expr))
4822      return true;
4823 
4824     // The expression has to be a constant. Memory references with relocations
4825     // don't come through here, as they use the <label> forms of the relevant
4826     // instructions.
4827     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4828     if (!CE)
4829       return Error (E, "constant expression expected");
4830 
4831     unsigned Align = 0;
4832     switch (CE->getValue()) {
4833     default:
4834       return Error(E,
4835                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4836     case 16:  Align = 2; break;
4837     case 32:  Align = 4; break;
4838     case 64:  Align = 8; break;
4839     case 128: Align = 16; break;
4840     case 256: Align = 32; break;
4841     }
4842 
4843     // Now we should have the closing ']'
4844     if (Parser.getTok().isNot(AsmToken::RBrac))
4845       return Error(Parser.getTok().getLoc(), "']' expected");
4846     E = Parser.getTok().getEndLoc();
4847     Parser.Lex(); // Eat right bracket token.
4848 
4849     // Don't worry about range checking the value here. That's handled by
4850     // the is*() predicates.
4851     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4852                                              ARM_AM::no_shift, 0, Align,
4853                                              false, S, E, AlignmentLoc));
4854 
4855     // If there's a pre-indexing writeback marker, '!', just add it as a token
4856     // operand.
4857     if (Parser.getTok().is(AsmToken::Exclaim)) {
4858       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4859       Parser.Lex(); // Eat the '!'.
4860     }
4861 
4862     return false;
4863   }
4864 
4865   // If we have a '#', it's an immediate offset, else assume it's a register
4866   // offset. Be friendly and also accept a plain integer (without a leading
4867   // hash) for gas compatibility.
4868   if (Parser.getTok().is(AsmToken::Hash) ||
4869       Parser.getTok().is(AsmToken::Dollar) ||
4870       Parser.getTok().is(AsmToken::Integer)) {
4871     if (Parser.getTok().isNot(AsmToken::Integer))
4872       Parser.Lex(); // Eat '#' or '$'.
4873     E = Parser.getTok().getLoc();
4874 
4875     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4876     const MCExpr *Offset;
4877     if (getParser().parseExpression(Offset))
4878      return true;
4879 
4880     // The expression has to be a constant. Memory references with relocations
4881     // don't come through here, as they use the <label> forms of the relevant
4882     // instructions.
4883     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4884     if (!CE)
4885       return Error (E, "constant expression expected");
4886 
4887     // If the constant was #-0, represent it as INT32_MIN.
4888     int32_t Val = CE->getValue();
4889     if (isNegative && Val == 0)
4890       CE = MCConstantExpr::create(INT32_MIN, getContext());
4891 
4892     // Now we should have the closing ']'
4893     if (Parser.getTok().isNot(AsmToken::RBrac))
4894       return Error(Parser.getTok().getLoc(), "']' expected");
4895     E = Parser.getTok().getEndLoc();
4896     Parser.Lex(); // Eat right bracket token.
4897 
4898     // Don't worry about range checking the value here. That's handled by
4899     // the is*() predicates.
4900     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4901                                              ARM_AM::no_shift, 0, 0,
4902                                              false, S, E));
4903 
4904     // If there's a pre-indexing writeback marker, '!', just add it as a token
4905     // operand.
4906     if (Parser.getTok().is(AsmToken::Exclaim)) {
4907       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4908       Parser.Lex(); // Eat the '!'.
4909     }
4910 
4911     return false;
4912   }
4913 
4914   // The register offset is optionally preceded by a '+' or '-'
4915   bool isNegative = false;
4916   if (Parser.getTok().is(AsmToken::Minus)) {
4917     isNegative = true;
4918     Parser.Lex(); // Eat the '-'.
4919   } else if (Parser.getTok().is(AsmToken::Plus)) {
4920     // Nothing to do.
4921     Parser.Lex(); // Eat the '+'.
4922   }
4923 
4924   E = Parser.getTok().getLoc();
4925   int OffsetRegNum = tryParseRegister();
4926   if (OffsetRegNum == -1)
4927     return Error(E, "register expected");
4928 
4929   // If there's a shift operator, handle it.
4930   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4931   unsigned ShiftImm = 0;
4932   if (Parser.getTok().is(AsmToken::Comma)) {
4933     Parser.Lex(); // Eat the ','.
4934     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4935       return true;
4936   }
4937 
4938   // Now we should have the closing ']'
4939   if (Parser.getTok().isNot(AsmToken::RBrac))
4940     return Error(Parser.getTok().getLoc(), "']' expected");
4941   E = Parser.getTok().getEndLoc();
4942   Parser.Lex(); // Eat right bracket token.
4943 
4944   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
4945                                            ShiftType, ShiftImm, 0, isNegative,
4946                                            S, E));
4947 
4948   // If there's a pre-indexing writeback marker, '!', just add it as a token
4949   // operand.
4950   if (Parser.getTok().is(AsmToken::Exclaim)) {
4951     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4952     Parser.Lex(); // Eat the '!'.
4953   }
4954 
4955   return false;
4956 }
4957 
4958 /// parseMemRegOffsetShift - one of these two:
4959 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4960 ///   rrx
4961 /// return true if it parses a shift otherwise it returns false.
4962 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4963                                           unsigned &Amount) {
4964   MCAsmParser &Parser = getParser();
4965   SMLoc Loc = Parser.getTok().getLoc();
4966   const AsmToken &Tok = Parser.getTok();
4967   if (Tok.isNot(AsmToken::Identifier))
4968     return true;
4969   StringRef ShiftName = Tok.getString();
4970   if (ShiftName == "lsl" || ShiftName == "LSL" ||
4971       ShiftName == "asl" || ShiftName == "ASL")
4972     St = ARM_AM::lsl;
4973   else if (ShiftName == "lsr" || ShiftName == "LSR")
4974     St = ARM_AM::lsr;
4975   else if (ShiftName == "asr" || ShiftName == "ASR")
4976     St = ARM_AM::asr;
4977   else if (ShiftName == "ror" || ShiftName == "ROR")
4978     St = ARM_AM::ror;
4979   else if (ShiftName == "rrx" || ShiftName == "RRX")
4980     St = ARM_AM::rrx;
4981   else
4982     return Error(Loc, "illegal shift operator");
4983   Parser.Lex(); // Eat shift type token.
4984 
4985   // rrx stands alone.
4986   Amount = 0;
4987   if (St != ARM_AM::rrx) {
4988     Loc = Parser.getTok().getLoc();
4989     // A '#' and a shift amount.
4990     const AsmToken &HashTok = Parser.getTok();
4991     if (HashTok.isNot(AsmToken::Hash) &&
4992         HashTok.isNot(AsmToken::Dollar))
4993       return Error(HashTok.getLoc(), "'#' expected");
4994     Parser.Lex(); // Eat hash token.
4995 
4996     const MCExpr *Expr;
4997     if (getParser().parseExpression(Expr))
4998       return true;
4999     // Range check the immediate.
5000     // lsl, ror: 0 <= imm <= 31
5001     // lsr, asr: 0 <= imm <= 32
5002     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5003     if (!CE)
5004       return Error(Loc, "shift amount must be an immediate");
5005     int64_t Imm = CE->getValue();
5006     if (Imm < 0 ||
5007         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5008         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5009       return Error(Loc, "immediate shift value out of range");
5010     // If <ShiftTy> #0, turn it into a no_shift.
5011     if (Imm == 0)
5012       St = ARM_AM::lsl;
5013     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5014     if (Imm == 32)
5015       Imm = 0;
5016     Amount = Imm;
5017   }
5018 
5019   return false;
5020 }
5021 
5022 /// parseFPImm - A floating point immediate expression operand.
5023 OperandMatchResultTy
5024 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5025   MCAsmParser &Parser = getParser();
5026   // Anything that can accept a floating point constant as an operand
5027   // needs to go through here, as the regular parseExpression is
5028   // integer only.
5029   //
5030   // This routine still creates a generic Immediate operand, containing
5031   // a bitcast of the 64-bit floating point value. The various operands
5032   // that accept floats can check whether the value is valid for them
5033   // via the standard is*() predicates.
5034 
5035   SMLoc S = Parser.getTok().getLoc();
5036 
5037   if (Parser.getTok().isNot(AsmToken::Hash) &&
5038       Parser.getTok().isNot(AsmToken::Dollar))
5039     return MatchOperand_NoMatch;
5040 
5041   // Disambiguate the VMOV forms that can accept an FP immediate.
5042   // vmov.f32 <sreg>, #imm
5043   // vmov.f64 <dreg>, #imm
5044   // vmov.f32 <dreg>, #imm  @ vector f32x2
5045   // vmov.f32 <qreg>, #imm  @ vector f32x4
5046   //
5047   // There are also the NEON VMOV instructions which expect an
5048   // integer constant. Make sure we don't try to parse an FPImm
5049   // for these:
5050   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5051   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5052   bool isVmovf = TyOp.isToken() &&
5053                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5054                   TyOp.getToken() == ".f16");
5055   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5056   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5057                                          Mnemonic.getToken() == "fconsts");
5058   if (!(isVmovf || isFconst))
5059     return MatchOperand_NoMatch;
5060 
5061   Parser.Lex(); // Eat '#' or '$'.
5062 
5063   // Handle negation, as that still comes through as a separate token.
5064   bool isNegative = false;
5065   if (Parser.getTok().is(AsmToken::Minus)) {
5066     isNegative = true;
5067     Parser.Lex();
5068   }
5069   const AsmToken &Tok = Parser.getTok();
5070   SMLoc Loc = Tok.getLoc();
5071   if (Tok.is(AsmToken::Real) && isVmovf) {
5072     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5073     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5074     // If we had a '-' in front, toggle the sign bit.
5075     IntVal ^= (uint64_t)isNegative << 31;
5076     Parser.Lex(); // Eat the token.
5077     Operands.push_back(ARMOperand::CreateImm(
5078           MCConstantExpr::create(IntVal, getContext()),
5079           S, Parser.getTok().getLoc()));
5080     return MatchOperand_Success;
5081   }
5082   // Also handle plain integers. Instructions which allow floating point
5083   // immediates also allow a raw encoded 8-bit value.
5084   if (Tok.is(AsmToken::Integer) && isFconst) {
5085     int64_t Val = Tok.getIntVal();
5086     Parser.Lex(); // Eat the token.
5087     if (Val > 255 || Val < 0) {
5088       Error(Loc, "encoded floating point value out of range");
5089       return MatchOperand_ParseFail;
5090     }
5091     float RealVal = ARM_AM::getFPImmFloat(Val);
5092     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5093 
5094     Operands.push_back(ARMOperand::CreateImm(
5095         MCConstantExpr::create(Val, getContext()), S,
5096         Parser.getTok().getLoc()));
5097     return MatchOperand_Success;
5098   }
5099 
5100   Error(Loc, "invalid floating point immediate");
5101   return MatchOperand_ParseFail;
5102 }
5103 
5104 /// Parse a arm instruction operand.  For now this parses the operand regardless
5105 /// of the mnemonic.
5106 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5107   MCAsmParser &Parser = getParser();
5108   SMLoc S, E;
5109 
5110   // Check if the current operand has a custom associated parser, if so, try to
5111   // custom parse the operand, or fallback to the general approach.
5112   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5113   if (ResTy == MatchOperand_Success)
5114     return false;
5115   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5116   // there was a match, but an error occurred, in which case, just return that
5117   // the operand parsing failed.
5118   if (ResTy == MatchOperand_ParseFail)
5119     return true;
5120 
5121   switch (getLexer().getKind()) {
5122   default:
5123     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5124     return true;
5125   case AsmToken::Identifier: {
5126     // If we've seen a branch mnemonic, the next operand must be a label.  This
5127     // is true even if the label is a register name.  So "br r1" means branch to
5128     // label "r1".
5129     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5130     if (!ExpectLabel) {
5131       if (!tryParseRegisterWithWriteBack(Operands))
5132         return false;
5133       int Res = tryParseShiftRegister(Operands);
5134       if (Res == 0) // success
5135         return false;
5136       else if (Res == -1) // irrecoverable error
5137         return true;
5138       // If this is VMRS, check for the apsr_nzcv operand.
5139       if (Mnemonic == "vmrs" &&
5140           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5141         S = Parser.getTok().getLoc();
5142         Parser.Lex();
5143         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5144         return false;
5145       }
5146     }
5147 
5148     // Fall though for the Identifier case that is not a register or a
5149     // special name.
5150     LLVM_FALLTHROUGH;
5151   }
5152   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5153   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5154   case AsmToken::String:  // quoted label names.
5155   case AsmToken::Dot: {   // . as a branch target
5156     // This was not a register so parse other operands that start with an
5157     // identifier (like labels) as expressions and create them as immediates.
5158     const MCExpr *IdVal;
5159     S = Parser.getTok().getLoc();
5160     if (getParser().parseExpression(IdVal))
5161       return true;
5162     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5163     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5164     return false;
5165   }
5166   case AsmToken::LBrac:
5167     return parseMemory(Operands);
5168   case AsmToken::LCurly:
5169     return parseRegisterList(Operands);
5170   case AsmToken::Dollar:
5171   case AsmToken::Hash: {
5172     // #42 -> immediate.
5173     S = Parser.getTok().getLoc();
5174     Parser.Lex();
5175 
5176     if (Parser.getTok().isNot(AsmToken::Colon)) {
5177       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5178       const MCExpr *ImmVal;
5179       if (getParser().parseExpression(ImmVal))
5180         return true;
5181       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5182       if (CE) {
5183         int32_t Val = CE->getValue();
5184         if (isNegative && Val == 0)
5185           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5186       }
5187       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5188       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5189 
5190       // There can be a trailing '!' on operands that we want as a separate
5191       // '!' Token operand. Handle that here. For example, the compatibility
5192       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5193       if (Parser.getTok().is(AsmToken::Exclaim)) {
5194         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5195                                                    Parser.getTok().getLoc()));
5196         Parser.Lex(); // Eat exclaim token
5197       }
5198       return false;
5199     }
5200     // w/ a ':' after the '#', it's just like a plain ':'.
5201     LLVM_FALLTHROUGH;
5202   }
5203   case AsmToken::Colon: {
5204     S = Parser.getTok().getLoc();
5205     // ":lower16:" and ":upper16:" expression prefixes
5206     // FIXME: Check it's an expression prefix,
5207     // e.g. (FOO - :lower16:BAR) isn't legal.
5208     ARMMCExpr::VariantKind RefKind;
5209     if (parsePrefix(RefKind))
5210       return true;
5211 
5212     const MCExpr *SubExprVal;
5213     if (getParser().parseExpression(SubExprVal))
5214       return true;
5215 
5216     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5217                                               getContext());
5218     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5219     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5220     return false;
5221   }
5222   case AsmToken::Equal: {
5223     S = Parser.getTok().getLoc();
5224     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5225       return Error(S, "unexpected token in operand");
5226     Parser.Lex(); // Eat '='
5227     const MCExpr *SubExprVal;
5228     if (getParser().parseExpression(SubExprVal))
5229       return true;
5230     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5231 
5232     // execute-only: we assume that assembly programmers know what they are
5233     // doing and allow literal pool creation here
5234     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5235     return false;
5236   }
5237   }
5238 }
5239 
5240 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5241 //  :lower16: and :upper16:.
5242 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5243   MCAsmParser &Parser = getParser();
5244   RefKind = ARMMCExpr::VK_ARM_None;
5245 
5246   // consume an optional '#' (GNU compatibility)
5247   if (getLexer().is(AsmToken::Hash))
5248     Parser.Lex();
5249 
5250   // :lower16: and :upper16: modifiers
5251   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5252   Parser.Lex(); // Eat ':'
5253 
5254   if (getLexer().isNot(AsmToken::Identifier)) {
5255     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5256     return true;
5257   }
5258 
5259   enum {
5260     COFF = (1 << MCObjectFileInfo::IsCOFF),
5261     ELF = (1 << MCObjectFileInfo::IsELF),
5262     MACHO = (1 << MCObjectFileInfo::IsMachO),
5263     WASM = (1 << MCObjectFileInfo::IsWasm),
5264   };
5265   static const struct PrefixEntry {
5266     const char *Spelling;
5267     ARMMCExpr::VariantKind VariantKind;
5268     uint8_t SupportedFormats;
5269   } PrefixEntries[] = {
5270     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5271     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5272   };
5273 
5274   StringRef IDVal = Parser.getTok().getIdentifier();
5275 
5276   const auto &Prefix =
5277       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5278                    [&IDVal](const PrefixEntry &PE) {
5279                       return PE.Spelling == IDVal;
5280                    });
5281   if (Prefix == std::end(PrefixEntries)) {
5282     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5283     return true;
5284   }
5285 
5286   uint8_t CurrentFormat;
5287   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5288   case MCObjectFileInfo::IsMachO:
5289     CurrentFormat = MACHO;
5290     break;
5291   case MCObjectFileInfo::IsELF:
5292     CurrentFormat = ELF;
5293     break;
5294   case MCObjectFileInfo::IsCOFF:
5295     CurrentFormat = COFF;
5296     break;
5297   case MCObjectFileInfo::IsWasm:
5298     CurrentFormat = WASM;
5299     break;
5300   }
5301 
5302   if (~Prefix->SupportedFormats & CurrentFormat) {
5303     Error(Parser.getTok().getLoc(),
5304           "cannot represent relocation in the current file format");
5305     return true;
5306   }
5307 
5308   RefKind = Prefix->VariantKind;
5309   Parser.Lex();
5310 
5311   if (getLexer().isNot(AsmToken::Colon)) {
5312     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5313     return true;
5314   }
5315   Parser.Lex(); // Eat the last ':'
5316 
5317   return false;
5318 }
5319 
5320 /// \brief Given a mnemonic, split out possible predication code and carry
5321 /// setting letters to form a canonical mnemonic and flags.
5322 //
5323 // FIXME: Would be nice to autogen this.
5324 // FIXME: This is a bit of a maze of special cases.
5325 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5326                                       unsigned &PredicationCode,
5327                                       bool &CarrySetting,
5328                                       unsigned &ProcessorIMod,
5329                                       StringRef &ITMask) {
5330   PredicationCode = ARMCC::AL;
5331   CarrySetting = false;
5332   ProcessorIMod = 0;
5333 
5334   // Ignore some mnemonics we know aren't predicated forms.
5335   //
5336   // FIXME: Would be nice to autogen this.
5337   if ((Mnemonic == "movs" && isThumb()) ||
5338       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5339       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5340       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5341       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5342       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5343       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5344       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5345       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5346       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5347       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5348       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5349       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5350       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5351       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
5352       Mnemonic == "vudot" || Mnemonic == "vsdot")
5353     return Mnemonic;
5354 
5355   // First, split out any predication code. Ignore mnemonics we know aren't
5356   // predicated but do have a carry-set and so weren't caught above.
5357   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5358       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5359       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5360       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5361     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5362       .Case("eq", ARMCC::EQ)
5363       .Case("ne", ARMCC::NE)
5364       .Case("hs", ARMCC::HS)
5365       .Case("cs", ARMCC::HS)
5366       .Case("lo", ARMCC::LO)
5367       .Case("cc", ARMCC::LO)
5368       .Case("mi", ARMCC::MI)
5369       .Case("pl", ARMCC::PL)
5370       .Case("vs", ARMCC::VS)
5371       .Case("vc", ARMCC::VC)
5372       .Case("hi", ARMCC::HI)
5373       .Case("ls", ARMCC::LS)
5374       .Case("ge", ARMCC::GE)
5375       .Case("lt", ARMCC::LT)
5376       .Case("gt", ARMCC::GT)
5377       .Case("le", ARMCC::LE)
5378       .Case("al", ARMCC::AL)
5379       .Default(~0U);
5380     if (CC != ~0U) {
5381       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5382       PredicationCode = CC;
5383     }
5384   }
5385 
5386   // Next, determine if we have a carry setting bit. We explicitly ignore all
5387   // the instructions we know end in 's'.
5388   if (Mnemonic.endswith("s") &&
5389       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5390         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5391         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5392         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5393         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5394         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5395         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5396         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5397         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5398         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5399         (Mnemonic == "movs" && isThumb()))) {
5400     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5401     CarrySetting = true;
5402   }
5403 
5404   // The "cps" instruction can have a interrupt mode operand which is glued into
5405   // the mnemonic. Check if this is the case, split it and parse the imod op
5406   if (Mnemonic.startswith("cps")) {
5407     // Split out any imod code.
5408     unsigned IMod =
5409       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5410       .Case("ie", ARM_PROC::IE)
5411       .Case("id", ARM_PROC::ID)
5412       .Default(~0U);
5413     if (IMod != ~0U) {
5414       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5415       ProcessorIMod = IMod;
5416     }
5417   }
5418 
5419   // The "it" instruction has the condition mask on the end of the mnemonic.
5420   if (Mnemonic.startswith("it")) {
5421     ITMask = Mnemonic.slice(2, Mnemonic.size());
5422     Mnemonic = Mnemonic.slice(0, 2);
5423   }
5424 
5425   return Mnemonic;
5426 }
5427 
5428 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5429 /// inclusion of carry set or predication code operands.
5430 //
5431 // FIXME: It would be nice to autogen this.
5432 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5433                                          bool &CanAcceptCarrySet,
5434                                          bool &CanAcceptPredicationCode) {
5435   CanAcceptCarrySet =
5436       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5437       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5438       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5439       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5440       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5441       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5442       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5443       (!isThumb() &&
5444        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5445         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5446 
5447   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5448       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5449       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5450       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5451       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5452       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5453       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5454       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5455       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5456       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5457       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5458       Mnemonic == "vmovx" || Mnemonic == "vins" ||
5459       Mnemonic == "vudot" || Mnemonic == "vsdot") {
5460     // These mnemonics are never predicable
5461     CanAcceptPredicationCode = false;
5462   } else if (!isThumb()) {
5463     // Some instructions are only predicable in Thumb mode
5464     CanAcceptPredicationCode =
5465         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5466         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5467         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5468         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5469         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5470         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5471         !Mnemonic.startswith("srs");
5472   } else if (isThumbOne()) {
5473     if (hasV6MOps())
5474       CanAcceptPredicationCode = Mnemonic != "movs";
5475     else
5476       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5477   } else
5478     CanAcceptPredicationCode = true;
5479 }
5480 
5481 // \brief Some Thumb instructions have two operand forms that are not
5482 // available as three operand, convert to two operand form if possible.
5483 //
5484 // FIXME: We would really like to be able to tablegen'erate this.
5485 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5486                                                  bool CarrySetting,
5487                                                  OperandVector &Operands) {
5488   if (Operands.size() != 6)
5489     return;
5490 
5491   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5492         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5493   if (!Op3.isReg() || !Op4.isReg())
5494     return;
5495 
5496   auto Op3Reg = Op3.getReg();
5497   auto Op4Reg = Op4.getReg();
5498 
5499   // For most Thumb2 cases we just generate the 3 operand form and reduce
5500   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5501   // won't accept SP or PC so we do the transformation here taking care
5502   // with immediate range in the 'add sp, sp #imm' case.
5503   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5504   if (isThumbTwo()) {
5505     if (Mnemonic != "add")
5506       return;
5507     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5508                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5509     if (!TryTransform) {
5510       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5511                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5512                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5513                        Op5.isImm() && !Op5.isImm0_508s4());
5514     }
5515     if (!TryTransform)
5516       return;
5517   } else if (!isThumbOne())
5518     return;
5519 
5520   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5521         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5522         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5523         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5524     return;
5525 
5526   // If first 2 operands of a 3 operand instruction are the same
5527   // then transform to 2 operand version of the same instruction
5528   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5529   bool Transform = Op3Reg == Op4Reg;
5530 
5531   // For communtative operations, we might be able to transform if we swap
5532   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5533   // as tADDrsp.
5534   const ARMOperand *LastOp = &Op5;
5535   bool Swap = false;
5536   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5537       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5538        Mnemonic == "and" || Mnemonic == "eor" ||
5539        Mnemonic == "adc" || Mnemonic == "orr")) {
5540     Swap = true;
5541     LastOp = &Op4;
5542     Transform = true;
5543   }
5544 
5545   // If both registers are the same then remove one of them from
5546   // the operand list, with certain exceptions.
5547   if (Transform) {
5548     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5549     // 2 operand forms don't exist.
5550     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5551         LastOp->isReg())
5552       Transform = false;
5553 
5554     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5555     // 3-bits because the ARMARM says not to.
5556     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5557       Transform = false;
5558   }
5559 
5560   if (Transform) {
5561     if (Swap)
5562       std::swap(Op4, Op5);
5563     Operands.erase(Operands.begin() + 3);
5564   }
5565 }
5566 
5567 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5568                                           OperandVector &Operands) {
5569   // FIXME: This is all horribly hacky. We really need a better way to deal
5570   // with optional operands like this in the matcher table.
5571 
5572   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5573   // another does not. Specifically, the MOVW instruction does not. So we
5574   // special case it here and remove the defaulted (non-setting) cc_out
5575   // operand if that's the instruction we're trying to match.
5576   //
5577   // We do this as post-processing of the explicit operands rather than just
5578   // conditionally adding the cc_out in the first place because we need
5579   // to check the type of the parsed immediate operand.
5580   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5581       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5582       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5583       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5584     return true;
5585 
5586   // Register-register 'add' for thumb does not have a cc_out operand
5587   // when there are only two register operands.
5588   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5589       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5590       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5591       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5592     return true;
5593   // Register-register 'add' for thumb does not have a cc_out operand
5594   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5595   // have to check the immediate range here since Thumb2 has a variant
5596   // that can handle a different range and has a cc_out operand.
5597   if (((isThumb() && Mnemonic == "add") ||
5598        (isThumbTwo() && Mnemonic == "sub")) &&
5599       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5600       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5601       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5602       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5603       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5604        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5605     return true;
5606   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5607   // imm0_4095 variant. That's the least-preferred variant when
5608   // selecting via the generic "add" mnemonic, so to know that we
5609   // should remove the cc_out operand, we have to explicitly check that
5610   // it's not one of the other variants. Ugh.
5611   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5612       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5613       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5614       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5615     // Nest conditions rather than one big 'if' statement for readability.
5616     //
5617     // If both registers are low, we're in an IT block, and the immediate is
5618     // in range, we should use encoding T1 instead, which has a cc_out.
5619     if (inITBlock() &&
5620         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5621         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5622         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5623       return false;
5624     // Check against T3. If the second register is the PC, this is an
5625     // alternate form of ADR, which uses encoding T4, so check for that too.
5626     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5627         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5628       return false;
5629 
5630     // Otherwise, we use encoding T4, which does not have a cc_out
5631     // operand.
5632     return true;
5633   }
5634 
5635   // The thumb2 multiply instruction doesn't have a CCOut register, so
5636   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5637   // use the 16-bit encoding or not.
5638   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5639       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5640       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5641       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5642       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5643       // If the registers aren't low regs, the destination reg isn't the
5644       // same as one of the source regs, or the cc_out operand is zero
5645       // outside of an IT block, we have to use the 32-bit encoding, so
5646       // remove the cc_out operand.
5647       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5648        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5649        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5650        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5651                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5652                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5653                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5654     return true;
5655 
5656   // Also check the 'mul' syntax variant that doesn't specify an explicit
5657   // destination register.
5658   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5659       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5660       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5661       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5662       // If the registers aren't low regs  or the cc_out operand is zero
5663       // outside of an IT block, we have to use the 32-bit encoding, so
5664       // remove the cc_out operand.
5665       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5666        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5667        !inITBlock()))
5668     return true;
5669 
5670 
5671 
5672   // Register-register 'add/sub' for thumb does not have a cc_out operand
5673   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5674   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5675   // right, this will result in better diagnostics (which operand is off)
5676   // anyway.
5677   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5678       (Operands.size() == 5 || Operands.size() == 6) &&
5679       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5680       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5681       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5682       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5683        (Operands.size() == 6 &&
5684         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5685     return true;
5686 
5687   return false;
5688 }
5689 
5690 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5691                                               OperandVector &Operands) {
5692   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5693   unsigned RegIdx = 3;
5694   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5695       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5696        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5697     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5698         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5699          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5700       RegIdx = 4;
5701 
5702     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5703         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5704              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5705          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5706              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5707       return true;
5708   }
5709   return false;
5710 }
5711 
5712 static bool isDataTypeToken(StringRef Tok) {
5713   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5714     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5715     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5716     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5717     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5718     Tok == ".f" || Tok == ".d";
5719 }
5720 
5721 // FIXME: This bit should probably be handled via an explicit match class
5722 // in the .td files that matches the suffix instead of having it be
5723 // a literal string token the way it is now.
5724 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5725   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5726 }
5727 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5728                                  unsigned VariantID);
5729 
5730 static bool RequiresVFPRegListValidation(StringRef Inst,
5731                                          bool &AcceptSinglePrecisionOnly,
5732                                          bool &AcceptDoublePrecisionOnly) {
5733   if (Inst.size() < 7)
5734     return false;
5735 
5736   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5737     StringRef AddressingMode = Inst.substr(4, 2);
5738     if (AddressingMode == "ia" || AddressingMode == "db" ||
5739         AddressingMode == "ea" || AddressingMode == "fd") {
5740       AcceptSinglePrecisionOnly = Inst[6] == 's';
5741       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5742       return true;
5743     }
5744   }
5745 
5746   return false;
5747 }
5748 
5749 /// Parse an arm instruction mnemonic followed by its operands.
5750 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5751                                     SMLoc NameLoc, OperandVector &Operands) {
5752   MCAsmParser &Parser = getParser();
5753   // FIXME: Can this be done via tablegen in some fashion?
5754   bool RequireVFPRegisterListCheck;
5755   bool AcceptSinglePrecisionOnly;
5756   bool AcceptDoublePrecisionOnly;
5757   RequireVFPRegisterListCheck =
5758     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5759                                  AcceptDoublePrecisionOnly);
5760 
5761   // Apply mnemonic aliases before doing anything else, as the destination
5762   // mnemonic may include suffices and we want to handle them normally.
5763   // The generic tblgen'erated code does this later, at the start of
5764   // MatchInstructionImpl(), but that's too late for aliases that include
5765   // any sort of suffix.
5766   uint64_t AvailableFeatures = getAvailableFeatures();
5767   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5768   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5769 
5770   // First check for the ARM-specific .req directive.
5771   if (Parser.getTok().is(AsmToken::Identifier) &&
5772       Parser.getTok().getIdentifier() == ".req") {
5773     parseDirectiveReq(Name, NameLoc);
5774     // We always return 'error' for this, as we're done with this
5775     // statement and don't need to match the 'instruction."
5776     return true;
5777   }
5778 
5779   // Create the leading tokens for the mnemonic, split by '.' characters.
5780   size_t Start = 0, Next = Name.find('.');
5781   StringRef Mnemonic = Name.slice(Start, Next);
5782 
5783   // Split out the predication code and carry setting flag from the mnemonic.
5784   unsigned PredicationCode;
5785   unsigned ProcessorIMod;
5786   bool CarrySetting;
5787   StringRef ITMask;
5788   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5789                            ProcessorIMod, ITMask);
5790 
5791   // In Thumb1, only the branch (B) instruction can be predicated.
5792   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5793     return Error(NameLoc, "conditional execution not supported in Thumb1");
5794   }
5795 
5796   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5797 
5798   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5799   // is the mask as it will be for the IT encoding if the conditional
5800   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5801   // where the conditional bit0 is zero, the instruction post-processing
5802   // will adjust the mask accordingly.
5803   if (Mnemonic == "it") {
5804     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5805     if (ITMask.size() > 3) {
5806       return Error(Loc, "too many conditions on IT instruction");
5807     }
5808     unsigned Mask = 8;
5809     for (unsigned i = ITMask.size(); i != 0; --i) {
5810       char pos = ITMask[i - 1];
5811       if (pos != 't' && pos != 'e') {
5812         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5813       }
5814       Mask >>= 1;
5815       if (ITMask[i - 1] == 't')
5816         Mask |= 8;
5817     }
5818     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5819   }
5820 
5821   // FIXME: This is all a pretty gross hack. We should automatically handle
5822   // optional operands like this via tblgen.
5823 
5824   // Next, add the CCOut and ConditionCode operands, if needed.
5825   //
5826   // For mnemonics which can ever incorporate a carry setting bit or predication
5827   // code, our matching model involves us always generating CCOut and
5828   // ConditionCode operands to match the mnemonic "as written" and then we let
5829   // the matcher deal with finding the right instruction or generating an
5830   // appropriate error.
5831   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5832   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5833 
5834   // If we had a carry-set on an instruction that can't do that, issue an
5835   // error.
5836   if (!CanAcceptCarrySet && CarrySetting) {
5837     return Error(NameLoc, "instruction '" + Mnemonic +
5838                  "' can not set flags, but 's' suffix specified");
5839   }
5840   // If we had a predication code on an instruction that can't do that, issue an
5841   // error.
5842   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5843     return Error(NameLoc, "instruction '" + Mnemonic +
5844                  "' is not predicable, but condition code specified");
5845   }
5846 
5847   // Add the carry setting operand, if necessary.
5848   if (CanAcceptCarrySet) {
5849     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5850     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5851                                                Loc));
5852   }
5853 
5854   // Add the predication code operand, if necessary.
5855   if (CanAcceptPredicationCode) {
5856     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5857                                       CarrySetting);
5858     Operands.push_back(ARMOperand::CreateCondCode(
5859                          ARMCC::CondCodes(PredicationCode), Loc));
5860   }
5861 
5862   // Add the processor imod operand, if necessary.
5863   if (ProcessorIMod) {
5864     Operands.push_back(ARMOperand::CreateImm(
5865           MCConstantExpr::create(ProcessorIMod, getContext()),
5866                                  NameLoc, NameLoc));
5867   } else if (Mnemonic == "cps" && isMClass()) {
5868     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5869   }
5870 
5871   // Add the remaining tokens in the mnemonic.
5872   while (Next != StringRef::npos) {
5873     Start = Next;
5874     Next = Name.find('.', Start + 1);
5875     StringRef ExtraToken = Name.slice(Start, Next);
5876 
5877     // Some NEON instructions have an optional datatype suffix that is
5878     // completely ignored. Check for that.
5879     if (isDataTypeToken(ExtraToken) &&
5880         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5881       continue;
5882 
5883     // For for ARM mode generate an error if the .n qualifier is used.
5884     if (ExtraToken == ".n" && !isThumb()) {
5885       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5886       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5887                    "arm mode");
5888     }
5889 
5890     // The .n qualifier is always discarded as that is what the tables
5891     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5892     // so discard it to avoid errors that can be caused by the matcher.
5893     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5894       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5895       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5896     }
5897   }
5898 
5899   // Read the remaining operands.
5900   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5901     // Read the first operand.
5902     if (parseOperand(Operands, Mnemonic)) {
5903       return true;
5904     }
5905 
5906     while (parseOptionalToken(AsmToken::Comma)) {
5907       // Parse and remember the operand.
5908       if (parseOperand(Operands, Mnemonic)) {
5909         return true;
5910       }
5911     }
5912   }
5913 
5914   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
5915     return true;
5916 
5917   if (RequireVFPRegisterListCheck) {
5918     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5919     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5920       return Error(Op.getStartLoc(),
5921                    "VFP/Neon single precision register expected");
5922     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5923       return Error(Op.getStartLoc(),
5924                    "VFP/Neon double precision register expected");
5925   }
5926 
5927   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
5928 
5929   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5930   // do and don't have a cc_out optional-def operand. With some spot-checks
5931   // of the operand list, we can figure out which variant we're trying to
5932   // parse and adjust accordingly before actually matching. We shouldn't ever
5933   // try to remove a cc_out operand that was explicitly set on the
5934   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5935   // table driven matcher doesn't fit well with the ARM instruction set.
5936   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
5937     Operands.erase(Operands.begin() + 1);
5938 
5939   // Some instructions have the same mnemonic, but don't always
5940   // have a predicate. Distinguish them here and delete the
5941   // predicate if needed.
5942   if (shouldOmitPredicateOperand(Mnemonic, Operands))
5943     Operands.erase(Operands.begin() + 1);
5944 
5945   // ARM mode 'blx' need special handling, as the register operand version
5946   // is predicable, but the label operand version is not. So, we can't rely
5947   // on the Mnemonic based checking to correctly figure out when to put
5948   // a k_CondCode operand in the list. If we're trying to match the label
5949   // version, remove the k_CondCode operand here.
5950   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
5951       static_cast<ARMOperand &>(*Operands[2]).isImm())
5952     Operands.erase(Operands.begin() + 1);
5953 
5954   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
5955   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
5956   // a single GPRPair reg operand is used in the .td file to replace the two
5957   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
5958   // expressed as a GPRPair, so we have to manually merge them.
5959   // FIXME: We would really like to be able to tablegen'erate this.
5960   if (!isThumb() && Operands.size() > 4 &&
5961       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
5962        Mnemonic == "stlexd")) {
5963     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
5964     unsigned Idx = isLoad ? 2 : 3;
5965     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
5966     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
5967 
5968     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
5969     // Adjust only if Op1 and Op2 are GPRs.
5970     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
5971         MRC.contains(Op2.getReg())) {
5972       unsigned Reg1 = Op1.getReg();
5973       unsigned Reg2 = Op2.getReg();
5974       unsigned Rt = MRI->getEncodingValue(Reg1);
5975       unsigned Rt2 = MRI->getEncodingValue(Reg2);
5976 
5977       // Rt2 must be Rt + 1 and Rt must be even.
5978       if (Rt + 1 != Rt2 || (Rt & 1)) {
5979         return Error(Op2.getStartLoc(),
5980                      isLoad ? "destination operands must be sequential"
5981                             : "source operands must be sequential");
5982       }
5983       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
5984           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
5985       Operands[Idx] =
5986           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
5987       Operands.erase(Operands.begin() + Idx + 1);
5988     }
5989   }
5990 
5991   // GNU Assembler extension (compatibility)
5992   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
5993     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5994     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5995     if (Op3.isMem()) {
5996       assert(Op2.isReg() && "expected register argument");
5997 
5998       unsigned SuperReg = MRI->getMatchingSuperReg(
5999           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
6000 
6001       assert(SuperReg && "expected register pair");
6002 
6003       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
6004 
6005       Operands.insert(
6006           Operands.begin() + 3,
6007           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6008     }
6009   }
6010 
6011   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6012   // does not fit with other "subs" and tblgen.
6013   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6014   // so the Mnemonic is the original name "subs" and delete the predicate
6015   // operand so it will match the table entry.
6016   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6017       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6018       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6019       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6020       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6021       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6022     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6023     Operands.erase(Operands.begin() + 1);
6024   }
6025   return false;
6026 }
6027 
6028 // Validate context-sensitive operand constraints.
6029 
6030 // return 'true' if register list contains non-low GPR registers,
6031 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6032 // 'containsReg' to true.
6033 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6034                                  unsigned Reg, unsigned HiReg,
6035                                  bool &containsReg) {
6036   containsReg = false;
6037   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6038     unsigned OpReg = Inst.getOperand(i).getReg();
6039     if (OpReg == Reg)
6040       containsReg = true;
6041     // Anything other than a low register isn't legal here.
6042     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6043       return true;
6044   }
6045   return false;
6046 }
6047 
6048 // Check if the specified regisgter is in the register list of the inst,
6049 // starting at the indicated operand number.
6050 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6051   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6052     unsigned OpReg = Inst.getOperand(i).getReg();
6053     if (OpReg == Reg)
6054       return true;
6055   }
6056   return false;
6057 }
6058 
6059 // Return true if instruction has the interesting property of being
6060 // allowed in IT blocks, but not being predicable.
6061 static bool instIsBreakpoint(const MCInst &Inst) {
6062     return Inst.getOpcode() == ARM::tBKPT ||
6063            Inst.getOpcode() == ARM::BKPT ||
6064            Inst.getOpcode() == ARM::tHLT ||
6065            Inst.getOpcode() == ARM::HLT;
6066 
6067 }
6068 
6069 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6070                                        const OperandVector &Operands,
6071                                        unsigned ListNo, bool IsARPop) {
6072   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6073   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6074 
6075   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6076   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6077   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6078 
6079   if (!IsARPop && ListContainsSP)
6080     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6081                  "SP may not be in the register list");
6082   else if (ListContainsPC && ListContainsLR)
6083     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6084                  "PC and LR may not be in the register list simultaneously");
6085   return false;
6086 }
6087 
6088 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6089                                        const OperandVector &Operands,
6090                                        unsigned ListNo) {
6091   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6092   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6093 
6094   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6095   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6096 
6097   if (ListContainsSP && ListContainsPC)
6098     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6099                  "SP and PC may not be in the register list");
6100   else if (ListContainsSP)
6101     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6102                  "SP may not be in the register list");
6103   else if (ListContainsPC)
6104     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6105                  "PC may not be in the register list");
6106   return false;
6107 }
6108 
6109 // FIXME: We would really like to be able to tablegen'erate this.
6110 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6111                                        const OperandVector &Operands) {
6112   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6113   SMLoc Loc = Operands[0]->getStartLoc();
6114 
6115   // Check the IT block state first.
6116   // NOTE: BKPT and HLT instructions have the interesting property of being
6117   // allowed in IT blocks, but not being predicable. They just always execute.
6118   if (inITBlock() && !instIsBreakpoint(Inst)) {
6119     // The instruction must be predicable.
6120     if (!MCID.isPredicable())
6121       return Error(Loc, "instructions in IT block must be predicable");
6122     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6123     if (Cond != currentITCond()) {
6124       // Find the condition code Operand to get its SMLoc information.
6125       SMLoc CondLoc;
6126       for (unsigned I = 1; I < Operands.size(); ++I)
6127         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6128           CondLoc = Operands[I]->getStartLoc();
6129       return Error(CondLoc, "incorrect condition in IT block; got '" +
6130                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6131                    "', but expected '" +
6132                    ARMCondCodeToString(ARMCC::CondCodes(currentITCond())) + "'");
6133     }
6134   // Check for non-'al' condition codes outside of the IT block.
6135   } else if (isThumbTwo() && MCID.isPredicable() &&
6136              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6137              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6138              Inst.getOpcode() != ARM::t2Bcc) {
6139     return Error(Loc, "predicated instructions must be in IT block");
6140   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6141              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6142                  ARMCC::AL) {
6143     return Warning(Loc, "predicated instructions should be in IT block");
6144   }
6145 
6146   // PC-setting instructions in an IT block, but not the last instruction of
6147   // the block, are UNPREDICTABLE.
6148   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6149     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6150   }
6151 
6152   const unsigned Opcode = Inst.getOpcode();
6153   switch (Opcode) {
6154   case ARM::LDRD:
6155   case ARM::LDRD_PRE:
6156   case ARM::LDRD_POST: {
6157     const unsigned RtReg = Inst.getOperand(0).getReg();
6158 
6159     // Rt can't be R14.
6160     if (RtReg == ARM::LR)
6161       return Error(Operands[3]->getStartLoc(),
6162                    "Rt can't be R14");
6163 
6164     const unsigned Rt = MRI->getEncodingValue(RtReg);
6165     // Rt must be even-numbered.
6166     if ((Rt & 1) == 1)
6167       return Error(Operands[3]->getStartLoc(),
6168                    "Rt must be even-numbered");
6169 
6170     // Rt2 must be Rt + 1.
6171     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6172     if (Rt2 != Rt + 1)
6173       return Error(Operands[3]->getStartLoc(),
6174                    "destination operands must be sequential");
6175 
6176     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6177       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6178       // For addressing modes with writeback, the base register needs to be
6179       // different from the destination registers.
6180       if (Rn == Rt || Rn == Rt2)
6181         return Error(Operands[3]->getStartLoc(),
6182                      "base register needs to be different from destination "
6183                      "registers");
6184     }
6185 
6186     return false;
6187   }
6188   case ARM::t2LDRDi8:
6189   case ARM::t2LDRD_PRE:
6190   case ARM::t2LDRD_POST: {
6191     // Rt2 must be different from Rt.
6192     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6193     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6194     if (Rt2 == Rt)
6195       return Error(Operands[3]->getStartLoc(),
6196                    "destination operands can't be identical");
6197     return false;
6198   }
6199   case ARM::t2BXJ: {
6200     const unsigned RmReg = Inst.getOperand(0).getReg();
6201     // Rm = SP is no longer unpredictable in v8-A
6202     if (RmReg == ARM::SP && !hasV8Ops())
6203       return Error(Operands[2]->getStartLoc(),
6204                    "r13 (SP) is an unpredictable operand to BXJ");
6205     return false;
6206   }
6207   case ARM::STRD: {
6208     // Rt2 must be Rt + 1.
6209     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6210     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6211     if (Rt2 != Rt + 1)
6212       return Error(Operands[3]->getStartLoc(),
6213                    "source operands must be sequential");
6214     return false;
6215   }
6216   case ARM::STRD_PRE:
6217   case ARM::STRD_POST: {
6218     // Rt2 must be Rt + 1.
6219     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6220     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6221     if (Rt2 != Rt + 1)
6222       return Error(Operands[3]->getStartLoc(),
6223                    "source operands must be sequential");
6224     return false;
6225   }
6226   case ARM::STR_PRE_IMM:
6227   case ARM::STR_PRE_REG:
6228   case ARM::STR_POST_IMM:
6229   case ARM::STR_POST_REG:
6230   case ARM::STRH_PRE:
6231   case ARM::STRH_POST:
6232   case ARM::STRB_PRE_IMM:
6233   case ARM::STRB_PRE_REG:
6234   case ARM::STRB_POST_IMM:
6235   case ARM::STRB_POST_REG: {
6236     // Rt must be different from Rn.
6237     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6238     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6239 
6240     if (Rt == Rn)
6241       return Error(Operands[3]->getStartLoc(),
6242                    "source register and base register can't be identical");
6243     return false;
6244   }
6245   case ARM::LDR_PRE_IMM:
6246   case ARM::LDR_PRE_REG:
6247   case ARM::LDR_POST_IMM:
6248   case ARM::LDR_POST_REG:
6249   case ARM::LDRH_PRE:
6250   case ARM::LDRH_POST:
6251   case ARM::LDRSH_PRE:
6252   case ARM::LDRSH_POST:
6253   case ARM::LDRB_PRE_IMM:
6254   case ARM::LDRB_PRE_REG:
6255   case ARM::LDRB_POST_IMM:
6256   case ARM::LDRB_POST_REG:
6257   case ARM::LDRSB_PRE:
6258   case ARM::LDRSB_POST: {
6259     // Rt must be different from Rn.
6260     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6261     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6262 
6263     if (Rt == Rn)
6264       return Error(Operands[3]->getStartLoc(),
6265                    "destination register and base register can't be identical");
6266     return false;
6267   }
6268   case ARM::SBFX:
6269   case ARM::UBFX: {
6270     // Width must be in range [1, 32-lsb].
6271     unsigned LSB = Inst.getOperand(2).getImm();
6272     unsigned Widthm1 = Inst.getOperand(3).getImm();
6273     if (Widthm1 >= 32 - LSB)
6274       return Error(Operands[5]->getStartLoc(),
6275                    "bitfield width must be in range [1,32-lsb]");
6276     return false;
6277   }
6278   // Notionally handles ARM::tLDMIA_UPD too.
6279   case ARM::tLDMIA: {
6280     // If we're parsing Thumb2, the .w variant is available and handles
6281     // most cases that are normally illegal for a Thumb1 LDM instruction.
6282     // We'll make the transformation in processInstruction() if necessary.
6283     //
6284     // Thumb LDM instructions are writeback iff the base register is not
6285     // in the register list.
6286     unsigned Rn = Inst.getOperand(0).getReg();
6287     bool HasWritebackToken =
6288         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6289          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6290     bool ListContainsBase;
6291     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6292       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6293                    "registers must be in range r0-r7");
6294     // If we should have writeback, then there should be a '!' token.
6295     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6296       return Error(Operands[2]->getStartLoc(),
6297                    "writeback operator '!' expected");
6298     // If we should not have writeback, there must not be a '!'. This is
6299     // true even for the 32-bit wide encodings.
6300     if (ListContainsBase && HasWritebackToken)
6301       return Error(Operands[3]->getStartLoc(),
6302                    "writeback operator '!' not allowed when base register "
6303                    "in register list");
6304 
6305     if (validatetLDMRegList(Inst, Operands, 3))
6306       return true;
6307     break;
6308   }
6309   case ARM::LDMIA_UPD:
6310   case ARM::LDMDB_UPD:
6311   case ARM::LDMIB_UPD:
6312   case ARM::LDMDA_UPD:
6313     // ARM variants loading and updating the same register are only officially
6314     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6315     if (!hasV7Ops())
6316       break;
6317     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6318       return Error(Operands.back()->getStartLoc(),
6319                    "writeback register not allowed in register list");
6320     break;
6321   case ARM::t2LDMIA:
6322   case ARM::t2LDMDB:
6323     if (validatetLDMRegList(Inst, Operands, 3))
6324       return true;
6325     break;
6326   case ARM::t2STMIA:
6327   case ARM::t2STMDB:
6328     if (validatetSTMRegList(Inst, Operands, 3))
6329       return true;
6330     break;
6331   case ARM::t2LDMIA_UPD:
6332   case ARM::t2LDMDB_UPD:
6333   case ARM::t2STMIA_UPD:
6334   case ARM::t2STMDB_UPD: {
6335     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6336       return Error(Operands.back()->getStartLoc(),
6337                    "writeback register not allowed in register list");
6338 
6339     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6340       if (validatetLDMRegList(Inst, Operands, 3))
6341         return true;
6342     } else {
6343       if (validatetSTMRegList(Inst, Operands, 3))
6344         return true;
6345     }
6346     break;
6347   }
6348   case ARM::sysLDMIA_UPD:
6349   case ARM::sysLDMDA_UPD:
6350   case ARM::sysLDMDB_UPD:
6351   case ARM::sysLDMIB_UPD:
6352     if (!listContainsReg(Inst, 3, ARM::PC))
6353       return Error(Operands[4]->getStartLoc(),
6354                    "writeback register only allowed on system LDM "
6355                    "if PC in register-list");
6356     break;
6357   case ARM::sysSTMIA_UPD:
6358   case ARM::sysSTMDA_UPD:
6359   case ARM::sysSTMDB_UPD:
6360   case ARM::sysSTMIB_UPD:
6361     return Error(Operands[2]->getStartLoc(),
6362                  "system STM cannot have writeback register");
6363   case ARM::tMUL: {
6364     // The second source operand must be the same register as the destination
6365     // operand.
6366     //
6367     // In this case, we must directly check the parsed operands because the
6368     // cvtThumbMultiply() function is written in such a way that it guarantees
6369     // this first statement is always true for the new Inst.  Essentially, the
6370     // destination is unconditionally copied into the second source operand
6371     // without checking to see if it matches what we actually parsed.
6372     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6373                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6374         (((ARMOperand &)*Operands[3]).getReg() !=
6375          ((ARMOperand &)*Operands[4]).getReg())) {
6376       return Error(Operands[3]->getStartLoc(),
6377                    "destination register must match source register");
6378     }
6379     break;
6380   }
6381   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6382   // so only issue a diagnostic for thumb1. The instructions will be
6383   // switched to the t2 encodings in processInstruction() if necessary.
6384   case ARM::tPOP: {
6385     bool ListContainsBase;
6386     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6387         !isThumbTwo())
6388       return Error(Operands[2]->getStartLoc(),
6389                    "registers must be in range r0-r7 or pc");
6390     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6391       return true;
6392     break;
6393   }
6394   case ARM::tPUSH: {
6395     bool ListContainsBase;
6396     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6397         !isThumbTwo())
6398       return Error(Operands[2]->getStartLoc(),
6399                    "registers must be in range r0-r7 or lr");
6400     if (validatetSTMRegList(Inst, Operands, 2))
6401       return true;
6402     break;
6403   }
6404   case ARM::tSTMIA_UPD: {
6405     bool ListContainsBase, InvalidLowList;
6406     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6407                                           0, ListContainsBase);
6408     if (InvalidLowList && !isThumbTwo())
6409       return Error(Operands[4]->getStartLoc(),
6410                    "registers must be in range r0-r7");
6411 
6412     // This would be converted to a 32-bit stm, but that's not valid if the
6413     // writeback register is in the list.
6414     if (InvalidLowList && ListContainsBase)
6415       return Error(Operands[4]->getStartLoc(),
6416                    "writeback operator '!' not allowed when base register "
6417                    "in register list");
6418 
6419     if (validatetSTMRegList(Inst, Operands, 4))
6420       return true;
6421     break;
6422   }
6423   case ARM::tADDrSP: {
6424     // If the non-SP source operand and the destination operand are not the
6425     // same, we need thumb2 (for the wide encoding), or we have an error.
6426     if (!isThumbTwo() &&
6427         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6428       return Error(Operands[4]->getStartLoc(),
6429                    "source register must be the same as destination");
6430     }
6431     break;
6432   }
6433   // Final range checking for Thumb unconditional branch instructions.
6434   case ARM::tB:
6435     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6436       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6437     break;
6438   case ARM::t2B: {
6439     int op = (Operands[2]->isImm()) ? 2 : 3;
6440     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6441       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6442     break;
6443   }
6444   // Final range checking for Thumb conditional branch instructions.
6445   case ARM::tBcc:
6446     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6447       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6448     break;
6449   case ARM::t2Bcc: {
6450     int Op = (Operands[2]->isImm()) ? 2 : 3;
6451     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6452       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6453     break;
6454   }
6455   case ARM::tCBZ:
6456   case ARM::tCBNZ: {
6457     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6458       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6459     break;
6460   }
6461   case ARM::MOVi16:
6462   case ARM::MOVTi16:
6463   case ARM::t2MOVi16:
6464   case ARM::t2MOVTi16:
6465     {
6466     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6467     // especially when we turn it into a movw and the expression <symbol> does
6468     // not have a :lower16: or :upper16 as part of the expression.  We don't
6469     // want the behavior of silently truncating, which can be unexpected and
6470     // lead to bugs that are difficult to find since this is an easy mistake
6471     // to make.
6472     int i = (Operands[3]->isImm()) ? 3 : 4;
6473     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6474     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6475     if (CE) break;
6476     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6477     if (!E) break;
6478     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6479     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6480                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6481       return Error(
6482           Op.getStartLoc(),
6483           "immediate expression for mov requires :lower16: or :upper16");
6484     break;
6485   }
6486   case ARM::HINT:
6487   case ARM::t2HINT: {
6488     if (hasRAS()) {
6489       // ESB is not predicable (pred must be AL)
6490       unsigned Imm8 = Inst.getOperand(0).getImm();
6491       unsigned Pred = Inst.getOperand(1).getImm();
6492       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6493         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6494                                                  "predicable, but condition "
6495                                                  "code specified");
6496     }
6497     // Without the RAS extension, this behaves as any other unallocated hint.
6498     break;
6499   }
6500   }
6501 
6502   return false;
6503 }
6504 
6505 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6506   switch(Opc) {
6507   default: llvm_unreachable("unexpected opcode!");
6508   // VST1LN
6509   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6510   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6511   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6512   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6513   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6514   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6515   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6516   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6517   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6518 
6519   // VST2LN
6520   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6521   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6522   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6523   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6524   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6525 
6526   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6527   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6528   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6529   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6530   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6531 
6532   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6533   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6534   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6535   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6536   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6537 
6538   // VST3LN
6539   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6540   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6541   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6542   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6543   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6544   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6545   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6546   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6547   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6548   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6549   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6550   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6551   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6552   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6553   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6554 
6555   // VST3
6556   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6557   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6558   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6559   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6560   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6561   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6562   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6563   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6564   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6565   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6566   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6567   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6568   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6569   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6570   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6571   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6572   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6573   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6574 
6575   // VST4LN
6576   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6577   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6578   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6579   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6580   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6581   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6582   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6583   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6584   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6585   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6586   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6587   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6588   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6589   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6590   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6591 
6592   // VST4
6593   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6594   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6595   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6596   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6597   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6598   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6599   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6600   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6601   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6602   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6603   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6604   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6605   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6606   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6607   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6608   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6609   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6610   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6611   }
6612 }
6613 
6614 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6615   switch(Opc) {
6616   default: llvm_unreachable("unexpected opcode!");
6617   // VLD1LN
6618   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6619   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6620   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6621   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6622   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6623   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6624   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6625   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6626   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6627 
6628   // VLD2LN
6629   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6630   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6631   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6632   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6633   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6634   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6635   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6636   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6637   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6638   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6639   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6640   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6641   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6642   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6643   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6644 
6645   // VLD3DUP
6646   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6647   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6648   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6649   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6650   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6651   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6652   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6653   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6654   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6655   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6656   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6657   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6658   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6659   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6660   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6661   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6662   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6663   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6664 
6665   // VLD3LN
6666   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6667   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6668   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6669   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6670   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6671   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6672   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6673   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6674   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6675   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6676   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6677   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6678   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6679   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6680   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6681 
6682   // VLD3
6683   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6684   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6685   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6686   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6687   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6688   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6689   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6690   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6691   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6692   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6693   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6694   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6695   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6696   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6697   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6698   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6699   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6700   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6701 
6702   // VLD4LN
6703   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6704   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6705   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6706   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6707   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6708   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6709   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6710   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6711   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6712   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6713   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6714   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6715   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6716   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6717   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6718 
6719   // VLD4DUP
6720   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6721   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6722   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6723   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6724   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6725   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6726   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6727   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6728   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6729   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6730   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6731   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6732   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6733   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6734   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6735   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6736   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6737   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6738 
6739   // VLD4
6740   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6741   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6742   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6743   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6744   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6745   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6746   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6747   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6748   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6749   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6750   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6751   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6752   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6753   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6754   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6755   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6756   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6757   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6758   }
6759 }
6760 
6761 bool ARMAsmParser::processInstruction(MCInst &Inst,
6762                                       const OperandVector &Operands,
6763                                       MCStreamer &Out) {
6764   // Check if we have the wide qualifier, because if it's present we
6765   // must avoid selecting a 16-bit thumb instruction.
6766   bool HasWideQualifier = false;
6767   for (auto &Op : Operands) {
6768     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
6769     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
6770       HasWideQualifier = true;
6771       break;
6772     }
6773   }
6774 
6775   switch (Inst.getOpcode()) {
6776   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6777   case ARM::LDRT_POST:
6778   case ARM::LDRBT_POST: {
6779     const unsigned Opcode =
6780       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6781                                            : ARM::LDRBT_POST_IMM;
6782     MCInst TmpInst;
6783     TmpInst.setOpcode(Opcode);
6784     TmpInst.addOperand(Inst.getOperand(0));
6785     TmpInst.addOperand(Inst.getOperand(1));
6786     TmpInst.addOperand(Inst.getOperand(1));
6787     TmpInst.addOperand(MCOperand::createReg(0));
6788     TmpInst.addOperand(MCOperand::createImm(0));
6789     TmpInst.addOperand(Inst.getOperand(2));
6790     TmpInst.addOperand(Inst.getOperand(3));
6791     Inst = TmpInst;
6792     return true;
6793   }
6794   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6795   case ARM::STRT_POST:
6796   case ARM::STRBT_POST: {
6797     const unsigned Opcode =
6798       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6799                                            : ARM::STRBT_POST_IMM;
6800     MCInst TmpInst;
6801     TmpInst.setOpcode(Opcode);
6802     TmpInst.addOperand(Inst.getOperand(1));
6803     TmpInst.addOperand(Inst.getOperand(0));
6804     TmpInst.addOperand(Inst.getOperand(1));
6805     TmpInst.addOperand(MCOperand::createReg(0));
6806     TmpInst.addOperand(MCOperand::createImm(0));
6807     TmpInst.addOperand(Inst.getOperand(2));
6808     TmpInst.addOperand(Inst.getOperand(3));
6809     Inst = TmpInst;
6810     return true;
6811   }
6812   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6813   case ARM::ADDri: {
6814     if (Inst.getOperand(1).getReg() != ARM::PC ||
6815         Inst.getOperand(5).getReg() != 0 ||
6816         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6817       return false;
6818     MCInst TmpInst;
6819     TmpInst.setOpcode(ARM::ADR);
6820     TmpInst.addOperand(Inst.getOperand(0));
6821     if (Inst.getOperand(2).isImm()) {
6822       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6823       // before passing it to the ADR instruction.
6824       unsigned Enc = Inst.getOperand(2).getImm();
6825       TmpInst.addOperand(MCOperand::createImm(
6826         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6827     } else {
6828       // Turn PC-relative expression into absolute expression.
6829       // Reading PC provides the start of the current instruction + 8 and
6830       // the transform to adr is biased by that.
6831       MCSymbol *Dot = getContext().createTempSymbol();
6832       Out.EmitLabel(Dot);
6833       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6834       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6835                                                      MCSymbolRefExpr::VK_None,
6836                                                      getContext());
6837       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6838       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6839                                                      getContext());
6840       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6841                                                         getContext());
6842       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6843     }
6844     TmpInst.addOperand(Inst.getOperand(3));
6845     TmpInst.addOperand(Inst.getOperand(4));
6846     Inst = TmpInst;
6847     return true;
6848   }
6849   // Aliases for alternate PC+imm syntax of LDR instructions.
6850   case ARM::t2LDRpcrel:
6851     // Select the narrow version if the immediate will fit.
6852     if (Inst.getOperand(1).getImm() > 0 &&
6853         Inst.getOperand(1).getImm() <= 0xff &&
6854         !HasWideQualifier)
6855       Inst.setOpcode(ARM::tLDRpci);
6856     else
6857       Inst.setOpcode(ARM::t2LDRpci);
6858     return true;
6859   case ARM::t2LDRBpcrel:
6860     Inst.setOpcode(ARM::t2LDRBpci);
6861     return true;
6862   case ARM::t2LDRHpcrel:
6863     Inst.setOpcode(ARM::t2LDRHpci);
6864     return true;
6865   case ARM::t2LDRSBpcrel:
6866     Inst.setOpcode(ARM::t2LDRSBpci);
6867     return true;
6868   case ARM::t2LDRSHpcrel:
6869     Inst.setOpcode(ARM::t2LDRSHpci);
6870     return true;
6871   case ARM::LDRConstPool:
6872   case ARM::tLDRConstPool:
6873   case ARM::t2LDRConstPool: {
6874     // Pseudo instruction ldr rt, =immediate is converted to a
6875     // MOV rt, immediate if immediate is known and representable
6876     // otherwise we create a constant pool entry that we load from.
6877     MCInst TmpInst;
6878     if (Inst.getOpcode() == ARM::LDRConstPool)
6879       TmpInst.setOpcode(ARM::LDRi12);
6880     else if (Inst.getOpcode() == ARM::tLDRConstPool)
6881       TmpInst.setOpcode(ARM::tLDRpci);
6882     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
6883       TmpInst.setOpcode(ARM::t2LDRpci);
6884     const ARMOperand &PoolOperand =
6885       (HasWideQualifier ?
6886        static_cast<ARMOperand &>(*Operands[4]) :
6887        static_cast<ARMOperand &>(*Operands[3]));
6888     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
6889     // If SubExprVal is a constant we may be able to use a MOV
6890     if (isa<MCConstantExpr>(SubExprVal) &&
6891         Inst.getOperand(0).getReg() != ARM::PC &&
6892         Inst.getOperand(0).getReg() != ARM::SP) {
6893       int64_t Value =
6894         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
6895       bool UseMov  = true;
6896       bool MovHasS = true;
6897       if (Inst.getOpcode() == ARM::LDRConstPool) {
6898         // ARM Constant
6899         if (ARM_AM::getSOImmVal(Value) != -1) {
6900           Value = ARM_AM::getSOImmVal(Value);
6901           TmpInst.setOpcode(ARM::MOVi);
6902         }
6903         else if (ARM_AM::getSOImmVal(~Value) != -1) {
6904           Value = ARM_AM::getSOImmVal(~Value);
6905           TmpInst.setOpcode(ARM::MVNi);
6906         }
6907         else if (hasV6T2Ops() &&
6908                  Value >=0 && Value < 65536) {
6909           TmpInst.setOpcode(ARM::MOVi16);
6910           MovHasS = false;
6911         }
6912         else
6913           UseMov = false;
6914       }
6915       else {
6916         // Thumb/Thumb2 Constant
6917         if (hasThumb2() &&
6918             ARM_AM::getT2SOImmVal(Value) != -1)
6919           TmpInst.setOpcode(ARM::t2MOVi);
6920         else if (hasThumb2() &&
6921                  ARM_AM::getT2SOImmVal(~Value) != -1) {
6922           TmpInst.setOpcode(ARM::t2MVNi);
6923           Value = ~Value;
6924         }
6925         else if (hasV8MBaseline() &&
6926                  Value >=0 && Value < 65536) {
6927           TmpInst.setOpcode(ARM::t2MOVi16);
6928           MovHasS = false;
6929         }
6930         else
6931           UseMov = false;
6932       }
6933       if (UseMov) {
6934         TmpInst.addOperand(Inst.getOperand(0));           // Rt
6935         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
6936         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
6937         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
6938         if (MovHasS)
6939           TmpInst.addOperand(MCOperand::createReg(0));    // S
6940         Inst = TmpInst;
6941         return true;
6942       }
6943     }
6944     // No opportunity to use MOV/MVN create constant pool
6945     const MCExpr *CPLoc =
6946       getTargetStreamer().addConstantPoolEntry(SubExprVal,
6947                                                PoolOperand.getStartLoc());
6948     TmpInst.addOperand(Inst.getOperand(0));           // Rt
6949     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
6950     if (TmpInst.getOpcode() == ARM::LDRi12)
6951       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
6952     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
6953     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
6954     Inst = TmpInst;
6955     return true;
6956   }
6957   // Handle NEON VST complex aliases.
6958   case ARM::VST1LNdWB_register_Asm_8:
6959   case ARM::VST1LNdWB_register_Asm_16:
6960   case ARM::VST1LNdWB_register_Asm_32: {
6961     MCInst TmpInst;
6962     // Shuffle the operands around so the lane index operand is in the
6963     // right place.
6964     unsigned Spacing;
6965     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6966     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6967     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6968     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6969     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6970     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6971     TmpInst.addOperand(Inst.getOperand(1)); // lane
6972     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6973     TmpInst.addOperand(Inst.getOperand(6));
6974     Inst = TmpInst;
6975     return true;
6976   }
6977 
6978   case ARM::VST2LNdWB_register_Asm_8:
6979   case ARM::VST2LNdWB_register_Asm_16:
6980   case ARM::VST2LNdWB_register_Asm_32:
6981   case ARM::VST2LNqWB_register_Asm_16:
6982   case ARM::VST2LNqWB_register_Asm_32: {
6983     MCInst TmpInst;
6984     // Shuffle the operands around so the lane index operand is in the
6985     // right place.
6986     unsigned Spacing;
6987     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6988     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6989     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6990     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6991     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6992     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6993     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6994                                             Spacing));
6995     TmpInst.addOperand(Inst.getOperand(1)); // lane
6996     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6997     TmpInst.addOperand(Inst.getOperand(6));
6998     Inst = TmpInst;
6999     return true;
7000   }
7001 
7002   case ARM::VST3LNdWB_register_Asm_8:
7003   case ARM::VST3LNdWB_register_Asm_16:
7004   case ARM::VST3LNdWB_register_Asm_32:
7005   case ARM::VST3LNqWB_register_Asm_16:
7006   case ARM::VST3LNqWB_register_Asm_32: {
7007     MCInst TmpInst;
7008     // Shuffle the operands around so the lane index operand is in the
7009     // right place.
7010     unsigned Spacing;
7011     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7012     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7013     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7014     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7015     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7016     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7017     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7018                                             Spacing));
7019     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7020                                             Spacing * 2));
7021     TmpInst.addOperand(Inst.getOperand(1)); // lane
7022     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7023     TmpInst.addOperand(Inst.getOperand(6));
7024     Inst = TmpInst;
7025     return true;
7026   }
7027 
7028   case ARM::VST4LNdWB_register_Asm_8:
7029   case ARM::VST4LNdWB_register_Asm_16:
7030   case ARM::VST4LNdWB_register_Asm_32:
7031   case ARM::VST4LNqWB_register_Asm_16:
7032   case ARM::VST4LNqWB_register_Asm_32: {
7033     MCInst TmpInst;
7034     // Shuffle the operands around so the lane index operand is in the
7035     // right place.
7036     unsigned Spacing;
7037     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7038     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7039     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7040     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7041     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7042     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7043     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7044                                             Spacing));
7045     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7046                                             Spacing * 2));
7047     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7048                                             Spacing * 3));
7049     TmpInst.addOperand(Inst.getOperand(1)); // lane
7050     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7051     TmpInst.addOperand(Inst.getOperand(6));
7052     Inst = TmpInst;
7053     return true;
7054   }
7055 
7056   case ARM::VST1LNdWB_fixed_Asm_8:
7057   case ARM::VST1LNdWB_fixed_Asm_16:
7058   case ARM::VST1LNdWB_fixed_Asm_32: {
7059     MCInst TmpInst;
7060     // Shuffle the operands around so the lane index operand is in the
7061     // right place.
7062     unsigned Spacing;
7063     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7064     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7065     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7066     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7067     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7068     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7069     TmpInst.addOperand(Inst.getOperand(1)); // lane
7070     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7071     TmpInst.addOperand(Inst.getOperand(5));
7072     Inst = TmpInst;
7073     return true;
7074   }
7075 
7076   case ARM::VST2LNdWB_fixed_Asm_8:
7077   case ARM::VST2LNdWB_fixed_Asm_16:
7078   case ARM::VST2LNdWB_fixed_Asm_32:
7079   case ARM::VST2LNqWB_fixed_Asm_16:
7080   case ARM::VST2LNqWB_fixed_Asm_32: {
7081     MCInst TmpInst;
7082     // Shuffle the operands around so the lane index operand is in the
7083     // right place.
7084     unsigned Spacing;
7085     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7086     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7087     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7088     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7089     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7090     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7091     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7092                                             Spacing));
7093     TmpInst.addOperand(Inst.getOperand(1)); // lane
7094     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7095     TmpInst.addOperand(Inst.getOperand(5));
7096     Inst = TmpInst;
7097     return true;
7098   }
7099 
7100   case ARM::VST3LNdWB_fixed_Asm_8:
7101   case ARM::VST3LNdWB_fixed_Asm_16:
7102   case ARM::VST3LNdWB_fixed_Asm_32:
7103   case ARM::VST3LNqWB_fixed_Asm_16:
7104   case ARM::VST3LNqWB_fixed_Asm_32: {
7105     MCInst TmpInst;
7106     // Shuffle the operands around so the lane index operand is in the
7107     // right place.
7108     unsigned Spacing;
7109     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7110     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7111     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7112     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7113     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7114     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7115     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7116                                             Spacing));
7117     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7118                                             Spacing * 2));
7119     TmpInst.addOperand(Inst.getOperand(1)); // lane
7120     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7121     TmpInst.addOperand(Inst.getOperand(5));
7122     Inst = TmpInst;
7123     return true;
7124   }
7125 
7126   case ARM::VST4LNdWB_fixed_Asm_8:
7127   case ARM::VST4LNdWB_fixed_Asm_16:
7128   case ARM::VST4LNdWB_fixed_Asm_32:
7129   case ARM::VST4LNqWB_fixed_Asm_16:
7130   case ARM::VST4LNqWB_fixed_Asm_32: {
7131     MCInst TmpInst;
7132     // Shuffle the operands around so the lane index operand is in the
7133     // right place.
7134     unsigned Spacing;
7135     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7136     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7137     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7138     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7139     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7140     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7141     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7142                                             Spacing));
7143     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7144                                             Spacing * 2));
7145     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7146                                             Spacing * 3));
7147     TmpInst.addOperand(Inst.getOperand(1)); // lane
7148     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7149     TmpInst.addOperand(Inst.getOperand(5));
7150     Inst = TmpInst;
7151     return true;
7152   }
7153 
7154   case ARM::VST1LNdAsm_8:
7155   case ARM::VST1LNdAsm_16:
7156   case ARM::VST1LNdAsm_32: {
7157     MCInst TmpInst;
7158     // Shuffle the operands around so the lane index operand is in the
7159     // right place.
7160     unsigned Spacing;
7161     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7162     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7163     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7164     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7165     TmpInst.addOperand(Inst.getOperand(1)); // lane
7166     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7167     TmpInst.addOperand(Inst.getOperand(5));
7168     Inst = TmpInst;
7169     return true;
7170   }
7171 
7172   case ARM::VST2LNdAsm_8:
7173   case ARM::VST2LNdAsm_16:
7174   case ARM::VST2LNdAsm_32:
7175   case ARM::VST2LNqAsm_16:
7176   case ARM::VST2LNqAsm_32: {
7177     MCInst TmpInst;
7178     // Shuffle the operands around so the lane index operand is in the
7179     // right place.
7180     unsigned Spacing;
7181     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7182     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7183     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7184     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7185     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7186                                             Spacing));
7187     TmpInst.addOperand(Inst.getOperand(1)); // lane
7188     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7189     TmpInst.addOperand(Inst.getOperand(5));
7190     Inst = TmpInst;
7191     return true;
7192   }
7193 
7194   case ARM::VST3LNdAsm_8:
7195   case ARM::VST3LNdAsm_16:
7196   case ARM::VST3LNdAsm_32:
7197   case ARM::VST3LNqAsm_16:
7198   case ARM::VST3LNqAsm_32: {
7199     MCInst TmpInst;
7200     // Shuffle the operands around so the lane index operand is in the
7201     // right place.
7202     unsigned Spacing;
7203     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7204     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7205     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7206     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7207     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7208                                             Spacing));
7209     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7210                                             Spacing * 2));
7211     TmpInst.addOperand(Inst.getOperand(1)); // lane
7212     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7213     TmpInst.addOperand(Inst.getOperand(5));
7214     Inst = TmpInst;
7215     return true;
7216   }
7217 
7218   case ARM::VST4LNdAsm_8:
7219   case ARM::VST4LNdAsm_16:
7220   case ARM::VST4LNdAsm_32:
7221   case ARM::VST4LNqAsm_16:
7222   case ARM::VST4LNqAsm_32: {
7223     MCInst TmpInst;
7224     // Shuffle the operands around so the lane index operand is in the
7225     // right place.
7226     unsigned Spacing;
7227     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7228     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7229     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7230     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7231     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7232                                             Spacing));
7233     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7234                                             Spacing * 2));
7235     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7236                                             Spacing * 3));
7237     TmpInst.addOperand(Inst.getOperand(1)); // lane
7238     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7239     TmpInst.addOperand(Inst.getOperand(5));
7240     Inst = TmpInst;
7241     return true;
7242   }
7243 
7244   // Handle NEON VLD complex aliases.
7245   case ARM::VLD1LNdWB_register_Asm_8:
7246   case ARM::VLD1LNdWB_register_Asm_16:
7247   case ARM::VLD1LNdWB_register_Asm_32: {
7248     MCInst TmpInst;
7249     // Shuffle the operands around so the lane index operand is in the
7250     // right place.
7251     unsigned Spacing;
7252     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7253     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7254     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7255     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7256     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7257     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7258     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7259     TmpInst.addOperand(Inst.getOperand(1)); // lane
7260     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7261     TmpInst.addOperand(Inst.getOperand(6));
7262     Inst = TmpInst;
7263     return true;
7264   }
7265 
7266   case ARM::VLD2LNdWB_register_Asm_8:
7267   case ARM::VLD2LNdWB_register_Asm_16:
7268   case ARM::VLD2LNdWB_register_Asm_32:
7269   case ARM::VLD2LNqWB_register_Asm_16:
7270   case ARM::VLD2LNqWB_register_Asm_32: {
7271     MCInst TmpInst;
7272     // Shuffle the operands around so the lane index operand is in the
7273     // right place.
7274     unsigned Spacing;
7275     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7276     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7277     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7278                                             Spacing));
7279     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7280     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7281     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7282     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7283     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7284     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7285                                             Spacing));
7286     TmpInst.addOperand(Inst.getOperand(1)); // lane
7287     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7288     TmpInst.addOperand(Inst.getOperand(6));
7289     Inst = TmpInst;
7290     return true;
7291   }
7292 
7293   case ARM::VLD3LNdWB_register_Asm_8:
7294   case ARM::VLD3LNdWB_register_Asm_16:
7295   case ARM::VLD3LNdWB_register_Asm_32:
7296   case ARM::VLD3LNqWB_register_Asm_16:
7297   case ARM::VLD3LNqWB_register_Asm_32: {
7298     MCInst TmpInst;
7299     // Shuffle the operands around so the lane index operand is in the
7300     // right place.
7301     unsigned Spacing;
7302     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7303     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7304     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7305                                             Spacing));
7306     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7307                                             Spacing * 2));
7308     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7309     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7310     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7311     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7312     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7313     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7314                                             Spacing));
7315     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7316                                             Spacing * 2));
7317     TmpInst.addOperand(Inst.getOperand(1)); // lane
7318     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7319     TmpInst.addOperand(Inst.getOperand(6));
7320     Inst = TmpInst;
7321     return true;
7322   }
7323 
7324   case ARM::VLD4LNdWB_register_Asm_8:
7325   case ARM::VLD4LNdWB_register_Asm_16:
7326   case ARM::VLD4LNdWB_register_Asm_32:
7327   case ARM::VLD4LNqWB_register_Asm_16:
7328   case ARM::VLD4LNqWB_register_Asm_32: {
7329     MCInst TmpInst;
7330     // Shuffle the operands around so the lane index operand is in the
7331     // right place.
7332     unsigned Spacing;
7333     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7334     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7335     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7336                                             Spacing));
7337     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7338                                             Spacing * 2));
7339     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7340                                             Spacing * 3));
7341     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7342     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7343     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7344     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7345     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7346     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7347                                             Spacing));
7348     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7349                                             Spacing * 2));
7350     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7351                                             Spacing * 3));
7352     TmpInst.addOperand(Inst.getOperand(1)); // lane
7353     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7354     TmpInst.addOperand(Inst.getOperand(6));
7355     Inst = TmpInst;
7356     return true;
7357   }
7358 
7359   case ARM::VLD1LNdWB_fixed_Asm_8:
7360   case ARM::VLD1LNdWB_fixed_Asm_16:
7361   case ARM::VLD1LNdWB_fixed_Asm_32: {
7362     MCInst TmpInst;
7363     // Shuffle the operands around so the lane index operand is in the
7364     // right place.
7365     unsigned Spacing;
7366     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7367     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7368     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7369     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7370     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7371     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7372     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7373     TmpInst.addOperand(Inst.getOperand(1)); // lane
7374     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7375     TmpInst.addOperand(Inst.getOperand(5));
7376     Inst = TmpInst;
7377     return true;
7378   }
7379 
7380   case ARM::VLD2LNdWB_fixed_Asm_8:
7381   case ARM::VLD2LNdWB_fixed_Asm_16:
7382   case ARM::VLD2LNdWB_fixed_Asm_32:
7383   case ARM::VLD2LNqWB_fixed_Asm_16:
7384   case ARM::VLD2LNqWB_fixed_Asm_32: {
7385     MCInst TmpInst;
7386     // Shuffle the operands around so the lane index operand is in the
7387     // right place.
7388     unsigned Spacing;
7389     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7390     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7391     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7392                                             Spacing));
7393     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7394     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7395     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7396     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7397     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7398     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7399                                             Spacing));
7400     TmpInst.addOperand(Inst.getOperand(1)); // lane
7401     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7402     TmpInst.addOperand(Inst.getOperand(5));
7403     Inst = TmpInst;
7404     return true;
7405   }
7406 
7407   case ARM::VLD3LNdWB_fixed_Asm_8:
7408   case ARM::VLD3LNdWB_fixed_Asm_16:
7409   case ARM::VLD3LNdWB_fixed_Asm_32:
7410   case ARM::VLD3LNqWB_fixed_Asm_16:
7411   case ARM::VLD3LNqWB_fixed_Asm_32: {
7412     MCInst TmpInst;
7413     // Shuffle the operands around so the lane index operand is in the
7414     // right place.
7415     unsigned Spacing;
7416     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7417     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7418     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7419                                             Spacing));
7420     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7421                                             Spacing * 2));
7422     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7423     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7424     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7425     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7426     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7427     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7428                                             Spacing));
7429     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7430                                             Spacing * 2));
7431     TmpInst.addOperand(Inst.getOperand(1)); // lane
7432     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7433     TmpInst.addOperand(Inst.getOperand(5));
7434     Inst = TmpInst;
7435     return true;
7436   }
7437 
7438   case ARM::VLD4LNdWB_fixed_Asm_8:
7439   case ARM::VLD4LNdWB_fixed_Asm_16:
7440   case ARM::VLD4LNdWB_fixed_Asm_32:
7441   case ARM::VLD4LNqWB_fixed_Asm_16:
7442   case ARM::VLD4LNqWB_fixed_Asm_32: {
7443     MCInst TmpInst;
7444     // Shuffle the operands around so the lane index operand is in the
7445     // right place.
7446     unsigned Spacing;
7447     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7448     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7449     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7450                                             Spacing));
7451     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7452                                             Spacing * 2));
7453     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7454                                             Spacing * 3));
7455     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7456     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7457     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7458     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7459     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7460     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7461                                             Spacing));
7462     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7463                                             Spacing * 2));
7464     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7465                                             Spacing * 3));
7466     TmpInst.addOperand(Inst.getOperand(1)); // lane
7467     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7468     TmpInst.addOperand(Inst.getOperand(5));
7469     Inst = TmpInst;
7470     return true;
7471   }
7472 
7473   case ARM::VLD1LNdAsm_8:
7474   case ARM::VLD1LNdAsm_16:
7475   case ARM::VLD1LNdAsm_32: {
7476     MCInst TmpInst;
7477     // Shuffle the operands around so the lane index operand is in the
7478     // right place.
7479     unsigned Spacing;
7480     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7481     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7482     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7483     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7484     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7485     TmpInst.addOperand(Inst.getOperand(1)); // lane
7486     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7487     TmpInst.addOperand(Inst.getOperand(5));
7488     Inst = TmpInst;
7489     return true;
7490   }
7491 
7492   case ARM::VLD2LNdAsm_8:
7493   case ARM::VLD2LNdAsm_16:
7494   case ARM::VLD2LNdAsm_32:
7495   case ARM::VLD2LNqAsm_16:
7496   case ARM::VLD2LNqAsm_32: {
7497     MCInst TmpInst;
7498     // Shuffle the operands around so the lane index operand is in the
7499     // right place.
7500     unsigned Spacing;
7501     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7502     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7503     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7504                                             Spacing));
7505     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7506     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7507     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7508     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7509                                             Spacing));
7510     TmpInst.addOperand(Inst.getOperand(1)); // lane
7511     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7512     TmpInst.addOperand(Inst.getOperand(5));
7513     Inst = TmpInst;
7514     return true;
7515   }
7516 
7517   case ARM::VLD3LNdAsm_8:
7518   case ARM::VLD3LNdAsm_16:
7519   case ARM::VLD3LNdAsm_32:
7520   case ARM::VLD3LNqAsm_16:
7521   case ARM::VLD3LNqAsm_32: {
7522     MCInst TmpInst;
7523     // Shuffle the operands around so the lane index operand is in the
7524     // right place.
7525     unsigned Spacing;
7526     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7527     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7528     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7529                                             Spacing));
7530     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7531                                             Spacing * 2));
7532     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7533     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7534     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7535     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7536                                             Spacing));
7537     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7538                                             Spacing * 2));
7539     TmpInst.addOperand(Inst.getOperand(1)); // lane
7540     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7541     TmpInst.addOperand(Inst.getOperand(5));
7542     Inst = TmpInst;
7543     return true;
7544   }
7545 
7546   case ARM::VLD4LNdAsm_8:
7547   case ARM::VLD4LNdAsm_16:
7548   case ARM::VLD4LNdAsm_32:
7549   case ARM::VLD4LNqAsm_16:
7550   case ARM::VLD4LNqAsm_32: {
7551     MCInst TmpInst;
7552     // Shuffle the operands around so the lane index operand is in the
7553     // right place.
7554     unsigned Spacing;
7555     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7556     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7557     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7558                                             Spacing));
7559     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7560                                             Spacing * 2));
7561     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7562                                             Spacing * 3));
7563     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7564     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7565     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7566     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7567                                             Spacing));
7568     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7569                                             Spacing * 2));
7570     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7571                                             Spacing * 3));
7572     TmpInst.addOperand(Inst.getOperand(1)); // lane
7573     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7574     TmpInst.addOperand(Inst.getOperand(5));
7575     Inst = TmpInst;
7576     return true;
7577   }
7578 
7579   // VLD3DUP single 3-element structure to all lanes instructions.
7580   case ARM::VLD3DUPdAsm_8:
7581   case ARM::VLD3DUPdAsm_16:
7582   case ARM::VLD3DUPdAsm_32:
7583   case ARM::VLD3DUPqAsm_8:
7584   case ARM::VLD3DUPqAsm_16:
7585   case ARM::VLD3DUPqAsm_32: {
7586     MCInst TmpInst;
7587     unsigned Spacing;
7588     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7589     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7590     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7591                                             Spacing));
7592     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7593                                             Spacing * 2));
7594     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7595     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7596     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7597     TmpInst.addOperand(Inst.getOperand(4));
7598     Inst = TmpInst;
7599     return true;
7600   }
7601 
7602   case ARM::VLD3DUPdWB_fixed_Asm_8:
7603   case ARM::VLD3DUPdWB_fixed_Asm_16:
7604   case ARM::VLD3DUPdWB_fixed_Asm_32:
7605   case ARM::VLD3DUPqWB_fixed_Asm_8:
7606   case ARM::VLD3DUPqWB_fixed_Asm_16:
7607   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7608     MCInst TmpInst;
7609     unsigned Spacing;
7610     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7611     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7612     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7613                                             Spacing));
7614     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7615                                             Spacing * 2));
7616     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7617     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7618     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7619     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7620     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7621     TmpInst.addOperand(Inst.getOperand(4));
7622     Inst = TmpInst;
7623     return true;
7624   }
7625 
7626   case ARM::VLD3DUPdWB_register_Asm_8:
7627   case ARM::VLD3DUPdWB_register_Asm_16:
7628   case ARM::VLD3DUPdWB_register_Asm_32:
7629   case ARM::VLD3DUPqWB_register_Asm_8:
7630   case ARM::VLD3DUPqWB_register_Asm_16:
7631   case ARM::VLD3DUPqWB_register_Asm_32: {
7632     MCInst TmpInst;
7633     unsigned Spacing;
7634     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7635     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7636     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7637                                             Spacing));
7638     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7639                                             Spacing * 2));
7640     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7641     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7642     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7643     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7644     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7645     TmpInst.addOperand(Inst.getOperand(5));
7646     Inst = TmpInst;
7647     return true;
7648   }
7649 
7650   // VLD3 multiple 3-element structure instructions.
7651   case ARM::VLD3dAsm_8:
7652   case ARM::VLD3dAsm_16:
7653   case ARM::VLD3dAsm_32:
7654   case ARM::VLD3qAsm_8:
7655   case ARM::VLD3qAsm_16:
7656   case ARM::VLD3qAsm_32: {
7657     MCInst TmpInst;
7658     unsigned Spacing;
7659     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7660     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7661     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7662                                             Spacing));
7663     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7664                                             Spacing * 2));
7665     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7666     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7667     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7668     TmpInst.addOperand(Inst.getOperand(4));
7669     Inst = TmpInst;
7670     return true;
7671   }
7672 
7673   case ARM::VLD3dWB_fixed_Asm_8:
7674   case ARM::VLD3dWB_fixed_Asm_16:
7675   case ARM::VLD3dWB_fixed_Asm_32:
7676   case ARM::VLD3qWB_fixed_Asm_8:
7677   case ARM::VLD3qWB_fixed_Asm_16:
7678   case ARM::VLD3qWB_fixed_Asm_32: {
7679     MCInst TmpInst;
7680     unsigned Spacing;
7681     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7682     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7683     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7684                                             Spacing));
7685     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7686                                             Spacing * 2));
7687     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7688     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7689     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7690     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7691     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7692     TmpInst.addOperand(Inst.getOperand(4));
7693     Inst = TmpInst;
7694     return true;
7695   }
7696 
7697   case ARM::VLD3dWB_register_Asm_8:
7698   case ARM::VLD3dWB_register_Asm_16:
7699   case ARM::VLD3dWB_register_Asm_32:
7700   case ARM::VLD3qWB_register_Asm_8:
7701   case ARM::VLD3qWB_register_Asm_16:
7702   case ARM::VLD3qWB_register_Asm_32: {
7703     MCInst TmpInst;
7704     unsigned Spacing;
7705     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7706     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7707     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7708                                             Spacing));
7709     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7710                                             Spacing * 2));
7711     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7712     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7713     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7714     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7715     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7716     TmpInst.addOperand(Inst.getOperand(5));
7717     Inst = TmpInst;
7718     return true;
7719   }
7720 
7721   // VLD4DUP single 3-element structure to all lanes instructions.
7722   case ARM::VLD4DUPdAsm_8:
7723   case ARM::VLD4DUPdAsm_16:
7724   case ARM::VLD4DUPdAsm_32:
7725   case ARM::VLD4DUPqAsm_8:
7726   case ARM::VLD4DUPqAsm_16:
7727   case ARM::VLD4DUPqAsm_32: {
7728     MCInst TmpInst;
7729     unsigned Spacing;
7730     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7731     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7732     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7733                                             Spacing));
7734     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7735                                             Spacing * 2));
7736     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7737                                             Spacing * 3));
7738     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7739     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7740     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7741     TmpInst.addOperand(Inst.getOperand(4));
7742     Inst = TmpInst;
7743     return true;
7744   }
7745 
7746   case ARM::VLD4DUPdWB_fixed_Asm_8:
7747   case ARM::VLD4DUPdWB_fixed_Asm_16:
7748   case ARM::VLD4DUPdWB_fixed_Asm_32:
7749   case ARM::VLD4DUPqWB_fixed_Asm_8:
7750   case ARM::VLD4DUPqWB_fixed_Asm_16:
7751   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7752     MCInst TmpInst;
7753     unsigned Spacing;
7754     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7755     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7756     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7757                                             Spacing));
7758     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7759                                             Spacing * 2));
7760     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7761                                             Spacing * 3));
7762     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7763     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7764     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7765     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7766     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7767     TmpInst.addOperand(Inst.getOperand(4));
7768     Inst = TmpInst;
7769     return true;
7770   }
7771 
7772   case ARM::VLD4DUPdWB_register_Asm_8:
7773   case ARM::VLD4DUPdWB_register_Asm_16:
7774   case ARM::VLD4DUPdWB_register_Asm_32:
7775   case ARM::VLD4DUPqWB_register_Asm_8:
7776   case ARM::VLD4DUPqWB_register_Asm_16:
7777   case ARM::VLD4DUPqWB_register_Asm_32: {
7778     MCInst TmpInst;
7779     unsigned Spacing;
7780     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7781     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7782     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7783                                             Spacing));
7784     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7785                                             Spacing * 2));
7786     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7787                                             Spacing * 3));
7788     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7789     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7790     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7791     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7792     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7793     TmpInst.addOperand(Inst.getOperand(5));
7794     Inst = TmpInst;
7795     return true;
7796   }
7797 
7798   // VLD4 multiple 4-element structure instructions.
7799   case ARM::VLD4dAsm_8:
7800   case ARM::VLD4dAsm_16:
7801   case ARM::VLD4dAsm_32:
7802   case ARM::VLD4qAsm_8:
7803   case ARM::VLD4qAsm_16:
7804   case ARM::VLD4qAsm_32: {
7805     MCInst TmpInst;
7806     unsigned Spacing;
7807     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7808     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7809     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7810                                             Spacing));
7811     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7812                                             Spacing * 2));
7813     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7814                                             Spacing * 3));
7815     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7816     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7817     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7818     TmpInst.addOperand(Inst.getOperand(4));
7819     Inst = TmpInst;
7820     return true;
7821   }
7822 
7823   case ARM::VLD4dWB_fixed_Asm_8:
7824   case ARM::VLD4dWB_fixed_Asm_16:
7825   case ARM::VLD4dWB_fixed_Asm_32:
7826   case ARM::VLD4qWB_fixed_Asm_8:
7827   case ARM::VLD4qWB_fixed_Asm_16:
7828   case ARM::VLD4qWB_fixed_Asm_32: {
7829     MCInst TmpInst;
7830     unsigned Spacing;
7831     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7832     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7833     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7834                                             Spacing));
7835     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7836                                             Spacing * 2));
7837     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7838                                             Spacing * 3));
7839     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7840     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7841     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7842     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7843     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7844     TmpInst.addOperand(Inst.getOperand(4));
7845     Inst = TmpInst;
7846     return true;
7847   }
7848 
7849   case ARM::VLD4dWB_register_Asm_8:
7850   case ARM::VLD4dWB_register_Asm_16:
7851   case ARM::VLD4dWB_register_Asm_32:
7852   case ARM::VLD4qWB_register_Asm_8:
7853   case ARM::VLD4qWB_register_Asm_16:
7854   case ARM::VLD4qWB_register_Asm_32: {
7855     MCInst TmpInst;
7856     unsigned Spacing;
7857     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7858     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7859     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7860                                             Spacing));
7861     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7862                                             Spacing * 2));
7863     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7864                                             Spacing * 3));
7865     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7866     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7867     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7868     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7869     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7870     TmpInst.addOperand(Inst.getOperand(5));
7871     Inst = TmpInst;
7872     return true;
7873   }
7874 
7875   // VST3 multiple 3-element structure instructions.
7876   case ARM::VST3dAsm_8:
7877   case ARM::VST3dAsm_16:
7878   case ARM::VST3dAsm_32:
7879   case ARM::VST3qAsm_8:
7880   case ARM::VST3qAsm_16:
7881   case ARM::VST3qAsm_32: {
7882     MCInst TmpInst;
7883     unsigned Spacing;
7884     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7885     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7886     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7887     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7888     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7889                                             Spacing));
7890     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7891                                             Spacing * 2));
7892     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7893     TmpInst.addOperand(Inst.getOperand(4));
7894     Inst = TmpInst;
7895     return true;
7896   }
7897 
7898   case ARM::VST3dWB_fixed_Asm_8:
7899   case ARM::VST3dWB_fixed_Asm_16:
7900   case ARM::VST3dWB_fixed_Asm_32:
7901   case ARM::VST3qWB_fixed_Asm_8:
7902   case ARM::VST3qWB_fixed_Asm_16:
7903   case ARM::VST3qWB_fixed_Asm_32: {
7904     MCInst TmpInst;
7905     unsigned Spacing;
7906     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7907     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7908     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7909     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7910     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7911     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7912     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7913                                             Spacing));
7914     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7915                                             Spacing * 2));
7916     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7917     TmpInst.addOperand(Inst.getOperand(4));
7918     Inst = TmpInst;
7919     return true;
7920   }
7921 
7922   case ARM::VST3dWB_register_Asm_8:
7923   case ARM::VST3dWB_register_Asm_16:
7924   case ARM::VST3dWB_register_Asm_32:
7925   case ARM::VST3qWB_register_Asm_8:
7926   case ARM::VST3qWB_register_Asm_16:
7927   case ARM::VST3qWB_register_Asm_32: {
7928     MCInst TmpInst;
7929     unsigned Spacing;
7930     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7931     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7932     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7933     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7934     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7935     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7936     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7937                                             Spacing));
7938     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7939                                             Spacing * 2));
7940     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7941     TmpInst.addOperand(Inst.getOperand(5));
7942     Inst = TmpInst;
7943     return true;
7944   }
7945 
7946   // VST4 multiple 3-element structure instructions.
7947   case ARM::VST4dAsm_8:
7948   case ARM::VST4dAsm_16:
7949   case ARM::VST4dAsm_32:
7950   case ARM::VST4qAsm_8:
7951   case ARM::VST4qAsm_16:
7952   case ARM::VST4qAsm_32: {
7953     MCInst TmpInst;
7954     unsigned Spacing;
7955     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7956     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7957     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7958     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7959     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7960                                             Spacing));
7961     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7962                                             Spacing * 2));
7963     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7964                                             Spacing * 3));
7965     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7966     TmpInst.addOperand(Inst.getOperand(4));
7967     Inst = TmpInst;
7968     return true;
7969   }
7970 
7971   case ARM::VST4dWB_fixed_Asm_8:
7972   case ARM::VST4dWB_fixed_Asm_16:
7973   case ARM::VST4dWB_fixed_Asm_32:
7974   case ARM::VST4qWB_fixed_Asm_8:
7975   case ARM::VST4qWB_fixed_Asm_16:
7976   case ARM::VST4qWB_fixed_Asm_32: {
7977     MCInst TmpInst;
7978     unsigned Spacing;
7979     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7980     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7981     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7982     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7983     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7984     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7985     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7986                                             Spacing));
7987     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7988                                             Spacing * 2));
7989     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7990                                             Spacing * 3));
7991     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7992     TmpInst.addOperand(Inst.getOperand(4));
7993     Inst = TmpInst;
7994     return true;
7995   }
7996 
7997   case ARM::VST4dWB_register_Asm_8:
7998   case ARM::VST4dWB_register_Asm_16:
7999   case ARM::VST4dWB_register_Asm_32:
8000   case ARM::VST4qWB_register_Asm_8:
8001   case ARM::VST4qWB_register_Asm_16:
8002   case ARM::VST4qWB_register_Asm_32: {
8003     MCInst TmpInst;
8004     unsigned Spacing;
8005     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8006     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8007     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8008     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8009     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8010     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8011     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8012                                             Spacing));
8013     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8014                                             Spacing * 2));
8015     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8016                                             Spacing * 3));
8017     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8018     TmpInst.addOperand(Inst.getOperand(5));
8019     Inst = TmpInst;
8020     return true;
8021   }
8022 
8023   // Handle encoding choice for the shift-immediate instructions.
8024   case ARM::t2LSLri:
8025   case ARM::t2LSRri:
8026   case ARM::t2ASRri: {
8027     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8028         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8029         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8030         !HasWideQualifier) {
8031       unsigned NewOpc;
8032       switch (Inst.getOpcode()) {
8033       default: llvm_unreachable("unexpected opcode");
8034       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8035       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8036       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8037       }
8038       // The Thumb1 operands aren't in the same order. Awesome, eh?
8039       MCInst TmpInst;
8040       TmpInst.setOpcode(NewOpc);
8041       TmpInst.addOperand(Inst.getOperand(0));
8042       TmpInst.addOperand(Inst.getOperand(5));
8043       TmpInst.addOperand(Inst.getOperand(1));
8044       TmpInst.addOperand(Inst.getOperand(2));
8045       TmpInst.addOperand(Inst.getOperand(3));
8046       TmpInst.addOperand(Inst.getOperand(4));
8047       Inst = TmpInst;
8048       return true;
8049     }
8050     return false;
8051   }
8052 
8053   // Handle the Thumb2 mode MOV complex aliases.
8054   case ARM::t2MOVsr:
8055   case ARM::t2MOVSsr: {
8056     // Which instruction to expand to depends on the CCOut operand and
8057     // whether we're in an IT block if the register operands are low
8058     // registers.
8059     bool isNarrow = false;
8060     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8061         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8062         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8063         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8064         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8065         !HasWideQualifier)
8066       isNarrow = true;
8067     MCInst TmpInst;
8068     unsigned newOpc;
8069     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8070     default: llvm_unreachable("unexpected opcode!");
8071     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8072     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8073     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8074     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8075     }
8076     TmpInst.setOpcode(newOpc);
8077     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8078     if (isNarrow)
8079       TmpInst.addOperand(MCOperand::createReg(
8080           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8081     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8082     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8083     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8084     TmpInst.addOperand(Inst.getOperand(5));
8085     if (!isNarrow)
8086       TmpInst.addOperand(MCOperand::createReg(
8087           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8088     Inst = TmpInst;
8089     return true;
8090   }
8091   case ARM::t2MOVsi:
8092   case ARM::t2MOVSsi: {
8093     // Which instruction to expand to depends on the CCOut operand and
8094     // whether we're in an IT block if the register operands are low
8095     // registers.
8096     bool isNarrow = false;
8097     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8098         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8099         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8100         !HasWideQualifier)
8101       isNarrow = true;
8102     MCInst TmpInst;
8103     unsigned newOpc;
8104     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8105     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8106     bool isMov = false;
8107     // MOV rd, rm, LSL #0 is actually a MOV instruction
8108     if (Shift == ARM_AM::lsl && Amount == 0) {
8109       isMov = true;
8110       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8111       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8112       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8113       // instead.
8114       if (inITBlock()) {
8115         isNarrow = false;
8116       }
8117       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8118     } else {
8119       switch(Shift) {
8120       default: llvm_unreachable("unexpected opcode!");
8121       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8122       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8123       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8124       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8125       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8126       }
8127     }
8128     if (Amount == 32) Amount = 0;
8129     TmpInst.setOpcode(newOpc);
8130     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8131     if (isNarrow && !isMov)
8132       TmpInst.addOperand(MCOperand::createReg(
8133           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8134     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8135     if (newOpc != ARM::t2RRX && !isMov)
8136       TmpInst.addOperand(MCOperand::createImm(Amount));
8137     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8138     TmpInst.addOperand(Inst.getOperand(4));
8139     if (!isNarrow)
8140       TmpInst.addOperand(MCOperand::createReg(
8141           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8142     Inst = TmpInst;
8143     return true;
8144   }
8145   // Handle the ARM mode MOV complex aliases.
8146   case ARM::ASRr:
8147   case ARM::LSRr:
8148   case ARM::LSLr:
8149   case ARM::RORr: {
8150     ARM_AM::ShiftOpc ShiftTy;
8151     switch(Inst.getOpcode()) {
8152     default: llvm_unreachable("unexpected opcode!");
8153     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8154     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8155     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8156     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8157     }
8158     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8159     MCInst TmpInst;
8160     TmpInst.setOpcode(ARM::MOVsr);
8161     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8162     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8163     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8164     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8165     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8166     TmpInst.addOperand(Inst.getOperand(4));
8167     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8168     Inst = TmpInst;
8169     return true;
8170   }
8171   case ARM::ASRi:
8172   case ARM::LSRi:
8173   case ARM::LSLi:
8174   case ARM::RORi: {
8175     ARM_AM::ShiftOpc ShiftTy;
8176     switch(Inst.getOpcode()) {
8177     default: llvm_unreachable("unexpected opcode!");
8178     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8179     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8180     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8181     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8182     }
8183     // A shift by zero is a plain MOVr, not a MOVsi.
8184     unsigned Amt = Inst.getOperand(2).getImm();
8185     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8186     // A shift by 32 should be encoded as 0 when permitted
8187     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8188       Amt = 0;
8189     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8190     MCInst TmpInst;
8191     TmpInst.setOpcode(Opc);
8192     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8193     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8194     if (Opc == ARM::MOVsi)
8195       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8196     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8197     TmpInst.addOperand(Inst.getOperand(4));
8198     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8199     Inst = TmpInst;
8200     return true;
8201   }
8202   case ARM::RRXi: {
8203     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8204     MCInst TmpInst;
8205     TmpInst.setOpcode(ARM::MOVsi);
8206     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8207     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8208     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8209     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8210     TmpInst.addOperand(Inst.getOperand(3));
8211     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8212     Inst = TmpInst;
8213     return true;
8214   }
8215   case ARM::t2LDMIA_UPD: {
8216     // If this is a load of a single register, then we should use
8217     // a post-indexed LDR instruction instead, per the ARM ARM.
8218     if (Inst.getNumOperands() != 5)
8219       return false;
8220     MCInst TmpInst;
8221     TmpInst.setOpcode(ARM::t2LDR_POST);
8222     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8223     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8224     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8225     TmpInst.addOperand(MCOperand::createImm(4));
8226     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8227     TmpInst.addOperand(Inst.getOperand(3));
8228     Inst = TmpInst;
8229     return true;
8230   }
8231   case ARM::t2STMDB_UPD: {
8232     // If this is a store of a single register, then we should use
8233     // a pre-indexed STR instruction instead, per the ARM ARM.
8234     if (Inst.getNumOperands() != 5)
8235       return false;
8236     MCInst TmpInst;
8237     TmpInst.setOpcode(ARM::t2STR_PRE);
8238     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8239     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8240     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8241     TmpInst.addOperand(MCOperand::createImm(-4));
8242     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8243     TmpInst.addOperand(Inst.getOperand(3));
8244     Inst = TmpInst;
8245     return true;
8246   }
8247   case ARM::LDMIA_UPD:
8248     // If this is a load of a single register via a 'pop', then we should use
8249     // a post-indexed LDR instruction instead, per the ARM ARM.
8250     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8251         Inst.getNumOperands() == 5) {
8252       MCInst TmpInst;
8253       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8254       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8255       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8256       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8257       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8258       TmpInst.addOperand(MCOperand::createImm(4));
8259       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8260       TmpInst.addOperand(Inst.getOperand(3));
8261       Inst = TmpInst;
8262       return true;
8263     }
8264     break;
8265   case ARM::STMDB_UPD:
8266     // If this is a store of a single register via a 'push', then we should use
8267     // a pre-indexed STR instruction instead, per the ARM ARM.
8268     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8269         Inst.getNumOperands() == 5) {
8270       MCInst TmpInst;
8271       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8272       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8273       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8274       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8275       TmpInst.addOperand(MCOperand::createImm(-4));
8276       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8277       TmpInst.addOperand(Inst.getOperand(3));
8278       Inst = TmpInst;
8279     }
8280     break;
8281   case ARM::t2ADDri12:
8282     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8283     // mnemonic was used (not "addw"), encoding T3 is preferred.
8284     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8285         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8286       break;
8287     Inst.setOpcode(ARM::t2ADDri);
8288     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8289     break;
8290   case ARM::t2SUBri12:
8291     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8292     // mnemonic was used (not "subw"), encoding T3 is preferred.
8293     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8294         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8295       break;
8296     Inst.setOpcode(ARM::t2SUBri);
8297     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8298     break;
8299   case ARM::tADDi8:
8300     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8301     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8302     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8303     // to encoding T1 if <Rd> is omitted."
8304     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8305       Inst.setOpcode(ARM::tADDi3);
8306       return true;
8307     }
8308     break;
8309   case ARM::tSUBi8:
8310     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8311     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8312     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8313     // to encoding T1 if <Rd> is omitted."
8314     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8315       Inst.setOpcode(ARM::tSUBi3);
8316       return true;
8317     }
8318     break;
8319   case ARM::t2ADDri:
8320   case ARM::t2SUBri: {
8321     // If the destination and first source operand are the same, and
8322     // the flags are compatible with the current IT status, use encoding T2
8323     // instead of T3. For compatibility with the system 'as'. Make sure the
8324     // wide encoding wasn't explicit.
8325     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8326         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8327         (Inst.getOperand(2).isImm() &&
8328          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8329         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8330         HasWideQualifier)
8331       break;
8332     MCInst TmpInst;
8333     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8334                       ARM::tADDi8 : ARM::tSUBi8);
8335     TmpInst.addOperand(Inst.getOperand(0));
8336     TmpInst.addOperand(Inst.getOperand(5));
8337     TmpInst.addOperand(Inst.getOperand(0));
8338     TmpInst.addOperand(Inst.getOperand(2));
8339     TmpInst.addOperand(Inst.getOperand(3));
8340     TmpInst.addOperand(Inst.getOperand(4));
8341     Inst = TmpInst;
8342     return true;
8343   }
8344   case ARM::t2ADDrr: {
8345     // If the destination and first source operand are the same, and
8346     // there's no setting of the flags, use encoding T2 instead of T3.
8347     // Note that this is only for ADD, not SUB. This mirrors the system
8348     // 'as' behaviour.  Also take advantage of ADD being commutative.
8349     // Make sure the wide encoding wasn't explicit.
8350     bool Swap = false;
8351     auto DestReg = Inst.getOperand(0).getReg();
8352     bool Transform = DestReg == Inst.getOperand(1).getReg();
8353     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8354       Transform = true;
8355       Swap = true;
8356     }
8357     if (!Transform ||
8358         Inst.getOperand(5).getReg() != 0 ||
8359         HasWideQualifier)
8360       break;
8361     MCInst TmpInst;
8362     TmpInst.setOpcode(ARM::tADDhirr);
8363     TmpInst.addOperand(Inst.getOperand(0));
8364     TmpInst.addOperand(Inst.getOperand(0));
8365     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8366     TmpInst.addOperand(Inst.getOperand(3));
8367     TmpInst.addOperand(Inst.getOperand(4));
8368     Inst = TmpInst;
8369     return true;
8370   }
8371   case ARM::tADDrSP: {
8372     // If the non-SP source operand and the destination operand are not the
8373     // same, we need to use the 32-bit encoding if it's available.
8374     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8375       Inst.setOpcode(ARM::t2ADDrr);
8376       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8377       return true;
8378     }
8379     break;
8380   }
8381   case ARM::tB:
8382     // A Thumb conditional branch outside of an IT block is a tBcc.
8383     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8384       Inst.setOpcode(ARM::tBcc);
8385       return true;
8386     }
8387     break;
8388   case ARM::t2B:
8389     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8390     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8391       Inst.setOpcode(ARM::t2Bcc);
8392       return true;
8393     }
8394     break;
8395   case ARM::t2Bcc:
8396     // If the conditional is AL or we're in an IT block, we really want t2B.
8397     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8398       Inst.setOpcode(ARM::t2B);
8399       return true;
8400     }
8401     break;
8402   case ARM::tBcc:
8403     // If the conditional is AL, we really want tB.
8404     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8405       Inst.setOpcode(ARM::tB);
8406       return true;
8407     }
8408     break;
8409   case ARM::tLDMIA: {
8410     // If the register list contains any high registers, or if the writeback
8411     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8412     // instead if we're in Thumb2. Otherwise, this should have generated
8413     // an error in validateInstruction().
8414     unsigned Rn = Inst.getOperand(0).getReg();
8415     bool hasWritebackToken =
8416         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8417          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8418     bool listContainsBase;
8419     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8420         (!listContainsBase && !hasWritebackToken) ||
8421         (listContainsBase && hasWritebackToken)) {
8422       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8423       assert (isThumbTwo());
8424       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8425       // If we're switching to the updating version, we need to insert
8426       // the writeback tied operand.
8427       if (hasWritebackToken)
8428         Inst.insert(Inst.begin(),
8429                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8430       return true;
8431     }
8432     break;
8433   }
8434   case ARM::tSTMIA_UPD: {
8435     // If the register list contains any high registers, we need to use
8436     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8437     // should have generated an error in validateInstruction().
8438     unsigned Rn = Inst.getOperand(0).getReg();
8439     bool listContainsBase;
8440     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8441       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8442       assert (isThumbTwo());
8443       Inst.setOpcode(ARM::t2STMIA_UPD);
8444       return true;
8445     }
8446     break;
8447   }
8448   case ARM::tPOP: {
8449     bool listContainsBase;
8450     // If the register list contains any high registers, we need to use
8451     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8452     // should have generated an error in validateInstruction().
8453     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8454       return false;
8455     assert (isThumbTwo());
8456     Inst.setOpcode(ARM::t2LDMIA_UPD);
8457     // Add the base register and writeback operands.
8458     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8459     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8460     return true;
8461   }
8462   case ARM::tPUSH: {
8463     bool listContainsBase;
8464     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8465       return false;
8466     assert (isThumbTwo());
8467     Inst.setOpcode(ARM::t2STMDB_UPD);
8468     // Add the base register and writeback operands.
8469     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8470     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8471     return true;
8472   }
8473   case ARM::t2MOVi: {
8474     // If we can use the 16-bit encoding and the user didn't explicitly
8475     // request the 32-bit variant, transform it here.
8476     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8477         (Inst.getOperand(1).isImm() &&
8478          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8479         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8480         !HasWideQualifier) {
8481       // The operands aren't in the same order for tMOVi8...
8482       MCInst TmpInst;
8483       TmpInst.setOpcode(ARM::tMOVi8);
8484       TmpInst.addOperand(Inst.getOperand(0));
8485       TmpInst.addOperand(Inst.getOperand(4));
8486       TmpInst.addOperand(Inst.getOperand(1));
8487       TmpInst.addOperand(Inst.getOperand(2));
8488       TmpInst.addOperand(Inst.getOperand(3));
8489       Inst = TmpInst;
8490       return true;
8491     }
8492     break;
8493   }
8494   case ARM::t2MOVr: {
8495     // If we can use the 16-bit encoding and the user didn't explicitly
8496     // request the 32-bit variant, transform it here.
8497     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8498         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8499         Inst.getOperand(2).getImm() == ARMCC::AL &&
8500         Inst.getOperand(4).getReg() == ARM::CPSR &&
8501         !HasWideQualifier) {
8502       // The operands aren't the same for tMOV[S]r... (no cc_out)
8503       MCInst TmpInst;
8504       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8505       TmpInst.addOperand(Inst.getOperand(0));
8506       TmpInst.addOperand(Inst.getOperand(1));
8507       TmpInst.addOperand(Inst.getOperand(2));
8508       TmpInst.addOperand(Inst.getOperand(3));
8509       Inst = TmpInst;
8510       return true;
8511     }
8512     break;
8513   }
8514   case ARM::t2SXTH:
8515   case ARM::t2SXTB:
8516   case ARM::t2UXTH:
8517   case ARM::t2UXTB: {
8518     // If we can use the 16-bit encoding and the user didn't explicitly
8519     // request the 32-bit variant, transform it here.
8520     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8521         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8522         Inst.getOperand(2).getImm() == 0 &&
8523         !HasWideQualifier) {
8524       unsigned NewOpc;
8525       switch (Inst.getOpcode()) {
8526       default: llvm_unreachable("Illegal opcode!");
8527       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8528       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8529       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8530       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8531       }
8532       // The operands aren't the same for thumb1 (no rotate operand).
8533       MCInst TmpInst;
8534       TmpInst.setOpcode(NewOpc);
8535       TmpInst.addOperand(Inst.getOperand(0));
8536       TmpInst.addOperand(Inst.getOperand(1));
8537       TmpInst.addOperand(Inst.getOperand(3));
8538       TmpInst.addOperand(Inst.getOperand(4));
8539       Inst = TmpInst;
8540       return true;
8541     }
8542     break;
8543   }
8544   case ARM::MOVsi: {
8545     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8546     // rrx shifts and asr/lsr of #32 is encoded as 0
8547     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8548       return false;
8549     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8550       // Shifting by zero is accepted as a vanilla 'MOVr'
8551       MCInst TmpInst;
8552       TmpInst.setOpcode(ARM::MOVr);
8553       TmpInst.addOperand(Inst.getOperand(0));
8554       TmpInst.addOperand(Inst.getOperand(1));
8555       TmpInst.addOperand(Inst.getOperand(3));
8556       TmpInst.addOperand(Inst.getOperand(4));
8557       TmpInst.addOperand(Inst.getOperand(5));
8558       Inst = TmpInst;
8559       return true;
8560     }
8561     return false;
8562   }
8563   case ARM::ANDrsi:
8564   case ARM::ORRrsi:
8565   case ARM::EORrsi:
8566   case ARM::BICrsi:
8567   case ARM::SUBrsi:
8568   case ARM::ADDrsi: {
8569     unsigned newOpc;
8570     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8571     if (SOpc == ARM_AM::rrx) return false;
8572     switch (Inst.getOpcode()) {
8573     default: llvm_unreachable("unexpected opcode!");
8574     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8575     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8576     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8577     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8578     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8579     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8580     }
8581     // If the shift is by zero, use the non-shifted instruction definition.
8582     // The exception is for right shifts, where 0 == 32
8583     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8584         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8585       MCInst TmpInst;
8586       TmpInst.setOpcode(newOpc);
8587       TmpInst.addOperand(Inst.getOperand(0));
8588       TmpInst.addOperand(Inst.getOperand(1));
8589       TmpInst.addOperand(Inst.getOperand(2));
8590       TmpInst.addOperand(Inst.getOperand(4));
8591       TmpInst.addOperand(Inst.getOperand(5));
8592       TmpInst.addOperand(Inst.getOperand(6));
8593       Inst = TmpInst;
8594       return true;
8595     }
8596     return false;
8597   }
8598   case ARM::ITasm:
8599   case ARM::t2IT: {
8600     MCOperand &MO = Inst.getOperand(1);
8601     unsigned Mask = MO.getImm();
8602     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8603 
8604     // Set up the IT block state according to the IT instruction we just
8605     // matched.
8606     assert(!inITBlock() && "nested IT blocks?!");
8607     startExplicitITBlock(Cond, Mask);
8608     MO.setImm(getITMaskEncoding());
8609     break;
8610   }
8611   case ARM::t2LSLrr:
8612   case ARM::t2LSRrr:
8613   case ARM::t2ASRrr:
8614   case ARM::t2SBCrr:
8615   case ARM::t2RORrr:
8616   case ARM::t2BICrr:
8617   {
8618     // Assemblers should use the narrow encodings of these instructions when permissible.
8619     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8620          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8621         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8622         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8623         !HasWideQualifier) {
8624       unsigned NewOpc;
8625       switch (Inst.getOpcode()) {
8626         default: llvm_unreachable("unexpected opcode");
8627         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8628         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8629         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8630         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8631         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8632         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8633       }
8634       MCInst TmpInst;
8635       TmpInst.setOpcode(NewOpc);
8636       TmpInst.addOperand(Inst.getOperand(0));
8637       TmpInst.addOperand(Inst.getOperand(5));
8638       TmpInst.addOperand(Inst.getOperand(1));
8639       TmpInst.addOperand(Inst.getOperand(2));
8640       TmpInst.addOperand(Inst.getOperand(3));
8641       TmpInst.addOperand(Inst.getOperand(4));
8642       Inst = TmpInst;
8643       return true;
8644     }
8645     return false;
8646   }
8647   case ARM::t2ANDrr:
8648   case ARM::t2EORrr:
8649   case ARM::t2ADCrr:
8650   case ARM::t2ORRrr:
8651   {
8652     // Assemblers should use the narrow encodings of these instructions when permissible.
8653     // These instructions are special in that they are commutable, so shorter encodings
8654     // are available more often.
8655     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8656          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8657         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8658          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8659         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8660         !HasWideQualifier) {
8661       unsigned NewOpc;
8662       switch (Inst.getOpcode()) {
8663         default: llvm_unreachable("unexpected opcode");
8664         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8665         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8666         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8667         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8668       }
8669       MCInst TmpInst;
8670       TmpInst.setOpcode(NewOpc);
8671       TmpInst.addOperand(Inst.getOperand(0));
8672       TmpInst.addOperand(Inst.getOperand(5));
8673       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8674         TmpInst.addOperand(Inst.getOperand(1));
8675         TmpInst.addOperand(Inst.getOperand(2));
8676       } else {
8677         TmpInst.addOperand(Inst.getOperand(2));
8678         TmpInst.addOperand(Inst.getOperand(1));
8679       }
8680       TmpInst.addOperand(Inst.getOperand(3));
8681       TmpInst.addOperand(Inst.getOperand(4));
8682       Inst = TmpInst;
8683       return true;
8684     }
8685     return false;
8686   }
8687   }
8688   return false;
8689 }
8690 
8691 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8692   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8693   // suffix depending on whether they're in an IT block or not.
8694   unsigned Opc = Inst.getOpcode();
8695   const MCInstrDesc &MCID = MII.get(Opc);
8696   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8697     assert(MCID.hasOptionalDef() &&
8698            "optionally flag setting instruction missing optional def operand");
8699     assert(MCID.NumOperands == Inst.getNumOperands() &&
8700            "operand count mismatch!");
8701     // Find the optional-def operand (cc_out).
8702     unsigned OpNo;
8703     for (OpNo = 0;
8704          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8705          ++OpNo)
8706       ;
8707     // If we're parsing Thumb1, reject it completely.
8708     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8709       return Match_RequiresFlagSetting;
8710     // If we're parsing Thumb2, which form is legal depends on whether we're
8711     // in an IT block.
8712     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8713         !inITBlock())
8714       return Match_RequiresITBlock;
8715     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8716         inITBlock())
8717       return Match_RequiresNotITBlock;
8718     // LSL with zero immediate is not allowed in an IT block
8719     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8720       return Match_RequiresNotITBlock;
8721   } else if (isThumbOne()) {
8722     // Some high-register supporting Thumb1 encodings only allow both registers
8723     // to be from r0-r7 when in Thumb2.
8724     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8725         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8726         isARMLowRegister(Inst.getOperand(2).getReg()))
8727       return Match_RequiresThumb2;
8728     // Others only require ARMv6 or later.
8729     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8730              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8731              isARMLowRegister(Inst.getOperand(1).getReg()))
8732       return Match_RequiresV6;
8733   }
8734 
8735   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8736   // than the loop below can handle, so it uses the GPRnopc register class and
8737   // we do SP handling here.
8738   if (Opc == ARM::t2MOVr && !hasV8Ops())
8739   {
8740     // SP as both source and destination is not allowed
8741     if (Inst.getOperand(0).getReg() == ARM::SP &&
8742         Inst.getOperand(1).getReg() == ARM::SP)
8743       return Match_RequiresV8;
8744     // When flags-setting SP as either source or destination is not allowed
8745     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8746         (Inst.getOperand(0).getReg() == ARM::SP ||
8747          Inst.getOperand(1).getReg() == ARM::SP))
8748       return Match_RequiresV8;
8749   }
8750 
8751   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8752     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8753       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8754       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8755         return Match_RequiresV8;
8756       else if (Inst.getOperand(I).getReg() == ARM::PC)
8757         return Match_InvalidOperand;
8758     }
8759 
8760   return Match_Success;
8761 }
8762 
8763 namespace llvm {
8764 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8765   return true; // In an assembly source, no need to second-guess
8766 }
8767 }
8768 
8769 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8770 // the last instruction in the block.
8771 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8772   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8773 
8774   // All branch & call instructions terminate IT blocks.
8775   if (MCID.isTerminator() || MCID.isCall() || MCID.isReturn() ||
8776       MCID.isBranch() || MCID.isIndirectBranch())
8777     return true;
8778 
8779   // Any arithmetic instruction which writes to the PC also terminates the IT
8780   // block.
8781   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8782     MCOperand &Op = Inst.getOperand(OpIdx);
8783     if (Op.isReg() && Op.getReg() == ARM::PC)
8784       return true;
8785   }
8786 
8787   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8788     return true;
8789 
8790   // Instructions with variable operand lists, which write to the variable
8791   // operands. We only care about Thumb instructions here, as ARM instructions
8792   // obviously can't be in an IT block.
8793   switch (Inst.getOpcode()) {
8794   case ARM::tLDMIA:
8795   case ARM::t2LDMIA:
8796   case ARM::t2LDMIA_UPD:
8797   case ARM::t2LDMDB:
8798   case ARM::t2LDMDB_UPD:
8799     if (listContainsReg(Inst, 3, ARM::PC))
8800       return true;
8801     break;
8802   case ARM::tPOP:
8803     if (listContainsReg(Inst, 2, ARM::PC))
8804       return true;
8805     break;
8806   }
8807 
8808   return false;
8809 }
8810 
8811 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8812                                           uint64_t &ErrorInfo,
8813                                           bool MatchingInlineAsm,
8814                                           bool &EmitInITBlock,
8815                                           MCStreamer &Out) {
8816   // If we can't use an implicit IT block here, just match as normal.
8817   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8818     return MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8819 
8820   // Try to match the instruction in an extension of the current IT block (if
8821   // there is one).
8822   if (inImplicitITBlock()) {
8823     extendImplicitITBlock(ITState.Cond);
8824     if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8825             Match_Success) {
8826       // The match succeded, but we still have to check that the instruction is
8827       // valid in this implicit IT block.
8828       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8829       if (MCID.isPredicable()) {
8830         ARMCC::CondCodes InstCond =
8831             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8832                 .getImm();
8833         ARMCC::CondCodes ITCond = currentITCond();
8834         if (InstCond == ITCond) {
8835           EmitInITBlock = true;
8836           return Match_Success;
8837         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
8838           invertCurrentITCondition();
8839           EmitInITBlock = true;
8840           return Match_Success;
8841         }
8842       }
8843     }
8844     rewindImplicitITPosition();
8845   }
8846 
8847   // Finish the current IT block, and try to match outside any IT block.
8848   flushPendingInstructions(Out);
8849   unsigned PlainMatchResult =
8850       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8851   if (PlainMatchResult == Match_Success) {
8852     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8853     if (MCID.isPredicable()) {
8854       ARMCC::CondCodes InstCond =
8855           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8856               .getImm();
8857       // Some forms of the branch instruction have their own condition code
8858       // fields, so can be conditionally executed without an IT block.
8859       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
8860         EmitInITBlock = false;
8861         return Match_Success;
8862       }
8863       if (InstCond == ARMCC::AL) {
8864         EmitInITBlock = false;
8865         return Match_Success;
8866       }
8867     } else {
8868       EmitInITBlock = false;
8869       return Match_Success;
8870     }
8871   }
8872 
8873   // Try to match in a new IT block. The matcher doesn't check the actual
8874   // condition, so we create an IT block with a dummy condition, and fix it up
8875   // once we know the actual condition.
8876   startImplicitITBlock();
8877   if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8878       Match_Success) {
8879     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8880     if (MCID.isPredicable()) {
8881       ITState.Cond =
8882           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8883               .getImm();
8884       EmitInITBlock = true;
8885       return Match_Success;
8886     }
8887   }
8888   discardImplicitITBlock();
8889 
8890   // If none of these succeed, return the error we got when trying to match
8891   // outside any IT blocks.
8892   EmitInITBlock = false;
8893   return PlainMatchResult;
8894 }
8895 
8896 std::string ARMMnemonicSpellCheck(StringRef S, uint64_t FBS);
8897 
8898 static const char *getSubtargetFeatureName(uint64_t Val);
8899 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8900                                            OperandVector &Operands,
8901                                            MCStreamer &Out, uint64_t &ErrorInfo,
8902                                            bool MatchingInlineAsm) {
8903   MCInst Inst;
8904   unsigned MatchResult;
8905   bool PendConditionalInstruction = false;
8906 
8907   MatchResult = MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm,
8908                                  PendConditionalInstruction, Out);
8909 
8910   SMLoc ErrorLoc;
8911   if (ErrorInfo < Operands.size()) {
8912     ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8913     if (ErrorLoc == SMLoc())
8914       ErrorLoc = IDLoc;
8915   }
8916 
8917   switch (MatchResult) {
8918   case Match_Success:
8919     // Context sensitive operand constraints aren't handled by the matcher,
8920     // so check them here.
8921     if (validateInstruction(Inst, Operands)) {
8922       // Still progress the IT block, otherwise one wrong condition causes
8923       // nasty cascading errors.
8924       forwardITPosition();
8925       return true;
8926     }
8927 
8928     { // processInstruction() updates inITBlock state, we need to save it away
8929       bool wasInITBlock = inITBlock();
8930 
8931       // Some instructions need post-processing to, for example, tweak which
8932       // encoding is selected. Loop on it while changes happen so the
8933       // individual transformations can chain off each other. E.g.,
8934       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
8935       while (processInstruction(Inst, Operands, Out))
8936         ;
8937 
8938       // Only after the instruction is fully processed, we can validate it
8939       if (wasInITBlock && hasV8Ops() && isThumb() &&
8940           !isV8EligibleForIT(&Inst)) {
8941         Warning(IDLoc, "deprecated instruction in IT block");
8942       }
8943     }
8944 
8945     // Only move forward at the very end so that everything in validate
8946     // and process gets a consistent answer about whether we're in an IT
8947     // block.
8948     forwardITPosition();
8949 
8950     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
8951     // doesn't actually encode.
8952     if (Inst.getOpcode() == ARM::ITasm)
8953       return false;
8954 
8955     Inst.setLoc(IDLoc);
8956     if (PendConditionalInstruction) {
8957       PendingConditionalInsts.push_back(Inst);
8958       if (isITBlockFull() || isITBlockTerminator(Inst))
8959         flushPendingInstructions(Out);
8960     } else {
8961       Out.EmitInstruction(Inst, getSTI());
8962     }
8963     return false;
8964   case Match_MissingFeature: {
8965     assert(ErrorInfo && "Unknown missing feature!");
8966     // Special case the error message for the very common case where only
8967     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
8968     std::string Msg = "instruction requires:";
8969     uint64_t Mask = 1;
8970     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
8971       if (ErrorInfo & Mask) {
8972         Msg += " ";
8973         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
8974       }
8975       Mask <<= 1;
8976     }
8977     return Error(IDLoc, Msg);
8978   }
8979   case Match_InvalidOperand: {
8980     SMLoc ErrorLoc = IDLoc;
8981     if (ErrorInfo != ~0ULL) {
8982       if (ErrorInfo >= Operands.size())
8983         return Error(IDLoc, "too few operands for instruction");
8984 
8985       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8986       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8987     }
8988 
8989     return Error(ErrorLoc, "invalid operand for instruction");
8990   }
8991   case Match_MnemonicFail: {
8992     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
8993     std::string Suggestion = ARMMnemonicSpellCheck(
8994       ((ARMOperand &)*Operands[0]).getToken(), FBS);
8995     return Error(IDLoc, "invalid instruction" + Suggestion,
8996                  ((ARMOperand &)*Operands[0]).getLocRange());
8997   }
8998   case Match_RequiresNotITBlock:
8999     return Error(IDLoc, "flag setting instruction only valid outside IT block");
9000   case Match_RequiresITBlock:
9001     return Error(IDLoc, "instruction only valid inside IT block");
9002   case Match_RequiresV6:
9003     return Error(IDLoc, "instruction variant requires ARMv6 or later");
9004   case Match_RequiresThumb2:
9005     return Error(IDLoc, "instruction variant requires Thumb2");
9006   case Match_RequiresV8:
9007     return Error(IDLoc, "instruction variant requires ARMv8 or later");
9008   case Match_RequiresFlagSetting:
9009     return Error(IDLoc, "no flag-preserving variant of this instruction available");
9010   case Match_ImmRange0_1:
9011     return Error(ErrorLoc, "immediate operand must be in the range [0,1]");
9012   case Match_ImmRange0_3:
9013     return Error(ErrorLoc, "immediate operand must be in the range [0,3]");
9014   case Match_ImmRange0_7:
9015     return Error(ErrorLoc, "immediate operand must be in the range [0,7]");
9016   case Match_ImmRange0_15:
9017     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
9018   case Match_ImmRange0_31:
9019     return Error(ErrorLoc, "immediate operand must be in the range [0,31]");
9020   case Match_ImmRange0_32:
9021     return Error(ErrorLoc, "immediate operand must be in the range [0,32]");
9022   case Match_ImmRange0_63:
9023     return Error(ErrorLoc, "immediate operand must be in the range [0,63]");
9024   case Match_ImmRange0_239:
9025     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
9026   case Match_ImmRange0_255:
9027     return Error(ErrorLoc, "immediate operand must be in the range [0,255]");
9028   case Match_ImmRange0_4095:
9029     return Error(ErrorLoc, "immediate operand must be in the range [0,4095]");
9030   case Match_ImmRange0_65535:
9031     return Error(ErrorLoc, "immediate operand must be in the range [0,65535]");
9032   case Match_ImmRange1_7:
9033     return Error(ErrorLoc, "immediate operand must be in the range [1,7]");
9034   case Match_ImmRange1_8:
9035     return Error(ErrorLoc, "immediate operand must be in the range [1,8]");
9036   case Match_ImmRange1_15:
9037     return Error(ErrorLoc, "immediate operand must be in the range [1,15]");
9038   case Match_ImmRange1_16:
9039     return Error(ErrorLoc, "immediate operand must be in the range [1,16]");
9040   case Match_ImmRange1_31:
9041     return Error(ErrorLoc, "immediate operand must be in the range [1,31]");
9042   case Match_ImmRange1_32:
9043     return Error(ErrorLoc, "immediate operand must be in the range [1,32]");
9044   case Match_ImmRange1_64:
9045     return Error(ErrorLoc, "immediate operand must be in the range [1,64]");
9046   case Match_ImmRange8_8:
9047     return Error(ErrorLoc, "immediate operand must be 8.");
9048   case Match_ImmRange16_16:
9049     return Error(ErrorLoc, "immediate operand must be 16.");
9050   case Match_ImmRange32_32:
9051     return Error(ErrorLoc, "immediate operand must be 32.");
9052   case Match_ImmRange256_65535:
9053     return Error(ErrorLoc, "immediate operand must be in the range [255,65535]");
9054   case Match_ImmRange0_16777215:
9055     return Error(ErrorLoc, "immediate operand must be in the range [0,0xffffff]");
9056   case Match_AlignedMemoryRequiresNone:
9057   case Match_DupAlignedMemoryRequiresNone:
9058   case Match_AlignedMemoryRequires16:
9059   case Match_DupAlignedMemoryRequires16:
9060   case Match_AlignedMemoryRequires32:
9061   case Match_DupAlignedMemoryRequires32:
9062   case Match_AlignedMemoryRequires64:
9063   case Match_DupAlignedMemoryRequires64:
9064   case Match_AlignedMemoryRequires64or128:
9065   case Match_DupAlignedMemoryRequires64or128:
9066   case Match_AlignedMemoryRequires64or128or256:
9067   {
9068     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
9069     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9070     switch (MatchResult) {
9071       default:
9072         llvm_unreachable("Missing Match_Aligned type");
9073       case Match_AlignedMemoryRequiresNone:
9074       case Match_DupAlignedMemoryRequiresNone:
9075         return Error(ErrorLoc, "alignment must be omitted");
9076       case Match_AlignedMemoryRequires16:
9077       case Match_DupAlignedMemoryRequires16:
9078         return Error(ErrorLoc, "alignment must be 16 or omitted");
9079       case Match_AlignedMemoryRequires32:
9080       case Match_DupAlignedMemoryRequires32:
9081         return Error(ErrorLoc, "alignment must be 32 or omitted");
9082       case Match_AlignedMemoryRequires64:
9083       case Match_DupAlignedMemoryRequires64:
9084         return Error(ErrorLoc, "alignment must be 64 or omitted");
9085       case Match_AlignedMemoryRequires64or128:
9086       case Match_DupAlignedMemoryRequires64or128:
9087         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
9088       case Match_AlignedMemoryRequires64or128or256:
9089         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
9090     }
9091   }
9092   }
9093 
9094   llvm_unreachable("Implement any new match types added!");
9095 }
9096 
9097 /// parseDirective parses the arm specific directives
9098 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9099   const MCObjectFileInfo::Environment Format =
9100     getContext().getObjectFileInfo()->getObjectFileType();
9101   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9102   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9103 
9104   StringRef IDVal = DirectiveID.getIdentifier();
9105   if (IDVal == ".word")
9106     parseLiteralValues(4, DirectiveID.getLoc());
9107   else if (IDVal == ".short" || IDVal == ".hword")
9108     parseLiteralValues(2, DirectiveID.getLoc());
9109   else if (IDVal == ".thumb")
9110     parseDirectiveThumb(DirectiveID.getLoc());
9111   else if (IDVal == ".arm")
9112     parseDirectiveARM(DirectiveID.getLoc());
9113   else if (IDVal == ".thumb_func")
9114     parseDirectiveThumbFunc(DirectiveID.getLoc());
9115   else if (IDVal == ".code")
9116     parseDirectiveCode(DirectiveID.getLoc());
9117   else if (IDVal == ".syntax")
9118     parseDirectiveSyntax(DirectiveID.getLoc());
9119   else if (IDVal == ".unreq")
9120     parseDirectiveUnreq(DirectiveID.getLoc());
9121   else if (IDVal == ".fnend")
9122     parseDirectiveFnEnd(DirectiveID.getLoc());
9123   else if (IDVal == ".cantunwind")
9124     parseDirectiveCantUnwind(DirectiveID.getLoc());
9125   else if (IDVal == ".personality")
9126     parseDirectivePersonality(DirectiveID.getLoc());
9127   else if (IDVal == ".handlerdata")
9128     parseDirectiveHandlerData(DirectiveID.getLoc());
9129   else if (IDVal == ".setfp")
9130     parseDirectiveSetFP(DirectiveID.getLoc());
9131   else if (IDVal == ".pad")
9132     parseDirectivePad(DirectiveID.getLoc());
9133   else if (IDVal == ".save")
9134     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9135   else if (IDVal == ".vsave")
9136     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9137   else if (IDVal == ".ltorg" || IDVal == ".pool")
9138     parseDirectiveLtorg(DirectiveID.getLoc());
9139   else if (IDVal == ".even")
9140     parseDirectiveEven(DirectiveID.getLoc());
9141   else if (IDVal == ".personalityindex")
9142     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9143   else if (IDVal == ".unwind_raw")
9144     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9145   else if (IDVal == ".movsp")
9146     parseDirectiveMovSP(DirectiveID.getLoc());
9147   else if (IDVal == ".arch_extension")
9148     parseDirectiveArchExtension(DirectiveID.getLoc());
9149   else if (IDVal == ".align")
9150     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9151   else if (IDVal == ".thumb_set")
9152     parseDirectiveThumbSet(DirectiveID.getLoc());
9153   else if (!IsMachO && !IsCOFF) {
9154     if (IDVal == ".arch")
9155       parseDirectiveArch(DirectiveID.getLoc());
9156     else if (IDVal == ".cpu")
9157       parseDirectiveCPU(DirectiveID.getLoc());
9158     else if (IDVal == ".eabi_attribute")
9159       parseDirectiveEabiAttr(DirectiveID.getLoc());
9160     else if (IDVal == ".fpu")
9161       parseDirectiveFPU(DirectiveID.getLoc());
9162     else if (IDVal == ".fnstart")
9163       parseDirectiveFnStart(DirectiveID.getLoc());
9164     else if (IDVal == ".inst")
9165       parseDirectiveInst(DirectiveID.getLoc());
9166     else if (IDVal == ".inst.n")
9167       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9168     else if (IDVal == ".inst.w")
9169       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9170     else if (IDVal == ".object_arch")
9171       parseDirectiveObjectArch(DirectiveID.getLoc());
9172     else if (IDVal == ".tlsdescseq")
9173       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9174     else
9175       return true;
9176   } else
9177     return true;
9178   return false;
9179 }
9180 
9181 /// parseLiteralValues
9182 ///  ::= .hword expression [, expression]*
9183 ///  ::= .short expression [, expression]*
9184 ///  ::= .word expression [, expression]*
9185 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9186   auto parseOne = [&]() -> bool {
9187     const MCExpr *Value;
9188     if (getParser().parseExpression(Value))
9189       return true;
9190     getParser().getStreamer().EmitValue(Value, Size, L);
9191     return false;
9192   };
9193   return (parseMany(parseOne));
9194 }
9195 
9196 /// parseDirectiveThumb
9197 ///  ::= .thumb
9198 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9199   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9200       check(!hasThumb(), L, "target does not support Thumb mode"))
9201     return true;
9202 
9203   if (!isThumb())
9204     SwitchMode();
9205 
9206   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9207   return false;
9208 }
9209 
9210 /// parseDirectiveARM
9211 ///  ::= .arm
9212 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9213   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9214       check(!hasARM(), L, "target does not support ARM mode"))
9215     return true;
9216 
9217   if (isThumb())
9218     SwitchMode();
9219   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9220   return false;
9221 }
9222 
9223 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9224   // We need to flush the current implicit IT block on a label, because it is
9225   // not legal to branch into an IT block.
9226   flushPendingInstructions(getStreamer());
9227   if (NextSymbolIsThumb) {
9228     getParser().getStreamer().EmitThumbFunc(Symbol);
9229     NextSymbolIsThumb = false;
9230   }
9231 }
9232 
9233 /// parseDirectiveThumbFunc
9234 ///  ::= .thumbfunc symbol_name
9235 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9236   MCAsmParser &Parser = getParser();
9237   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9238   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9239 
9240   // Darwin asm has (optionally) function name after .thumb_func direction
9241   // ELF doesn't
9242 
9243   if (IsMachO) {
9244     if (Parser.getTok().is(AsmToken::Identifier) ||
9245         Parser.getTok().is(AsmToken::String)) {
9246       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9247           Parser.getTok().getIdentifier());
9248       getParser().getStreamer().EmitThumbFunc(Func);
9249       Parser.Lex();
9250       if (parseToken(AsmToken::EndOfStatement,
9251                      "unexpected token in '.thumb_func' directive"))
9252         return true;
9253       return false;
9254     }
9255   }
9256 
9257   if (parseToken(AsmToken::EndOfStatement,
9258                  "unexpected token in '.thumb_func' directive"))
9259     return true;
9260 
9261   NextSymbolIsThumb = true;
9262   return false;
9263 }
9264 
9265 /// parseDirectiveSyntax
9266 ///  ::= .syntax unified | divided
9267 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9268   MCAsmParser &Parser = getParser();
9269   const AsmToken &Tok = Parser.getTok();
9270   if (Tok.isNot(AsmToken::Identifier)) {
9271     Error(L, "unexpected token in .syntax directive");
9272     return false;
9273   }
9274 
9275   StringRef Mode = Tok.getString();
9276   Parser.Lex();
9277   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9278             "'.syntax divided' arm assembly not supported") ||
9279       check(Mode != "unified" && Mode != "UNIFIED", L,
9280             "unrecognized syntax mode in .syntax directive") ||
9281       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9282     return true;
9283 
9284   // TODO tell the MC streamer the mode
9285   // getParser().getStreamer().Emit???();
9286   return false;
9287 }
9288 
9289 /// parseDirectiveCode
9290 ///  ::= .code 16 | 32
9291 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9292   MCAsmParser &Parser = getParser();
9293   const AsmToken &Tok = Parser.getTok();
9294   if (Tok.isNot(AsmToken::Integer))
9295     return Error(L, "unexpected token in .code directive");
9296   int64_t Val = Parser.getTok().getIntVal();
9297   if (Val != 16 && Val != 32) {
9298     Error(L, "invalid operand to .code directive");
9299     return false;
9300   }
9301   Parser.Lex();
9302 
9303   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9304     return true;
9305 
9306   if (Val == 16) {
9307     if (!hasThumb())
9308       return Error(L, "target does not support Thumb mode");
9309 
9310     if (!isThumb())
9311       SwitchMode();
9312     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9313   } else {
9314     if (!hasARM())
9315       return Error(L, "target does not support ARM mode");
9316 
9317     if (isThumb())
9318       SwitchMode();
9319     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9320   }
9321 
9322   return false;
9323 }
9324 
9325 /// parseDirectiveReq
9326 ///  ::= name .req registername
9327 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9328   MCAsmParser &Parser = getParser();
9329   Parser.Lex(); // Eat the '.req' token.
9330   unsigned Reg;
9331   SMLoc SRegLoc, ERegLoc;
9332   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9333             "register name expected") ||
9334       parseToken(AsmToken::EndOfStatement,
9335                  "unexpected input in .req directive."))
9336     return true;
9337 
9338   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9339     return Error(SRegLoc,
9340                  "redefinition of '" + Name + "' does not match original.");
9341 
9342   return false;
9343 }
9344 
9345 /// parseDirectiveUneq
9346 ///  ::= .unreq registername
9347 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9348   MCAsmParser &Parser = getParser();
9349   if (Parser.getTok().isNot(AsmToken::Identifier))
9350     return Error(L, "unexpected input in .unreq directive.");
9351   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9352   Parser.Lex(); // Eat the identifier.
9353   if (parseToken(AsmToken::EndOfStatement,
9354                  "unexpected input in '.unreq' directive"))
9355     return true;
9356   return false;
9357 }
9358 
9359 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9360 // before, if supported by the new target, or emit mapping symbols for the mode
9361 // switch.
9362 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9363   if (WasThumb != isThumb()) {
9364     if (WasThumb && hasThumb()) {
9365       // Stay in Thumb mode
9366       SwitchMode();
9367     } else if (!WasThumb && hasARM()) {
9368       // Stay in ARM mode
9369       SwitchMode();
9370     } else {
9371       // Mode switch forced, because the new arch doesn't support the old mode.
9372       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9373                                                             : MCAF_Code32);
9374       // Warn about the implcit mode switch. GAS does not switch modes here,
9375       // but instead stays in the old mode, reporting an error on any following
9376       // instructions as the mode does not exist on the target.
9377       Warning(Loc, Twine("new target does not support ") +
9378                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9379                        (!WasThumb ? "thumb" : "arm") + " mode");
9380     }
9381   }
9382 }
9383 
9384 /// parseDirectiveArch
9385 ///  ::= .arch token
9386 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9387   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9388   ARM::ArchKind ID = ARM::parseArch(Arch);
9389 
9390   if (ID == ARM::ArchKind::INVALID)
9391     return Error(L, "Unknown arch name");
9392 
9393   bool WasThumb = isThumb();
9394   Triple T;
9395   MCSubtargetInfo &STI = copySTI();
9396   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9397   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9398   FixModeAfterArchChange(WasThumb, L);
9399 
9400   getTargetStreamer().emitArch(ID);
9401   return false;
9402 }
9403 
9404 /// parseDirectiveEabiAttr
9405 ///  ::= .eabi_attribute int, int [, "str"]
9406 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9407 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9408   MCAsmParser &Parser = getParser();
9409   int64_t Tag;
9410   SMLoc TagLoc;
9411   TagLoc = Parser.getTok().getLoc();
9412   if (Parser.getTok().is(AsmToken::Identifier)) {
9413     StringRef Name = Parser.getTok().getIdentifier();
9414     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9415     if (Tag == -1) {
9416       Error(TagLoc, "attribute name not recognised: " + Name);
9417       return false;
9418     }
9419     Parser.Lex();
9420   } else {
9421     const MCExpr *AttrExpr;
9422 
9423     TagLoc = Parser.getTok().getLoc();
9424     if (Parser.parseExpression(AttrExpr))
9425       return true;
9426 
9427     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9428     if (check(!CE, TagLoc, "expected numeric constant"))
9429       return true;
9430 
9431     Tag = CE->getValue();
9432   }
9433 
9434   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9435     return true;
9436 
9437   StringRef StringValue = "";
9438   bool IsStringValue = false;
9439 
9440   int64_t IntegerValue = 0;
9441   bool IsIntegerValue = false;
9442 
9443   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9444     IsStringValue = true;
9445   else if (Tag == ARMBuildAttrs::compatibility) {
9446     IsStringValue = true;
9447     IsIntegerValue = true;
9448   } else if (Tag < 32 || Tag % 2 == 0)
9449     IsIntegerValue = true;
9450   else if (Tag % 2 == 1)
9451     IsStringValue = true;
9452   else
9453     llvm_unreachable("invalid tag type");
9454 
9455   if (IsIntegerValue) {
9456     const MCExpr *ValueExpr;
9457     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9458     if (Parser.parseExpression(ValueExpr))
9459       return true;
9460 
9461     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9462     if (!CE)
9463       return Error(ValueExprLoc, "expected numeric constant");
9464     IntegerValue = CE->getValue();
9465   }
9466 
9467   if (Tag == ARMBuildAttrs::compatibility) {
9468     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9469       return true;
9470   }
9471 
9472   if (IsStringValue) {
9473     if (Parser.getTok().isNot(AsmToken::String))
9474       return Error(Parser.getTok().getLoc(), "bad string constant");
9475 
9476     StringValue = Parser.getTok().getStringContents();
9477     Parser.Lex();
9478   }
9479 
9480   if (Parser.parseToken(AsmToken::EndOfStatement,
9481                         "unexpected token in '.eabi_attribute' directive"))
9482     return true;
9483 
9484   if (IsIntegerValue && IsStringValue) {
9485     assert(Tag == ARMBuildAttrs::compatibility);
9486     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9487   } else if (IsIntegerValue)
9488     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9489   else if (IsStringValue)
9490     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9491   return false;
9492 }
9493 
9494 /// parseDirectiveCPU
9495 ///  ::= .cpu str
9496 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9497   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9498   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9499 
9500   // FIXME: This is using table-gen data, but should be moved to
9501   // ARMTargetParser once that is table-gen'd.
9502   if (!getSTI().isCPUStringValid(CPU))
9503     return Error(L, "Unknown CPU name");
9504 
9505   bool WasThumb = isThumb();
9506   MCSubtargetInfo &STI = copySTI();
9507   STI.setDefaultFeatures(CPU, "");
9508   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9509   FixModeAfterArchChange(WasThumb, L);
9510 
9511   return false;
9512 }
9513 /// parseDirectiveFPU
9514 ///  ::= .fpu str
9515 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9516   SMLoc FPUNameLoc = getTok().getLoc();
9517   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9518 
9519   unsigned ID = ARM::parseFPU(FPU);
9520   std::vector<StringRef> Features;
9521   if (!ARM::getFPUFeatures(ID, Features))
9522     return Error(FPUNameLoc, "Unknown FPU name");
9523 
9524   MCSubtargetInfo &STI = copySTI();
9525   for (auto Feature : Features)
9526     STI.ApplyFeatureFlag(Feature);
9527   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9528 
9529   getTargetStreamer().emitFPU(ID);
9530   return false;
9531 }
9532 
9533 /// parseDirectiveFnStart
9534 ///  ::= .fnstart
9535 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9536   if (parseToken(AsmToken::EndOfStatement,
9537                  "unexpected token in '.fnstart' directive"))
9538     return true;
9539 
9540   if (UC.hasFnStart()) {
9541     Error(L, ".fnstart starts before the end of previous one");
9542     UC.emitFnStartLocNotes();
9543     return true;
9544   }
9545 
9546   // Reset the unwind directives parser state
9547   UC.reset();
9548 
9549   getTargetStreamer().emitFnStart();
9550 
9551   UC.recordFnStart(L);
9552   return false;
9553 }
9554 
9555 /// parseDirectiveFnEnd
9556 ///  ::= .fnend
9557 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9558   if (parseToken(AsmToken::EndOfStatement,
9559                  "unexpected token in '.fnend' directive"))
9560     return true;
9561   // Check the ordering of unwind directives
9562   if (!UC.hasFnStart())
9563     return Error(L, ".fnstart must precede .fnend directive");
9564 
9565   // Reset the unwind directives parser state
9566   getTargetStreamer().emitFnEnd();
9567 
9568   UC.reset();
9569   return false;
9570 }
9571 
9572 /// parseDirectiveCantUnwind
9573 ///  ::= .cantunwind
9574 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9575   if (parseToken(AsmToken::EndOfStatement,
9576                  "unexpected token in '.cantunwind' directive"))
9577     return true;
9578 
9579   UC.recordCantUnwind(L);
9580   // Check the ordering of unwind directives
9581   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9582     return true;
9583 
9584   if (UC.hasHandlerData()) {
9585     Error(L, ".cantunwind can't be used with .handlerdata directive");
9586     UC.emitHandlerDataLocNotes();
9587     return true;
9588   }
9589   if (UC.hasPersonality()) {
9590     Error(L, ".cantunwind can't be used with .personality directive");
9591     UC.emitPersonalityLocNotes();
9592     return true;
9593   }
9594 
9595   getTargetStreamer().emitCantUnwind();
9596   return false;
9597 }
9598 
9599 /// parseDirectivePersonality
9600 ///  ::= .personality name
9601 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9602   MCAsmParser &Parser = getParser();
9603   bool HasExistingPersonality = UC.hasPersonality();
9604 
9605   // Parse the name of the personality routine
9606   if (Parser.getTok().isNot(AsmToken::Identifier))
9607     return Error(L, "unexpected input in .personality directive.");
9608   StringRef Name(Parser.getTok().getIdentifier());
9609   Parser.Lex();
9610 
9611   if (parseToken(AsmToken::EndOfStatement,
9612                  "unexpected token in '.personality' directive"))
9613     return true;
9614 
9615   UC.recordPersonality(L);
9616 
9617   // Check the ordering of unwind directives
9618   if (!UC.hasFnStart())
9619     return Error(L, ".fnstart must precede .personality directive");
9620   if (UC.cantUnwind()) {
9621     Error(L, ".personality can't be used with .cantunwind directive");
9622     UC.emitCantUnwindLocNotes();
9623     return true;
9624   }
9625   if (UC.hasHandlerData()) {
9626     Error(L, ".personality must precede .handlerdata directive");
9627     UC.emitHandlerDataLocNotes();
9628     return true;
9629   }
9630   if (HasExistingPersonality) {
9631     Error(L, "multiple personality directives");
9632     UC.emitPersonalityLocNotes();
9633     return true;
9634   }
9635 
9636   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9637   getTargetStreamer().emitPersonality(PR);
9638   return false;
9639 }
9640 
9641 /// parseDirectiveHandlerData
9642 ///  ::= .handlerdata
9643 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9644   if (parseToken(AsmToken::EndOfStatement,
9645                  "unexpected token in '.handlerdata' directive"))
9646     return true;
9647 
9648   UC.recordHandlerData(L);
9649   // Check the ordering of unwind directives
9650   if (!UC.hasFnStart())
9651     return Error(L, ".fnstart must precede .personality directive");
9652   if (UC.cantUnwind()) {
9653     Error(L, ".handlerdata can't be used with .cantunwind directive");
9654     UC.emitCantUnwindLocNotes();
9655     return true;
9656   }
9657 
9658   getTargetStreamer().emitHandlerData();
9659   return false;
9660 }
9661 
9662 /// parseDirectiveSetFP
9663 ///  ::= .setfp fpreg, spreg [, offset]
9664 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9665   MCAsmParser &Parser = getParser();
9666   // Check the ordering of unwind directives
9667   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9668       check(UC.hasHandlerData(), L,
9669             ".setfp must precede .handlerdata directive"))
9670     return true;
9671 
9672   // Parse fpreg
9673   SMLoc FPRegLoc = Parser.getTok().getLoc();
9674   int FPReg = tryParseRegister();
9675 
9676   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9677       Parser.parseToken(AsmToken::Comma, "comma expected"))
9678     return true;
9679 
9680   // Parse spreg
9681   SMLoc SPRegLoc = Parser.getTok().getLoc();
9682   int SPReg = tryParseRegister();
9683   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9684       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9685             "register should be either $sp or the latest fp register"))
9686     return true;
9687 
9688   // Update the frame pointer register
9689   UC.saveFPReg(FPReg);
9690 
9691   // Parse offset
9692   int64_t Offset = 0;
9693   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9694     if (Parser.getTok().isNot(AsmToken::Hash) &&
9695         Parser.getTok().isNot(AsmToken::Dollar))
9696       return Error(Parser.getTok().getLoc(), "'#' expected");
9697     Parser.Lex(); // skip hash token.
9698 
9699     const MCExpr *OffsetExpr;
9700     SMLoc ExLoc = Parser.getTok().getLoc();
9701     SMLoc EndLoc;
9702     if (getParser().parseExpression(OffsetExpr, EndLoc))
9703       return Error(ExLoc, "malformed setfp offset");
9704     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9705     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9706       return true;
9707     Offset = CE->getValue();
9708   }
9709 
9710   if (Parser.parseToken(AsmToken::EndOfStatement))
9711     return true;
9712 
9713   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9714                                 static_cast<unsigned>(SPReg), Offset);
9715   return false;
9716 }
9717 
9718 /// parseDirective
9719 ///  ::= .pad offset
9720 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9721   MCAsmParser &Parser = getParser();
9722   // Check the ordering of unwind directives
9723   if (!UC.hasFnStart())
9724     return Error(L, ".fnstart must precede .pad directive");
9725   if (UC.hasHandlerData())
9726     return Error(L, ".pad must precede .handlerdata directive");
9727 
9728   // Parse the offset
9729   if (Parser.getTok().isNot(AsmToken::Hash) &&
9730       Parser.getTok().isNot(AsmToken::Dollar))
9731     return Error(Parser.getTok().getLoc(), "'#' expected");
9732   Parser.Lex(); // skip hash token.
9733 
9734   const MCExpr *OffsetExpr;
9735   SMLoc ExLoc = Parser.getTok().getLoc();
9736   SMLoc EndLoc;
9737   if (getParser().parseExpression(OffsetExpr, EndLoc))
9738     return Error(ExLoc, "malformed pad offset");
9739   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9740   if (!CE)
9741     return Error(ExLoc, "pad offset must be an immediate");
9742 
9743   if (parseToken(AsmToken::EndOfStatement,
9744                  "unexpected token in '.pad' directive"))
9745     return true;
9746 
9747   getTargetStreamer().emitPad(CE->getValue());
9748   return false;
9749 }
9750 
9751 /// parseDirectiveRegSave
9752 ///  ::= .save  { registers }
9753 ///  ::= .vsave { registers }
9754 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9755   // Check the ordering of unwind directives
9756   if (!UC.hasFnStart())
9757     return Error(L, ".fnstart must precede .save or .vsave directives");
9758   if (UC.hasHandlerData())
9759     return Error(L, ".save or .vsave must precede .handlerdata directive");
9760 
9761   // RAII object to make sure parsed operands are deleted.
9762   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9763 
9764   // Parse the register list
9765   if (parseRegisterList(Operands) ||
9766       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9767     return true;
9768   ARMOperand &Op = (ARMOperand &)*Operands[0];
9769   if (!IsVector && !Op.isRegList())
9770     return Error(L, ".save expects GPR registers");
9771   if (IsVector && !Op.isDPRRegList())
9772     return Error(L, ".vsave expects DPR registers");
9773 
9774   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9775   return false;
9776 }
9777 
9778 /// parseDirectiveInst
9779 ///  ::= .inst opcode [, ...]
9780 ///  ::= .inst.n opcode [, ...]
9781 ///  ::= .inst.w opcode [, ...]
9782 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9783   int Width = 4;
9784 
9785   if (isThumb()) {
9786     switch (Suffix) {
9787     case 'n':
9788       Width = 2;
9789       break;
9790     case 'w':
9791       break;
9792     default:
9793       return Error(Loc, "cannot determine Thumb instruction size, "
9794                         "use inst.n/inst.w instead");
9795     }
9796   } else {
9797     if (Suffix)
9798       return Error(Loc, "width suffixes are invalid in ARM mode");
9799   }
9800 
9801   auto parseOne = [&]() -> bool {
9802     const MCExpr *Expr;
9803     if (getParser().parseExpression(Expr))
9804       return true;
9805     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9806     if (!Value) {
9807       return Error(Loc, "expected constant expression");
9808     }
9809 
9810     switch (Width) {
9811     case 2:
9812       if (Value->getValue() > 0xffff)
9813         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9814       break;
9815     case 4:
9816       if (Value->getValue() > 0xffffffff)
9817         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9818                               " operand is too big");
9819       break;
9820     default:
9821       llvm_unreachable("only supported widths are 2 and 4");
9822     }
9823 
9824     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9825     return false;
9826   };
9827 
9828   if (parseOptionalToken(AsmToken::EndOfStatement))
9829     return Error(Loc, "expected expression following directive");
9830   if (parseMany(parseOne))
9831     return true;
9832   return false;
9833 }
9834 
9835 /// parseDirectiveLtorg
9836 ///  ::= .ltorg | .pool
9837 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9838   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9839     return true;
9840   getTargetStreamer().emitCurrentConstantPool();
9841   return false;
9842 }
9843 
9844 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9845   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9846 
9847   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9848     return true;
9849 
9850   if (!Section) {
9851     getStreamer().InitSections(false);
9852     Section = getStreamer().getCurrentSectionOnly();
9853   }
9854 
9855   assert(Section && "must have section to emit alignment");
9856   if (Section->UseCodeAlign())
9857     getStreamer().EmitCodeAlignment(2);
9858   else
9859     getStreamer().EmitValueToAlignment(2);
9860 
9861   return false;
9862 }
9863 
9864 /// parseDirectivePersonalityIndex
9865 ///   ::= .personalityindex index
9866 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9867   MCAsmParser &Parser = getParser();
9868   bool HasExistingPersonality = UC.hasPersonality();
9869 
9870   const MCExpr *IndexExpression;
9871   SMLoc IndexLoc = Parser.getTok().getLoc();
9872   if (Parser.parseExpression(IndexExpression) ||
9873       parseToken(AsmToken::EndOfStatement,
9874                  "unexpected token in '.personalityindex' directive")) {
9875     return true;
9876   }
9877 
9878   UC.recordPersonalityIndex(L);
9879 
9880   if (!UC.hasFnStart()) {
9881     return Error(L, ".fnstart must precede .personalityindex directive");
9882   }
9883   if (UC.cantUnwind()) {
9884     Error(L, ".personalityindex cannot be used with .cantunwind");
9885     UC.emitCantUnwindLocNotes();
9886     return true;
9887   }
9888   if (UC.hasHandlerData()) {
9889     Error(L, ".personalityindex must precede .handlerdata directive");
9890     UC.emitHandlerDataLocNotes();
9891     return true;
9892   }
9893   if (HasExistingPersonality) {
9894     Error(L, "multiple personality directives");
9895     UC.emitPersonalityLocNotes();
9896     return true;
9897   }
9898 
9899   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9900   if (!CE)
9901     return Error(IndexLoc, "index must be a constant number");
9902   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9903     return Error(IndexLoc,
9904                  "personality routine index should be in range [0-3]");
9905 
9906   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9907   return false;
9908 }
9909 
9910 /// parseDirectiveUnwindRaw
9911 ///   ::= .unwind_raw offset, opcode [, opcode...]
9912 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9913   MCAsmParser &Parser = getParser();
9914   int64_t StackOffset;
9915   const MCExpr *OffsetExpr;
9916   SMLoc OffsetLoc = getLexer().getLoc();
9917 
9918   if (!UC.hasFnStart())
9919     return Error(L, ".fnstart must precede .unwind_raw directives");
9920   if (getParser().parseExpression(OffsetExpr))
9921     return Error(OffsetLoc, "expected expression");
9922 
9923   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9924   if (!CE)
9925     return Error(OffsetLoc, "offset must be a constant");
9926 
9927   StackOffset = CE->getValue();
9928 
9929   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
9930     return true;
9931 
9932   SmallVector<uint8_t, 16> Opcodes;
9933 
9934   auto parseOne = [&]() -> bool {
9935     const MCExpr *OE;
9936     SMLoc OpcodeLoc = getLexer().getLoc();
9937     if (check(getLexer().is(AsmToken::EndOfStatement) ||
9938                   Parser.parseExpression(OE),
9939               OpcodeLoc, "expected opcode expression"))
9940       return true;
9941     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9942     if (!OC)
9943       return Error(OpcodeLoc, "opcode value must be a constant");
9944     const int64_t Opcode = OC->getValue();
9945     if (Opcode & ~0xff)
9946       return Error(OpcodeLoc, "invalid opcode");
9947     Opcodes.push_back(uint8_t(Opcode));
9948     return false;
9949   };
9950 
9951   // Must have at least 1 element
9952   SMLoc OpcodeLoc = getLexer().getLoc();
9953   if (parseOptionalToken(AsmToken::EndOfStatement))
9954     return Error(OpcodeLoc, "expected opcode expression");
9955   if (parseMany(parseOne))
9956     return true;
9957 
9958   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9959   return false;
9960 }
9961 
9962 /// parseDirectiveTLSDescSeq
9963 ///   ::= .tlsdescseq tls-variable
9964 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9965   MCAsmParser &Parser = getParser();
9966 
9967   if (getLexer().isNot(AsmToken::Identifier))
9968     return TokError("expected variable after '.tlsdescseq' directive");
9969 
9970   const MCSymbolRefExpr *SRE =
9971     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
9972                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9973   Lex();
9974 
9975   if (parseToken(AsmToken::EndOfStatement,
9976                  "unexpected token in '.tlsdescseq' directive"))
9977     return true;
9978 
9979   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9980   return false;
9981 }
9982 
9983 /// parseDirectiveMovSP
9984 ///  ::= .movsp reg [, #offset]
9985 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
9986   MCAsmParser &Parser = getParser();
9987   if (!UC.hasFnStart())
9988     return Error(L, ".fnstart must precede .movsp directives");
9989   if (UC.getFPReg() != ARM::SP)
9990     return Error(L, "unexpected .movsp directive");
9991 
9992   SMLoc SPRegLoc = Parser.getTok().getLoc();
9993   int SPReg = tryParseRegister();
9994   if (SPReg == -1)
9995     return Error(SPRegLoc, "register expected");
9996   if (SPReg == ARM::SP || SPReg == ARM::PC)
9997     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
9998 
9999   int64_t Offset = 0;
10000   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10001     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10002       return true;
10003 
10004     const MCExpr *OffsetExpr;
10005     SMLoc OffsetLoc = Parser.getTok().getLoc();
10006 
10007     if (Parser.parseExpression(OffsetExpr))
10008       return Error(OffsetLoc, "malformed offset expression");
10009 
10010     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10011     if (!CE)
10012       return Error(OffsetLoc, "offset must be an immediate constant");
10013 
10014     Offset = CE->getValue();
10015   }
10016 
10017   if (parseToken(AsmToken::EndOfStatement,
10018                  "unexpected token in '.movsp' directive"))
10019     return true;
10020 
10021   getTargetStreamer().emitMovSP(SPReg, Offset);
10022   UC.saveFPReg(SPReg);
10023 
10024   return false;
10025 }
10026 
10027 /// parseDirectiveObjectArch
10028 ///   ::= .object_arch name
10029 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10030   MCAsmParser &Parser = getParser();
10031   if (getLexer().isNot(AsmToken::Identifier))
10032     return Error(getLexer().getLoc(), "unexpected token");
10033 
10034   StringRef Arch = Parser.getTok().getString();
10035   SMLoc ArchLoc = Parser.getTok().getLoc();
10036   Lex();
10037 
10038   ARM::ArchKind ID = ARM::parseArch(Arch);
10039 
10040   if (ID == ARM::ArchKind::INVALID)
10041     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10042   if (parseToken(AsmToken::EndOfStatement))
10043     return true;
10044 
10045   getTargetStreamer().emitObjectArch(ID);
10046   return false;
10047 }
10048 
10049 /// parseDirectiveAlign
10050 ///   ::= .align
10051 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10052   // NOTE: if this is not the end of the statement, fall back to the target
10053   // agnostic handling for this directive which will correctly handle this.
10054   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10055     // '.align' is target specifically handled to mean 2**2 byte alignment.
10056     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10057     assert(Section && "must have section to emit alignment");
10058     if (Section->UseCodeAlign())
10059       getStreamer().EmitCodeAlignment(4, 0);
10060     else
10061       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10062     return false;
10063   }
10064   return true;
10065 }
10066 
10067 /// parseDirectiveThumbSet
10068 ///  ::= .thumb_set name, value
10069 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10070   MCAsmParser &Parser = getParser();
10071 
10072   StringRef Name;
10073   if (check(Parser.parseIdentifier(Name),
10074             "expected identifier after '.thumb_set'") ||
10075       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10076     return true;
10077 
10078   MCSymbol *Sym;
10079   const MCExpr *Value;
10080   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10081                                                Parser, Sym, Value))
10082     return true;
10083 
10084   getTargetStreamer().emitThumbSet(Sym, Value);
10085   return false;
10086 }
10087 
10088 /// Force static initialization.
10089 extern "C" void LLVMInitializeARMAsmParser() {
10090   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10091   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10092   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10093   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10094 }
10095 
10096 #define GET_REGISTER_MATCHER
10097 #define GET_SUBTARGET_FEATURE_NAME
10098 #define GET_MATCHER_IMPLEMENTATION
10099 #include "ARMGenAsmMatcher.inc"
10100 
10101 // FIXME: This structure should be moved inside ARMTargetParser
10102 // when we start to table-generate them, and we can use the ARM
10103 // flags below, that were generated by table-gen.
10104 static const struct {
10105   const unsigned Kind;
10106   const uint64_t ArchCheck;
10107   const FeatureBitset Features;
10108 } Extensions[] = {
10109   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10110   { ARM::AEK_CRYPTO,  Feature_HasV8,
10111     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10112   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10113   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10114     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10115   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10116   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10117   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10118   // FIXME: Only available in A-class, isel not predicated
10119   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10120   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10121   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10122   // FIXME: Unsupported extensions.
10123   { ARM::AEK_OS, Feature_None, {} },
10124   { ARM::AEK_IWMMXT, Feature_None, {} },
10125   { ARM::AEK_IWMMXT2, Feature_None, {} },
10126   { ARM::AEK_MAVERICK, Feature_None, {} },
10127   { ARM::AEK_XSCALE, Feature_None, {} },
10128 };
10129 
10130 /// parseDirectiveArchExtension
10131 ///   ::= .arch_extension [no]feature
10132 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10133   MCAsmParser &Parser = getParser();
10134 
10135   if (getLexer().isNot(AsmToken::Identifier))
10136     return Error(getLexer().getLoc(), "expected architecture extension name");
10137 
10138   StringRef Name = Parser.getTok().getString();
10139   SMLoc ExtLoc = Parser.getTok().getLoc();
10140   Lex();
10141 
10142   if (parseToken(AsmToken::EndOfStatement,
10143                  "unexpected token in '.arch_extension' directive"))
10144     return true;
10145 
10146   bool EnableFeature = true;
10147   if (Name.startswith_lower("no")) {
10148     EnableFeature = false;
10149     Name = Name.substr(2);
10150   }
10151   unsigned FeatureKind = ARM::parseArchExt(Name);
10152   if (FeatureKind == ARM::AEK_INVALID)
10153     return Error(ExtLoc, "unknown architectural extension: " + Name);
10154 
10155   for (const auto &Extension : Extensions) {
10156     if (Extension.Kind != FeatureKind)
10157       continue;
10158 
10159     if (Extension.Features.none())
10160       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10161 
10162     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10163       return Error(ExtLoc, "architectural extension '" + Name +
10164                                "' is not "
10165                                "allowed for the current base architecture");
10166 
10167     MCSubtargetInfo &STI = copySTI();
10168     FeatureBitset ToggleFeatures = EnableFeature
10169       ? (~STI.getFeatureBits() & Extension.Features)
10170       : ( STI.getFeatureBits() & Extension.Features);
10171 
10172     uint64_t Features =
10173         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10174     setAvailableFeatures(Features);
10175     return false;
10176   }
10177 
10178   return Error(ExtLoc, "unknown architectural extension: " + Name);
10179 }
10180 
10181 // Define this matcher function after the auto-generated include so we
10182 // have the match class enum definitions.
10183 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10184                                                   unsigned Kind) {
10185   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10186   // If the kind is a token for a literal immediate, check if our asm
10187   // operand matches. This is for InstAliases which have a fixed-value
10188   // immediate in the syntax.
10189   switch (Kind) {
10190   default: break;
10191   case MCK__35_0:
10192     if (Op.isImm())
10193       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10194         if (CE->getValue() == 0)
10195           return Match_Success;
10196     break;
10197   case MCK_ModImm:
10198     if (Op.isImm()) {
10199       const MCExpr *SOExpr = Op.getImm();
10200       int64_t Value;
10201       if (!SOExpr->evaluateAsAbsolute(Value))
10202         return Match_Success;
10203       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
10204              "expression value must be representable in 32 bits");
10205     }
10206     break;
10207   case MCK_rGPR:
10208     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10209       return Match_Success;
10210     break;
10211   case MCK_GPRPair:
10212     if (Op.isReg() &&
10213         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10214       return Match_Success;
10215     break;
10216   }
10217   return Match_InvalidOperand;
10218 }
10219