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 "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMMCExpr.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
24 #include "llvm/MC/MCELFStreamer.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCObjectFileInfo.h"
30 #include "llvm/MC/MCParser/MCAsmLexer.h"
31 #include "llvm/MC/MCParser/MCAsmParser.h"
32 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
33 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
34 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
35 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/MC/MCSection.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSubtargetInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/ARMBuildAttributes.h"
41 #include "llvm/Support/ARMEHABI.h"
42 #include "llvm/Support/COFF.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ELF.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetParser.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/raw_ostream.h"
51 
52 using namespace llvm;
53 
54 namespace {
55 
56 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
57 
58 static cl::opt<ImplicitItModeTy> ImplicitItMode(
59     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
60     cl::desc("Allow conditional instructions outdside of an IT block"),
61     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
62                           "Accept in both ISAs, emit implicit ITs in Thumb"),
63                clEnumValN(ImplicitItModeTy::Never, "never",
64                           "Warn in ARM, reject in Thumb"),
65                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
66                           "Accept in ARM, reject in Thumb"),
67                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
68                           "Warn in ARM, emit implicit ITs in Thumb")));
69 
70 class ARMOperand;
71 
72 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
73 
74 class UnwindContext {
75   MCAsmParser &Parser;
76 
77   typedef SmallVector<SMLoc, 4> Locs;
78 
79   Locs FnStartLocs;
80   Locs CantUnwindLocs;
81   Locs PersonalityLocs;
82   Locs PersonalityIndexLocs;
83   Locs HandlerDataLocs;
84   int FPReg;
85 
86 public:
87   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
88 
89   bool hasFnStart() const { return !FnStartLocs.empty(); }
90   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
91   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
92   bool hasPersonality() const {
93     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
94   }
95 
96   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
97   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
98   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
99   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
100   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
101 
102   void saveFPReg(int Reg) { FPReg = Reg; }
103   int getFPReg() const { return FPReg; }
104 
105   void emitFnStartLocNotes() const {
106     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
107          FI != FE; ++FI)
108       Parser.Note(*FI, ".fnstart was specified here");
109   }
110   void emitCantUnwindLocNotes() const {
111     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
112                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
113       Parser.Note(*UI, ".cantunwind was specified here");
114   }
115   void emitHandlerDataLocNotes() const {
116     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
117                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
118       Parser.Note(*HI, ".handlerdata was specified here");
119   }
120   void emitPersonalityLocNotes() const {
121     for (Locs::const_iterator PI = PersonalityLocs.begin(),
122                               PE = PersonalityLocs.end(),
123                               PII = PersonalityIndexLocs.begin(),
124                               PIE = PersonalityIndexLocs.end();
125          PI != PE || PII != PIE;) {
126       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
127         Parser.Note(*PI++, ".personality was specified here");
128       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
129         Parser.Note(*PII++, ".personalityindex was specified here");
130       else
131         llvm_unreachable(".personality and .personalityindex cannot be "
132                          "at the same location");
133     }
134   }
135 
136   void reset() {
137     FnStartLocs = Locs();
138     CantUnwindLocs = Locs();
139     PersonalityLocs = Locs();
140     HandlerDataLocs = Locs();
141     PersonalityIndexLocs = Locs();
142     FPReg = ARM::SP;
143   }
144 };
145 
146 class ARMAsmParser : public MCTargetAsmParser {
147   const MCInstrInfo &MII;
148   const MCRegisterInfo *MRI;
149   UnwindContext UC;
150 
151   ARMTargetStreamer &getTargetStreamer() {
152     assert(getParser().getStreamer().getTargetStreamer() &&
153            "do not have a target streamer");
154     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
155     return static_cast<ARMTargetStreamer &>(TS);
156   }
157 
158   // Map of register aliases registers via the .req directive.
159   StringMap<unsigned> RegisterReqs;
160 
161   bool NextSymbolIsThumb;
162 
163   bool useImplicitITThumb() const {
164     return ImplicitItMode == ImplicitItModeTy::Always ||
165            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
166   }
167 
168   bool useImplicitITARM() const {
169     return ImplicitItMode == ImplicitItModeTy::Always ||
170            ImplicitItMode == ImplicitItModeTy::ARMOnly;
171   }
172 
173   struct {
174     ARMCC::CondCodes Cond;    // Condition for IT block.
175     unsigned Mask:4;          // Condition mask for instructions.
176                               // Starting at first 1 (from lsb).
177                               //   '1'  condition as indicated in IT.
178                               //   '0'  inverse of condition (else).
179                               // Count of instructions in IT block is
180                               // 4 - trailingzeroes(mask)
181                               // Note that this does not have the same encoding
182                               // as in the IT instruction, which also depends
183                               // on the low bit of the condition code.
184 
185     unsigned CurPosition;     // Current position in parsing of IT
186                               // block. In range [0,4], with 0 being the IT
187                               // instruction itself. Initialized according to
188                               // count of instructions in block.  ~0U if no
189                               // active IT block.
190 
191     bool IsExplicit;          // true  - The IT instruction was present in the
192                               //         input, we should not modify it.
193                               // false - The IT instruction was added
194                               //         implicitly, we can extend it if that
195                               //         would be legal.
196   } ITState;
197 
198   llvm::SmallVector<MCInst, 4> PendingConditionalInsts;
199 
200   void flushPendingInstructions(MCStreamer &Out) override {
201     if (!inImplicitITBlock()) {
202       assert(PendingConditionalInsts.size() == 0);
203       return;
204     }
205 
206     // Emit the IT instruction
207     unsigned Mask = getITMaskEncoding();
208     MCInst ITInst;
209     ITInst.setOpcode(ARM::t2IT);
210     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
211     ITInst.addOperand(MCOperand::createImm(Mask));
212     Out.EmitInstruction(ITInst, getSTI());
213 
214     // Emit the conditonal instructions
215     assert(PendingConditionalInsts.size() <= 4);
216     for (const MCInst &Inst : PendingConditionalInsts) {
217       Out.EmitInstruction(Inst, getSTI());
218     }
219     PendingConditionalInsts.clear();
220 
221     // Clear the IT state
222     ITState.Mask = 0;
223     ITState.CurPosition = ~0U;
224   }
225 
226   bool inITBlock() { return ITState.CurPosition != ~0U; }
227   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
228   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
229   bool lastInITBlock() {
230     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
231   }
232   void forwardITPosition() {
233     if (!inITBlock()) return;
234     // Move to the next instruction in the IT block, if there is one. If not,
235     // mark the block as done, except for implicit IT blocks, which we leave
236     // open until we find an instruction that can't be added to it.
237     unsigned TZ = countTrailingZeros(ITState.Mask);
238     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
239       ITState.CurPosition = ~0U; // Done with the IT block after this.
240   }
241 
242   // Rewind the state of the current IT block, removing the last slot from it.
243   void rewindImplicitITPosition() {
244     assert(inImplicitITBlock());
245     assert(ITState.CurPosition > 1);
246     ITState.CurPosition--;
247     unsigned TZ = countTrailingZeros(ITState.Mask);
248     unsigned NewMask = 0;
249     NewMask |= ITState.Mask & (0xC << TZ);
250     NewMask |= 0x2 << TZ;
251     ITState.Mask = NewMask;
252   }
253 
254   // Rewind the state of the current IT block, removing the last slot from it.
255   // If we were at the first slot, this closes the IT block.
256   void discardImplicitITBlock() {
257     assert(inImplicitITBlock());
258     assert(ITState.CurPosition == 1);
259     ITState.CurPosition = ~0U;
260     return;
261   }
262 
263   // Get the encoding of the IT mask, as it will appear in an IT instruction.
264   unsigned getITMaskEncoding() {
265     assert(inITBlock());
266     unsigned Mask = ITState.Mask;
267     unsigned TZ = countTrailingZeros(Mask);
268     if ((ITState.Cond & 1) == 0) {
269       assert(Mask && TZ <= 3 && "illegal IT mask value!");
270       Mask ^= (0xE << TZ) & 0xF;
271     }
272     return Mask;
273   }
274 
275   // Get the condition code corresponding to the current IT block slot.
276   ARMCC::CondCodes currentITCond() {
277     unsigned MaskBit;
278     if (ITState.CurPosition == 1)
279       MaskBit = 1;
280     else
281       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
282 
283     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
284   }
285 
286   // Invert the condition of the current IT block slot without changing any
287   // other slots in the same block.
288   void invertCurrentITCondition() {
289     if (ITState.CurPosition == 1) {
290       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
291     } else {
292       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
293     }
294   }
295 
296   // Returns true if the current IT block is full (all 4 slots used).
297   bool isITBlockFull() {
298     return inITBlock() && (ITState.Mask & 1);
299   }
300 
301   // Extend the current implicit IT block to have one more slot with the given
302   // condition code.
303   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
304     assert(inImplicitITBlock());
305     assert(!isITBlockFull());
306     assert(Cond == ITState.Cond ||
307            Cond == ARMCC::getOppositeCondition(ITState.Cond));
308     unsigned TZ = countTrailingZeros(ITState.Mask);
309     unsigned NewMask = 0;
310     // Keep any existing condition bits.
311     NewMask |= ITState.Mask & (0xE << TZ);
312     // Insert the new condition bit.
313     NewMask |= (Cond == ITState.Cond) << TZ;
314     // Move the trailing 1 down one bit.
315     NewMask |= 1 << (TZ - 1);
316     ITState.Mask = NewMask;
317   }
318 
319   // Create a new implicit IT block with a dummy condition code.
320   void startImplicitITBlock() {
321     assert(!inITBlock());
322     ITState.Cond = ARMCC::AL;
323     ITState.Mask = 8;
324     ITState.CurPosition = 1;
325     ITState.IsExplicit = false;
326     return;
327   }
328 
329   // Create a new explicit IT block with the given condition and mask. The mask
330   // should be in the parsed format, with a 1 implying 't', regardless of the
331   // low bit of the condition.
332   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
333     assert(!inITBlock());
334     ITState.Cond = Cond;
335     ITState.Mask = Mask;
336     ITState.CurPosition = 0;
337     ITState.IsExplicit = true;
338     return;
339   }
340 
341   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
342     return getParser().Note(L, Msg, Range);
343   }
344   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
345     return getParser().Warning(L, Msg, Range);
346   }
347   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
348     return getParser().Error(L, Msg, Range);
349   }
350 
351   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
352                            unsigned ListNo, bool IsARPop = false);
353   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
354                            unsigned ListNo);
355 
356   int tryParseRegister();
357   bool tryParseRegisterWithWriteBack(OperandVector &);
358   int tryParseShiftRegister(OperandVector &);
359   bool parseRegisterList(OperandVector &);
360   bool parseMemory(OperandVector &);
361   bool parseOperand(OperandVector &, StringRef Mnemonic);
362   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
363   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
364                               unsigned &ShiftAmount);
365   bool parseLiteralValues(unsigned Size, SMLoc L);
366   bool parseDirectiveThumb(SMLoc L);
367   bool parseDirectiveARM(SMLoc L);
368   bool parseDirectiveThumbFunc(SMLoc L);
369   bool parseDirectiveCode(SMLoc L);
370   bool parseDirectiveSyntax(SMLoc L);
371   bool parseDirectiveReq(StringRef Name, SMLoc L);
372   bool parseDirectiveUnreq(SMLoc L);
373   bool parseDirectiveArch(SMLoc L);
374   bool parseDirectiveEabiAttr(SMLoc L);
375   bool parseDirectiveCPU(SMLoc L);
376   bool parseDirectiveFPU(SMLoc L);
377   bool parseDirectiveFnStart(SMLoc L);
378   bool parseDirectiveFnEnd(SMLoc L);
379   bool parseDirectiveCantUnwind(SMLoc L);
380   bool parseDirectivePersonality(SMLoc L);
381   bool parseDirectiveHandlerData(SMLoc L);
382   bool parseDirectiveSetFP(SMLoc L);
383   bool parseDirectivePad(SMLoc L);
384   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
385   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
386   bool parseDirectiveLtorg(SMLoc L);
387   bool parseDirectiveEven(SMLoc L);
388   bool parseDirectivePersonalityIndex(SMLoc L);
389   bool parseDirectiveUnwindRaw(SMLoc L);
390   bool parseDirectiveTLSDescSeq(SMLoc L);
391   bool parseDirectiveMovSP(SMLoc L);
392   bool parseDirectiveObjectArch(SMLoc L);
393   bool parseDirectiveArchExtension(SMLoc L);
394   bool parseDirectiveAlign(SMLoc L);
395   bool parseDirectiveThumbSet(SMLoc L);
396 
397   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
398                           bool &CarrySetting, unsigned &ProcessorIMod,
399                           StringRef &ITMask);
400   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
401                              bool &CanAcceptCarrySet,
402                              bool &CanAcceptPredicationCode);
403 
404   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
405                                      OperandVector &Operands);
406   bool isThumb() const {
407     // FIXME: Can tablegen auto-generate this?
408     return getSTI().getFeatureBits()[ARM::ModeThumb];
409   }
410   bool isThumbOne() const {
411     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
412   }
413   bool isThumbTwo() const {
414     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
415   }
416   bool hasThumb() const {
417     return getSTI().getFeatureBits()[ARM::HasV4TOps];
418   }
419   bool hasThumb2() const {
420     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
421   }
422   bool hasV6Ops() const {
423     return getSTI().getFeatureBits()[ARM::HasV6Ops];
424   }
425   bool hasV6T2Ops() const {
426     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
427   }
428   bool hasV6MOps() const {
429     return getSTI().getFeatureBits()[ARM::HasV6MOps];
430   }
431   bool hasV7Ops() const {
432     return getSTI().getFeatureBits()[ARM::HasV7Ops];
433   }
434   bool hasV8Ops() const {
435     return getSTI().getFeatureBits()[ARM::HasV8Ops];
436   }
437   bool hasV8MBaseline() const {
438     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
439   }
440   bool hasV8MMainline() const {
441     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
442   }
443   bool has8MSecExt() const {
444     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
445   }
446   bool hasARM() const {
447     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
448   }
449   bool hasDSP() const {
450     return getSTI().getFeatureBits()[ARM::FeatureDSP];
451   }
452   bool hasD16() const {
453     return getSTI().getFeatureBits()[ARM::FeatureD16];
454   }
455   bool hasV8_1aOps() const {
456     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
457   }
458   bool hasRAS() const {
459     return getSTI().getFeatureBits()[ARM::FeatureRAS];
460   }
461 
462   void SwitchMode() {
463     MCSubtargetInfo &STI = copySTI();
464     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
465     setAvailableFeatures(FB);
466   }
467   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
468   bool isMClass() const {
469     return getSTI().getFeatureBits()[ARM::FeatureMClass];
470   }
471 
472   /// @name Auto-generated Match Functions
473   /// {
474 
475 #define GET_ASSEMBLER_HEADER
476 #include "ARMGenAsmMatcher.inc"
477 
478   /// }
479 
480   OperandMatchResultTy parseITCondCode(OperandVector &);
481   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
482   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
483   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
484   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
485   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
486   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
487   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
488   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
489   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
490                                    int High);
491   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
492     return parsePKHImm(O, "lsl", 0, 31);
493   }
494   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
495     return parsePKHImm(O, "asr", 1, 32);
496   }
497   OperandMatchResultTy parseSetEndImm(OperandVector &);
498   OperandMatchResultTy parseShifterImm(OperandVector &);
499   OperandMatchResultTy parseRotImm(OperandVector &);
500   OperandMatchResultTy parseModImm(OperandVector &);
501   OperandMatchResultTy parseBitfield(OperandVector &);
502   OperandMatchResultTy parsePostIdxReg(OperandVector &);
503   OperandMatchResultTy parseAM3Offset(OperandVector &);
504   OperandMatchResultTy parseFPImm(OperandVector &);
505   OperandMatchResultTy parseVectorList(OperandVector &);
506   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
507                                        SMLoc &EndLoc);
508 
509   // Asm Match Converter Methods
510   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
511   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
512 
513   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
514   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
515   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
516   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
517   bool isITBlockTerminator(MCInst &Inst) const;
518 
519 public:
520   enum ARMMatchResultTy {
521     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
522     Match_RequiresNotITBlock,
523     Match_RequiresV6,
524     Match_RequiresThumb2,
525     Match_RequiresV8,
526     Match_RequiresFlagSetting,
527 #define GET_OPERAND_DIAGNOSTIC_TYPES
528 #include "ARMGenAsmMatcher.inc"
529 
530   };
531 
532   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
533                const MCInstrInfo &MII, const MCTargetOptions &Options)
534     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
535     MCAsmParserExtension::Initialize(Parser);
536 
537     // Cache the MCRegisterInfo.
538     MRI = getContext().getRegisterInfo();
539 
540     // Initialize the set of available features.
541     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
542 
543     // Not in an ITBlock to start with.
544     ITState.CurPosition = ~0U;
545 
546     NextSymbolIsThumb = false;
547   }
548 
549   // Implementation of the MCTargetAsmParser interface:
550   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
551   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
552                         SMLoc NameLoc, OperandVector &Operands) override;
553   bool ParseDirective(AsmToken DirectiveID) override;
554 
555   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
556                                       unsigned Kind) override;
557   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
558 
559   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
560                                OperandVector &Operands, MCStreamer &Out,
561                                uint64_t &ErrorInfo,
562                                bool MatchingInlineAsm) override;
563   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
564                             uint64_t &ErrorInfo, bool MatchingInlineAsm,
565                             bool &EmitInITBlock, MCStreamer &Out);
566   void onLabelParsed(MCSymbol *Symbol) override;
567 };
568 } // end anonymous namespace
569 
570 namespace {
571 
572 /// ARMOperand - Instances of this class represent a parsed ARM machine
573 /// operand.
574 class ARMOperand : public MCParsedAsmOperand {
575   enum KindTy {
576     k_CondCode,
577     k_CCOut,
578     k_ITCondMask,
579     k_CoprocNum,
580     k_CoprocReg,
581     k_CoprocOption,
582     k_Immediate,
583     k_MemBarrierOpt,
584     k_InstSyncBarrierOpt,
585     k_Memory,
586     k_PostIndexRegister,
587     k_MSRMask,
588     k_BankedReg,
589     k_ProcIFlags,
590     k_VectorIndex,
591     k_Register,
592     k_RegisterList,
593     k_DPRRegisterList,
594     k_SPRRegisterList,
595     k_VectorList,
596     k_VectorListAllLanes,
597     k_VectorListIndexed,
598     k_ShiftedRegister,
599     k_ShiftedImmediate,
600     k_ShifterImmediate,
601     k_RotateImmediate,
602     k_ModifiedImmediate,
603     k_ConstantPoolImmediate,
604     k_BitfieldDescriptor,
605     k_Token,
606   } Kind;
607 
608   SMLoc StartLoc, EndLoc, AlignmentLoc;
609   SmallVector<unsigned, 8> Registers;
610 
611   struct CCOp {
612     ARMCC::CondCodes Val;
613   };
614 
615   struct CopOp {
616     unsigned Val;
617   };
618 
619   struct CoprocOptionOp {
620     unsigned Val;
621   };
622 
623   struct ITMaskOp {
624     unsigned Mask:4;
625   };
626 
627   struct MBOptOp {
628     ARM_MB::MemBOpt Val;
629   };
630 
631   struct ISBOptOp {
632     ARM_ISB::InstSyncBOpt Val;
633   };
634 
635   struct IFlagsOp {
636     ARM_PROC::IFlags Val;
637   };
638 
639   struct MMaskOp {
640     unsigned Val;
641   };
642 
643   struct BankedRegOp {
644     unsigned Val;
645   };
646 
647   struct TokOp {
648     const char *Data;
649     unsigned Length;
650   };
651 
652   struct RegOp {
653     unsigned RegNum;
654   };
655 
656   // A vector register list is a sequential list of 1 to 4 registers.
657   struct VectorListOp {
658     unsigned RegNum;
659     unsigned Count;
660     unsigned LaneIndex;
661     bool isDoubleSpaced;
662   };
663 
664   struct VectorIndexOp {
665     unsigned Val;
666   };
667 
668   struct ImmOp {
669     const MCExpr *Val;
670   };
671 
672   /// Combined record for all forms of ARM address expressions.
673   struct MemoryOp {
674     unsigned BaseRegNum;
675     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
676     // was specified.
677     const MCConstantExpr *OffsetImm;  // Offset immediate value
678     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
679     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
680     unsigned ShiftImm;        // shift for OffsetReg.
681     unsigned Alignment;       // 0 = no alignment specified
682     // n = alignment in bytes (2, 4, 8, 16, or 32)
683     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
684   };
685 
686   struct PostIdxRegOp {
687     unsigned RegNum;
688     bool isAdd;
689     ARM_AM::ShiftOpc ShiftTy;
690     unsigned ShiftImm;
691   };
692 
693   struct ShifterImmOp {
694     bool isASR;
695     unsigned Imm;
696   };
697 
698   struct RegShiftedRegOp {
699     ARM_AM::ShiftOpc ShiftTy;
700     unsigned SrcReg;
701     unsigned ShiftReg;
702     unsigned ShiftImm;
703   };
704 
705   struct RegShiftedImmOp {
706     ARM_AM::ShiftOpc ShiftTy;
707     unsigned SrcReg;
708     unsigned ShiftImm;
709   };
710 
711   struct RotImmOp {
712     unsigned Imm;
713   };
714 
715   struct ModImmOp {
716     unsigned Bits;
717     unsigned Rot;
718   };
719 
720   struct BitfieldOp {
721     unsigned LSB;
722     unsigned Width;
723   };
724 
725   union {
726     struct CCOp CC;
727     struct CopOp Cop;
728     struct CoprocOptionOp CoprocOption;
729     struct MBOptOp MBOpt;
730     struct ISBOptOp ISBOpt;
731     struct ITMaskOp ITMask;
732     struct IFlagsOp IFlags;
733     struct MMaskOp MMask;
734     struct BankedRegOp BankedReg;
735     struct TokOp Tok;
736     struct RegOp Reg;
737     struct VectorListOp VectorList;
738     struct VectorIndexOp VectorIndex;
739     struct ImmOp Imm;
740     struct MemoryOp Memory;
741     struct PostIdxRegOp PostIdxReg;
742     struct ShifterImmOp ShifterImm;
743     struct RegShiftedRegOp RegShiftedReg;
744     struct RegShiftedImmOp RegShiftedImm;
745     struct RotImmOp RotImm;
746     struct ModImmOp ModImm;
747     struct BitfieldOp Bitfield;
748   };
749 
750 public:
751   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
752 
753   /// getStartLoc - Get the location of the first token of this operand.
754   SMLoc getStartLoc() const override { return StartLoc; }
755   /// getEndLoc - Get the location of the last token of this operand.
756   SMLoc getEndLoc() const override { return EndLoc; }
757   /// getLocRange - Get the range between the first and last token of this
758   /// operand.
759   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
760 
761   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
762   SMLoc getAlignmentLoc() const {
763     assert(Kind == k_Memory && "Invalid access!");
764     return AlignmentLoc;
765   }
766 
767   ARMCC::CondCodes getCondCode() const {
768     assert(Kind == k_CondCode && "Invalid access!");
769     return CC.Val;
770   }
771 
772   unsigned getCoproc() const {
773     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
774     return Cop.Val;
775   }
776 
777   StringRef getToken() const {
778     assert(Kind == k_Token && "Invalid access!");
779     return StringRef(Tok.Data, Tok.Length);
780   }
781 
782   unsigned getReg() const override {
783     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
784     return Reg.RegNum;
785   }
786 
787   const SmallVectorImpl<unsigned> &getRegList() const {
788     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
789             Kind == k_SPRRegisterList) && "Invalid access!");
790     return Registers;
791   }
792 
793   const MCExpr *getImm() const {
794     assert(isImm() && "Invalid access!");
795     return Imm.Val;
796   }
797 
798   const MCExpr *getConstantPoolImm() const {
799     assert(isConstantPoolImm() && "Invalid access!");
800     return Imm.Val;
801   }
802 
803   unsigned getVectorIndex() const {
804     assert(Kind == k_VectorIndex && "Invalid access!");
805     return VectorIndex.Val;
806   }
807 
808   ARM_MB::MemBOpt getMemBarrierOpt() const {
809     assert(Kind == k_MemBarrierOpt && "Invalid access!");
810     return MBOpt.Val;
811   }
812 
813   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
814     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
815     return ISBOpt.Val;
816   }
817 
818   ARM_PROC::IFlags getProcIFlags() const {
819     assert(Kind == k_ProcIFlags && "Invalid access!");
820     return IFlags.Val;
821   }
822 
823   unsigned getMSRMask() const {
824     assert(Kind == k_MSRMask && "Invalid access!");
825     return MMask.Val;
826   }
827 
828   unsigned getBankedReg() const {
829     assert(Kind == k_BankedReg && "Invalid access!");
830     return BankedReg.Val;
831   }
832 
833   bool isCoprocNum() const { return Kind == k_CoprocNum; }
834   bool isCoprocReg() const { return Kind == k_CoprocReg; }
835   bool isCoprocOption() const { return Kind == k_CoprocOption; }
836   bool isCondCode() const { return Kind == k_CondCode; }
837   bool isCCOut() const { return Kind == k_CCOut; }
838   bool isITMask() const { return Kind == k_ITCondMask; }
839   bool isITCondCode() const { return Kind == k_CondCode; }
840   bool isImm() const override {
841     return Kind == k_Immediate;
842   }
843 
844   bool isARMBranchTarget() const {
845     if (!isImm()) return false;
846 
847     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
848       return CE->getValue() % 4 == 0;
849     return true;
850   }
851 
852 
853   bool isThumbBranchTarget() const {
854     if (!isImm()) return false;
855 
856     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
857       return CE->getValue() % 2 == 0;
858     return true;
859   }
860 
861   // checks whether this operand is an unsigned offset which fits is a field
862   // of specified width and scaled by a specific number of bits
863   template<unsigned width, unsigned scale>
864   bool isUnsignedOffset() const {
865     if (!isImm()) return false;
866     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
867     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
868       int64_t Val = CE->getValue();
869       int64_t Align = 1LL << scale;
870       int64_t Max = Align * ((1LL << width) - 1);
871       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
872     }
873     return false;
874   }
875   // checks whether this operand is an signed offset which fits is a field
876   // of specified width and scaled by a specific number of bits
877   template<unsigned width, unsigned scale>
878   bool isSignedOffset() const {
879     if (!isImm()) return false;
880     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
881     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
882       int64_t Val = CE->getValue();
883       int64_t Align = 1LL << scale;
884       int64_t Max = Align * ((1LL << (width-1)) - 1);
885       int64_t Min = -Align * (1LL << (width-1));
886       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
887     }
888     return false;
889   }
890 
891   // checks whether this operand is a memory operand computed as an offset
892   // applied to PC. the offset may have 8 bits of magnitude and is represented
893   // with two bits of shift. textually it may be either [pc, #imm], #imm or
894   // relocable expression...
895   bool isThumbMemPC() const {
896     int64_t Val = 0;
897     if (isImm()) {
898       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
899       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
900       if (!CE) return false;
901       Val = CE->getValue();
902     }
903     else if (isMem()) {
904       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
905       if(Memory.BaseRegNum != ARM::PC) return false;
906       Val = Memory.OffsetImm->getValue();
907     }
908     else return false;
909     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
910   }
911   bool isFPImm() const {
912     if (!isImm()) return false;
913     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
914     if (!CE) return false;
915     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
916     return Val != -1;
917   }
918 
919   template<int64_t N, int64_t M>
920   bool isImmediate() const {
921     if (!isImm()) return false;
922     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
923     if (!CE) return false;
924     int64_t Value = CE->getValue();
925     return Value >= N && Value <= M;
926   }
927   template<int64_t N, int64_t M>
928   bool isImmediateS4() 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 & 3) == 0) && Value >= N && Value <= M;
934   }
935   bool isFBits16() const {
936     return isImmediate<0, 17>();
937   }
938   bool isFBits32() const {
939     return isImmediate<1, 33>();
940   }
941   bool isImm8s4() const {
942     return isImmediateS4<-1020, 1020>();
943   }
944   bool isImm0_1020s4() const {
945     return isImmediateS4<0, 1020>();
946   }
947   bool isImm0_508s4() const {
948     return isImmediateS4<0, 508>();
949   }
950   bool isImm0_508s4Neg() const {
951     if (!isImm()) return false;
952     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
953     if (!CE) return false;
954     int64_t Value = -CE->getValue();
955     // explicitly exclude zero. we want that to use the normal 0_508 version.
956     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
957   }
958   bool isImm0_4095Neg() 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     return Value > 0 && Value < 4096;
964   }
965   bool isImm0_7() const {
966     return isImmediate<0, 7>();
967   }
968   bool isImm1_16() const {
969     return isImmediate<1, 16>();
970   }
971   bool isImm1_32() const {
972     return isImmediate<1, 32>();
973   }
974   bool isImm8_255() const {
975     return isImmediate<8, 255>();
976   }
977   bool isImm256_65535Expr() const {
978     if (!isImm()) return false;
979     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
980     // If it's not a constant expression, it'll generate a fixup and be
981     // handled later.
982     if (!CE) return true;
983     int64_t Value = CE->getValue();
984     return Value >= 256 && Value < 65536;
985   }
986   bool isImm0_65535Expr() const {
987     if (!isImm()) return false;
988     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
989     // If it's not a constant expression, it'll generate a fixup and be
990     // handled later.
991     if (!CE) return true;
992     int64_t Value = CE->getValue();
993     return Value >= 0 && Value < 65536;
994   }
995   bool isImm24bit() const {
996     return isImmediate<0, 0xffffff + 1>();
997   }
998   bool isImmThumbSR() const {
999     return isImmediate<1, 33>();
1000   }
1001   bool isPKHLSLImm() const {
1002     return isImmediate<0, 32>();
1003   }
1004   bool isPKHASRImm() const {
1005     return isImmediate<0, 33>();
1006   }
1007   bool isAdrLabel() const {
1008     // If we have an immediate that's not a constant, treat it as a label
1009     // reference needing a fixup.
1010     if (isImm() && !isa<MCConstantExpr>(getImm()))
1011       return true;
1012 
1013     // If it is a constant, it must fit into a modified immediate encoding.
1014     if (!isImm()) return false;
1015     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1016     if (!CE) return false;
1017     int64_t Value = CE->getValue();
1018     return (ARM_AM::getSOImmVal(Value) != -1 ||
1019             ARM_AM::getSOImmVal(-Value) != -1);
1020   }
1021   bool isT2SOImm() const {
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::getT2SOImmVal(Value) != -1;
1027   }
1028   bool isT2SOImmNot() const {
1029     if (!isImm()) return false;
1030     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1031     if (!CE) return false;
1032     int64_t Value = CE->getValue();
1033     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1034       ARM_AM::getT2SOImmVal(~Value) != -1;
1035   }
1036   bool isT2SOImmNeg() const {
1037     if (!isImm()) return false;
1038     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1039     if (!CE) return false;
1040     int64_t Value = CE->getValue();
1041     // Only use this when not representable as a plain so_imm.
1042     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1043       ARM_AM::getT2SOImmVal(-Value) != -1;
1044   }
1045   bool isSetEndImm() 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 Value == 1 || Value == 0;
1051   }
1052   bool isReg() const override { return Kind == k_Register; }
1053   bool isRegList() const { return Kind == k_RegisterList; }
1054   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1055   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1056   bool isToken() const override { return Kind == k_Token; }
1057   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1058   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1059   bool isMem() const override { return Kind == k_Memory; }
1060   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1061   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1062   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1063   bool isRotImm() const { return Kind == k_RotateImmediate; }
1064   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1065   bool isModImmNot() const {
1066     if (!isImm()) return false;
1067     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1068     if (!CE) return false;
1069     int64_t Value = CE->getValue();
1070     return ARM_AM::getSOImmVal(~Value) != -1;
1071   }
1072   bool isModImmNeg() const {
1073     if (!isImm()) return false;
1074     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1075     if (!CE) return false;
1076     int64_t Value = CE->getValue();
1077     return ARM_AM::getSOImmVal(Value) == -1 &&
1078       ARM_AM::getSOImmVal(-Value) != -1;
1079   }
1080   bool isThumbModImmNeg1_7() const {
1081     if (!isImm()) return false;
1082     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1083     if (!CE) return false;
1084     int32_t Value = -(int32_t)CE->getValue();
1085     return 0 < Value && Value < 8;
1086   }
1087   bool isThumbModImmNeg8_255() const {
1088     if (!isImm()) return false;
1089     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1090     if (!CE) return false;
1091     int32_t Value = -(int32_t)CE->getValue();
1092     return 7 < Value && Value < 256;
1093   }
1094   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1095   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1096   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1097   bool isPostIdxReg() const {
1098     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1099   }
1100   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1101     if (!isMem())
1102       return false;
1103     // No offset of any kind.
1104     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1105      (alignOK || Memory.Alignment == Alignment);
1106   }
1107   bool isMemPCRelImm12() const {
1108     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1109       return false;
1110     // Base register must be PC.
1111     if (Memory.BaseRegNum != ARM::PC)
1112       return false;
1113     // Immediate offset in range [-4095, 4095].
1114     if (!Memory.OffsetImm) return true;
1115     int64_t Val = Memory.OffsetImm->getValue();
1116     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1117   }
1118   bool isAlignedMemory() const {
1119     return isMemNoOffset(true);
1120   }
1121   bool isAlignedMemoryNone() const {
1122     return isMemNoOffset(false, 0);
1123   }
1124   bool isDupAlignedMemoryNone() const {
1125     return isMemNoOffset(false, 0);
1126   }
1127   bool isAlignedMemory16() const {
1128     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1129       return true;
1130     return isMemNoOffset(false, 0);
1131   }
1132   bool isDupAlignedMemory16() const {
1133     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1134       return true;
1135     return isMemNoOffset(false, 0);
1136   }
1137   bool isAlignedMemory32() const {
1138     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1139       return true;
1140     return isMemNoOffset(false, 0);
1141   }
1142   bool isDupAlignedMemory32() const {
1143     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1144       return true;
1145     return isMemNoOffset(false, 0);
1146   }
1147   bool isAlignedMemory64() const {
1148     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1149       return true;
1150     return isMemNoOffset(false, 0);
1151   }
1152   bool isDupAlignedMemory64() const {
1153     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1154       return true;
1155     return isMemNoOffset(false, 0);
1156   }
1157   bool isAlignedMemory64or128() const {
1158     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1159       return true;
1160     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1161       return true;
1162     return isMemNoOffset(false, 0);
1163   }
1164   bool isDupAlignedMemory64or128() const {
1165     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1166       return true;
1167     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1168       return true;
1169     return isMemNoOffset(false, 0);
1170   }
1171   bool isAlignedMemory64or128or256() const {
1172     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1173       return true;
1174     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1175       return true;
1176     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1177       return true;
1178     return isMemNoOffset(false, 0);
1179   }
1180   bool isAddrMode2() const {
1181     if (!isMem() || Memory.Alignment != 0) return false;
1182     // Check for register offset.
1183     if (Memory.OffsetRegNum) return true;
1184     // Immediate offset in range [-4095, 4095].
1185     if (!Memory.OffsetImm) return true;
1186     int64_t Val = Memory.OffsetImm->getValue();
1187     return Val > -4096 && Val < 4096;
1188   }
1189   bool isAM2OffsetImm() const {
1190     if (!isImm()) return false;
1191     // Immediate offset in range [-4095, 4095].
1192     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1193     if (!CE) return false;
1194     int64_t Val = CE->getValue();
1195     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1196   }
1197   bool isAddrMode3() const {
1198     // If we have an immediate that's not a constant, treat it as a label
1199     // reference needing a fixup. If it is a constant, it's something else
1200     // and we reject it.
1201     if (isImm() && !isa<MCConstantExpr>(getImm()))
1202       return true;
1203     if (!isMem() || Memory.Alignment != 0) return false;
1204     // No shifts are legal for AM3.
1205     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1206     // Check for register offset.
1207     if (Memory.OffsetRegNum) return true;
1208     // Immediate offset in range [-255, 255].
1209     if (!Memory.OffsetImm) return true;
1210     int64_t Val = Memory.OffsetImm->getValue();
1211     // The #-0 offset is encoded as INT32_MIN, and we have to check
1212     // for this too.
1213     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1214   }
1215   bool isAM3Offset() const {
1216     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1217       return false;
1218     if (Kind == k_PostIndexRegister)
1219       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1220     // Immediate offset in range [-255, 255].
1221     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1222     if (!CE) return false;
1223     int64_t Val = CE->getValue();
1224     // Special case, #-0 is INT32_MIN.
1225     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1226   }
1227   bool isAddrMode5() const {
1228     // If we have an immediate that's not a constant, treat it as a label
1229     // reference needing a fixup. If it is a constant, it's something else
1230     // and we reject it.
1231     if (isImm() && !isa<MCConstantExpr>(getImm()))
1232       return true;
1233     if (!isMem() || Memory.Alignment != 0) return false;
1234     // Check for register offset.
1235     if (Memory.OffsetRegNum) return false;
1236     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1237     if (!Memory.OffsetImm) return true;
1238     int64_t Val = Memory.OffsetImm->getValue();
1239     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1240       Val == INT32_MIN;
1241   }
1242   bool isAddrMode5FP16() const {
1243     // If we have an immediate that's not a constant, treat it as a label
1244     // reference needing a fixup. If it is a constant, it's something else
1245     // and we reject it.
1246     if (isImm() && !isa<MCConstantExpr>(getImm()))
1247       return true;
1248     if (!isMem() || Memory.Alignment != 0) return false;
1249     // Check for register offset.
1250     if (Memory.OffsetRegNum) return false;
1251     // Immediate offset in range [-510, 510] and a multiple of 2.
1252     if (!Memory.OffsetImm) return true;
1253     int64_t Val = Memory.OffsetImm->getValue();
1254     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) || Val == INT32_MIN;
1255   }
1256   bool isMemTBB() const {
1257     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1258         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1259       return false;
1260     return true;
1261   }
1262   bool isMemTBH() const {
1263     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1264         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1265         Memory.Alignment != 0 )
1266       return false;
1267     return true;
1268   }
1269   bool isMemRegOffset() const {
1270     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1271       return false;
1272     return true;
1273   }
1274   bool isT2MemRegOffset() const {
1275     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1276         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1277       return false;
1278     // Only lsl #{0, 1, 2, 3} allowed.
1279     if (Memory.ShiftType == ARM_AM::no_shift)
1280       return true;
1281     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1282       return false;
1283     return true;
1284   }
1285   bool isMemThumbRR() const {
1286     // Thumb reg+reg addressing is simple. Just two registers, a base and
1287     // an offset. No shifts, negations or any other complicating factors.
1288     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1289         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1290       return false;
1291     return isARMLowRegister(Memory.BaseRegNum) &&
1292       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1293   }
1294   bool isMemThumbRIs4() const {
1295     if (!isMem() || Memory.OffsetRegNum != 0 ||
1296         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1297       return false;
1298     // Immediate offset, multiple of 4 in range [0, 124].
1299     if (!Memory.OffsetImm) return true;
1300     int64_t Val = Memory.OffsetImm->getValue();
1301     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1302   }
1303   bool isMemThumbRIs2() const {
1304     if (!isMem() || Memory.OffsetRegNum != 0 ||
1305         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1306       return false;
1307     // Immediate offset, multiple of 4 in range [0, 62].
1308     if (!Memory.OffsetImm) return true;
1309     int64_t Val = Memory.OffsetImm->getValue();
1310     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1311   }
1312   bool isMemThumbRIs1() const {
1313     if (!isMem() || Memory.OffsetRegNum != 0 ||
1314         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1315       return false;
1316     // Immediate offset in range [0, 31].
1317     if (!Memory.OffsetImm) return true;
1318     int64_t Val = Memory.OffsetImm->getValue();
1319     return Val >= 0 && Val <= 31;
1320   }
1321   bool isMemThumbSPI() const {
1322     if (!isMem() || Memory.OffsetRegNum != 0 ||
1323         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1324       return false;
1325     // Immediate offset, multiple of 4 in range [0, 1020].
1326     if (!Memory.OffsetImm) return true;
1327     int64_t Val = Memory.OffsetImm->getValue();
1328     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1329   }
1330   bool isMemImm8s4Offset() const {
1331     // If we have an immediate that's not a constant, treat it as a label
1332     // reference needing a fixup. If it is a constant, it's something else
1333     // and we reject it.
1334     if (isImm() && !isa<MCConstantExpr>(getImm()))
1335       return true;
1336     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1337       return false;
1338     // Immediate offset a multiple of 4 in range [-1020, 1020].
1339     if (!Memory.OffsetImm) return true;
1340     int64_t Val = Memory.OffsetImm->getValue();
1341     // Special case, #-0 is INT32_MIN.
1342     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1343   }
1344   bool isMemImm0_1020s4Offset() const {
1345     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1346       return false;
1347     // Immediate offset a multiple of 4 in range [0, 1020].
1348     if (!Memory.OffsetImm) return true;
1349     int64_t Val = Memory.OffsetImm->getValue();
1350     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1351   }
1352   bool isMemImm8Offset() const {
1353     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1354       return false;
1355     // Base reg of PC isn't allowed for these encodings.
1356     if (Memory.BaseRegNum == ARM::PC) return false;
1357     // Immediate offset in range [-255, 255].
1358     if (!Memory.OffsetImm) return true;
1359     int64_t Val = Memory.OffsetImm->getValue();
1360     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1361   }
1362   bool isMemPosImm8Offset() const {
1363     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1364       return false;
1365     // Immediate offset in range [0, 255].
1366     if (!Memory.OffsetImm) return true;
1367     int64_t Val = Memory.OffsetImm->getValue();
1368     return Val >= 0 && Val < 256;
1369   }
1370   bool isMemNegImm8Offset() const {
1371     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1372       return false;
1373     // Base reg of PC isn't allowed for these encodings.
1374     if (Memory.BaseRegNum == ARM::PC) return false;
1375     // Immediate offset in range [-255, -1].
1376     if (!Memory.OffsetImm) return false;
1377     int64_t Val = Memory.OffsetImm->getValue();
1378     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1379   }
1380   bool isMemUImm12Offset() const {
1381     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1382       return false;
1383     // Immediate offset in range [0, 4095].
1384     if (!Memory.OffsetImm) return true;
1385     int64_t Val = Memory.OffsetImm->getValue();
1386     return (Val >= 0 && Val < 4096);
1387   }
1388   bool isMemImm12Offset() const {
1389     // If we have an immediate that's not a constant, treat it as a label
1390     // reference needing a fixup. If it is a constant, it's something else
1391     // and we reject it.
1392 
1393     if (isImm() && !isa<MCConstantExpr>(getImm()))
1394       return true;
1395 
1396     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1397       return false;
1398     // Immediate offset in range [-4095, 4095].
1399     if (!Memory.OffsetImm) return true;
1400     int64_t Val = Memory.OffsetImm->getValue();
1401     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1402   }
1403   bool isConstPoolAsmImm() const {
1404     // Delay processing of Constant Pool Immediate, this will turn into
1405     // a constant. Match no other operand
1406     return (isConstantPoolImm());
1407   }
1408   bool isPostIdxImm8() const {
1409     if (!isImm()) return false;
1410     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1411     if (!CE) return false;
1412     int64_t Val = CE->getValue();
1413     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1414   }
1415   bool isPostIdxImm8s4() const {
1416     if (!isImm()) return false;
1417     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1418     if (!CE) return false;
1419     int64_t Val = CE->getValue();
1420     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1421       (Val == INT32_MIN);
1422   }
1423 
1424   bool isMSRMask() const { return Kind == k_MSRMask; }
1425   bool isBankedReg() const { return Kind == k_BankedReg; }
1426   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1427 
1428   // NEON operands.
1429   bool isSingleSpacedVectorList() const {
1430     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1431   }
1432   bool isDoubleSpacedVectorList() const {
1433     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1434   }
1435   bool isVecListOneD() const {
1436     if (!isSingleSpacedVectorList()) return false;
1437     return VectorList.Count == 1;
1438   }
1439 
1440   bool isVecListDPair() const {
1441     if (!isSingleSpacedVectorList()) return false;
1442     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1443               .contains(VectorList.RegNum));
1444   }
1445 
1446   bool isVecListThreeD() const {
1447     if (!isSingleSpacedVectorList()) return false;
1448     return VectorList.Count == 3;
1449   }
1450 
1451   bool isVecListFourD() const {
1452     if (!isSingleSpacedVectorList()) return false;
1453     return VectorList.Count == 4;
1454   }
1455 
1456   bool isVecListDPairSpaced() const {
1457     if (Kind != k_VectorList) return false;
1458     if (isSingleSpacedVectorList()) return false;
1459     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1460               .contains(VectorList.RegNum));
1461   }
1462 
1463   bool isVecListThreeQ() const {
1464     if (!isDoubleSpacedVectorList()) return false;
1465     return VectorList.Count == 3;
1466   }
1467 
1468   bool isVecListFourQ() const {
1469     if (!isDoubleSpacedVectorList()) return false;
1470     return VectorList.Count == 4;
1471   }
1472 
1473   bool isSingleSpacedVectorAllLanes() const {
1474     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1475   }
1476   bool isDoubleSpacedVectorAllLanes() const {
1477     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1478   }
1479   bool isVecListOneDAllLanes() const {
1480     if (!isSingleSpacedVectorAllLanes()) return false;
1481     return VectorList.Count == 1;
1482   }
1483 
1484   bool isVecListDPairAllLanes() const {
1485     if (!isSingleSpacedVectorAllLanes()) return false;
1486     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1487               .contains(VectorList.RegNum));
1488   }
1489 
1490   bool isVecListDPairSpacedAllLanes() const {
1491     if (!isDoubleSpacedVectorAllLanes()) return false;
1492     return VectorList.Count == 2;
1493   }
1494 
1495   bool isVecListThreeDAllLanes() const {
1496     if (!isSingleSpacedVectorAllLanes()) return false;
1497     return VectorList.Count == 3;
1498   }
1499 
1500   bool isVecListThreeQAllLanes() const {
1501     if (!isDoubleSpacedVectorAllLanes()) return false;
1502     return VectorList.Count == 3;
1503   }
1504 
1505   bool isVecListFourDAllLanes() const {
1506     if (!isSingleSpacedVectorAllLanes()) return false;
1507     return VectorList.Count == 4;
1508   }
1509 
1510   bool isVecListFourQAllLanes() const {
1511     if (!isDoubleSpacedVectorAllLanes()) return false;
1512     return VectorList.Count == 4;
1513   }
1514 
1515   bool isSingleSpacedVectorIndexed() const {
1516     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1517   }
1518   bool isDoubleSpacedVectorIndexed() const {
1519     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1520   }
1521   bool isVecListOneDByteIndexed() const {
1522     if (!isSingleSpacedVectorIndexed()) return false;
1523     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1524   }
1525 
1526   bool isVecListOneDHWordIndexed() const {
1527     if (!isSingleSpacedVectorIndexed()) return false;
1528     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1529   }
1530 
1531   bool isVecListOneDWordIndexed() const {
1532     if (!isSingleSpacedVectorIndexed()) return false;
1533     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1534   }
1535 
1536   bool isVecListTwoDByteIndexed() const {
1537     if (!isSingleSpacedVectorIndexed()) return false;
1538     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1539   }
1540 
1541   bool isVecListTwoDHWordIndexed() const {
1542     if (!isSingleSpacedVectorIndexed()) return false;
1543     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1544   }
1545 
1546   bool isVecListTwoQWordIndexed() const {
1547     if (!isDoubleSpacedVectorIndexed()) return false;
1548     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1549   }
1550 
1551   bool isVecListTwoQHWordIndexed() const {
1552     if (!isDoubleSpacedVectorIndexed()) return false;
1553     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1554   }
1555 
1556   bool isVecListTwoDWordIndexed() const {
1557     if (!isSingleSpacedVectorIndexed()) return false;
1558     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1559   }
1560 
1561   bool isVecListThreeDByteIndexed() const {
1562     if (!isSingleSpacedVectorIndexed()) return false;
1563     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1564   }
1565 
1566   bool isVecListThreeDHWordIndexed() const {
1567     if (!isSingleSpacedVectorIndexed()) return false;
1568     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1569   }
1570 
1571   bool isVecListThreeQWordIndexed() const {
1572     if (!isDoubleSpacedVectorIndexed()) return false;
1573     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1574   }
1575 
1576   bool isVecListThreeQHWordIndexed() const {
1577     if (!isDoubleSpacedVectorIndexed()) return false;
1578     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1579   }
1580 
1581   bool isVecListThreeDWordIndexed() const {
1582     if (!isSingleSpacedVectorIndexed()) return false;
1583     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1584   }
1585 
1586   bool isVecListFourDByteIndexed() const {
1587     if (!isSingleSpacedVectorIndexed()) return false;
1588     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1589   }
1590 
1591   bool isVecListFourDHWordIndexed() const {
1592     if (!isSingleSpacedVectorIndexed()) return false;
1593     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1594   }
1595 
1596   bool isVecListFourQWordIndexed() const {
1597     if (!isDoubleSpacedVectorIndexed()) return false;
1598     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1599   }
1600 
1601   bool isVecListFourQHWordIndexed() const {
1602     if (!isDoubleSpacedVectorIndexed()) return false;
1603     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1604   }
1605 
1606   bool isVecListFourDWordIndexed() const {
1607     if (!isSingleSpacedVectorIndexed()) return false;
1608     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1609   }
1610 
1611   bool isVectorIndex8() const {
1612     if (Kind != k_VectorIndex) return false;
1613     return VectorIndex.Val < 8;
1614   }
1615   bool isVectorIndex16() const {
1616     if (Kind != k_VectorIndex) return false;
1617     return VectorIndex.Val < 4;
1618   }
1619   bool isVectorIndex32() const {
1620     if (Kind != k_VectorIndex) return false;
1621     return VectorIndex.Val < 2;
1622   }
1623 
1624   bool isNEONi8splat() const {
1625     if (!isImm()) return false;
1626     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1627     // Must be a constant.
1628     if (!CE) return false;
1629     int64_t Value = CE->getValue();
1630     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1631     // value.
1632     return Value >= 0 && Value < 256;
1633   }
1634 
1635   bool isNEONi16splat() const {
1636     if (isNEONByteReplicate(2))
1637       return false; // Leave that for bytes replication and forbid by default.
1638     if (!isImm())
1639       return false;
1640     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1641     // Must be a constant.
1642     if (!CE) return false;
1643     unsigned Value = CE->getValue();
1644     return ARM_AM::isNEONi16splat(Value);
1645   }
1646 
1647   bool isNEONi16splatNot() const {
1648     if (!isImm())
1649       return false;
1650     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1651     // Must be a constant.
1652     if (!CE) return false;
1653     unsigned Value = CE->getValue();
1654     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1655   }
1656 
1657   bool isNEONi32splat() const {
1658     if (isNEONByteReplicate(4))
1659       return false; // Leave that for bytes replication and forbid by default.
1660     if (!isImm())
1661       return false;
1662     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1663     // Must be a constant.
1664     if (!CE) return false;
1665     unsigned Value = CE->getValue();
1666     return ARM_AM::isNEONi32splat(Value);
1667   }
1668 
1669   bool isNEONi32splatNot() const {
1670     if (!isImm())
1671       return false;
1672     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1673     // Must be a constant.
1674     if (!CE) return false;
1675     unsigned Value = CE->getValue();
1676     return ARM_AM::isNEONi32splat(~Value);
1677   }
1678 
1679   bool isNEONByteReplicate(unsigned NumBytes) const {
1680     if (!isImm())
1681       return false;
1682     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1683     // Must be a constant.
1684     if (!CE)
1685       return false;
1686     int64_t Value = CE->getValue();
1687     if (!Value)
1688       return false; // Don't bother with zero.
1689 
1690     unsigned char B = Value & 0xff;
1691     for (unsigned i = 1; i < NumBytes; ++i) {
1692       Value >>= 8;
1693       if ((Value & 0xff) != B)
1694         return false;
1695     }
1696     return true;
1697   }
1698   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1699   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1700   bool isNEONi32vmov() const {
1701     if (isNEONByteReplicate(4))
1702       return false; // Let it to be classified as byte-replicate case.
1703     if (!isImm())
1704       return false;
1705     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1706     // Must be a constant.
1707     if (!CE)
1708       return false;
1709     int64_t Value = CE->getValue();
1710     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1711     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1712     // FIXME: This is probably wrong and a copy and paste from previous example
1713     return (Value >= 0 && Value < 256) ||
1714       (Value >= 0x0100 && Value <= 0xff00) ||
1715       (Value >= 0x010000 && Value <= 0xff0000) ||
1716       (Value >= 0x01000000 && Value <= 0xff000000) ||
1717       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1718       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1719   }
1720   bool isNEONi32vmovNeg() const {
1721     if (!isImm()) return false;
1722     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1723     // Must be a constant.
1724     if (!CE) return false;
1725     int64_t Value = ~CE->getValue();
1726     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1727     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1728     // FIXME: This is probably wrong and a copy and paste from previous example
1729     return (Value >= 0 && Value < 256) ||
1730       (Value >= 0x0100 && Value <= 0xff00) ||
1731       (Value >= 0x010000 && Value <= 0xff0000) ||
1732       (Value >= 0x01000000 && Value <= 0xff000000) ||
1733       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1734       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1735   }
1736 
1737   bool isNEONi64splat() 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     uint64_t Value = CE->getValue();
1743     // i64 value with each byte being either 0 or 0xff.
1744     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1745       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1746     return true;
1747   }
1748 
1749   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1750     // Add as immediates when possible.  Null MCExpr = 0.
1751     if (!Expr)
1752       Inst.addOperand(MCOperand::createImm(0));
1753     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1754       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1755     else
1756       Inst.addOperand(MCOperand::createExpr(Expr));
1757   }
1758 
1759   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
1760     assert(N == 1 && "Invalid number of operands!");
1761     addExpr(Inst, getImm());
1762   }
1763 
1764   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
1765     assert(N == 1 && "Invalid number of operands!");
1766     addExpr(Inst, getImm());
1767   }
1768 
1769   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1770     assert(N == 2 && "Invalid number of operands!");
1771     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1772     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1773     Inst.addOperand(MCOperand::createReg(RegNum));
1774   }
1775 
1776   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1777     assert(N == 1 && "Invalid number of operands!");
1778     Inst.addOperand(MCOperand::createImm(getCoproc()));
1779   }
1780 
1781   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1782     assert(N == 1 && "Invalid number of operands!");
1783     Inst.addOperand(MCOperand::createImm(getCoproc()));
1784   }
1785 
1786   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1787     assert(N == 1 && "Invalid number of operands!");
1788     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1789   }
1790 
1791   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1792     assert(N == 1 && "Invalid number of operands!");
1793     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1794   }
1795 
1796   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1797     assert(N == 1 && "Invalid number of operands!");
1798     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1799   }
1800 
1801   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1802     assert(N == 1 && "Invalid number of operands!");
1803     Inst.addOperand(MCOperand::createReg(getReg()));
1804   }
1805 
1806   void addRegOperands(MCInst &Inst, unsigned N) const {
1807     assert(N == 1 && "Invalid number of operands!");
1808     Inst.addOperand(MCOperand::createReg(getReg()));
1809   }
1810 
1811   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1812     assert(N == 3 && "Invalid number of operands!");
1813     assert(isRegShiftedReg() &&
1814            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1815     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1816     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1817     Inst.addOperand(MCOperand::createImm(
1818       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1819   }
1820 
1821   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1822     assert(N == 2 && "Invalid number of operands!");
1823     assert(isRegShiftedImm() &&
1824            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1825     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1826     // Shift of #32 is encoded as 0 where permitted
1827     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1828     Inst.addOperand(MCOperand::createImm(
1829       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1830   }
1831 
1832   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1833     assert(N == 1 && "Invalid number of operands!");
1834     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1835                                          ShifterImm.Imm));
1836   }
1837 
1838   void addRegListOperands(MCInst &Inst, unsigned N) const {
1839     assert(N == 1 && "Invalid number of operands!");
1840     const SmallVectorImpl<unsigned> &RegList = getRegList();
1841     for (SmallVectorImpl<unsigned>::const_iterator
1842            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1843       Inst.addOperand(MCOperand::createReg(*I));
1844   }
1845 
1846   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1847     addRegListOperands(Inst, N);
1848   }
1849 
1850   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1851     addRegListOperands(Inst, N);
1852   }
1853 
1854   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1855     assert(N == 1 && "Invalid number of operands!");
1856     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1857     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1858   }
1859 
1860   void addModImmOperands(MCInst &Inst, unsigned N) const {
1861     assert(N == 1 && "Invalid number of operands!");
1862 
1863     // Support for fixups (MCFixup)
1864     if (isImm())
1865       return addImmOperands(Inst, N);
1866 
1867     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
1868   }
1869 
1870   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1871     assert(N == 1 && "Invalid number of operands!");
1872     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1873     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1874     Inst.addOperand(MCOperand::createImm(Enc));
1875   }
1876 
1877   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1878     assert(N == 1 && "Invalid number of operands!");
1879     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1880     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1881     Inst.addOperand(MCOperand::createImm(Enc));
1882   }
1883 
1884   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
1885     assert(N == 1 && "Invalid number of operands!");
1886     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1887     uint32_t Val = -CE->getValue();
1888     Inst.addOperand(MCOperand::createImm(Val));
1889   }
1890 
1891   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
1892     assert(N == 1 && "Invalid number of operands!");
1893     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1894     uint32_t Val = -CE->getValue();
1895     Inst.addOperand(MCOperand::createImm(Val));
1896   }
1897 
1898   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1899     assert(N == 1 && "Invalid number of operands!");
1900     // Munge the lsb/width into a bitfield mask.
1901     unsigned lsb = Bitfield.LSB;
1902     unsigned width = Bitfield.Width;
1903     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1904     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1905                       (32 - (lsb + width)));
1906     Inst.addOperand(MCOperand::createImm(Mask));
1907   }
1908 
1909   void addImmOperands(MCInst &Inst, unsigned N) const {
1910     assert(N == 1 && "Invalid number of operands!");
1911     addExpr(Inst, getImm());
1912   }
1913 
1914   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1915     assert(N == 1 && "Invalid number of operands!");
1916     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1917     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
1918   }
1919 
1920   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1921     assert(N == 1 && "Invalid number of operands!");
1922     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1923     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
1924   }
1925 
1926   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1927     assert(N == 1 && "Invalid number of operands!");
1928     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1929     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1930     Inst.addOperand(MCOperand::createImm(Val));
1931   }
1932 
1933   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1934     assert(N == 1 && "Invalid number of operands!");
1935     // FIXME: We really want to scale the value here, but the LDRD/STRD
1936     // instruction don't encode operands that way yet.
1937     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1938     Inst.addOperand(MCOperand::createImm(CE->getValue()));
1939   }
1940 
1941   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1942     assert(N == 1 && "Invalid number of operands!");
1943     // The immediate is scaled by four in the encoding and is stored
1944     // in the MCInst as such. Lop off the low two bits here.
1945     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1946     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1947   }
1948 
1949   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1950     assert(N == 1 && "Invalid number of operands!");
1951     // The immediate is scaled by four in the encoding and is stored
1952     // in the MCInst as such. Lop off the low two bits here.
1953     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1954     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
1955   }
1956 
1957   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1958     assert(N == 1 && "Invalid number of operands!");
1959     // The immediate is scaled by four in the encoding and is stored
1960     // in the MCInst as such. Lop off the low two bits here.
1961     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1962     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1963   }
1964 
1965   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1966     assert(N == 1 && "Invalid number of operands!");
1967     // The constant encodes as the immediate-1, and we store in the instruction
1968     // the bits as encoded, so subtract off one here.
1969     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1970     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1971   }
1972 
1973   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1974     assert(N == 1 && "Invalid number of operands!");
1975     // The constant encodes as the immediate-1, and we store in the instruction
1976     // the bits as encoded, so subtract off one here.
1977     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1978     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1979   }
1980 
1981   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1982     assert(N == 1 && "Invalid number of operands!");
1983     // The constant encodes as the immediate, except for 32, which encodes as
1984     // zero.
1985     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1986     unsigned Imm = CE->getValue();
1987     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
1988   }
1989 
1990   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1991     assert(N == 1 && "Invalid number of operands!");
1992     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1993     // the instruction as well.
1994     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1995     int Val = CE->getValue();
1996     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
1997   }
1998 
1999   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2000     assert(N == 1 && "Invalid number of operands!");
2001     // The operand is actually a t2_so_imm, but we have its bitwise
2002     // negation in the assembly source, so twiddle it here.
2003     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2004     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2005   }
2006 
2007   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2008     assert(N == 1 && "Invalid number of operands!");
2009     // The operand is actually a t2_so_imm, but we have its
2010     // negation in the assembly source, so twiddle it here.
2011     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2012     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2013   }
2014 
2015   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2016     assert(N == 1 && "Invalid number of operands!");
2017     // The operand is actually an imm0_4095, but we have its
2018     // negation in the assembly source, so twiddle it here.
2019     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2020     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2021   }
2022 
2023   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2024     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2025       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2026       return;
2027     }
2028 
2029     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2030     assert(SR && "Unknown value type!");
2031     Inst.addOperand(MCOperand::createExpr(SR));
2032   }
2033 
2034   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2035     assert(N == 1 && "Invalid number of operands!");
2036     if (isImm()) {
2037       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2038       if (CE) {
2039         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2040         return;
2041       }
2042 
2043       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2044 
2045       assert(SR && "Unknown value type!");
2046       Inst.addOperand(MCOperand::createExpr(SR));
2047       return;
2048     }
2049 
2050     assert(isMem()  && "Unknown value type!");
2051     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2052     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2053   }
2054 
2055   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2056     assert(N == 1 && "Invalid number of operands!");
2057     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2058   }
2059 
2060   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2061     assert(N == 1 && "Invalid number of operands!");
2062     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2063   }
2064 
2065   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2066     assert(N == 1 && "Invalid number of operands!");
2067     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2068   }
2069 
2070   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2071     assert(N == 1 && "Invalid number of operands!");
2072     int32_t Imm = Memory.OffsetImm->getValue();
2073     Inst.addOperand(MCOperand::createImm(Imm));
2074   }
2075 
2076   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2077     assert(N == 1 && "Invalid number of operands!");
2078     assert(isImm() && "Not an immediate!");
2079 
2080     // If we have an immediate that's not a constant, treat it as a label
2081     // reference needing a fixup.
2082     if (!isa<MCConstantExpr>(getImm())) {
2083       Inst.addOperand(MCOperand::createExpr(getImm()));
2084       return;
2085     }
2086 
2087     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2088     int Val = CE->getValue();
2089     Inst.addOperand(MCOperand::createImm(Val));
2090   }
2091 
2092   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2093     assert(N == 2 && "Invalid number of operands!");
2094     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2095     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2096   }
2097 
2098   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2099     addAlignedMemoryOperands(Inst, N);
2100   }
2101 
2102   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2103     addAlignedMemoryOperands(Inst, N);
2104   }
2105 
2106   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2107     addAlignedMemoryOperands(Inst, N);
2108   }
2109 
2110   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2111     addAlignedMemoryOperands(Inst, N);
2112   }
2113 
2114   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2115     addAlignedMemoryOperands(Inst, N);
2116   }
2117 
2118   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2119     addAlignedMemoryOperands(Inst, N);
2120   }
2121 
2122   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2123     addAlignedMemoryOperands(Inst, N);
2124   }
2125 
2126   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2127     addAlignedMemoryOperands(Inst, N);
2128   }
2129 
2130   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2131     addAlignedMemoryOperands(Inst, N);
2132   }
2133 
2134   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2135     addAlignedMemoryOperands(Inst, N);
2136   }
2137 
2138   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2139     addAlignedMemoryOperands(Inst, N);
2140   }
2141 
2142   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2143     assert(N == 3 && "Invalid number of operands!");
2144     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2145     if (!Memory.OffsetRegNum) {
2146       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2147       // Special case for #-0
2148       if (Val == INT32_MIN) Val = 0;
2149       if (Val < 0) Val = -Val;
2150       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2151     } else {
2152       // For register offset, we encode the shift type and negation flag
2153       // here.
2154       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2155                               Memory.ShiftImm, Memory.ShiftType);
2156     }
2157     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2158     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2159     Inst.addOperand(MCOperand::createImm(Val));
2160   }
2161 
2162   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2163     assert(N == 2 && "Invalid number of operands!");
2164     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2165     assert(CE && "non-constant AM2OffsetImm operand!");
2166     int32_t Val = CE->getValue();
2167     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2168     // Special case for #-0
2169     if (Val == INT32_MIN) Val = 0;
2170     if (Val < 0) Val = -Val;
2171     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2172     Inst.addOperand(MCOperand::createReg(0));
2173     Inst.addOperand(MCOperand::createImm(Val));
2174   }
2175 
2176   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2177     assert(N == 3 && "Invalid number of operands!");
2178     // If we have an immediate that's not a constant, treat it as a label
2179     // reference needing a fixup. If it is a constant, it's something else
2180     // and we reject it.
2181     if (isImm()) {
2182       Inst.addOperand(MCOperand::createExpr(getImm()));
2183       Inst.addOperand(MCOperand::createReg(0));
2184       Inst.addOperand(MCOperand::createImm(0));
2185       return;
2186     }
2187 
2188     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2189     if (!Memory.OffsetRegNum) {
2190       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2191       // Special case for #-0
2192       if (Val == INT32_MIN) Val = 0;
2193       if (Val < 0) Val = -Val;
2194       Val = ARM_AM::getAM3Opc(AddSub, Val);
2195     } else {
2196       // For register offset, we encode the shift type and negation flag
2197       // here.
2198       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2199     }
2200     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2201     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2202     Inst.addOperand(MCOperand::createImm(Val));
2203   }
2204 
2205   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2206     assert(N == 2 && "Invalid number of operands!");
2207     if (Kind == k_PostIndexRegister) {
2208       int32_t Val =
2209         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2210       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2211       Inst.addOperand(MCOperand::createImm(Val));
2212       return;
2213     }
2214 
2215     // Constant offset.
2216     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2217     int32_t Val = CE->getValue();
2218     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2219     // Special case for #-0
2220     if (Val == INT32_MIN) Val = 0;
2221     if (Val < 0) Val = -Val;
2222     Val = ARM_AM::getAM3Opc(AddSub, Val);
2223     Inst.addOperand(MCOperand::createReg(0));
2224     Inst.addOperand(MCOperand::createImm(Val));
2225   }
2226 
2227   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2228     assert(N == 2 && "Invalid number of operands!");
2229     // If we have an immediate that's not a constant, treat it as a label
2230     // reference needing a fixup. If it is a constant, it's something else
2231     // and we reject it.
2232     if (isImm()) {
2233       Inst.addOperand(MCOperand::createExpr(getImm()));
2234       Inst.addOperand(MCOperand::createImm(0));
2235       return;
2236     }
2237 
2238     // The lower two bits are always zero and as such are not encoded.
2239     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2240     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2241     // Special case for #-0
2242     if (Val == INT32_MIN) Val = 0;
2243     if (Val < 0) Val = -Val;
2244     Val = ARM_AM::getAM5Opc(AddSub, Val);
2245     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2246     Inst.addOperand(MCOperand::createImm(Val));
2247   }
2248 
2249   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2250     assert(N == 2 && "Invalid number of operands!");
2251     // If we have an immediate that's not a constant, treat it as a label
2252     // reference needing a fixup. If it is a constant, it's something else
2253     // and we reject it.
2254     if (isImm()) {
2255       Inst.addOperand(MCOperand::createExpr(getImm()));
2256       Inst.addOperand(MCOperand::createImm(0));
2257       return;
2258     }
2259 
2260     // The lower bit is always zero and as such is not encoded.
2261     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2262     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2263     // Special case for #-0
2264     if (Val == INT32_MIN) Val = 0;
2265     if (Val < 0) Val = -Val;
2266     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2267     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2268     Inst.addOperand(MCOperand::createImm(Val));
2269   }
2270 
2271   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2272     assert(N == 2 && "Invalid number of operands!");
2273     // If we have an immediate that's not a constant, treat it as a label
2274     // reference needing a fixup. If it is a constant, it's something else
2275     // and we reject it.
2276     if (isImm()) {
2277       Inst.addOperand(MCOperand::createExpr(getImm()));
2278       Inst.addOperand(MCOperand::createImm(0));
2279       return;
2280     }
2281 
2282     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2283     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2284     Inst.addOperand(MCOperand::createImm(Val));
2285   }
2286 
2287   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2288     assert(N == 2 && "Invalid number of operands!");
2289     // The lower two bits are always zero and as such are not encoded.
2290     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2291     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2292     Inst.addOperand(MCOperand::createImm(Val));
2293   }
2294 
2295   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2296     assert(N == 2 && "Invalid number of operands!");
2297     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2298     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2299     Inst.addOperand(MCOperand::createImm(Val));
2300   }
2301 
2302   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2303     addMemImm8OffsetOperands(Inst, N);
2304   }
2305 
2306   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2307     addMemImm8OffsetOperands(Inst, N);
2308   }
2309 
2310   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2311     assert(N == 2 && "Invalid number of operands!");
2312     // If this is an immediate, it's a label reference.
2313     if (isImm()) {
2314       addExpr(Inst, getImm());
2315       Inst.addOperand(MCOperand::createImm(0));
2316       return;
2317     }
2318 
2319     // Otherwise, it's a normal memory reg+offset.
2320     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2321     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2322     Inst.addOperand(MCOperand::createImm(Val));
2323   }
2324 
2325   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2326     assert(N == 2 && "Invalid number of operands!");
2327     // If this is an immediate, it's a label reference.
2328     if (isImm()) {
2329       addExpr(Inst, getImm());
2330       Inst.addOperand(MCOperand::createImm(0));
2331       return;
2332     }
2333 
2334     // Otherwise, it's a normal memory reg+offset.
2335     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2336     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2337     Inst.addOperand(MCOperand::createImm(Val));
2338   }
2339 
2340   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2341     assert(N == 1 && "Invalid number of operands!");
2342     // This is container for the immediate that we will create the constant
2343     // pool from
2344     addExpr(Inst, getConstantPoolImm());
2345     return;
2346   }
2347 
2348   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2349     assert(N == 2 && "Invalid number of operands!");
2350     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2351     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2352   }
2353 
2354   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2355     assert(N == 2 && "Invalid number of operands!");
2356     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2357     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2358   }
2359 
2360   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2361     assert(N == 3 && "Invalid number of operands!");
2362     unsigned Val =
2363       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2364                         Memory.ShiftImm, Memory.ShiftType);
2365     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2366     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2367     Inst.addOperand(MCOperand::createImm(Val));
2368   }
2369 
2370   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2371     assert(N == 3 && "Invalid number of operands!");
2372     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2373     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2374     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2375   }
2376 
2377   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2378     assert(N == 2 && "Invalid number of operands!");
2379     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2380     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2381   }
2382 
2383   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2384     assert(N == 2 && "Invalid number of operands!");
2385     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2386     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2387     Inst.addOperand(MCOperand::createImm(Val));
2388   }
2389 
2390   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2391     assert(N == 2 && "Invalid number of operands!");
2392     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2393     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2394     Inst.addOperand(MCOperand::createImm(Val));
2395   }
2396 
2397   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2398     assert(N == 2 && "Invalid number of operands!");
2399     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2400     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2401     Inst.addOperand(MCOperand::createImm(Val));
2402   }
2403 
2404   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2405     assert(N == 2 && "Invalid number of operands!");
2406     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2407     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2408     Inst.addOperand(MCOperand::createImm(Val));
2409   }
2410 
2411   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2412     assert(N == 1 && "Invalid number of operands!");
2413     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2414     assert(CE && "non-constant post-idx-imm8 operand!");
2415     int Imm = CE->getValue();
2416     bool isAdd = Imm >= 0;
2417     if (Imm == INT32_MIN) Imm = 0;
2418     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2419     Inst.addOperand(MCOperand::createImm(Imm));
2420   }
2421 
2422   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2423     assert(N == 1 && "Invalid number of operands!");
2424     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2425     assert(CE && "non-constant post-idx-imm8s4 operand!");
2426     int Imm = CE->getValue();
2427     bool isAdd = Imm >= 0;
2428     if (Imm == INT32_MIN) Imm = 0;
2429     // Immediate is scaled by 4.
2430     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2431     Inst.addOperand(MCOperand::createImm(Imm));
2432   }
2433 
2434   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2435     assert(N == 2 && "Invalid number of operands!");
2436     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2437     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2438   }
2439 
2440   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2441     assert(N == 2 && "Invalid number of operands!");
2442     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2443     // The sign, shift type, and shift amount are encoded in a single operand
2444     // using the AM2 encoding helpers.
2445     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2446     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2447                                      PostIdxReg.ShiftTy);
2448     Inst.addOperand(MCOperand::createImm(Imm));
2449   }
2450 
2451   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2452     assert(N == 1 && "Invalid number of operands!");
2453     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2454   }
2455 
2456   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2457     assert(N == 1 && "Invalid number of operands!");
2458     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2459   }
2460 
2461   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2462     assert(N == 1 && "Invalid number of operands!");
2463     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2464   }
2465 
2466   void addVecListOperands(MCInst &Inst, unsigned N) const {
2467     assert(N == 1 && "Invalid number of operands!");
2468     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2469   }
2470 
2471   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2472     assert(N == 2 && "Invalid number of operands!");
2473     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2474     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2475   }
2476 
2477   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2478     assert(N == 1 && "Invalid number of operands!");
2479     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2480   }
2481 
2482   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2483     assert(N == 1 && "Invalid number of operands!");
2484     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2485   }
2486 
2487   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2488     assert(N == 1 && "Invalid number of operands!");
2489     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2490   }
2491 
2492   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2493     assert(N == 1 && "Invalid number of operands!");
2494     // The immediate encodes the type of constant as well as the value.
2495     // Mask in that this is an i8 splat.
2496     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2497     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2498   }
2499 
2500   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2501     assert(N == 1 && "Invalid number of operands!");
2502     // The immediate encodes the type of constant as well as the value.
2503     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2504     unsigned Value = CE->getValue();
2505     Value = ARM_AM::encodeNEONi16splat(Value);
2506     Inst.addOperand(MCOperand::createImm(Value));
2507   }
2508 
2509   void addNEONi16splatNotOperands(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     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2513     unsigned Value = CE->getValue();
2514     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2515     Inst.addOperand(MCOperand::createImm(Value));
2516   }
2517 
2518   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2519     assert(N == 1 && "Invalid number of operands!");
2520     // The immediate encodes the type of constant as well as the value.
2521     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2522     unsigned Value = CE->getValue();
2523     Value = ARM_AM::encodeNEONi32splat(Value);
2524     Inst.addOperand(MCOperand::createImm(Value));
2525   }
2526 
2527   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2528     assert(N == 1 && "Invalid number of operands!");
2529     // The immediate encodes the type of constant as well as the value.
2530     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2531     unsigned Value = CE->getValue();
2532     Value = ARM_AM::encodeNEONi32splat(~Value);
2533     Inst.addOperand(MCOperand::createImm(Value));
2534   }
2535 
2536   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2537     assert(N == 1 && "Invalid number of operands!");
2538     // The immediate encodes the type of constant as well as the value.
2539     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2540     unsigned Value = CE->getValue();
2541     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2542             Inst.getOpcode() == ARM::VMOVv16i8) &&
2543            "All vmvn instructions that wants to replicate non-zero byte "
2544            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2545     unsigned B = ((~Value) & 0xff);
2546     B |= 0xe00; // cmode = 0b1110
2547     Inst.addOperand(MCOperand::createImm(B));
2548   }
2549   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2550     assert(N == 1 && "Invalid number of operands!");
2551     // The immediate encodes the type of constant as well as the value.
2552     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2553     unsigned Value = CE->getValue();
2554     if (Value >= 256 && Value <= 0xffff)
2555       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2556     else if (Value > 0xffff && Value <= 0xffffff)
2557       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2558     else if (Value > 0xffffff)
2559       Value = (Value >> 24) | 0x600;
2560     Inst.addOperand(MCOperand::createImm(Value));
2561   }
2562 
2563   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2564     assert(N == 1 && "Invalid number of operands!");
2565     // The immediate encodes the type of constant as well as the value.
2566     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2567     unsigned Value = CE->getValue();
2568     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2569             Inst.getOpcode() == ARM::VMOVv16i8) &&
2570            "All instructions that wants to replicate non-zero byte "
2571            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2572     unsigned B = Value & 0xff;
2573     B |= 0xe00; // cmode = 0b1110
2574     Inst.addOperand(MCOperand::createImm(B));
2575   }
2576   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2577     assert(N == 1 && "Invalid number of operands!");
2578     // The immediate encodes the type of constant as well as the value.
2579     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2580     unsigned Value = ~CE->getValue();
2581     if (Value >= 256 && Value <= 0xffff)
2582       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2583     else if (Value > 0xffff && Value <= 0xffffff)
2584       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2585     else if (Value > 0xffffff)
2586       Value = (Value >> 24) | 0x600;
2587     Inst.addOperand(MCOperand::createImm(Value));
2588   }
2589 
2590   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2591     assert(N == 1 && "Invalid number of operands!");
2592     // The immediate encodes the type of constant as well as the value.
2593     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2594     uint64_t Value = CE->getValue();
2595     unsigned Imm = 0;
2596     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2597       Imm |= (Value & 1) << i;
2598     }
2599     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2600   }
2601 
2602   void print(raw_ostream &OS) const override;
2603 
2604   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2605     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2606     Op->ITMask.Mask = Mask;
2607     Op->StartLoc = S;
2608     Op->EndLoc = S;
2609     return Op;
2610   }
2611 
2612   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2613                                                     SMLoc S) {
2614     auto Op = make_unique<ARMOperand>(k_CondCode);
2615     Op->CC.Val = CC;
2616     Op->StartLoc = S;
2617     Op->EndLoc = S;
2618     return Op;
2619   }
2620 
2621   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2622     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2623     Op->Cop.Val = CopVal;
2624     Op->StartLoc = S;
2625     Op->EndLoc = S;
2626     return Op;
2627   }
2628 
2629   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2630     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2631     Op->Cop.Val = CopVal;
2632     Op->StartLoc = S;
2633     Op->EndLoc = S;
2634     return Op;
2635   }
2636 
2637   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2638                                                         SMLoc E) {
2639     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2640     Op->Cop.Val = Val;
2641     Op->StartLoc = S;
2642     Op->EndLoc = E;
2643     return Op;
2644   }
2645 
2646   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2647     auto Op = make_unique<ARMOperand>(k_CCOut);
2648     Op->Reg.RegNum = RegNum;
2649     Op->StartLoc = S;
2650     Op->EndLoc = S;
2651     return Op;
2652   }
2653 
2654   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2655     auto Op = make_unique<ARMOperand>(k_Token);
2656     Op->Tok.Data = Str.data();
2657     Op->Tok.Length = Str.size();
2658     Op->StartLoc = S;
2659     Op->EndLoc = S;
2660     return Op;
2661   }
2662 
2663   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2664                                                SMLoc E) {
2665     auto Op = make_unique<ARMOperand>(k_Register);
2666     Op->Reg.RegNum = RegNum;
2667     Op->StartLoc = S;
2668     Op->EndLoc = E;
2669     return Op;
2670   }
2671 
2672   static std::unique_ptr<ARMOperand>
2673   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2674                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2675                         SMLoc E) {
2676     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2677     Op->RegShiftedReg.ShiftTy = ShTy;
2678     Op->RegShiftedReg.SrcReg = SrcReg;
2679     Op->RegShiftedReg.ShiftReg = ShiftReg;
2680     Op->RegShiftedReg.ShiftImm = ShiftImm;
2681     Op->StartLoc = S;
2682     Op->EndLoc = E;
2683     return Op;
2684   }
2685 
2686   static std::unique_ptr<ARMOperand>
2687   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2688                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2689     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2690     Op->RegShiftedImm.ShiftTy = ShTy;
2691     Op->RegShiftedImm.SrcReg = SrcReg;
2692     Op->RegShiftedImm.ShiftImm = ShiftImm;
2693     Op->StartLoc = S;
2694     Op->EndLoc = E;
2695     return Op;
2696   }
2697 
2698   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2699                                                       SMLoc S, SMLoc E) {
2700     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2701     Op->ShifterImm.isASR = isASR;
2702     Op->ShifterImm.Imm = Imm;
2703     Op->StartLoc = S;
2704     Op->EndLoc = E;
2705     return Op;
2706   }
2707 
2708   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2709                                                   SMLoc E) {
2710     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2711     Op->RotImm.Imm = Imm;
2712     Op->StartLoc = S;
2713     Op->EndLoc = E;
2714     return Op;
2715   }
2716 
2717   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2718                                                   SMLoc S, SMLoc E) {
2719     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2720     Op->ModImm.Bits = Bits;
2721     Op->ModImm.Rot = Rot;
2722     Op->StartLoc = S;
2723     Op->EndLoc = E;
2724     return Op;
2725   }
2726 
2727   static std::unique_ptr<ARMOperand>
2728   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2729     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
2730     Op->Imm.Val = Val;
2731     Op->StartLoc = S;
2732     Op->EndLoc = E;
2733     return Op;
2734   }
2735 
2736   static std::unique_ptr<ARMOperand>
2737   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2738     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2739     Op->Bitfield.LSB = LSB;
2740     Op->Bitfield.Width = Width;
2741     Op->StartLoc = S;
2742     Op->EndLoc = E;
2743     return Op;
2744   }
2745 
2746   static std::unique_ptr<ARMOperand>
2747   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2748                 SMLoc StartLoc, SMLoc EndLoc) {
2749     assert (Regs.size() > 0 && "RegList contains no registers?");
2750     KindTy Kind = k_RegisterList;
2751 
2752     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2753       Kind = k_DPRRegisterList;
2754     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2755              contains(Regs.front().second))
2756       Kind = k_SPRRegisterList;
2757 
2758     // Sort based on the register encoding values.
2759     array_pod_sort(Regs.begin(), Regs.end());
2760 
2761     auto Op = make_unique<ARMOperand>(Kind);
2762     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2763            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2764       Op->Registers.push_back(I->second);
2765     Op->StartLoc = StartLoc;
2766     Op->EndLoc = EndLoc;
2767     return Op;
2768   }
2769 
2770   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2771                                                       unsigned Count,
2772                                                       bool isDoubleSpaced,
2773                                                       SMLoc S, SMLoc E) {
2774     auto Op = make_unique<ARMOperand>(k_VectorList);
2775     Op->VectorList.RegNum = RegNum;
2776     Op->VectorList.Count = Count;
2777     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2778     Op->StartLoc = S;
2779     Op->EndLoc = E;
2780     return Op;
2781   }
2782 
2783   static std::unique_ptr<ARMOperand>
2784   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2785                            SMLoc S, SMLoc E) {
2786     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2787     Op->VectorList.RegNum = RegNum;
2788     Op->VectorList.Count = Count;
2789     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2790     Op->StartLoc = S;
2791     Op->EndLoc = E;
2792     return Op;
2793   }
2794 
2795   static std::unique_ptr<ARMOperand>
2796   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2797                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2798     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2799     Op->VectorList.RegNum = RegNum;
2800     Op->VectorList.Count = Count;
2801     Op->VectorList.LaneIndex = Index;
2802     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2803     Op->StartLoc = S;
2804     Op->EndLoc = E;
2805     return Op;
2806   }
2807 
2808   static std::unique_ptr<ARMOperand>
2809   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2810     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2811     Op->VectorIndex.Val = Idx;
2812     Op->StartLoc = S;
2813     Op->EndLoc = E;
2814     return Op;
2815   }
2816 
2817   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2818                                                SMLoc E) {
2819     auto Op = make_unique<ARMOperand>(k_Immediate);
2820     Op->Imm.Val = Val;
2821     Op->StartLoc = S;
2822     Op->EndLoc = E;
2823     return Op;
2824   }
2825 
2826   static std::unique_ptr<ARMOperand>
2827   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2828             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2829             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2830             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2831     auto Op = make_unique<ARMOperand>(k_Memory);
2832     Op->Memory.BaseRegNum = BaseRegNum;
2833     Op->Memory.OffsetImm = OffsetImm;
2834     Op->Memory.OffsetRegNum = OffsetRegNum;
2835     Op->Memory.ShiftType = ShiftType;
2836     Op->Memory.ShiftImm = ShiftImm;
2837     Op->Memory.Alignment = Alignment;
2838     Op->Memory.isNegative = isNegative;
2839     Op->StartLoc = S;
2840     Op->EndLoc = E;
2841     Op->AlignmentLoc = AlignmentLoc;
2842     return Op;
2843   }
2844 
2845   static std::unique_ptr<ARMOperand>
2846   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2847                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2848     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2849     Op->PostIdxReg.RegNum = RegNum;
2850     Op->PostIdxReg.isAdd = isAdd;
2851     Op->PostIdxReg.ShiftTy = ShiftTy;
2852     Op->PostIdxReg.ShiftImm = ShiftImm;
2853     Op->StartLoc = S;
2854     Op->EndLoc = E;
2855     return Op;
2856   }
2857 
2858   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2859                                                          SMLoc S) {
2860     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2861     Op->MBOpt.Val = Opt;
2862     Op->StartLoc = S;
2863     Op->EndLoc = S;
2864     return Op;
2865   }
2866 
2867   static std::unique_ptr<ARMOperand>
2868   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2869     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2870     Op->ISBOpt.Val = Opt;
2871     Op->StartLoc = S;
2872     Op->EndLoc = S;
2873     return Op;
2874   }
2875 
2876   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2877                                                       SMLoc S) {
2878     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2879     Op->IFlags.Val = IFlags;
2880     Op->StartLoc = S;
2881     Op->EndLoc = S;
2882     return Op;
2883   }
2884 
2885   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2886     auto Op = make_unique<ARMOperand>(k_MSRMask);
2887     Op->MMask.Val = MMask;
2888     Op->StartLoc = S;
2889     Op->EndLoc = S;
2890     return Op;
2891   }
2892 
2893   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2894     auto Op = make_unique<ARMOperand>(k_BankedReg);
2895     Op->BankedReg.Val = Reg;
2896     Op->StartLoc = S;
2897     Op->EndLoc = S;
2898     return Op;
2899   }
2900 };
2901 
2902 } // end anonymous namespace.
2903 
2904 void ARMOperand::print(raw_ostream &OS) const {
2905   switch (Kind) {
2906   case k_CondCode:
2907     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2908     break;
2909   case k_CCOut:
2910     OS << "<ccout " << getReg() << ">";
2911     break;
2912   case k_ITCondMask: {
2913     static const char *const MaskStr[] = {
2914       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2915       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2916     };
2917     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2918     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2919     break;
2920   }
2921   case k_CoprocNum:
2922     OS << "<coprocessor number: " << getCoproc() << ">";
2923     break;
2924   case k_CoprocReg:
2925     OS << "<coprocessor register: " << getCoproc() << ">";
2926     break;
2927   case k_CoprocOption:
2928     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2929     break;
2930   case k_MSRMask:
2931     OS << "<mask: " << getMSRMask() << ">";
2932     break;
2933   case k_BankedReg:
2934     OS << "<banked reg: " << getBankedReg() << ">";
2935     break;
2936   case k_Immediate:
2937     OS << *getImm();
2938     break;
2939   case k_MemBarrierOpt:
2940     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2941     break;
2942   case k_InstSyncBarrierOpt:
2943     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2944     break;
2945   case k_Memory:
2946     OS << "<memory "
2947        << " base:" << Memory.BaseRegNum;
2948     OS << ">";
2949     break;
2950   case k_PostIndexRegister:
2951     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2952        << PostIdxReg.RegNum;
2953     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2954       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2955          << PostIdxReg.ShiftImm;
2956     OS << ">";
2957     break;
2958   case k_ProcIFlags: {
2959     OS << "<ARM_PROC::";
2960     unsigned IFlags = getProcIFlags();
2961     for (int i=2; i >= 0; --i)
2962       if (IFlags & (1 << i))
2963         OS << ARM_PROC::IFlagsToString(1 << i);
2964     OS << ">";
2965     break;
2966   }
2967   case k_Register:
2968     OS << "<register " << getReg() << ">";
2969     break;
2970   case k_ShifterImmediate:
2971     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2972        << " #" << ShifterImm.Imm << ">";
2973     break;
2974   case k_ShiftedRegister:
2975     OS << "<so_reg_reg "
2976        << RegShiftedReg.SrcReg << " "
2977        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2978        << " " << RegShiftedReg.ShiftReg << ">";
2979     break;
2980   case k_ShiftedImmediate:
2981     OS << "<so_reg_imm "
2982        << RegShiftedImm.SrcReg << " "
2983        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2984        << " #" << RegShiftedImm.ShiftImm << ">";
2985     break;
2986   case k_RotateImmediate:
2987     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2988     break;
2989   case k_ModifiedImmediate:
2990     OS << "<mod_imm #" << ModImm.Bits << ", #"
2991        <<  ModImm.Rot << ")>";
2992     break;
2993   case k_ConstantPoolImmediate:
2994     OS << "<constant_pool_imm #" << *getConstantPoolImm();
2995     break;
2996   case k_BitfieldDescriptor:
2997     OS << "<bitfield " << "lsb: " << Bitfield.LSB
2998        << ", width: " << Bitfield.Width << ">";
2999     break;
3000   case k_RegisterList:
3001   case k_DPRRegisterList:
3002   case k_SPRRegisterList: {
3003     OS << "<register_list ";
3004 
3005     const SmallVectorImpl<unsigned> &RegList = getRegList();
3006     for (SmallVectorImpl<unsigned>::const_iterator
3007            I = RegList.begin(), E = RegList.end(); I != E; ) {
3008       OS << *I;
3009       if (++I < E) OS << ", ";
3010     }
3011 
3012     OS << ">";
3013     break;
3014   }
3015   case k_VectorList:
3016     OS << "<vector_list " << VectorList.Count << " * "
3017        << VectorList.RegNum << ">";
3018     break;
3019   case k_VectorListAllLanes:
3020     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3021        << VectorList.RegNum << ">";
3022     break;
3023   case k_VectorListIndexed:
3024     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3025        << VectorList.Count << " * " << VectorList.RegNum << ">";
3026     break;
3027   case k_Token:
3028     OS << "'" << getToken() << "'";
3029     break;
3030   case k_VectorIndex:
3031     OS << "<vectorindex " << getVectorIndex() << ">";
3032     break;
3033   }
3034 }
3035 
3036 /// @name Auto-generated Match Functions
3037 /// {
3038 
3039 static unsigned MatchRegisterName(StringRef Name);
3040 
3041 /// }
3042 
3043 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3044                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3045   const AsmToken &Tok = getParser().getTok();
3046   StartLoc = Tok.getLoc();
3047   EndLoc = Tok.getEndLoc();
3048   RegNo = tryParseRegister();
3049 
3050   return (RegNo == (unsigned)-1);
3051 }
3052 
3053 /// Try to parse a register name.  The token must be an Identifier when called,
3054 /// and if it is a register name the token is eaten and the register number is
3055 /// returned.  Otherwise return -1.
3056 ///
3057 int ARMAsmParser::tryParseRegister() {
3058   MCAsmParser &Parser = getParser();
3059   const AsmToken &Tok = Parser.getTok();
3060   if (Tok.isNot(AsmToken::Identifier)) return -1;
3061 
3062   std::string lowerCase = Tok.getString().lower();
3063   unsigned RegNum = MatchRegisterName(lowerCase);
3064   if (!RegNum) {
3065     RegNum = StringSwitch<unsigned>(lowerCase)
3066       .Case("r13", ARM::SP)
3067       .Case("r14", ARM::LR)
3068       .Case("r15", ARM::PC)
3069       .Case("ip", ARM::R12)
3070       // Additional register name aliases for 'gas' compatibility.
3071       .Case("a1", ARM::R0)
3072       .Case("a2", ARM::R1)
3073       .Case("a3", ARM::R2)
3074       .Case("a4", ARM::R3)
3075       .Case("v1", ARM::R4)
3076       .Case("v2", ARM::R5)
3077       .Case("v3", ARM::R6)
3078       .Case("v4", ARM::R7)
3079       .Case("v5", ARM::R8)
3080       .Case("v6", ARM::R9)
3081       .Case("v7", ARM::R10)
3082       .Case("v8", ARM::R11)
3083       .Case("sb", ARM::R9)
3084       .Case("sl", ARM::R10)
3085       .Case("fp", ARM::R11)
3086       .Default(0);
3087   }
3088   if (!RegNum) {
3089     // Check for aliases registered via .req. Canonicalize to lower case.
3090     // That's more consistent since register names are case insensitive, and
3091     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3092     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3093     // If no match, return failure.
3094     if (Entry == RegisterReqs.end())
3095       return -1;
3096     Parser.Lex(); // Eat identifier token.
3097     return Entry->getValue();
3098   }
3099 
3100   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3101   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3102     return -1;
3103 
3104   Parser.Lex(); // Eat identifier token.
3105 
3106   return RegNum;
3107 }
3108 
3109 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3110 // If a recoverable error occurs, return 1. If an irrecoverable error
3111 // occurs, return -1. An irrecoverable error is one where tokens have been
3112 // consumed in the process of trying to parse the shifter (i.e., when it is
3113 // indeed a shifter operand, but malformed).
3114 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3115   MCAsmParser &Parser = getParser();
3116   SMLoc S = Parser.getTok().getLoc();
3117   const AsmToken &Tok = Parser.getTok();
3118   if (Tok.isNot(AsmToken::Identifier))
3119     return -1;
3120 
3121   std::string lowerCase = Tok.getString().lower();
3122   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3123       .Case("asl", ARM_AM::lsl)
3124       .Case("lsl", ARM_AM::lsl)
3125       .Case("lsr", ARM_AM::lsr)
3126       .Case("asr", ARM_AM::asr)
3127       .Case("ror", ARM_AM::ror)
3128       .Case("rrx", ARM_AM::rrx)
3129       .Default(ARM_AM::no_shift);
3130 
3131   if (ShiftTy == ARM_AM::no_shift)
3132     return 1;
3133 
3134   Parser.Lex(); // Eat the operator.
3135 
3136   // The source register for the shift has already been added to the
3137   // operand list, so we need to pop it off and combine it into the shifted
3138   // register operand instead.
3139   std::unique_ptr<ARMOperand> PrevOp(
3140       (ARMOperand *)Operands.pop_back_val().release());
3141   if (!PrevOp->isReg())
3142     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3143   int SrcReg = PrevOp->getReg();
3144 
3145   SMLoc EndLoc;
3146   int64_t Imm = 0;
3147   int ShiftReg = 0;
3148   if (ShiftTy == ARM_AM::rrx) {
3149     // RRX Doesn't have an explicit shift amount. The encoder expects
3150     // the shift register to be the same as the source register. Seems odd,
3151     // but OK.
3152     ShiftReg = SrcReg;
3153   } else {
3154     // Figure out if this is shifted by a constant or a register (for non-RRX).
3155     if (Parser.getTok().is(AsmToken::Hash) ||
3156         Parser.getTok().is(AsmToken::Dollar)) {
3157       Parser.Lex(); // Eat hash.
3158       SMLoc ImmLoc = Parser.getTok().getLoc();
3159       const MCExpr *ShiftExpr = nullptr;
3160       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3161         Error(ImmLoc, "invalid immediate shift value");
3162         return -1;
3163       }
3164       // The expression must be evaluatable as an immediate.
3165       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3166       if (!CE) {
3167         Error(ImmLoc, "invalid immediate shift value");
3168         return -1;
3169       }
3170       // Range check the immediate.
3171       // lsl, ror: 0 <= imm <= 31
3172       // lsr, asr: 0 <= imm <= 32
3173       Imm = CE->getValue();
3174       if (Imm < 0 ||
3175           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3176           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3177         Error(ImmLoc, "immediate shift value out of range");
3178         return -1;
3179       }
3180       // shift by zero is a nop. Always send it through as lsl.
3181       // ('as' compatibility)
3182       if (Imm == 0)
3183         ShiftTy = ARM_AM::lsl;
3184     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3185       SMLoc L = Parser.getTok().getLoc();
3186       EndLoc = Parser.getTok().getEndLoc();
3187       ShiftReg = tryParseRegister();
3188       if (ShiftReg == -1) {
3189         Error(L, "expected immediate or register in shift operand");
3190         return -1;
3191       }
3192     } else {
3193       Error(Parser.getTok().getLoc(),
3194             "expected immediate or register in shift operand");
3195       return -1;
3196     }
3197   }
3198 
3199   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3200     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3201                                                          ShiftReg, Imm,
3202                                                          S, EndLoc));
3203   else
3204     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3205                                                           S, EndLoc));
3206 
3207   return 0;
3208 }
3209 
3210 
3211 /// Try to parse a register name.  The token must be an Identifier when called.
3212 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3213 /// if there is a "writeback". 'true' if it's not a register.
3214 ///
3215 /// TODO this is likely to change to allow different register types and or to
3216 /// parse for a specific register type.
3217 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3218   MCAsmParser &Parser = getParser();
3219   const AsmToken &RegTok = Parser.getTok();
3220   int RegNo = tryParseRegister();
3221   if (RegNo == -1)
3222     return true;
3223 
3224   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3225                                            RegTok.getEndLoc()));
3226 
3227   const AsmToken &ExclaimTok = Parser.getTok();
3228   if (ExclaimTok.is(AsmToken::Exclaim)) {
3229     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3230                                                ExclaimTok.getLoc()));
3231     Parser.Lex(); // Eat exclaim token
3232     return false;
3233   }
3234 
3235   // Also check for an index operand. This is only legal for vector registers,
3236   // but that'll get caught OK in operand matching, so we don't need to
3237   // explicitly filter everything else out here.
3238   if (Parser.getTok().is(AsmToken::LBrac)) {
3239     SMLoc SIdx = Parser.getTok().getLoc();
3240     Parser.Lex(); // Eat left bracket token.
3241 
3242     const MCExpr *ImmVal;
3243     if (getParser().parseExpression(ImmVal))
3244       return true;
3245     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3246     if (!MCE)
3247       return TokError("immediate value expected for vector index");
3248 
3249     if (Parser.getTok().isNot(AsmToken::RBrac))
3250       return Error(Parser.getTok().getLoc(), "']' expected");
3251 
3252     SMLoc E = Parser.getTok().getEndLoc();
3253     Parser.Lex(); // Eat right bracket token.
3254 
3255     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3256                                                      SIdx, E,
3257                                                      getContext()));
3258   }
3259 
3260   return false;
3261 }
3262 
3263 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3264 /// instruction with a symbolic operand name.
3265 /// We accept "crN" syntax for GAS compatibility.
3266 /// <operand-name> ::= <prefix><number>
3267 /// If CoprocOp is 'c', then:
3268 ///   <prefix> ::= c | cr
3269 /// If CoprocOp is 'p', then :
3270 ///   <prefix> ::= p
3271 /// <number> ::= integer in range [0, 15]
3272 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3273   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3274   // but efficient.
3275   if (Name.size() < 2 || Name[0] != CoprocOp)
3276     return -1;
3277   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3278 
3279   switch (Name.size()) {
3280   default: return -1;
3281   case 1:
3282     switch (Name[0]) {
3283     default:  return -1;
3284     case '0': return 0;
3285     case '1': return 1;
3286     case '2': return 2;
3287     case '3': return 3;
3288     case '4': return 4;
3289     case '5': return 5;
3290     case '6': return 6;
3291     case '7': return 7;
3292     case '8': return 8;
3293     case '9': return 9;
3294     }
3295   case 2:
3296     if (Name[0] != '1')
3297       return -1;
3298     switch (Name[1]) {
3299     default:  return -1;
3300     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3301     // However, old cores (v5/v6) did use them in that way.
3302     case '0': return 10;
3303     case '1': return 11;
3304     case '2': return 12;
3305     case '3': return 13;
3306     case '4': return 14;
3307     case '5': return 15;
3308     }
3309   }
3310 }
3311 
3312 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3313 OperandMatchResultTy
3314 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3315   MCAsmParser &Parser = getParser();
3316   SMLoc S = Parser.getTok().getLoc();
3317   const AsmToken &Tok = Parser.getTok();
3318   if (!Tok.is(AsmToken::Identifier))
3319     return MatchOperand_NoMatch;
3320   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3321     .Case("eq", ARMCC::EQ)
3322     .Case("ne", ARMCC::NE)
3323     .Case("hs", ARMCC::HS)
3324     .Case("cs", ARMCC::HS)
3325     .Case("lo", ARMCC::LO)
3326     .Case("cc", ARMCC::LO)
3327     .Case("mi", ARMCC::MI)
3328     .Case("pl", ARMCC::PL)
3329     .Case("vs", ARMCC::VS)
3330     .Case("vc", ARMCC::VC)
3331     .Case("hi", ARMCC::HI)
3332     .Case("ls", ARMCC::LS)
3333     .Case("ge", ARMCC::GE)
3334     .Case("lt", ARMCC::LT)
3335     .Case("gt", ARMCC::GT)
3336     .Case("le", ARMCC::LE)
3337     .Case("al", ARMCC::AL)
3338     .Default(~0U);
3339   if (CC == ~0U)
3340     return MatchOperand_NoMatch;
3341   Parser.Lex(); // Eat the token.
3342 
3343   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3344 
3345   return MatchOperand_Success;
3346 }
3347 
3348 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3349 /// token must be an Identifier when called, and if it is a coprocessor
3350 /// number, the token is eaten and the operand is added to the operand list.
3351 OperandMatchResultTy
3352 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3353   MCAsmParser &Parser = getParser();
3354   SMLoc S = Parser.getTok().getLoc();
3355   const AsmToken &Tok = Parser.getTok();
3356   if (Tok.isNot(AsmToken::Identifier))
3357     return MatchOperand_NoMatch;
3358 
3359   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3360   if (Num == -1)
3361     return MatchOperand_NoMatch;
3362   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3363   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3364     return MatchOperand_NoMatch;
3365 
3366   Parser.Lex(); // Eat identifier token.
3367   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3368   return MatchOperand_Success;
3369 }
3370 
3371 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3372 /// token must be an Identifier when called, and if it is a coprocessor
3373 /// number, the token is eaten and the operand is added to the operand list.
3374 OperandMatchResultTy
3375 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3376   MCAsmParser &Parser = getParser();
3377   SMLoc S = Parser.getTok().getLoc();
3378   const AsmToken &Tok = Parser.getTok();
3379   if (Tok.isNot(AsmToken::Identifier))
3380     return MatchOperand_NoMatch;
3381 
3382   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3383   if (Reg == -1)
3384     return MatchOperand_NoMatch;
3385 
3386   Parser.Lex(); // Eat identifier token.
3387   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3388   return MatchOperand_Success;
3389 }
3390 
3391 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3392 /// coproc_option : '{' imm0_255 '}'
3393 OperandMatchResultTy
3394 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3395   MCAsmParser &Parser = getParser();
3396   SMLoc S = Parser.getTok().getLoc();
3397 
3398   // If this isn't a '{', this isn't a coprocessor immediate operand.
3399   if (Parser.getTok().isNot(AsmToken::LCurly))
3400     return MatchOperand_NoMatch;
3401   Parser.Lex(); // Eat the '{'
3402 
3403   const MCExpr *Expr;
3404   SMLoc Loc = Parser.getTok().getLoc();
3405   if (getParser().parseExpression(Expr)) {
3406     Error(Loc, "illegal expression");
3407     return MatchOperand_ParseFail;
3408   }
3409   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3410   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3411     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3412     return MatchOperand_ParseFail;
3413   }
3414   int Val = CE->getValue();
3415 
3416   // Check for and consume the closing '}'
3417   if (Parser.getTok().isNot(AsmToken::RCurly))
3418     return MatchOperand_ParseFail;
3419   SMLoc E = Parser.getTok().getEndLoc();
3420   Parser.Lex(); // Eat the '}'
3421 
3422   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3423   return MatchOperand_Success;
3424 }
3425 
3426 // For register list parsing, we need to map from raw GPR register numbering
3427 // to the enumeration values. The enumeration values aren't sorted by
3428 // register number due to our using "sp", "lr" and "pc" as canonical names.
3429 static unsigned getNextRegister(unsigned Reg) {
3430   // If this is a GPR, we need to do it manually, otherwise we can rely
3431   // on the sort ordering of the enumeration since the other reg-classes
3432   // are sane.
3433   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3434     return Reg + 1;
3435   switch(Reg) {
3436   default: llvm_unreachable("Invalid GPR number!");
3437   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3438   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3439   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3440   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3441   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3442   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3443   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3444   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3445   }
3446 }
3447 
3448 // Return the low-subreg of a given Q register.
3449 static unsigned getDRegFromQReg(unsigned QReg) {
3450   switch (QReg) {
3451   default: llvm_unreachable("expected a Q register!");
3452   case ARM::Q0:  return ARM::D0;
3453   case ARM::Q1:  return ARM::D2;
3454   case ARM::Q2:  return ARM::D4;
3455   case ARM::Q3:  return ARM::D6;
3456   case ARM::Q4:  return ARM::D8;
3457   case ARM::Q5:  return ARM::D10;
3458   case ARM::Q6:  return ARM::D12;
3459   case ARM::Q7:  return ARM::D14;
3460   case ARM::Q8:  return ARM::D16;
3461   case ARM::Q9:  return ARM::D18;
3462   case ARM::Q10: return ARM::D20;
3463   case ARM::Q11: return ARM::D22;
3464   case ARM::Q12: return ARM::D24;
3465   case ARM::Q13: return ARM::D26;
3466   case ARM::Q14: return ARM::D28;
3467   case ARM::Q15: return ARM::D30;
3468   }
3469 }
3470 
3471 /// Parse a register list.
3472 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3473   MCAsmParser &Parser = getParser();
3474   if (Parser.getTok().isNot(AsmToken::LCurly))
3475     return TokError("Token is not a Left Curly Brace");
3476   SMLoc S = Parser.getTok().getLoc();
3477   Parser.Lex(); // Eat '{' token.
3478   SMLoc RegLoc = Parser.getTok().getLoc();
3479 
3480   // Check the first register in the list to see what register class
3481   // this is a list of.
3482   int Reg = tryParseRegister();
3483   if (Reg == -1)
3484     return Error(RegLoc, "register expected");
3485 
3486   // The reglist instructions have at most 16 registers, so reserve
3487   // space for that many.
3488   int EReg = 0;
3489   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3490 
3491   // Allow Q regs and just interpret them as the two D sub-registers.
3492   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3493     Reg = getDRegFromQReg(Reg);
3494     EReg = MRI->getEncodingValue(Reg);
3495     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3496     ++Reg;
3497   }
3498   const MCRegisterClass *RC;
3499   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3500     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3501   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3502     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3503   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3504     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3505   else
3506     return Error(RegLoc, "invalid register in register list");
3507 
3508   // Store the register.
3509   EReg = MRI->getEncodingValue(Reg);
3510   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3511 
3512   // This starts immediately after the first register token in the list,
3513   // so we can see either a comma or a minus (range separator) as a legal
3514   // next token.
3515   while (Parser.getTok().is(AsmToken::Comma) ||
3516          Parser.getTok().is(AsmToken::Minus)) {
3517     if (Parser.getTok().is(AsmToken::Minus)) {
3518       Parser.Lex(); // Eat the minus.
3519       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3520       int EndReg = tryParseRegister();
3521       if (EndReg == -1)
3522         return Error(AfterMinusLoc, "register expected");
3523       // Allow Q regs and just interpret them as the two D sub-registers.
3524       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3525         EndReg = getDRegFromQReg(EndReg) + 1;
3526       // If the register is the same as the start reg, there's nothing
3527       // more to do.
3528       if (Reg == EndReg)
3529         continue;
3530       // The register must be in the same register class as the first.
3531       if (!RC->contains(EndReg))
3532         return Error(AfterMinusLoc, "invalid register in register list");
3533       // Ranges must go from low to high.
3534       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3535         return Error(AfterMinusLoc, "bad range in register list");
3536 
3537       // Add all the registers in the range to the register list.
3538       while (Reg != EndReg) {
3539         Reg = getNextRegister(Reg);
3540         EReg = MRI->getEncodingValue(Reg);
3541         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3542       }
3543       continue;
3544     }
3545     Parser.Lex(); // Eat the comma.
3546     RegLoc = Parser.getTok().getLoc();
3547     int OldReg = Reg;
3548     const AsmToken RegTok = Parser.getTok();
3549     Reg = tryParseRegister();
3550     if (Reg == -1)
3551       return Error(RegLoc, "register expected");
3552     // Allow Q regs and just interpret them as the two D sub-registers.
3553     bool isQReg = false;
3554     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3555       Reg = getDRegFromQReg(Reg);
3556       isQReg = true;
3557     }
3558     // The register must be in the same register class as the first.
3559     if (!RC->contains(Reg))
3560       return Error(RegLoc, "invalid register in register list");
3561     // List must be monotonically increasing.
3562     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3563       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3564         Warning(RegLoc, "register list not in ascending order");
3565       else
3566         return Error(RegLoc, "register list not in ascending order");
3567     }
3568     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3569       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3570               ") in register list");
3571       continue;
3572     }
3573     // VFP register lists must also be contiguous.
3574     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3575         Reg != OldReg + 1)
3576       return Error(RegLoc, "non-contiguous register range");
3577     EReg = MRI->getEncodingValue(Reg);
3578     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3579     if (isQReg) {
3580       EReg = MRI->getEncodingValue(++Reg);
3581       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3582     }
3583   }
3584 
3585   if (Parser.getTok().isNot(AsmToken::RCurly))
3586     return Error(Parser.getTok().getLoc(), "'}' expected");
3587   SMLoc E = Parser.getTok().getEndLoc();
3588   Parser.Lex(); // Eat '}' token.
3589 
3590   // Push the register list operand.
3591   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3592 
3593   // The ARM system instruction variants for LDM/STM have a '^' token here.
3594   if (Parser.getTok().is(AsmToken::Caret)) {
3595     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3596     Parser.Lex(); // Eat '^' token.
3597   }
3598 
3599   return false;
3600 }
3601 
3602 // Helper function to parse the lane index for vector lists.
3603 OperandMatchResultTy ARMAsmParser::
3604 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3605   MCAsmParser &Parser = getParser();
3606   Index = 0; // Always return a defined index value.
3607   if (Parser.getTok().is(AsmToken::LBrac)) {
3608     Parser.Lex(); // Eat the '['.
3609     if (Parser.getTok().is(AsmToken::RBrac)) {
3610       // "Dn[]" is the 'all lanes' syntax.
3611       LaneKind = AllLanes;
3612       EndLoc = Parser.getTok().getEndLoc();
3613       Parser.Lex(); // Eat the ']'.
3614       return MatchOperand_Success;
3615     }
3616 
3617     // There's an optional '#' token here. Normally there wouldn't be, but
3618     // inline assemble puts one in, and it's friendly to accept that.
3619     if (Parser.getTok().is(AsmToken::Hash))
3620       Parser.Lex(); // Eat '#' or '$'.
3621 
3622     const MCExpr *LaneIndex;
3623     SMLoc Loc = Parser.getTok().getLoc();
3624     if (getParser().parseExpression(LaneIndex)) {
3625       Error(Loc, "illegal expression");
3626       return MatchOperand_ParseFail;
3627     }
3628     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3629     if (!CE) {
3630       Error(Loc, "lane index must be empty or an integer");
3631       return MatchOperand_ParseFail;
3632     }
3633     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3634       Error(Parser.getTok().getLoc(), "']' expected");
3635       return MatchOperand_ParseFail;
3636     }
3637     EndLoc = Parser.getTok().getEndLoc();
3638     Parser.Lex(); // Eat the ']'.
3639     int64_t Val = CE->getValue();
3640 
3641     // FIXME: Make this range check context sensitive for .8, .16, .32.
3642     if (Val < 0 || Val > 7) {
3643       Error(Parser.getTok().getLoc(), "lane index out of range");
3644       return MatchOperand_ParseFail;
3645     }
3646     Index = Val;
3647     LaneKind = IndexedLane;
3648     return MatchOperand_Success;
3649   }
3650   LaneKind = NoLanes;
3651   return MatchOperand_Success;
3652 }
3653 
3654 // parse a vector register list
3655 OperandMatchResultTy
3656 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3657   MCAsmParser &Parser = getParser();
3658   VectorLaneTy LaneKind;
3659   unsigned LaneIndex;
3660   SMLoc S = Parser.getTok().getLoc();
3661   // As an extension (to match gas), support a plain D register or Q register
3662   // (without encosing curly braces) as a single or double entry list,
3663   // respectively.
3664   if (Parser.getTok().is(AsmToken::Identifier)) {
3665     SMLoc E = Parser.getTok().getEndLoc();
3666     int Reg = tryParseRegister();
3667     if (Reg == -1)
3668       return MatchOperand_NoMatch;
3669     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3670       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3671       if (Res != MatchOperand_Success)
3672         return Res;
3673       switch (LaneKind) {
3674       case NoLanes:
3675         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3676         break;
3677       case AllLanes:
3678         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3679                                                                 S, E));
3680         break;
3681       case IndexedLane:
3682         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3683                                                                LaneIndex,
3684                                                                false, S, E));
3685         break;
3686       }
3687       return MatchOperand_Success;
3688     }
3689     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3690       Reg = getDRegFromQReg(Reg);
3691       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3692       if (Res != MatchOperand_Success)
3693         return Res;
3694       switch (LaneKind) {
3695       case NoLanes:
3696         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3697                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3698         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3699         break;
3700       case AllLanes:
3701         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3702                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3703         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3704                                                                 S, E));
3705         break;
3706       case IndexedLane:
3707         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3708                                                                LaneIndex,
3709                                                                false, S, E));
3710         break;
3711       }
3712       return MatchOperand_Success;
3713     }
3714     Error(S, "vector register expected");
3715     return MatchOperand_ParseFail;
3716   }
3717 
3718   if (Parser.getTok().isNot(AsmToken::LCurly))
3719     return MatchOperand_NoMatch;
3720 
3721   Parser.Lex(); // Eat '{' token.
3722   SMLoc RegLoc = Parser.getTok().getLoc();
3723 
3724   int Reg = tryParseRegister();
3725   if (Reg == -1) {
3726     Error(RegLoc, "register expected");
3727     return MatchOperand_ParseFail;
3728   }
3729   unsigned Count = 1;
3730   int Spacing = 0;
3731   unsigned FirstReg = Reg;
3732   // The list is of D registers, but we also allow Q regs and just interpret
3733   // them as the two D sub-registers.
3734   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3735     FirstReg = Reg = getDRegFromQReg(Reg);
3736     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3737                  // it's ambiguous with four-register single spaced.
3738     ++Reg;
3739     ++Count;
3740   }
3741 
3742   SMLoc E;
3743   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3744     return MatchOperand_ParseFail;
3745 
3746   while (Parser.getTok().is(AsmToken::Comma) ||
3747          Parser.getTok().is(AsmToken::Minus)) {
3748     if (Parser.getTok().is(AsmToken::Minus)) {
3749       if (!Spacing)
3750         Spacing = 1; // Register range implies a single spaced list.
3751       else if (Spacing == 2) {
3752         Error(Parser.getTok().getLoc(),
3753               "sequential registers in double spaced list");
3754         return MatchOperand_ParseFail;
3755       }
3756       Parser.Lex(); // Eat the minus.
3757       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3758       int EndReg = tryParseRegister();
3759       if (EndReg == -1) {
3760         Error(AfterMinusLoc, "register expected");
3761         return MatchOperand_ParseFail;
3762       }
3763       // Allow Q regs and just interpret them as the two D sub-registers.
3764       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3765         EndReg = getDRegFromQReg(EndReg) + 1;
3766       // If the register is the same as the start reg, there's nothing
3767       // more to do.
3768       if (Reg == EndReg)
3769         continue;
3770       // The register must be in the same register class as the first.
3771       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3772         Error(AfterMinusLoc, "invalid register in register list");
3773         return MatchOperand_ParseFail;
3774       }
3775       // Ranges must go from low to high.
3776       if (Reg > EndReg) {
3777         Error(AfterMinusLoc, "bad range in register list");
3778         return MatchOperand_ParseFail;
3779       }
3780       // Parse the lane specifier if present.
3781       VectorLaneTy NextLaneKind;
3782       unsigned NextLaneIndex;
3783       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3784           MatchOperand_Success)
3785         return MatchOperand_ParseFail;
3786       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3787         Error(AfterMinusLoc, "mismatched lane index in register list");
3788         return MatchOperand_ParseFail;
3789       }
3790 
3791       // Add all the registers in the range to the register list.
3792       Count += EndReg - Reg;
3793       Reg = EndReg;
3794       continue;
3795     }
3796     Parser.Lex(); // Eat the comma.
3797     RegLoc = Parser.getTok().getLoc();
3798     int OldReg = Reg;
3799     Reg = tryParseRegister();
3800     if (Reg == -1) {
3801       Error(RegLoc, "register expected");
3802       return MatchOperand_ParseFail;
3803     }
3804     // vector register lists must be contiguous.
3805     // It's OK to use the enumeration values directly here rather, as the
3806     // VFP register classes have the enum sorted properly.
3807     //
3808     // The list is of D registers, but we also allow Q regs and just interpret
3809     // them as the two D sub-registers.
3810     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3811       if (!Spacing)
3812         Spacing = 1; // Register range implies a single spaced list.
3813       else if (Spacing == 2) {
3814         Error(RegLoc,
3815               "invalid register in double-spaced list (must be 'D' register')");
3816         return MatchOperand_ParseFail;
3817       }
3818       Reg = getDRegFromQReg(Reg);
3819       if (Reg != OldReg + 1) {
3820         Error(RegLoc, "non-contiguous register range");
3821         return MatchOperand_ParseFail;
3822       }
3823       ++Reg;
3824       Count += 2;
3825       // Parse the lane specifier if present.
3826       VectorLaneTy NextLaneKind;
3827       unsigned NextLaneIndex;
3828       SMLoc LaneLoc = Parser.getTok().getLoc();
3829       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3830           MatchOperand_Success)
3831         return MatchOperand_ParseFail;
3832       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3833         Error(LaneLoc, "mismatched lane index in register list");
3834         return MatchOperand_ParseFail;
3835       }
3836       continue;
3837     }
3838     // Normal D register.
3839     // Figure out the register spacing (single or double) of the list if
3840     // we don't know it already.
3841     if (!Spacing)
3842       Spacing = 1 + (Reg == OldReg + 2);
3843 
3844     // Just check that it's contiguous and keep going.
3845     if (Reg != OldReg + Spacing) {
3846       Error(RegLoc, "non-contiguous register range");
3847       return MatchOperand_ParseFail;
3848     }
3849     ++Count;
3850     // Parse the lane specifier if present.
3851     VectorLaneTy NextLaneKind;
3852     unsigned NextLaneIndex;
3853     SMLoc EndLoc = Parser.getTok().getLoc();
3854     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3855       return MatchOperand_ParseFail;
3856     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3857       Error(EndLoc, "mismatched lane index in register list");
3858       return MatchOperand_ParseFail;
3859     }
3860   }
3861 
3862   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3863     Error(Parser.getTok().getLoc(), "'}' expected");
3864     return MatchOperand_ParseFail;
3865   }
3866   E = Parser.getTok().getEndLoc();
3867   Parser.Lex(); // Eat '}' token.
3868 
3869   switch (LaneKind) {
3870   case NoLanes:
3871     // Two-register operands have been converted to the
3872     // composite register classes.
3873     if (Count == 2) {
3874       const MCRegisterClass *RC = (Spacing == 1) ?
3875         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3876         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3877       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3878     }
3879 
3880     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3881                                                     (Spacing == 2), S, E));
3882     break;
3883   case AllLanes:
3884     // Two-register operands have been converted to the
3885     // composite register classes.
3886     if (Count == 2) {
3887       const MCRegisterClass *RC = (Spacing == 1) ?
3888         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3889         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3890       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3891     }
3892     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3893                                                             (Spacing == 2),
3894                                                             S, E));
3895     break;
3896   case IndexedLane:
3897     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3898                                                            LaneIndex,
3899                                                            (Spacing == 2),
3900                                                            S, E));
3901     break;
3902   }
3903   return MatchOperand_Success;
3904 }
3905 
3906 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3907 OperandMatchResultTy
3908 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3909   MCAsmParser &Parser = getParser();
3910   SMLoc S = Parser.getTok().getLoc();
3911   const AsmToken &Tok = Parser.getTok();
3912   unsigned Opt;
3913 
3914   if (Tok.is(AsmToken::Identifier)) {
3915     StringRef OptStr = Tok.getString();
3916 
3917     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3918       .Case("sy",    ARM_MB::SY)
3919       .Case("st",    ARM_MB::ST)
3920       .Case("ld",    ARM_MB::LD)
3921       .Case("sh",    ARM_MB::ISH)
3922       .Case("ish",   ARM_MB::ISH)
3923       .Case("shst",  ARM_MB::ISHST)
3924       .Case("ishst", ARM_MB::ISHST)
3925       .Case("ishld", ARM_MB::ISHLD)
3926       .Case("nsh",   ARM_MB::NSH)
3927       .Case("un",    ARM_MB::NSH)
3928       .Case("nshst", ARM_MB::NSHST)
3929       .Case("nshld", ARM_MB::NSHLD)
3930       .Case("unst",  ARM_MB::NSHST)
3931       .Case("osh",   ARM_MB::OSH)
3932       .Case("oshst", ARM_MB::OSHST)
3933       .Case("oshld", ARM_MB::OSHLD)
3934       .Default(~0U);
3935 
3936     // ishld, oshld, nshld and ld are only available from ARMv8.
3937     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3938                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3939       Opt = ~0U;
3940 
3941     if (Opt == ~0U)
3942       return MatchOperand_NoMatch;
3943 
3944     Parser.Lex(); // Eat identifier token.
3945   } else if (Tok.is(AsmToken::Hash) ||
3946              Tok.is(AsmToken::Dollar) ||
3947              Tok.is(AsmToken::Integer)) {
3948     if (Parser.getTok().isNot(AsmToken::Integer))
3949       Parser.Lex(); // Eat '#' or '$'.
3950     SMLoc Loc = Parser.getTok().getLoc();
3951 
3952     const MCExpr *MemBarrierID;
3953     if (getParser().parseExpression(MemBarrierID)) {
3954       Error(Loc, "illegal expression");
3955       return MatchOperand_ParseFail;
3956     }
3957 
3958     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3959     if (!CE) {
3960       Error(Loc, "constant expression expected");
3961       return MatchOperand_ParseFail;
3962     }
3963 
3964     int Val = CE->getValue();
3965     if (Val & ~0xf) {
3966       Error(Loc, "immediate value out of range");
3967       return MatchOperand_ParseFail;
3968     }
3969 
3970     Opt = ARM_MB::RESERVED_0 + Val;
3971   } else
3972     return MatchOperand_ParseFail;
3973 
3974   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3975   return MatchOperand_Success;
3976 }
3977 
3978 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3979 OperandMatchResultTy
3980 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3981   MCAsmParser &Parser = getParser();
3982   SMLoc S = Parser.getTok().getLoc();
3983   const AsmToken &Tok = Parser.getTok();
3984   unsigned Opt;
3985 
3986   if (Tok.is(AsmToken::Identifier)) {
3987     StringRef OptStr = Tok.getString();
3988 
3989     if (OptStr.equals_lower("sy"))
3990       Opt = ARM_ISB::SY;
3991     else
3992       return MatchOperand_NoMatch;
3993 
3994     Parser.Lex(); // Eat identifier token.
3995   } else if (Tok.is(AsmToken::Hash) ||
3996              Tok.is(AsmToken::Dollar) ||
3997              Tok.is(AsmToken::Integer)) {
3998     if (Parser.getTok().isNot(AsmToken::Integer))
3999       Parser.Lex(); // Eat '#' or '$'.
4000     SMLoc Loc = Parser.getTok().getLoc();
4001 
4002     const MCExpr *ISBarrierID;
4003     if (getParser().parseExpression(ISBarrierID)) {
4004       Error(Loc, "illegal expression");
4005       return MatchOperand_ParseFail;
4006     }
4007 
4008     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4009     if (!CE) {
4010       Error(Loc, "constant expression expected");
4011       return MatchOperand_ParseFail;
4012     }
4013 
4014     int Val = CE->getValue();
4015     if (Val & ~0xf) {
4016       Error(Loc, "immediate value out of range");
4017       return MatchOperand_ParseFail;
4018     }
4019 
4020     Opt = ARM_ISB::RESERVED_0 + Val;
4021   } else
4022     return MatchOperand_ParseFail;
4023 
4024   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4025           (ARM_ISB::InstSyncBOpt)Opt, S));
4026   return MatchOperand_Success;
4027 }
4028 
4029 
4030 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4031 OperandMatchResultTy
4032 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4033   MCAsmParser &Parser = getParser();
4034   SMLoc S = Parser.getTok().getLoc();
4035   const AsmToken &Tok = Parser.getTok();
4036   if (!Tok.is(AsmToken::Identifier))
4037     return MatchOperand_NoMatch;
4038   StringRef IFlagsStr = Tok.getString();
4039 
4040   // An iflags string of "none" is interpreted to mean that none of the AIF
4041   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4042   unsigned IFlags = 0;
4043   if (IFlagsStr != "none") {
4044         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4045       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
4046         .Case("a", ARM_PROC::A)
4047         .Case("i", ARM_PROC::I)
4048         .Case("f", ARM_PROC::F)
4049         .Default(~0U);
4050 
4051       // If some specific iflag is already set, it means that some letter is
4052       // present more than once, this is not acceptable.
4053       if (Flag == ~0U || (IFlags & Flag))
4054         return MatchOperand_NoMatch;
4055 
4056       IFlags |= Flag;
4057     }
4058   }
4059 
4060   Parser.Lex(); // Eat identifier token.
4061   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4062   return MatchOperand_Success;
4063 }
4064 
4065 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4066 OperandMatchResultTy
4067 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4068   MCAsmParser &Parser = getParser();
4069   SMLoc S = Parser.getTok().getLoc();
4070   const AsmToken &Tok = Parser.getTok();
4071   if (!Tok.is(AsmToken::Identifier))
4072     return MatchOperand_NoMatch;
4073   StringRef Mask = Tok.getString();
4074 
4075   if (isMClass()) {
4076     // See ARMv6-M 10.1.1
4077     std::string Name = Mask.lower();
4078     unsigned FlagsVal = StringSwitch<unsigned>(Name)
4079       // Note: in the documentation:
4080       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
4081       //  for MSR APSR_nzcvq.
4082       // but we do make it an alias here.  This is so to get the "mask encoding"
4083       // bits correct on MSR APSR writes.
4084       //
4085       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
4086       // should really only be allowed when writing a special register.  Note
4087       // they get dropped in the MRS instruction reading a special register as
4088       // the SYSm field is only 8 bits.
4089       .Case("apsr", 0x800)
4090       .Case("apsr_nzcvq", 0x800)
4091       .Case("apsr_g", 0x400)
4092       .Case("apsr_nzcvqg", 0xc00)
4093       .Case("iapsr", 0x801)
4094       .Case("iapsr_nzcvq", 0x801)
4095       .Case("iapsr_g", 0x401)
4096       .Case("iapsr_nzcvqg", 0xc01)
4097       .Case("eapsr", 0x802)
4098       .Case("eapsr_nzcvq", 0x802)
4099       .Case("eapsr_g", 0x402)
4100       .Case("eapsr_nzcvqg", 0xc02)
4101       .Case("xpsr", 0x803)
4102       .Case("xpsr_nzcvq", 0x803)
4103       .Case("xpsr_g", 0x403)
4104       .Case("xpsr_nzcvqg", 0xc03)
4105       .Case("ipsr", 0x805)
4106       .Case("epsr", 0x806)
4107       .Case("iepsr", 0x807)
4108       .Case("msp", 0x808)
4109       .Case("psp", 0x809)
4110       .Case("primask", 0x810)
4111       .Case("basepri", 0x811)
4112       .Case("basepri_max", 0x812)
4113       .Case("faultmask", 0x813)
4114       .Case("control", 0x814)
4115       .Case("msplim", 0x80a)
4116       .Case("psplim", 0x80b)
4117       .Case("msp_ns", 0x888)
4118       .Case("psp_ns", 0x889)
4119       .Case("msplim_ns", 0x88a)
4120       .Case("psplim_ns", 0x88b)
4121       .Case("primask_ns", 0x890)
4122       .Case("basepri_ns", 0x891)
4123       .Case("basepri_max_ns", 0x892)
4124       .Case("faultmask_ns", 0x893)
4125       .Case("control_ns", 0x894)
4126       .Case("sp_ns", 0x898)
4127       .Default(~0U);
4128 
4129     if (FlagsVal == ~0U)
4130       return MatchOperand_NoMatch;
4131 
4132     if (!hasDSP() && (FlagsVal & 0x400))
4133       // The _g and _nzcvqg versions are only valid if the DSP extension is
4134       // available.
4135       return MatchOperand_NoMatch;
4136 
4137     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
4138       // basepri, basepri_max and faultmask only valid for V7m.
4139       return MatchOperand_NoMatch;
4140 
4141     if (!has8MSecExt() && (FlagsVal == 0x80a || FlagsVal == 0x80b ||
4142                              (FlagsVal > 0x814 && FlagsVal < 0xc00)))
4143       return MatchOperand_NoMatch;
4144 
4145     if (!hasV8MMainline() && (FlagsVal == 0x88a || FlagsVal == 0x88b ||
4146                               (FlagsVal > 0x890 && FlagsVal <= 0x893)))
4147       return MatchOperand_NoMatch;
4148 
4149     Parser.Lex(); // Eat identifier token.
4150     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4151     return MatchOperand_Success;
4152   }
4153 
4154   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4155   size_t Start = 0, Next = Mask.find('_');
4156   StringRef Flags = "";
4157   std::string SpecReg = Mask.slice(Start, Next).lower();
4158   if (Next != StringRef::npos)
4159     Flags = Mask.slice(Next+1, Mask.size());
4160 
4161   // FlagsVal contains the complete mask:
4162   // 3-0: Mask
4163   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4164   unsigned FlagsVal = 0;
4165 
4166   if (SpecReg == "apsr") {
4167     FlagsVal = StringSwitch<unsigned>(Flags)
4168     .Case("nzcvq",  0x8) // same as CPSR_f
4169     .Case("g",      0x4) // same as CPSR_s
4170     .Case("nzcvqg", 0xc) // same as CPSR_fs
4171     .Default(~0U);
4172 
4173     if (FlagsVal == ~0U) {
4174       if (!Flags.empty())
4175         return MatchOperand_NoMatch;
4176       else
4177         FlagsVal = 8; // No flag
4178     }
4179   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4180     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4181     if (Flags == "all" || Flags == "")
4182       Flags = "fc";
4183     for (int i = 0, e = Flags.size(); i != e; ++i) {
4184       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4185       .Case("c", 1)
4186       .Case("x", 2)
4187       .Case("s", 4)
4188       .Case("f", 8)
4189       .Default(~0U);
4190 
4191       // If some specific flag is already set, it means that some letter is
4192       // present more than once, this is not acceptable.
4193       if (Flag == ~0U || (FlagsVal & Flag))
4194         return MatchOperand_NoMatch;
4195       FlagsVal |= Flag;
4196     }
4197   } else // No match for special register.
4198     return MatchOperand_NoMatch;
4199 
4200   // Special register without flags is NOT equivalent to "fc" flags.
4201   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4202   // two lines would enable gas compatibility at the expense of breaking
4203   // round-tripping.
4204   //
4205   // if (!FlagsVal)
4206   //  FlagsVal = 0x9;
4207 
4208   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4209   if (SpecReg == "spsr")
4210     FlagsVal |= 16;
4211 
4212   Parser.Lex(); // Eat identifier token.
4213   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4214   return MatchOperand_Success;
4215 }
4216 
4217 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4218 /// use in the MRS/MSR instructions added to support virtualization.
4219 OperandMatchResultTy
4220 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4221   MCAsmParser &Parser = getParser();
4222   SMLoc S = Parser.getTok().getLoc();
4223   const AsmToken &Tok = Parser.getTok();
4224   if (!Tok.is(AsmToken::Identifier))
4225     return MatchOperand_NoMatch;
4226   StringRef RegName = Tok.getString();
4227 
4228   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4229   // and bit 5 is R.
4230   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4231                           .Case("r8_usr", 0x00)
4232                           .Case("r9_usr", 0x01)
4233                           .Case("r10_usr", 0x02)
4234                           .Case("r11_usr", 0x03)
4235                           .Case("r12_usr", 0x04)
4236                           .Case("sp_usr", 0x05)
4237                           .Case("lr_usr", 0x06)
4238                           .Case("r8_fiq", 0x08)
4239                           .Case("r9_fiq", 0x09)
4240                           .Case("r10_fiq", 0x0a)
4241                           .Case("r11_fiq", 0x0b)
4242                           .Case("r12_fiq", 0x0c)
4243                           .Case("sp_fiq", 0x0d)
4244                           .Case("lr_fiq", 0x0e)
4245                           .Case("lr_irq", 0x10)
4246                           .Case("sp_irq", 0x11)
4247                           .Case("lr_svc", 0x12)
4248                           .Case("sp_svc", 0x13)
4249                           .Case("lr_abt", 0x14)
4250                           .Case("sp_abt", 0x15)
4251                           .Case("lr_und", 0x16)
4252                           .Case("sp_und", 0x17)
4253                           .Case("lr_mon", 0x1c)
4254                           .Case("sp_mon", 0x1d)
4255                           .Case("elr_hyp", 0x1e)
4256                           .Case("sp_hyp", 0x1f)
4257                           .Case("spsr_fiq", 0x2e)
4258                           .Case("spsr_irq", 0x30)
4259                           .Case("spsr_svc", 0x32)
4260                           .Case("spsr_abt", 0x34)
4261                           .Case("spsr_und", 0x36)
4262                           .Case("spsr_mon", 0x3c)
4263                           .Case("spsr_hyp", 0x3e)
4264                           .Default(~0U);
4265 
4266   if (Encoding == ~0U)
4267     return MatchOperand_NoMatch;
4268 
4269   Parser.Lex(); // Eat identifier token.
4270   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4271   return MatchOperand_Success;
4272 }
4273 
4274 OperandMatchResultTy
4275 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4276                           int High) {
4277   MCAsmParser &Parser = getParser();
4278   const AsmToken &Tok = Parser.getTok();
4279   if (Tok.isNot(AsmToken::Identifier)) {
4280     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4281     return MatchOperand_ParseFail;
4282   }
4283   StringRef ShiftName = Tok.getString();
4284   std::string LowerOp = Op.lower();
4285   std::string UpperOp = Op.upper();
4286   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4287     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4288     return MatchOperand_ParseFail;
4289   }
4290   Parser.Lex(); // Eat shift type token.
4291 
4292   // There must be a '#' and a shift amount.
4293   if (Parser.getTok().isNot(AsmToken::Hash) &&
4294       Parser.getTok().isNot(AsmToken::Dollar)) {
4295     Error(Parser.getTok().getLoc(), "'#' expected");
4296     return MatchOperand_ParseFail;
4297   }
4298   Parser.Lex(); // Eat hash token.
4299 
4300   const MCExpr *ShiftAmount;
4301   SMLoc Loc = Parser.getTok().getLoc();
4302   SMLoc EndLoc;
4303   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4304     Error(Loc, "illegal expression");
4305     return MatchOperand_ParseFail;
4306   }
4307   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4308   if (!CE) {
4309     Error(Loc, "constant expression expected");
4310     return MatchOperand_ParseFail;
4311   }
4312   int Val = CE->getValue();
4313   if (Val < Low || Val > High) {
4314     Error(Loc, "immediate value out of range");
4315     return MatchOperand_ParseFail;
4316   }
4317 
4318   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4319 
4320   return MatchOperand_Success;
4321 }
4322 
4323 OperandMatchResultTy
4324 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4325   MCAsmParser &Parser = getParser();
4326   const AsmToken &Tok = Parser.getTok();
4327   SMLoc S = Tok.getLoc();
4328   if (Tok.isNot(AsmToken::Identifier)) {
4329     Error(S, "'be' or 'le' operand expected");
4330     return MatchOperand_ParseFail;
4331   }
4332   int Val = StringSwitch<int>(Tok.getString().lower())
4333     .Case("be", 1)
4334     .Case("le", 0)
4335     .Default(-1);
4336   Parser.Lex(); // Eat the token.
4337 
4338   if (Val == -1) {
4339     Error(S, "'be' or 'le' operand expected");
4340     return MatchOperand_ParseFail;
4341   }
4342   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4343                                                                   getContext()),
4344                                            S, Tok.getEndLoc()));
4345   return MatchOperand_Success;
4346 }
4347 
4348 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4349 /// instructions. Legal values are:
4350 ///     lsl #n  'n' in [0,31]
4351 ///     asr #n  'n' in [1,32]
4352 ///             n == 32 encoded as n == 0.
4353 OperandMatchResultTy
4354 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4355   MCAsmParser &Parser = getParser();
4356   const AsmToken &Tok = Parser.getTok();
4357   SMLoc S = Tok.getLoc();
4358   if (Tok.isNot(AsmToken::Identifier)) {
4359     Error(S, "shift operator 'asr' or 'lsl' expected");
4360     return MatchOperand_ParseFail;
4361   }
4362   StringRef ShiftName = Tok.getString();
4363   bool isASR;
4364   if (ShiftName == "lsl" || ShiftName == "LSL")
4365     isASR = false;
4366   else if (ShiftName == "asr" || ShiftName == "ASR")
4367     isASR = true;
4368   else {
4369     Error(S, "shift operator 'asr' or 'lsl' expected");
4370     return MatchOperand_ParseFail;
4371   }
4372   Parser.Lex(); // Eat the operator.
4373 
4374   // A '#' and a shift amount.
4375   if (Parser.getTok().isNot(AsmToken::Hash) &&
4376       Parser.getTok().isNot(AsmToken::Dollar)) {
4377     Error(Parser.getTok().getLoc(), "'#' expected");
4378     return MatchOperand_ParseFail;
4379   }
4380   Parser.Lex(); // Eat hash token.
4381   SMLoc ExLoc = Parser.getTok().getLoc();
4382 
4383   const MCExpr *ShiftAmount;
4384   SMLoc EndLoc;
4385   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4386     Error(ExLoc, "malformed shift expression");
4387     return MatchOperand_ParseFail;
4388   }
4389   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4390   if (!CE) {
4391     Error(ExLoc, "shift amount must be an immediate");
4392     return MatchOperand_ParseFail;
4393   }
4394 
4395   int64_t Val = CE->getValue();
4396   if (isASR) {
4397     // Shift amount must be in [1,32]
4398     if (Val < 1 || Val > 32) {
4399       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4400       return MatchOperand_ParseFail;
4401     }
4402     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4403     if (isThumb() && Val == 32) {
4404       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4405       return MatchOperand_ParseFail;
4406     }
4407     if (Val == 32) Val = 0;
4408   } else {
4409     // Shift amount must be in [1,32]
4410     if (Val < 0 || Val > 31) {
4411       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4412       return MatchOperand_ParseFail;
4413     }
4414   }
4415 
4416   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4417 
4418   return MatchOperand_Success;
4419 }
4420 
4421 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4422 /// of instructions. Legal values are:
4423 ///     ror #n  'n' in {0, 8, 16, 24}
4424 OperandMatchResultTy
4425 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4426   MCAsmParser &Parser = getParser();
4427   const AsmToken &Tok = Parser.getTok();
4428   SMLoc S = Tok.getLoc();
4429   if (Tok.isNot(AsmToken::Identifier))
4430     return MatchOperand_NoMatch;
4431   StringRef ShiftName = Tok.getString();
4432   if (ShiftName != "ror" && ShiftName != "ROR")
4433     return MatchOperand_NoMatch;
4434   Parser.Lex(); // Eat the operator.
4435 
4436   // A '#' and a rotate amount.
4437   if (Parser.getTok().isNot(AsmToken::Hash) &&
4438       Parser.getTok().isNot(AsmToken::Dollar)) {
4439     Error(Parser.getTok().getLoc(), "'#' expected");
4440     return MatchOperand_ParseFail;
4441   }
4442   Parser.Lex(); // Eat hash token.
4443   SMLoc ExLoc = Parser.getTok().getLoc();
4444 
4445   const MCExpr *ShiftAmount;
4446   SMLoc EndLoc;
4447   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4448     Error(ExLoc, "malformed rotate expression");
4449     return MatchOperand_ParseFail;
4450   }
4451   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4452   if (!CE) {
4453     Error(ExLoc, "rotate amount must be an immediate");
4454     return MatchOperand_ParseFail;
4455   }
4456 
4457   int64_t Val = CE->getValue();
4458   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4459   // normally, zero is represented in asm by omitting the rotate operand
4460   // entirely.
4461   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4462     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4463     return MatchOperand_ParseFail;
4464   }
4465 
4466   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4467 
4468   return MatchOperand_Success;
4469 }
4470 
4471 OperandMatchResultTy
4472 ARMAsmParser::parseModImm(OperandVector &Operands) {
4473   MCAsmParser &Parser = getParser();
4474   MCAsmLexer &Lexer = getLexer();
4475   int64_t Imm1, Imm2;
4476 
4477   SMLoc S = Parser.getTok().getLoc();
4478 
4479   // 1) A mod_imm operand can appear in the place of a register name:
4480   //   add r0, #mod_imm
4481   //   add r0, r0, #mod_imm
4482   // to correctly handle the latter, we bail out as soon as we see an
4483   // identifier.
4484   //
4485   // 2) Similarly, we do not want to parse into complex operands:
4486   //   mov r0, #mod_imm
4487   //   mov r0, :lower16:(_foo)
4488   if (Parser.getTok().is(AsmToken::Identifier) ||
4489       Parser.getTok().is(AsmToken::Colon))
4490     return MatchOperand_NoMatch;
4491 
4492   // Hash (dollar) is optional as per the ARMARM
4493   if (Parser.getTok().is(AsmToken::Hash) ||
4494       Parser.getTok().is(AsmToken::Dollar)) {
4495     // Avoid parsing into complex operands (#:)
4496     if (Lexer.peekTok().is(AsmToken::Colon))
4497       return MatchOperand_NoMatch;
4498 
4499     // Eat the hash (dollar)
4500     Parser.Lex();
4501   }
4502 
4503   SMLoc Sx1, Ex1;
4504   Sx1 = Parser.getTok().getLoc();
4505   const MCExpr *Imm1Exp;
4506   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4507     Error(Sx1, "malformed expression");
4508     return MatchOperand_ParseFail;
4509   }
4510 
4511   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4512 
4513   if (CE) {
4514     // Immediate must fit within 32-bits
4515     Imm1 = CE->getValue();
4516     int Enc = ARM_AM::getSOImmVal(Imm1);
4517     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4518       // We have a match!
4519       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4520                                                   (Enc & 0xF00) >> 7,
4521                                                   Sx1, Ex1));
4522       return MatchOperand_Success;
4523     }
4524 
4525     // We have parsed an immediate which is not for us, fallback to a plain
4526     // immediate. This can happen for instruction aliases. For an example,
4527     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4528     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4529     // instruction with a mod_imm operand. The alias is defined such that the
4530     // parser method is shared, that's why we have to do this here.
4531     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4532       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4533       return MatchOperand_Success;
4534     }
4535   } else {
4536     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4537     // MCFixup). Fallback to a plain immediate.
4538     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4539     return MatchOperand_Success;
4540   }
4541 
4542   // From this point onward, we expect the input to be a (#bits, #rot) pair
4543   if (Parser.getTok().isNot(AsmToken::Comma)) {
4544     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4545     return MatchOperand_ParseFail;
4546   }
4547 
4548   if (Imm1 & ~0xFF) {
4549     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4550     return MatchOperand_ParseFail;
4551   }
4552 
4553   // Eat the comma
4554   Parser.Lex();
4555 
4556   // Repeat for #rot
4557   SMLoc Sx2, Ex2;
4558   Sx2 = Parser.getTok().getLoc();
4559 
4560   // Eat the optional hash (dollar)
4561   if (Parser.getTok().is(AsmToken::Hash) ||
4562       Parser.getTok().is(AsmToken::Dollar))
4563     Parser.Lex();
4564 
4565   const MCExpr *Imm2Exp;
4566   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4567     Error(Sx2, "malformed expression");
4568     return MatchOperand_ParseFail;
4569   }
4570 
4571   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4572 
4573   if (CE) {
4574     Imm2 = CE->getValue();
4575     if (!(Imm2 & ~0x1E)) {
4576       // We have a match!
4577       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4578       return MatchOperand_Success;
4579     }
4580     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4581     return MatchOperand_ParseFail;
4582   } else {
4583     Error(Sx2, "constant expression expected");
4584     return MatchOperand_ParseFail;
4585   }
4586 }
4587 
4588 OperandMatchResultTy
4589 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4590   MCAsmParser &Parser = getParser();
4591   SMLoc S = Parser.getTok().getLoc();
4592   // The bitfield descriptor is really two operands, the LSB and the width.
4593   if (Parser.getTok().isNot(AsmToken::Hash) &&
4594       Parser.getTok().isNot(AsmToken::Dollar)) {
4595     Error(Parser.getTok().getLoc(), "'#' expected");
4596     return MatchOperand_ParseFail;
4597   }
4598   Parser.Lex(); // Eat hash token.
4599 
4600   const MCExpr *LSBExpr;
4601   SMLoc E = Parser.getTok().getLoc();
4602   if (getParser().parseExpression(LSBExpr)) {
4603     Error(E, "malformed immediate expression");
4604     return MatchOperand_ParseFail;
4605   }
4606   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4607   if (!CE) {
4608     Error(E, "'lsb' operand must be an immediate");
4609     return MatchOperand_ParseFail;
4610   }
4611 
4612   int64_t LSB = CE->getValue();
4613   // The LSB must be in the range [0,31]
4614   if (LSB < 0 || LSB > 31) {
4615     Error(E, "'lsb' operand must be in the range [0,31]");
4616     return MatchOperand_ParseFail;
4617   }
4618   E = Parser.getTok().getLoc();
4619 
4620   // Expect another immediate operand.
4621   if (Parser.getTok().isNot(AsmToken::Comma)) {
4622     Error(Parser.getTok().getLoc(), "too few operands");
4623     return MatchOperand_ParseFail;
4624   }
4625   Parser.Lex(); // Eat hash token.
4626   if (Parser.getTok().isNot(AsmToken::Hash) &&
4627       Parser.getTok().isNot(AsmToken::Dollar)) {
4628     Error(Parser.getTok().getLoc(), "'#' expected");
4629     return MatchOperand_ParseFail;
4630   }
4631   Parser.Lex(); // Eat hash token.
4632 
4633   const MCExpr *WidthExpr;
4634   SMLoc EndLoc;
4635   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4636     Error(E, "malformed immediate expression");
4637     return MatchOperand_ParseFail;
4638   }
4639   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4640   if (!CE) {
4641     Error(E, "'width' operand must be an immediate");
4642     return MatchOperand_ParseFail;
4643   }
4644 
4645   int64_t Width = CE->getValue();
4646   // The LSB must be in the range [1,32-lsb]
4647   if (Width < 1 || Width > 32 - LSB) {
4648     Error(E, "'width' operand must be in the range [1,32-lsb]");
4649     return MatchOperand_ParseFail;
4650   }
4651 
4652   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4653 
4654   return MatchOperand_Success;
4655 }
4656 
4657 OperandMatchResultTy
4658 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4659   // Check for a post-index addressing register operand. Specifically:
4660   // postidx_reg := '+' register {, shift}
4661   //              | '-' register {, shift}
4662   //              | register {, shift}
4663 
4664   // This method must return MatchOperand_NoMatch without consuming any tokens
4665   // in the case where there is no match, as other alternatives take other
4666   // parse methods.
4667   MCAsmParser &Parser = getParser();
4668   AsmToken Tok = Parser.getTok();
4669   SMLoc S = Tok.getLoc();
4670   bool haveEaten = false;
4671   bool isAdd = true;
4672   if (Tok.is(AsmToken::Plus)) {
4673     Parser.Lex(); // Eat the '+' token.
4674     haveEaten = true;
4675   } else if (Tok.is(AsmToken::Minus)) {
4676     Parser.Lex(); // Eat the '-' token.
4677     isAdd = false;
4678     haveEaten = true;
4679   }
4680 
4681   SMLoc E = Parser.getTok().getEndLoc();
4682   int Reg = tryParseRegister();
4683   if (Reg == -1) {
4684     if (!haveEaten)
4685       return MatchOperand_NoMatch;
4686     Error(Parser.getTok().getLoc(), "register expected");
4687     return MatchOperand_ParseFail;
4688   }
4689 
4690   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4691   unsigned ShiftImm = 0;
4692   if (Parser.getTok().is(AsmToken::Comma)) {
4693     Parser.Lex(); // Eat the ','.
4694     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4695       return MatchOperand_ParseFail;
4696 
4697     // FIXME: Only approximates end...may include intervening whitespace.
4698     E = Parser.getTok().getLoc();
4699   }
4700 
4701   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4702                                                   ShiftImm, S, E));
4703 
4704   return MatchOperand_Success;
4705 }
4706 
4707 OperandMatchResultTy
4708 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4709   // Check for a post-index addressing register operand. Specifically:
4710   // am3offset := '+' register
4711   //              | '-' register
4712   //              | register
4713   //              | # imm
4714   //              | # + imm
4715   //              | # - imm
4716 
4717   // This method must return MatchOperand_NoMatch without consuming any tokens
4718   // in the case where there is no match, as other alternatives take other
4719   // parse methods.
4720   MCAsmParser &Parser = getParser();
4721   AsmToken Tok = Parser.getTok();
4722   SMLoc S = Tok.getLoc();
4723 
4724   // Do immediates first, as we always parse those if we have a '#'.
4725   if (Parser.getTok().is(AsmToken::Hash) ||
4726       Parser.getTok().is(AsmToken::Dollar)) {
4727     Parser.Lex(); // Eat '#' or '$'.
4728     // Explicitly look for a '-', as we need to encode negative zero
4729     // differently.
4730     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4731     const MCExpr *Offset;
4732     SMLoc E;
4733     if (getParser().parseExpression(Offset, E))
4734       return MatchOperand_ParseFail;
4735     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4736     if (!CE) {
4737       Error(S, "constant expression expected");
4738       return MatchOperand_ParseFail;
4739     }
4740     // Negative zero is encoded as the flag value INT32_MIN.
4741     int32_t Val = CE->getValue();
4742     if (isNegative && Val == 0)
4743       Val = INT32_MIN;
4744 
4745     Operands.push_back(
4746       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4747 
4748     return MatchOperand_Success;
4749   }
4750 
4751 
4752   bool haveEaten = false;
4753   bool isAdd = true;
4754   if (Tok.is(AsmToken::Plus)) {
4755     Parser.Lex(); // Eat the '+' token.
4756     haveEaten = true;
4757   } else if (Tok.is(AsmToken::Minus)) {
4758     Parser.Lex(); // Eat the '-' token.
4759     isAdd = false;
4760     haveEaten = true;
4761   }
4762 
4763   Tok = Parser.getTok();
4764   int Reg = tryParseRegister();
4765   if (Reg == -1) {
4766     if (!haveEaten)
4767       return MatchOperand_NoMatch;
4768     Error(Tok.getLoc(), "register expected");
4769     return MatchOperand_ParseFail;
4770   }
4771 
4772   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4773                                                   0, S, Tok.getEndLoc()));
4774 
4775   return MatchOperand_Success;
4776 }
4777 
4778 /// Convert parsed operands to MCInst.  Needed here because this instruction
4779 /// only has two register operands, but multiplication is commutative so
4780 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4781 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4782                                     const OperandVector &Operands) {
4783   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4784   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4785   // If we have a three-operand form, make sure to set Rn to be the operand
4786   // that isn't the same as Rd.
4787   unsigned RegOp = 4;
4788   if (Operands.size() == 6 &&
4789       ((ARMOperand &)*Operands[4]).getReg() ==
4790           ((ARMOperand &)*Operands[3]).getReg())
4791     RegOp = 5;
4792   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4793   Inst.addOperand(Inst.getOperand(0));
4794   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4795 }
4796 
4797 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4798                                     const OperandVector &Operands) {
4799   int CondOp = -1, ImmOp = -1;
4800   switch(Inst.getOpcode()) {
4801     case ARM::tB:
4802     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4803 
4804     case ARM::t2B:
4805     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4806 
4807     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4808   }
4809   // first decide whether or not the branch should be conditional
4810   // by looking at it's location relative to an IT block
4811   if(inITBlock()) {
4812     // inside an IT block we cannot have any conditional branches. any
4813     // such instructions needs to be converted to unconditional form
4814     switch(Inst.getOpcode()) {
4815       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4816       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4817     }
4818   } else {
4819     // outside IT blocks we can only have unconditional branches with AL
4820     // condition code or conditional branches with non-AL condition code
4821     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4822     switch(Inst.getOpcode()) {
4823       case ARM::tB:
4824       case ARM::tBcc:
4825         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4826         break;
4827       case ARM::t2B:
4828       case ARM::t2Bcc:
4829         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4830         break;
4831     }
4832   }
4833 
4834   // now decide on encoding size based on branch target range
4835   switch(Inst.getOpcode()) {
4836     // classify tB as either t2B or t1B based on range of immediate operand
4837     case ARM::tB: {
4838       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4839       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4840         Inst.setOpcode(ARM::t2B);
4841       break;
4842     }
4843     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4844     case ARM::tBcc: {
4845       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4846       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4847         Inst.setOpcode(ARM::t2Bcc);
4848       break;
4849     }
4850   }
4851   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4852   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4853 }
4854 
4855 /// Parse an ARM memory expression, return false if successful else return true
4856 /// or an error.  The first token must be a '[' when called.
4857 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4858   MCAsmParser &Parser = getParser();
4859   SMLoc S, E;
4860   if (Parser.getTok().isNot(AsmToken::LBrac))
4861     return TokError("Token is not a Left Bracket");
4862   S = Parser.getTok().getLoc();
4863   Parser.Lex(); // Eat left bracket token.
4864 
4865   const AsmToken &BaseRegTok = Parser.getTok();
4866   int BaseRegNum = tryParseRegister();
4867   if (BaseRegNum == -1)
4868     return Error(BaseRegTok.getLoc(), "register expected");
4869 
4870   // The next token must either be a comma, a colon or a closing bracket.
4871   const AsmToken &Tok = Parser.getTok();
4872   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4873       !Tok.is(AsmToken::RBrac))
4874     return Error(Tok.getLoc(), "malformed memory operand");
4875 
4876   if (Tok.is(AsmToken::RBrac)) {
4877     E = Tok.getEndLoc();
4878     Parser.Lex(); // Eat right bracket token.
4879 
4880     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4881                                              ARM_AM::no_shift, 0, 0, false,
4882                                              S, E));
4883 
4884     // If there's a pre-indexing writeback marker, '!', just add it as a token
4885     // operand. It's rather odd, but syntactically valid.
4886     if (Parser.getTok().is(AsmToken::Exclaim)) {
4887       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4888       Parser.Lex(); // Eat the '!'.
4889     }
4890 
4891     return false;
4892   }
4893 
4894   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4895          "Lost colon or comma in memory operand?!");
4896   if (Tok.is(AsmToken::Comma)) {
4897     Parser.Lex(); // Eat the comma.
4898   }
4899 
4900   // If we have a ':', it's an alignment specifier.
4901   if (Parser.getTok().is(AsmToken::Colon)) {
4902     Parser.Lex(); // Eat the ':'.
4903     E = Parser.getTok().getLoc();
4904     SMLoc AlignmentLoc = Tok.getLoc();
4905 
4906     const MCExpr *Expr;
4907     if (getParser().parseExpression(Expr))
4908      return true;
4909 
4910     // The expression has to be a constant. Memory references with relocations
4911     // don't come through here, as they use the <label> forms of the relevant
4912     // instructions.
4913     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4914     if (!CE)
4915       return Error (E, "constant expression expected");
4916 
4917     unsigned Align = 0;
4918     switch (CE->getValue()) {
4919     default:
4920       return Error(E,
4921                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4922     case 16:  Align = 2; break;
4923     case 32:  Align = 4; break;
4924     case 64:  Align = 8; break;
4925     case 128: Align = 16; break;
4926     case 256: Align = 32; break;
4927     }
4928 
4929     // Now we should have the closing ']'
4930     if (Parser.getTok().isNot(AsmToken::RBrac))
4931       return Error(Parser.getTok().getLoc(), "']' expected");
4932     E = Parser.getTok().getEndLoc();
4933     Parser.Lex(); // Eat right bracket token.
4934 
4935     // Don't worry about range checking the value here. That's handled by
4936     // the is*() predicates.
4937     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4938                                              ARM_AM::no_shift, 0, Align,
4939                                              false, S, E, AlignmentLoc));
4940 
4941     // If there's a pre-indexing writeback marker, '!', just add it as a token
4942     // operand.
4943     if (Parser.getTok().is(AsmToken::Exclaim)) {
4944       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4945       Parser.Lex(); // Eat the '!'.
4946     }
4947 
4948     return false;
4949   }
4950 
4951   // If we have a '#', it's an immediate offset, else assume it's a register
4952   // offset. Be friendly and also accept a plain integer (without a leading
4953   // hash) for gas compatibility.
4954   if (Parser.getTok().is(AsmToken::Hash) ||
4955       Parser.getTok().is(AsmToken::Dollar) ||
4956       Parser.getTok().is(AsmToken::Integer)) {
4957     if (Parser.getTok().isNot(AsmToken::Integer))
4958       Parser.Lex(); // Eat '#' or '$'.
4959     E = Parser.getTok().getLoc();
4960 
4961     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4962     const MCExpr *Offset;
4963     if (getParser().parseExpression(Offset))
4964      return true;
4965 
4966     // The expression has to be a constant. Memory references with relocations
4967     // don't come through here, as they use the <label> forms of the relevant
4968     // instructions.
4969     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4970     if (!CE)
4971       return Error (E, "constant expression expected");
4972 
4973     // If the constant was #-0, represent it as INT32_MIN.
4974     int32_t Val = CE->getValue();
4975     if (isNegative && Val == 0)
4976       CE = MCConstantExpr::create(INT32_MIN, getContext());
4977 
4978     // Now we should have the closing ']'
4979     if (Parser.getTok().isNot(AsmToken::RBrac))
4980       return Error(Parser.getTok().getLoc(), "']' expected");
4981     E = Parser.getTok().getEndLoc();
4982     Parser.Lex(); // Eat right bracket token.
4983 
4984     // Don't worry about range checking the value here. That's handled by
4985     // the is*() predicates.
4986     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4987                                              ARM_AM::no_shift, 0, 0,
4988                                              false, S, E));
4989 
4990     // If there's a pre-indexing writeback marker, '!', just add it as a token
4991     // operand.
4992     if (Parser.getTok().is(AsmToken::Exclaim)) {
4993       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4994       Parser.Lex(); // Eat the '!'.
4995     }
4996 
4997     return false;
4998   }
4999 
5000   // The register offset is optionally preceded by a '+' or '-'
5001   bool isNegative = false;
5002   if (Parser.getTok().is(AsmToken::Minus)) {
5003     isNegative = true;
5004     Parser.Lex(); // Eat the '-'.
5005   } else if (Parser.getTok().is(AsmToken::Plus)) {
5006     // Nothing to do.
5007     Parser.Lex(); // Eat the '+'.
5008   }
5009 
5010   E = Parser.getTok().getLoc();
5011   int OffsetRegNum = tryParseRegister();
5012   if (OffsetRegNum == -1)
5013     return Error(E, "register expected");
5014 
5015   // If there's a shift operator, handle it.
5016   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5017   unsigned ShiftImm = 0;
5018   if (Parser.getTok().is(AsmToken::Comma)) {
5019     Parser.Lex(); // Eat the ','.
5020     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5021       return true;
5022   }
5023 
5024   // Now we should have the closing ']'
5025   if (Parser.getTok().isNot(AsmToken::RBrac))
5026     return Error(Parser.getTok().getLoc(), "']' expected");
5027   E = Parser.getTok().getEndLoc();
5028   Parser.Lex(); // Eat right bracket token.
5029 
5030   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5031                                            ShiftType, ShiftImm, 0, isNegative,
5032                                            S, E));
5033 
5034   // If there's a pre-indexing writeback marker, '!', just add it as a token
5035   // operand.
5036   if (Parser.getTok().is(AsmToken::Exclaim)) {
5037     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5038     Parser.Lex(); // Eat the '!'.
5039   }
5040 
5041   return false;
5042 }
5043 
5044 /// parseMemRegOffsetShift - one of these two:
5045 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5046 ///   rrx
5047 /// return true if it parses a shift otherwise it returns false.
5048 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5049                                           unsigned &Amount) {
5050   MCAsmParser &Parser = getParser();
5051   SMLoc Loc = Parser.getTok().getLoc();
5052   const AsmToken &Tok = Parser.getTok();
5053   if (Tok.isNot(AsmToken::Identifier))
5054     return true;
5055   StringRef ShiftName = Tok.getString();
5056   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5057       ShiftName == "asl" || ShiftName == "ASL")
5058     St = ARM_AM::lsl;
5059   else if (ShiftName == "lsr" || ShiftName == "LSR")
5060     St = ARM_AM::lsr;
5061   else if (ShiftName == "asr" || ShiftName == "ASR")
5062     St = ARM_AM::asr;
5063   else if (ShiftName == "ror" || ShiftName == "ROR")
5064     St = ARM_AM::ror;
5065   else if (ShiftName == "rrx" || ShiftName == "RRX")
5066     St = ARM_AM::rrx;
5067   else
5068     return Error(Loc, "illegal shift operator");
5069   Parser.Lex(); // Eat shift type token.
5070 
5071   // rrx stands alone.
5072   Amount = 0;
5073   if (St != ARM_AM::rrx) {
5074     Loc = Parser.getTok().getLoc();
5075     // A '#' and a shift amount.
5076     const AsmToken &HashTok = Parser.getTok();
5077     if (HashTok.isNot(AsmToken::Hash) &&
5078         HashTok.isNot(AsmToken::Dollar))
5079       return Error(HashTok.getLoc(), "'#' expected");
5080     Parser.Lex(); // Eat hash token.
5081 
5082     const MCExpr *Expr;
5083     if (getParser().parseExpression(Expr))
5084       return true;
5085     // Range check the immediate.
5086     // lsl, ror: 0 <= imm <= 31
5087     // lsr, asr: 0 <= imm <= 32
5088     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5089     if (!CE)
5090       return Error(Loc, "shift amount must be an immediate");
5091     int64_t Imm = CE->getValue();
5092     if (Imm < 0 ||
5093         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5094         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5095       return Error(Loc, "immediate shift value out of range");
5096     // If <ShiftTy> #0, turn it into a no_shift.
5097     if (Imm == 0)
5098       St = ARM_AM::lsl;
5099     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5100     if (Imm == 32)
5101       Imm = 0;
5102     Amount = Imm;
5103   }
5104 
5105   return false;
5106 }
5107 
5108 /// parseFPImm - A floating point immediate expression operand.
5109 OperandMatchResultTy
5110 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5111   MCAsmParser &Parser = getParser();
5112   // Anything that can accept a floating point constant as an operand
5113   // needs to go through here, as the regular parseExpression is
5114   // integer only.
5115   //
5116   // This routine still creates a generic Immediate operand, containing
5117   // a bitcast of the 64-bit floating point value. The various operands
5118   // that accept floats can check whether the value is valid for them
5119   // via the standard is*() predicates.
5120 
5121   SMLoc S = Parser.getTok().getLoc();
5122 
5123   if (Parser.getTok().isNot(AsmToken::Hash) &&
5124       Parser.getTok().isNot(AsmToken::Dollar))
5125     return MatchOperand_NoMatch;
5126 
5127   // Disambiguate the VMOV forms that can accept an FP immediate.
5128   // vmov.f32 <sreg>, #imm
5129   // vmov.f64 <dreg>, #imm
5130   // vmov.f32 <dreg>, #imm  @ vector f32x2
5131   // vmov.f32 <qreg>, #imm  @ vector f32x4
5132   //
5133   // There are also the NEON VMOV instructions which expect an
5134   // integer constant. Make sure we don't try to parse an FPImm
5135   // for these:
5136   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5137   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5138   bool isVmovf = TyOp.isToken() &&
5139                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5140                   TyOp.getToken() == ".f16");
5141   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5142   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5143                                          Mnemonic.getToken() == "fconsts");
5144   if (!(isVmovf || isFconst))
5145     return MatchOperand_NoMatch;
5146 
5147   Parser.Lex(); // Eat '#' or '$'.
5148 
5149   // Handle negation, as that still comes through as a separate token.
5150   bool isNegative = false;
5151   if (Parser.getTok().is(AsmToken::Minus)) {
5152     isNegative = true;
5153     Parser.Lex();
5154   }
5155   const AsmToken &Tok = Parser.getTok();
5156   SMLoc Loc = Tok.getLoc();
5157   if (Tok.is(AsmToken::Real) && isVmovf) {
5158     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5159     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5160     // If we had a '-' in front, toggle the sign bit.
5161     IntVal ^= (uint64_t)isNegative << 31;
5162     Parser.Lex(); // Eat the token.
5163     Operands.push_back(ARMOperand::CreateImm(
5164           MCConstantExpr::create(IntVal, getContext()),
5165           S, Parser.getTok().getLoc()));
5166     return MatchOperand_Success;
5167   }
5168   // Also handle plain integers. Instructions which allow floating point
5169   // immediates also allow a raw encoded 8-bit value.
5170   if (Tok.is(AsmToken::Integer) && isFconst) {
5171     int64_t Val = Tok.getIntVal();
5172     Parser.Lex(); // Eat the token.
5173     if (Val > 255 || Val < 0) {
5174       Error(Loc, "encoded floating point value out of range");
5175       return MatchOperand_ParseFail;
5176     }
5177     float RealVal = ARM_AM::getFPImmFloat(Val);
5178     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5179 
5180     Operands.push_back(ARMOperand::CreateImm(
5181         MCConstantExpr::create(Val, getContext()), S,
5182         Parser.getTok().getLoc()));
5183     return MatchOperand_Success;
5184   }
5185 
5186   Error(Loc, "invalid floating point immediate");
5187   return MatchOperand_ParseFail;
5188 }
5189 
5190 /// Parse a arm instruction operand.  For now this parses the operand regardless
5191 /// of the mnemonic.
5192 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5193   MCAsmParser &Parser = getParser();
5194   SMLoc S, E;
5195 
5196   // Check if the current operand has a custom associated parser, if so, try to
5197   // custom parse the operand, or fallback to the general approach.
5198   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5199   if (ResTy == MatchOperand_Success)
5200     return false;
5201   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5202   // there was a match, but an error occurred, in which case, just return that
5203   // the operand parsing failed.
5204   if (ResTy == MatchOperand_ParseFail)
5205     return true;
5206 
5207   switch (getLexer().getKind()) {
5208   default:
5209     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5210     return true;
5211   case AsmToken::Identifier: {
5212     // If we've seen a branch mnemonic, the next operand must be a label.  This
5213     // is true even if the label is a register name.  So "br r1" means branch to
5214     // label "r1".
5215     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5216     if (!ExpectLabel) {
5217       if (!tryParseRegisterWithWriteBack(Operands))
5218         return false;
5219       int Res = tryParseShiftRegister(Operands);
5220       if (Res == 0) // success
5221         return false;
5222       else if (Res == -1) // irrecoverable error
5223         return true;
5224       // If this is VMRS, check for the apsr_nzcv operand.
5225       if (Mnemonic == "vmrs" &&
5226           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5227         S = Parser.getTok().getLoc();
5228         Parser.Lex();
5229         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5230         return false;
5231       }
5232     }
5233 
5234     // Fall though for the Identifier case that is not a register or a
5235     // special name.
5236   }
5237   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5238   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5239   case AsmToken::String:  // quoted label names.
5240   case AsmToken::Dot: {   // . as a branch target
5241     // This was not a register so parse other operands that start with an
5242     // identifier (like labels) as expressions and create them as immediates.
5243     const MCExpr *IdVal;
5244     S = Parser.getTok().getLoc();
5245     if (getParser().parseExpression(IdVal))
5246       return true;
5247     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5248     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5249     return false;
5250   }
5251   case AsmToken::LBrac:
5252     return parseMemory(Operands);
5253   case AsmToken::LCurly:
5254     return parseRegisterList(Operands);
5255   case AsmToken::Dollar:
5256   case AsmToken::Hash: {
5257     // #42 -> immediate.
5258     S = Parser.getTok().getLoc();
5259     Parser.Lex();
5260 
5261     if (Parser.getTok().isNot(AsmToken::Colon)) {
5262       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5263       const MCExpr *ImmVal;
5264       if (getParser().parseExpression(ImmVal))
5265         return true;
5266       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5267       if (CE) {
5268         int32_t Val = CE->getValue();
5269         if (isNegative && Val == 0)
5270           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5271       }
5272       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5273       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5274 
5275       // There can be a trailing '!' on operands that we want as a separate
5276       // '!' Token operand. Handle that here. For example, the compatibility
5277       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5278       if (Parser.getTok().is(AsmToken::Exclaim)) {
5279         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5280                                                    Parser.getTok().getLoc()));
5281         Parser.Lex(); // Eat exclaim token
5282       }
5283       return false;
5284     }
5285     // w/ a ':' after the '#', it's just like a plain ':'.
5286     LLVM_FALLTHROUGH;
5287   }
5288   case AsmToken::Colon: {
5289     S = Parser.getTok().getLoc();
5290     // ":lower16:" and ":upper16:" expression prefixes
5291     // FIXME: Check it's an expression prefix,
5292     // e.g. (FOO - :lower16:BAR) isn't legal.
5293     ARMMCExpr::VariantKind RefKind;
5294     if (parsePrefix(RefKind))
5295       return true;
5296 
5297     const MCExpr *SubExprVal;
5298     if (getParser().parseExpression(SubExprVal))
5299       return true;
5300 
5301     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5302                                               getContext());
5303     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5304     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5305     return false;
5306   }
5307   case AsmToken::Equal: {
5308     S = Parser.getTok().getLoc();
5309     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5310       return Error(S, "unexpected token in operand");
5311     Parser.Lex(); // Eat '='
5312     const MCExpr *SubExprVal;
5313     if (getParser().parseExpression(SubExprVal))
5314       return true;
5315     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5316 
5317     // execute-only: we assume that assembly programmers know what they are
5318     // doing and allow literal pool creation here
5319     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5320     return false;
5321   }
5322   }
5323 }
5324 
5325 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5326 //  :lower16: and :upper16:.
5327 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5328   MCAsmParser &Parser = getParser();
5329   RefKind = ARMMCExpr::VK_ARM_None;
5330 
5331   // consume an optional '#' (GNU compatibility)
5332   if (getLexer().is(AsmToken::Hash))
5333     Parser.Lex();
5334 
5335   // :lower16: and :upper16: modifiers
5336   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5337   Parser.Lex(); // Eat ':'
5338 
5339   if (getLexer().isNot(AsmToken::Identifier)) {
5340     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5341     return true;
5342   }
5343 
5344   enum {
5345     COFF = (1 << MCObjectFileInfo::IsCOFF),
5346     ELF = (1 << MCObjectFileInfo::IsELF),
5347     MACHO = (1 << MCObjectFileInfo::IsMachO),
5348     WASM = (1 << MCObjectFileInfo::IsWasm),
5349   };
5350   static const struct PrefixEntry {
5351     const char *Spelling;
5352     ARMMCExpr::VariantKind VariantKind;
5353     uint8_t SupportedFormats;
5354   } PrefixEntries[] = {
5355     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5356     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5357   };
5358 
5359   StringRef IDVal = Parser.getTok().getIdentifier();
5360 
5361   const auto &Prefix =
5362       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5363                    [&IDVal](const PrefixEntry &PE) {
5364                       return PE.Spelling == IDVal;
5365                    });
5366   if (Prefix == std::end(PrefixEntries)) {
5367     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5368     return true;
5369   }
5370 
5371   uint8_t CurrentFormat;
5372   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5373   case MCObjectFileInfo::IsMachO:
5374     CurrentFormat = MACHO;
5375     break;
5376   case MCObjectFileInfo::IsELF:
5377     CurrentFormat = ELF;
5378     break;
5379   case MCObjectFileInfo::IsCOFF:
5380     CurrentFormat = COFF;
5381     break;
5382   case MCObjectFileInfo::IsWasm:
5383     CurrentFormat = WASM;
5384     break;
5385   }
5386 
5387   if (~Prefix->SupportedFormats & CurrentFormat) {
5388     Error(Parser.getTok().getLoc(),
5389           "cannot represent relocation in the current file format");
5390     return true;
5391   }
5392 
5393   RefKind = Prefix->VariantKind;
5394   Parser.Lex();
5395 
5396   if (getLexer().isNot(AsmToken::Colon)) {
5397     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5398     return true;
5399   }
5400   Parser.Lex(); // Eat the last ':'
5401 
5402   return false;
5403 }
5404 
5405 /// \brief Given a mnemonic, split out possible predication code and carry
5406 /// setting letters to form a canonical mnemonic and flags.
5407 //
5408 // FIXME: Would be nice to autogen this.
5409 // FIXME: This is a bit of a maze of special cases.
5410 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5411                                       unsigned &PredicationCode,
5412                                       bool &CarrySetting,
5413                                       unsigned &ProcessorIMod,
5414                                       StringRef &ITMask) {
5415   PredicationCode = ARMCC::AL;
5416   CarrySetting = false;
5417   ProcessorIMod = 0;
5418 
5419   // Ignore some mnemonics we know aren't predicated forms.
5420   //
5421   // FIXME: Would be nice to autogen this.
5422   if ((Mnemonic == "movs" && isThumb()) ||
5423       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5424       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5425       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5426       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5427       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5428       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5429       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5430       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5431       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5432       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5433       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5434       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5435       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5436       Mnemonic == "bxns"  || Mnemonic == "blxns")
5437     return Mnemonic;
5438 
5439   // First, split out any predication code. Ignore mnemonics we know aren't
5440   // predicated but do have a carry-set and so weren't caught above.
5441   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5442       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5443       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5444       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5445     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5446       .Case("eq", ARMCC::EQ)
5447       .Case("ne", ARMCC::NE)
5448       .Case("hs", ARMCC::HS)
5449       .Case("cs", ARMCC::HS)
5450       .Case("lo", ARMCC::LO)
5451       .Case("cc", ARMCC::LO)
5452       .Case("mi", ARMCC::MI)
5453       .Case("pl", ARMCC::PL)
5454       .Case("vs", ARMCC::VS)
5455       .Case("vc", ARMCC::VC)
5456       .Case("hi", ARMCC::HI)
5457       .Case("ls", ARMCC::LS)
5458       .Case("ge", ARMCC::GE)
5459       .Case("lt", ARMCC::LT)
5460       .Case("gt", ARMCC::GT)
5461       .Case("le", ARMCC::LE)
5462       .Case("al", ARMCC::AL)
5463       .Default(~0U);
5464     if (CC != ~0U) {
5465       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5466       PredicationCode = CC;
5467     }
5468   }
5469 
5470   // Next, determine if we have a carry setting bit. We explicitly ignore all
5471   // the instructions we know end in 's'.
5472   if (Mnemonic.endswith("s") &&
5473       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5474         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5475         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5476         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5477         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5478         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5479         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5480         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5481         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5482         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5483         (Mnemonic == "movs" && isThumb()))) {
5484     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5485     CarrySetting = true;
5486   }
5487 
5488   // The "cps" instruction can have a interrupt mode operand which is glued into
5489   // the mnemonic. Check if this is the case, split it and parse the imod op
5490   if (Mnemonic.startswith("cps")) {
5491     // Split out any imod code.
5492     unsigned IMod =
5493       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5494       .Case("ie", ARM_PROC::IE)
5495       .Case("id", ARM_PROC::ID)
5496       .Default(~0U);
5497     if (IMod != ~0U) {
5498       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5499       ProcessorIMod = IMod;
5500     }
5501   }
5502 
5503   // The "it" instruction has the condition mask on the end of the mnemonic.
5504   if (Mnemonic.startswith("it")) {
5505     ITMask = Mnemonic.slice(2, Mnemonic.size());
5506     Mnemonic = Mnemonic.slice(0, 2);
5507   }
5508 
5509   return Mnemonic;
5510 }
5511 
5512 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5513 /// inclusion of carry set or predication code operands.
5514 //
5515 // FIXME: It would be nice to autogen this.
5516 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5517                                          bool &CanAcceptCarrySet,
5518                                          bool &CanAcceptPredicationCode) {
5519   CanAcceptCarrySet =
5520       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5521       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5522       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5523       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5524       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5525       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5526       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5527       (!isThumb() &&
5528        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5529         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5530 
5531   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5532       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5533       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5534       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5535       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5536       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5537       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5538       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5539       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5540       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5541       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5542       Mnemonic == "vmovx" || Mnemonic == "vins") {
5543     // These mnemonics are never predicable
5544     CanAcceptPredicationCode = false;
5545   } else if (!isThumb()) {
5546     // Some instructions are only predicable in Thumb mode
5547     CanAcceptPredicationCode =
5548         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5549         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5550         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5551         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5552         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5553         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5554         !Mnemonic.startswith("srs");
5555   } else if (isThumbOne()) {
5556     if (hasV6MOps())
5557       CanAcceptPredicationCode = Mnemonic != "movs";
5558     else
5559       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5560   } else
5561     CanAcceptPredicationCode = true;
5562 }
5563 
5564 // \brief Some Thumb instructions have two operand forms that are not
5565 // available as three operand, convert to two operand form if possible.
5566 //
5567 // FIXME: We would really like to be able to tablegen'erate this.
5568 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5569                                                  bool CarrySetting,
5570                                                  OperandVector &Operands) {
5571   if (Operands.size() != 6)
5572     return;
5573 
5574   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5575         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5576   if (!Op3.isReg() || !Op4.isReg())
5577     return;
5578 
5579   auto Op3Reg = Op3.getReg();
5580   auto Op4Reg = Op4.getReg();
5581 
5582   // For most Thumb2 cases we just generate the 3 operand form and reduce
5583   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5584   // won't accept SP or PC so we do the transformation here taking care
5585   // with immediate range in the 'add sp, sp #imm' case.
5586   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5587   if (isThumbTwo()) {
5588     if (Mnemonic != "add")
5589       return;
5590     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5591                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5592     if (!TryTransform) {
5593       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5594                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5595                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5596                        Op5.isImm() && !Op5.isImm0_508s4());
5597     }
5598     if (!TryTransform)
5599       return;
5600   } else if (!isThumbOne())
5601     return;
5602 
5603   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5604         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5605         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5606         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5607     return;
5608 
5609   // If first 2 operands of a 3 operand instruction are the same
5610   // then transform to 2 operand version of the same instruction
5611   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5612   bool Transform = Op3Reg == Op4Reg;
5613 
5614   // For communtative operations, we might be able to transform if we swap
5615   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5616   // as tADDrsp.
5617   const ARMOperand *LastOp = &Op5;
5618   bool Swap = false;
5619   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5620       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5621        Mnemonic == "and" || Mnemonic == "eor" ||
5622        Mnemonic == "adc" || Mnemonic == "orr")) {
5623     Swap = true;
5624     LastOp = &Op4;
5625     Transform = true;
5626   }
5627 
5628   // If both registers are the same then remove one of them from
5629   // the operand list, with certain exceptions.
5630   if (Transform) {
5631     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5632     // 2 operand forms don't exist.
5633     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5634         LastOp->isReg())
5635       Transform = false;
5636 
5637     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5638     // 3-bits because the ARMARM says not to.
5639     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5640       Transform = false;
5641   }
5642 
5643   if (Transform) {
5644     if (Swap)
5645       std::swap(Op4, Op5);
5646     Operands.erase(Operands.begin() + 3);
5647   }
5648 }
5649 
5650 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5651                                           OperandVector &Operands) {
5652   // FIXME: This is all horribly hacky. We really need a better way to deal
5653   // with optional operands like this in the matcher table.
5654 
5655   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5656   // another does not. Specifically, the MOVW instruction does not. So we
5657   // special case it here and remove the defaulted (non-setting) cc_out
5658   // operand if that's the instruction we're trying to match.
5659   //
5660   // We do this as post-processing of the explicit operands rather than just
5661   // conditionally adding the cc_out in the first place because we need
5662   // to check the type of the parsed immediate operand.
5663   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5664       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5665       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5666       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5667     return true;
5668 
5669   // Register-register 'add' for thumb does not have a cc_out operand
5670   // when there are only two register operands.
5671   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5672       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5673       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5674       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5675     return true;
5676   // Register-register 'add' for thumb does not have a cc_out operand
5677   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5678   // have to check the immediate range here since Thumb2 has a variant
5679   // that can handle a different range and has a cc_out operand.
5680   if (((isThumb() && Mnemonic == "add") ||
5681        (isThumbTwo() && Mnemonic == "sub")) &&
5682       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5683       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5684       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5685       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5686       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5687        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5688     return true;
5689   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5690   // imm0_4095 variant. That's the least-preferred variant when
5691   // selecting via the generic "add" mnemonic, so to know that we
5692   // should remove the cc_out operand, we have to explicitly check that
5693   // it's not one of the other variants. Ugh.
5694   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5695       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5696       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5697       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5698     // Nest conditions rather than one big 'if' statement for readability.
5699     //
5700     // If both registers are low, we're in an IT block, and the immediate is
5701     // in range, we should use encoding T1 instead, which has a cc_out.
5702     if (inITBlock() &&
5703         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5704         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5705         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5706       return false;
5707     // Check against T3. If the second register is the PC, this is an
5708     // alternate form of ADR, which uses encoding T4, so check for that too.
5709     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5710         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5711       return false;
5712 
5713     // Otherwise, we use encoding T4, which does not have a cc_out
5714     // operand.
5715     return true;
5716   }
5717 
5718   // The thumb2 multiply instruction doesn't have a CCOut register, so
5719   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5720   // use the 16-bit encoding or not.
5721   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5722       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5723       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5724       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5725       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5726       // If the registers aren't low regs, the destination reg isn't the
5727       // same as one of the source regs, or the cc_out operand is zero
5728       // outside of an IT block, we have to use the 32-bit encoding, so
5729       // remove the cc_out operand.
5730       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5731        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5732        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5733        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5734                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5735                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5736                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5737     return true;
5738 
5739   // Also check the 'mul' syntax variant that doesn't specify an explicit
5740   // destination register.
5741   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5742       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5743       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5744       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5745       // If the registers aren't low regs  or the cc_out operand is zero
5746       // outside of an IT block, we have to use the 32-bit encoding, so
5747       // remove the cc_out operand.
5748       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5749        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5750        !inITBlock()))
5751     return true;
5752 
5753 
5754 
5755   // Register-register 'add/sub' for thumb does not have a cc_out operand
5756   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5757   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5758   // right, this will result in better diagnostics (which operand is off)
5759   // anyway.
5760   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5761       (Operands.size() == 5 || Operands.size() == 6) &&
5762       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5763       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5764       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5765       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5766        (Operands.size() == 6 &&
5767         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5768     return true;
5769 
5770   return false;
5771 }
5772 
5773 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5774                                               OperandVector &Operands) {
5775   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5776   unsigned RegIdx = 3;
5777   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5778       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5779        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5780     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5781         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5782          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5783       RegIdx = 4;
5784 
5785     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5786         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5787              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5788          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5789              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5790       return true;
5791   }
5792   return false;
5793 }
5794 
5795 static bool isDataTypeToken(StringRef Tok) {
5796   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5797     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5798     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5799     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5800     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5801     Tok == ".f" || Tok == ".d";
5802 }
5803 
5804 // FIXME: This bit should probably be handled via an explicit match class
5805 // in the .td files that matches the suffix instead of having it be
5806 // a literal string token the way it is now.
5807 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5808   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5809 }
5810 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5811                                  unsigned VariantID);
5812 
5813 static bool RequiresVFPRegListValidation(StringRef Inst,
5814                                          bool &AcceptSinglePrecisionOnly,
5815                                          bool &AcceptDoublePrecisionOnly) {
5816   if (Inst.size() < 7)
5817     return false;
5818 
5819   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5820     StringRef AddressingMode = Inst.substr(4, 2);
5821     if (AddressingMode == "ia" || AddressingMode == "db" ||
5822         AddressingMode == "ea" || AddressingMode == "fd") {
5823       AcceptSinglePrecisionOnly = Inst[6] == 's';
5824       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5825       return true;
5826     }
5827   }
5828 
5829   return false;
5830 }
5831 
5832 /// Parse an arm instruction mnemonic followed by its operands.
5833 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5834                                     SMLoc NameLoc, OperandVector &Operands) {
5835   MCAsmParser &Parser = getParser();
5836   // FIXME: Can this be done via tablegen in some fashion?
5837   bool RequireVFPRegisterListCheck;
5838   bool AcceptSinglePrecisionOnly;
5839   bool AcceptDoublePrecisionOnly;
5840   RequireVFPRegisterListCheck =
5841     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5842                                  AcceptDoublePrecisionOnly);
5843 
5844   // Apply mnemonic aliases before doing anything else, as the destination
5845   // mnemonic may include suffices and we want to handle them normally.
5846   // The generic tblgen'erated code does this later, at the start of
5847   // MatchInstructionImpl(), but that's too late for aliases that include
5848   // any sort of suffix.
5849   uint64_t AvailableFeatures = getAvailableFeatures();
5850   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5851   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5852 
5853   // First check for the ARM-specific .req directive.
5854   if (Parser.getTok().is(AsmToken::Identifier) &&
5855       Parser.getTok().getIdentifier() == ".req") {
5856     parseDirectiveReq(Name, NameLoc);
5857     // We always return 'error' for this, as we're done with this
5858     // statement and don't need to match the 'instruction."
5859     return true;
5860   }
5861 
5862   // Create the leading tokens for the mnemonic, split by '.' characters.
5863   size_t Start = 0, Next = Name.find('.');
5864   StringRef Mnemonic = Name.slice(Start, Next);
5865 
5866   // Split out the predication code and carry setting flag from the mnemonic.
5867   unsigned PredicationCode;
5868   unsigned ProcessorIMod;
5869   bool CarrySetting;
5870   StringRef ITMask;
5871   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5872                            ProcessorIMod, ITMask);
5873 
5874   // In Thumb1, only the branch (B) instruction can be predicated.
5875   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5876     return Error(NameLoc, "conditional execution not supported in Thumb1");
5877   }
5878 
5879   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5880 
5881   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5882   // is the mask as it will be for the IT encoding if the conditional
5883   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5884   // where the conditional bit0 is zero, the instruction post-processing
5885   // will adjust the mask accordingly.
5886   if (Mnemonic == "it") {
5887     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5888     if (ITMask.size() > 3) {
5889       return Error(Loc, "too many conditions on IT instruction");
5890     }
5891     unsigned Mask = 8;
5892     for (unsigned i = ITMask.size(); i != 0; --i) {
5893       char pos = ITMask[i - 1];
5894       if (pos != 't' && pos != 'e') {
5895         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5896       }
5897       Mask >>= 1;
5898       if (ITMask[i - 1] == 't')
5899         Mask |= 8;
5900     }
5901     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5902   }
5903 
5904   // FIXME: This is all a pretty gross hack. We should automatically handle
5905   // optional operands like this via tblgen.
5906 
5907   // Next, add the CCOut and ConditionCode operands, if needed.
5908   //
5909   // For mnemonics which can ever incorporate a carry setting bit or predication
5910   // code, our matching model involves us always generating CCOut and
5911   // ConditionCode operands to match the mnemonic "as written" and then we let
5912   // the matcher deal with finding the right instruction or generating an
5913   // appropriate error.
5914   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5915   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5916 
5917   // If we had a carry-set on an instruction that can't do that, issue an
5918   // error.
5919   if (!CanAcceptCarrySet && CarrySetting) {
5920     return Error(NameLoc, "instruction '" + Mnemonic +
5921                  "' can not set flags, but 's' suffix specified");
5922   }
5923   // If we had a predication code on an instruction that can't do that, issue an
5924   // error.
5925   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5926     return Error(NameLoc, "instruction '" + Mnemonic +
5927                  "' is not predicable, but condition code specified");
5928   }
5929 
5930   // Add the carry setting operand, if necessary.
5931   if (CanAcceptCarrySet) {
5932     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5933     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5934                                                Loc));
5935   }
5936 
5937   // Add the predication code operand, if necessary.
5938   if (CanAcceptPredicationCode) {
5939     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5940                                       CarrySetting);
5941     Operands.push_back(ARMOperand::CreateCondCode(
5942                          ARMCC::CondCodes(PredicationCode), Loc));
5943   }
5944 
5945   // Add the processor imod operand, if necessary.
5946   if (ProcessorIMod) {
5947     Operands.push_back(ARMOperand::CreateImm(
5948           MCConstantExpr::create(ProcessorIMod, getContext()),
5949                                  NameLoc, NameLoc));
5950   } else if (Mnemonic == "cps" && isMClass()) {
5951     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5952   }
5953 
5954   // Add the remaining tokens in the mnemonic.
5955   while (Next != StringRef::npos) {
5956     Start = Next;
5957     Next = Name.find('.', Start + 1);
5958     StringRef ExtraToken = Name.slice(Start, Next);
5959 
5960     // Some NEON instructions have an optional datatype suffix that is
5961     // completely ignored. Check for that.
5962     if (isDataTypeToken(ExtraToken) &&
5963         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5964       continue;
5965 
5966     // For for ARM mode generate an error if the .n qualifier is used.
5967     if (ExtraToken == ".n" && !isThumb()) {
5968       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5969       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5970                    "arm mode");
5971     }
5972 
5973     // The .n qualifier is always discarded as that is what the tables
5974     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5975     // so discard it to avoid errors that can be caused by the matcher.
5976     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5977       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5978       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5979     }
5980   }
5981 
5982   // Read the remaining operands.
5983   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5984     // Read the first operand.
5985     if (parseOperand(Operands, Mnemonic)) {
5986       return true;
5987     }
5988 
5989     while (parseOptionalToken(AsmToken::Comma)) {
5990       // Parse and remember the operand.
5991       if (parseOperand(Operands, Mnemonic)) {
5992         return true;
5993       }
5994     }
5995   }
5996 
5997   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
5998     return true;
5999 
6000   if (RequireVFPRegisterListCheck) {
6001     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
6002     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
6003       return Error(Op.getStartLoc(),
6004                    "VFP/Neon single precision register expected");
6005     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
6006       return Error(Op.getStartLoc(),
6007                    "VFP/Neon double precision register expected");
6008   }
6009 
6010   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6011 
6012   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6013   // do and don't have a cc_out optional-def operand. With some spot-checks
6014   // of the operand list, we can figure out which variant we're trying to
6015   // parse and adjust accordingly before actually matching. We shouldn't ever
6016   // try to remove a cc_out operand that was explicitly set on the
6017   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6018   // table driven matcher doesn't fit well with the ARM instruction set.
6019   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6020     Operands.erase(Operands.begin() + 1);
6021 
6022   // Some instructions have the same mnemonic, but don't always
6023   // have a predicate. Distinguish them here and delete the
6024   // predicate if needed.
6025   if (shouldOmitPredicateOperand(Mnemonic, Operands))
6026     Operands.erase(Operands.begin() + 1);
6027 
6028   // ARM mode 'blx' need special handling, as the register operand version
6029   // is predicable, but the label operand version is not. So, we can't rely
6030   // on the Mnemonic based checking to correctly figure out when to put
6031   // a k_CondCode operand in the list. If we're trying to match the label
6032   // version, remove the k_CondCode operand here.
6033   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6034       static_cast<ARMOperand &>(*Operands[2]).isImm())
6035     Operands.erase(Operands.begin() + 1);
6036 
6037   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6038   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6039   // a single GPRPair reg operand is used in the .td file to replace the two
6040   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6041   // expressed as a GPRPair, so we have to manually merge them.
6042   // FIXME: We would really like to be able to tablegen'erate this.
6043   if (!isThumb() && Operands.size() > 4 &&
6044       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6045        Mnemonic == "stlexd")) {
6046     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6047     unsigned Idx = isLoad ? 2 : 3;
6048     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6049     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6050 
6051     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6052     // Adjust only if Op1 and Op2 are GPRs.
6053     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6054         MRC.contains(Op2.getReg())) {
6055       unsigned Reg1 = Op1.getReg();
6056       unsigned Reg2 = Op2.getReg();
6057       unsigned Rt = MRI->getEncodingValue(Reg1);
6058       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6059 
6060       // Rt2 must be Rt + 1 and Rt must be even.
6061       if (Rt + 1 != Rt2 || (Rt & 1)) {
6062         return Error(Op2.getStartLoc(),
6063                      isLoad ? "destination operands must be sequential"
6064                             : "source operands must be sequential");
6065       }
6066       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6067           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6068       Operands[Idx] =
6069           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6070       Operands.erase(Operands.begin() + Idx + 1);
6071     }
6072   }
6073 
6074   // GNU Assembler extension (compatibility)
6075   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
6076     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6077     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6078     if (Op3.isMem()) {
6079       assert(Op2.isReg() && "expected register argument");
6080 
6081       unsigned SuperReg = MRI->getMatchingSuperReg(
6082           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
6083 
6084       assert(SuperReg && "expected register pair");
6085 
6086       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
6087 
6088       Operands.insert(
6089           Operands.begin() + 3,
6090           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6091     }
6092   }
6093 
6094   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6095   // does not fit with other "subs" and tblgen.
6096   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6097   // so the Mnemonic is the original name "subs" and delete the predicate
6098   // operand so it will match the table entry.
6099   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6100       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6101       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6102       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6103       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6104       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6105     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6106     Operands.erase(Operands.begin() + 1);
6107   }
6108   return false;
6109 }
6110 
6111 // Validate context-sensitive operand constraints.
6112 
6113 // return 'true' if register list contains non-low GPR registers,
6114 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6115 // 'containsReg' to true.
6116 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6117                                  unsigned Reg, unsigned HiReg,
6118                                  bool &containsReg) {
6119   containsReg = false;
6120   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6121     unsigned OpReg = Inst.getOperand(i).getReg();
6122     if (OpReg == Reg)
6123       containsReg = true;
6124     // Anything other than a low register isn't legal here.
6125     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6126       return true;
6127   }
6128   return false;
6129 }
6130 
6131 // Check if the specified regisgter is in the register list of the inst,
6132 // starting at the indicated operand number.
6133 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6134   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6135     unsigned OpReg = Inst.getOperand(i).getReg();
6136     if (OpReg == Reg)
6137       return true;
6138   }
6139   return false;
6140 }
6141 
6142 // Return true if instruction has the interesting property of being
6143 // allowed in IT blocks, but not being predicable.
6144 static bool instIsBreakpoint(const MCInst &Inst) {
6145     return Inst.getOpcode() == ARM::tBKPT ||
6146            Inst.getOpcode() == ARM::BKPT ||
6147            Inst.getOpcode() == ARM::tHLT ||
6148            Inst.getOpcode() == ARM::HLT;
6149 
6150 }
6151 
6152 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6153                                        const OperandVector &Operands,
6154                                        unsigned ListNo, bool IsARPop) {
6155   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6156   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6157 
6158   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6159   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6160   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6161 
6162   if (!IsARPop && ListContainsSP)
6163     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6164                  "SP may not be in the register list");
6165   else if (ListContainsPC && ListContainsLR)
6166     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6167                  "PC and LR may not be in the register list simultaneously");
6168   return false;
6169 }
6170 
6171 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6172                                        const OperandVector &Operands,
6173                                        unsigned ListNo) {
6174   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6175   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6176 
6177   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6178   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6179 
6180   if (ListContainsSP && ListContainsPC)
6181     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6182                  "SP and PC may not be in the register list");
6183   else if (ListContainsSP)
6184     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6185                  "SP may not be in the register list");
6186   else if (ListContainsPC)
6187     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6188                  "PC may not be in the register list");
6189   return false;
6190 }
6191 
6192 // FIXME: We would really like to be able to tablegen'erate this.
6193 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6194                                        const OperandVector &Operands) {
6195   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6196   SMLoc Loc = Operands[0]->getStartLoc();
6197 
6198   // Check the IT block state first.
6199   // NOTE: BKPT and HLT instructions have the interesting property of being
6200   // allowed in IT blocks, but not being predicable. They just always execute.
6201   if (inITBlock() && !instIsBreakpoint(Inst)) {
6202     // The instruction must be predicable.
6203     if (!MCID.isPredicable())
6204       return Error(Loc, "instructions in IT block must be predicable");
6205     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6206     if (Cond != currentITCond()) {
6207       // Find the condition code Operand to get its SMLoc information.
6208       SMLoc CondLoc;
6209       for (unsigned I = 1; I < Operands.size(); ++I)
6210         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6211           CondLoc = Operands[I]->getStartLoc();
6212       return Error(CondLoc, "incorrect condition in IT block; got '" +
6213                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6214                    "', but expected '" +
6215                    ARMCondCodeToString(ARMCC::CondCodes(currentITCond())) + "'");
6216     }
6217   // Check for non-'al' condition codes outside of the IT block.
6218   } else if (isThumbTwo() && MCID.isPredicable() &&
6219              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6220              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6221              Inst.getOpcode() != ARM::t2Bcc) {
6222     return Error(Loc, "predicated instructions must be in IT block");
6223   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6224              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6225                  ARMCC::AL) {
6226     return Warning(Loc, "predicated instructions should be in IT block");
6227   }
6228 
6229   // PC-setting instructions in an IT block, but not the last instruction of
6230   // the block, are UNPREDICTABLE.
6231   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6232     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6233   }
6234 
6235   const unsigned Opcode = Inst.getOpcode();
6236   switch (Opcode) {
6237   case ARM::LDRD:
6238   case ARM::LDRD_PRE:
6239   case ARM::LDRD_POST: {
6240     const unsigned RtReg = Inst.getOperand(0).getReg();
6241 
6242     // Rt can't be R14.
6243     if (RtReg == ARM::LR)
6244       return Error(Operands[3]->getStartLoc(),
6245                    "Rt can't be R14");
6246 
6247     const unsigned Rt = MRI->getEncodingValue(RtReg);
6248     // Rt must be even-numbered.
6249     if ((Rt & 1) == 1)
6250       return Error(Operands[3]->getStartLoc(),
6251                    "Rt must be even-numbered");
6252 
6253     // Rt2 must be Rt + 1.
6254     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6255     if (Rt2 != Rt + 1)
6256       return Error(Operands[3]->getStartLoc(),
6257                    "destination operands must be sequential");
6258 
6259     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6260       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6261       // For addressing modes with writeback, the base register needs to be
6262       // different from the destination registers.
6263       if (Rn == Rt || Rn == Rt2)
6264         return Error(Operands[3]->getStartLoc(),
6265                      "base register needs to be different from destination "
6266                      "registers");
6267     }
6268 
6269     return false;
6270   }
6271   case ARM::t2LDRDi8:
6272   case ARM::t2LDRD_PRE:
6273   case ARM::t2LDRD_POST: {
6274     // Rt2 must be different from Rt.
6275     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6276     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6277     if (Rt2 == Rt)
6278       return Error(Operands[3]->getStartLoc(),
6279                    "destination operands can't be identical");
6280     return false;
6281   }
6282   case ARM::t2BXJ: {
6283     const unsigned RmReg = Inst.getOperand(0).getReg();
6284     // Rm = SP is no longer unpredictable in v8-A
6285     if (RmReg == ARM::SP && !hasV8Ops())
6286       return Error(Operands[2]->getStartLoc(),
6287                    "r13 (SP) is an unpredictable operand to BXJ");
6288     return false;
6289   }
6290   case ARM::STRD: {
6291     // Rt2 must be Rt + 1.
6292     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6293     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6294     if (Rt2 != Rt + 1)
6295       return Error(Operands[3]->getStartLoc(),
6296                    "source operands must be sequential");
6297     return false;
6298   }
6299   case ARM::STRD_PRE:
6300   case ARM::STRD_POST: {
6301     // Rt2 must be Rt + 1.
6302     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6303     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6304     if (Rt2 != Rt + 1)
6305       return Error(Operands[3]->getStartLoc(),
6306                    "source operands must be sequential");
6307     return false;
6308   }
6309   case ARM::STR_PRE_IMM:
6310   case ARM::STR_PRE_REG:
6311   case ARM::STR_POST_IMM:
6312   case ARM::STR_POST_REG:
6313   case ARM::STRH_PRE:
6314   case ARM::STRH_POST:
6315   case ARM::STRB_PRE_IMM:
6316   case ARM::STRB_PRE_REG:
6317   case ARM::STRB_POST_IMM:
6318   case ARM::STRB_POST_REG: {
6319     // Rt must be different from Rn.
6320     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6321     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6322 
6323     if (Rt == Rn)
6324       return Error(Operands[3]->getStartLoc(),
6325                    "source register and base register can't be identical");
6326     return false;
6327   }
6328   case ARM::LDR_PRE_IMM:
6329   case ARM::LDR_PRE_REG:
6330   case ARM::LDR_POST_IMM:
6331   case ARM::LDR_POST_REG:
6332   case ARM::LDRH_PRE:
6333   case ARM::LDRH_POST:
6334   case ARM::LDRSH_PRE:
6335   case ARM::LDRSH_POST:
6336   case ARM::LDRB_PRE_IMM:
6337   case ARM::LDRB_PRE_REG:
6338   case ARM::LDRB_POST_IMM:
6339   case ARM::LDRB_POST_REG:
6340   case ARM::LDRSB_PRE:
6341   case ARM::LDRSB_POST: {
6342     // Rt must be different from Rn.
6343     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6344     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6345 
6346     if (Rt == Rn)
6347       return Error(Operands[3]->getStartLoc(),
6348                    "destination register and base register can't be identical");
6349     return false;
6350   }
6351   case ARM::SBFX:
6352   case ARM::UBFX: {
6353     // Width must be in range [1, 32-lsb].
6354     unsigned LSB = Inst.getOperand(2).getImm();
6355     unsigned Widthm1 = Inst.getOperand(3).getImm();
6356     if (Widthm1 >= 32 - LSB)
6357       return Error(Operands[5]->getStartLoc(),
6358                    "bitfield width must be in range [1,32-lsb]");
6359     return false;
6360   }
6361   // Notionally handles ARM::tLDMIA_UPD too.
6362   case ARM::tLDMIA: {
6363     // If we're parsing Thumb2, the .w variant is available and handles
6364     // most cases that are normally illegal for a Thumb1 LDM instruction.
6365     // We'll make the transformation in processInstruction() if necessary.
6366     //
6367     // Thumb LDM instructions are writeback iff the base register is not
6368     // in the register list.
6369     unsigned Rn = Inst.getOperand(0).getReg();
6370     bool HasWritebackToken =
6371         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6372          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6373     bool ListContainsBase;
6374     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6375       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6376                    "registers must be in range r0-r7");
6377     // If we should have writeback, then there should be a '!' token.
6378     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6379       return Error(Operands[2]->getStartLoc(),
6380                    "writeback operator '!' expected");
6381     // If we should not have writeback, there must not be a '!'. This is
6382     // true even for the 32-bit wide encodings.
6383     if (ListContainsBase && HasWritebackToken)
6384       return Error(Operands[3]->getStartLoc(),
6385                    "writeback operator '!' not allowed when base register "
6386                    "in register list");
6387 
6388     if (validatetLDMRegList(Inst, Operands, 3))
6389       return true;
6390     break;
6391   }
6392   case ARM::LDMIA_UPD:
6393   case ARM::LDMDB_UPD:
6394   case ARM::LDMIB_UPD:
6395   case ARM::LDMDA_UPD:
6396     // ARM variants loading and updating the same register are only officially
6397     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6398     if (!hasV7Ops())
6399       break;
6400     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6401       return Error(Operands.back()->getStartLoc(),
6402                    "writeback register not allowed in register list");
6403     break;
6404   case ARM::t2LDMIA:
6405   case ARM::t2LDMDB:
6406     if (validatetLDMRegList(Inst, Operands, 3))
6407       return true;
6408     break;
6409   case ARM::t2STMIA:
6410   case ARM::t2STMDB:
6411     if (validatetSTMRegList(Inst, Operands, 3))
6412       return true;
6413     break;
6414   case ARM::t2LDMIA_UPD:
6415   case ARM::t2LDMDB_UPD:
6416   case ARM::t2STMIA_UPD:
6417   case ARM::t2STMDB_UPD: {
6418     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6419       return Error(Operands.back()->getStartLoc(),
6420                    "writeback register not allowed in register list");
6421 
6422     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6423       if (validatetLDMRegList(Inst, Operands, 3))
6424         return true;
6425     } else {
6426       if (validatetSTMRegList(Inst, Operands, 3))
6427         return true;
6428     }
6429     break;
6430   }
6431   case ARM::sysLDMIA_UPD:
6432   case ARM::sysLDMDA_UPD:
6433   case ARM::sysLDMDB_UPD:
6434   case ARM::sysLDMIB_UPD:
6435     if (!listContainsReg(Inst, 3, ARM::PC))
6436       return Error(Operands[4]->getStartLoc(),
6437                    "writeback register only allowed on system LDM "
6438                    "if PC in register-list");
6439     break;
6440   case ARM::sysSTMIA_UPD:
6441   case ARM::sysSTMDA_UPD:
6442   case ARM::sysSTMDB_UPD:
6443   case ARM::sysSTMIB_UPD:
6444     return Error(Operands[2]->getStartLoc(),
6445                  "system STM cannot have writeback register");
6446   case ARM::tMUL: {
6447     // The second source operand must be the same register as the destination
6448     // operand.
6449     //
6450     // In this case, we must directly check the parsed operands because the
6451     // cvtThumbMultiply() function is written in such a way that it guarantees
6452     // this first statement is always true for the new Inst.  Essentially, the
6453     // destination is unconditionally copied into the second source operand
6454     // without checking to see if it matches what we actually parsed.
6455     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6456                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6457         (((ARMOperand &)*Operands[3]).getReg() !=
6458          ((ARMOperand &)*Operands[4]).getReg())) {
6459       return Error(Operands[3]->getStartLoc(),
6460                    "destination register must match source register");
6461     }
6462     break;
6463   }
6464   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6465   // so only issue a diagnostic for thumb1. The instructions will be
6466   // switched to the t2 encodings in processInstruction() if necessary.
6467   case ARM::tPOP: {
6468     bool ListContainsBase;
6469     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6470         !isThumbTwo())
6471       return Error(Operands[2]->getStartLoc(),
6472                    "registers must be in range r0-r7 or pc");
6473     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6474       return true;
6475     break;
6476   }
6477   case ARM::tPUSH: {
6478     bool ListContainsBase;
6479     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6480         !isThumbTwo())
6481       return Error(Operands[2]->getStartLoc(),
6482                    "registers must be in range r0-r7 or lr");
6483     if (validatetSTMRegList(Inst, Operands, 2))
6484       return true;
6485     break;
6486   }
6487   case ARM::tSTMIA_UPD: {
6488     bool ListContainsBase, InvalidLowList;
6489     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6490                                           0, ListContainsBase);
6491     if (InvalidLowList && !isThumbTwo())
6492       return Error(Operands[4]->getStartLoc(),
6493                    "registers must be in range r0-r7");
6494 
6495     // This would be converted to a 32-bit stm, but that's not valid if the
6496     // writeback register is in the list.
6497     if (InvalidLowList && ListContainsBase)
6498       return Error(Operands[4]->getStartLoc(),
6499                    "writeback operator '!' not allowed when base register "
6500                    "in register list");
6501 
6502     if (validatetSTMRegList(Inst, Operands, 4))
6503       return true;
6504     break;
6505   }
6506   case ARM::tADDrSP: {
6507     // If the non-SP source operand and the destination operand are not the
6508     // same, we need thumb2 (for the wide encoding), or we have an error.
6509     if (!isThumbTwo() &&
6510         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6511       return Error(Operands[4]->getStartLoc(),
6512                    "source register must be the same as destination");
6513     }
6514     break;
6515   }
6516   // Final range checking for Thumb unconditional branch instructions.
6517   case ARM::tB:
6518     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6519       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6520     break;
6521   case ARM::t2B: {
6522     int op = (Operands[2]->isImm()) ? 2 : 3;
6523     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6524       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6525     break;
6526   }
6527   // Final range checking for Thumb conditional branch instructions.
6528   case ARM::tBcc:
6529     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6530       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6531     break;
6532   case ARM::t2Bcc: {
6533     int Op = (Operands[2]->isImm()) ? 2 : 3;
6534     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6535       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6536     break;
6537   }
6538   case ARM::tCBZ:
6539   case ARM::tCBNZ: {
6540     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6541       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6542     break;
6543   }
6544   case ARM::MOVi16:
6545   case ARM::MOVTi16:
6546   case ARM::t2MOVi16:
6547   case ARM::t2MOVTi16:
6548     {
6549     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6550     // especially when we turn it into a movw and the expression <symbol> does
6551     // not have a :lower16: or :upper16 as part of the expression.  We don't
6552     // want the behavior of silently truncating, which can be unexpected and
6553     // lead to bugs that are difficult to find since this is an easy mistake
6554     // to make.
6555     int i = (Operands[3]->isImm()) ? 3 : 4;
6556     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6557     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6558     if (CE) break;
6559     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6560     if (!E) break;
6561     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6562     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6563                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6564       return Error(
6565           Op.getStartLoc(),
6566           "immediate expression for mov requires :lower16: or :upper16");
6567     break;
6568   }
6569   case ARM::HINT:
6570   case ARM::t2HINT: {
6571     if (hasRAS()) {
6572       // ESB is not predicable (pred must be AL)
6573       unsigned Imm8 = Inst.getOperand(0).getImm();
6574       unsigned Pred = Inst.getOperand(1).getImm();
6575       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6576         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6577                                                  "predicable, but condition "
6578                                                  "code specified");
6579     }
6580     // Without the RAS extension, this behaves as any other unallocated hint.
6581     break;
6582   }
6583   }
6584 
6585   return false;
6586 }
6587 
6588 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6589   switch(Opc) {
6590   default: llvm_unreachable("unexpected opcode!");
6591   // VST1LN
6592   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6593   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6594   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6595   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6596   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6597   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6598   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6599   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6600   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6601 
6602   // VST2LN
6603   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6604   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6605   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6606   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6607   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6608 
6609   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6610   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6611   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6612   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6613   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6614 
6615   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6616   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6617   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6618   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6619   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6620 
6621   // VST3LN
6622   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6623   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6624   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6625   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6626   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6627   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6628   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6629   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6630   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6631   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6632   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6633   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6634   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6635   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6636   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6637 
6638   // VST3
6639   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6640   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6641   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6642   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6643   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6644   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6645   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6646   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6647   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6648   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6649   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6650   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6651   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6652   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6653   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6654   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6655   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6656   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6657 
6658   // VST4LN
6659   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6660   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6661   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6662   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6663   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6664   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6665   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6666   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6667   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6668   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6669   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6670   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6671   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6672   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6673   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6674 
6675   // VST4
6676   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6677   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6678   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6679   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6680   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6681   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6682   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6683   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6684   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6685   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6686   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6687   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6688   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6689   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6690   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6691   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6692   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6693   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6694   }
6695 }
6696 
6697 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6698   switch(Opc) {
6699   default: llvm_unreachable("unexpected opcode!");
6700   // VLD1LN
6701   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6702   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6703   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6704   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6705   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6706   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6707   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6708   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6709   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6710 
6711   // VLD2LN
6712   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6713   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6714   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6715   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6716   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6717   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6718   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6719   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6720   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6721   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6722   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6723   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6724   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6725   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6726   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6727 
6728   // VLD3DUP
6729   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6730   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6731   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6732   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6733   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6734   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6735   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6736   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6737   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6738   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6739   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6740   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6741   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6742   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6743   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6744   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6745   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6746   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6747 
6748   // VLD3LN
6749   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6750   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6751   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6752   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6753   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6754   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6755   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6756   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6757   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6758   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6759   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6760   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6761   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6762   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6763   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6764 
6765   // VLD3
6766   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6767   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6768   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6769   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6770   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6771   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6772   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6773   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6774   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6775   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6776   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6777   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6778   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6779   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6780   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6781   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6782   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6783   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6784 
6785   // VLD4LN
6786   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6787   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6788   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6789   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6790   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6791   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6792   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6793   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6794   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6795   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6796   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6797   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6798   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6799   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6800   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6801 
6802   // VLD4DUP
6803   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6804   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6805   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6806   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6807   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6808   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6809   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6810   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6811   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6812   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6813   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6814   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6815   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6816   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6817   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6818   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6819   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6820   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6821 
6822   // VLD4
6823   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6824   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6825   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6826   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6827   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6828   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6829   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6830   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6831   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6832   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6833   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6834   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6835   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6836   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6837   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6838   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6839   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6840   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6841   }
6842 }
6843 
6844 bool ARMAsmParser::processInstruction(MCInst &Inst,
6845                                       const OperandVector &Operands,
6846                                       MCStreamer &Out) {
6847   switch (Inst.getOpcode()) {
6848   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6849   case ARM::LDRT_POST:
6850   case ARM::LDRBT_POST: {
6851     const unsigned Opcode =
6852       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6853                                            : ARM::LDRBT_POST_IMM;
6854     MCInst TmpInst;
6855     TmpInst.setOpcode(Opcode);
6856     TmpInst.addOperand(Inst.getOperand(0));
6857     TmpInst.addOperand(Inst.getOperand(1));
6858     TmpInst.addOperand(Inst.getOperand(1));
6859     TmpInst.addOperand(MCOperand::createReg(0));
6860     TmpInst.addOperand(MCOperand::createImm(0));
6861     TmpInst.addOperand(Inst.getOperand(2));
6862     TmpInst.addOperand(Inst.getOperand(3));
6863     Inst = TmpInst;
6864     return true;
6865   }
6866   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6867   case ARM::STRT_POST:
6868   case ARM::STRBT_POST: {
6869     const unsigned Opcode =
6870       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6871                                            : ARM::STRBT_POST_IMM;
6872     MCInst TmpInst;
6873     TmpInst.setOpcode(Opcode);
6874     TmpInst.addOperand(Inst.getOperand(1));
6875     TmpInst.addOperand(Inst.getOperand(0));
6876     TmpInst.addOperand(Inst.getOperand(1));
6877     TmpInst.addOperand(MCOperand::createReg(0));
6878     TmpInst.addOperand(MCOperand::createImm(0));
6879     TmpInst.addOperand(Inst.getOperand(2));
6880     TmpInst.addOperand(Inst.getOperand(3));
6881     Inst = TmpInst;
6882     return true;
6883   }
6884   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6885   case ARM::ADDri: {
6886     if (Inst.getOperand(1).getReg() != ARM::PC ||
6887         Inst.getOperand(5).getReg() != 0 ||
6888         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6889       return false;
6890     MCInst TmpInst;
6891     TmpInst.setOpcode(ARM::ADR);
6892     TmpInst.addOperand(Inst.getOperand(0));
6893     if (Inst.getOperand(2).isImm()) {
6894       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6895       // before passing it to the ADR instruction.
6896       unsigned Enc = Inst.getOperand(2).getImm();
6897       TmpInst.addOperand(MCOperand::createImm(
6898         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6899     } else {
6900       // Turn PC-relative expression into absolute expression.
6901       // Reading PC provides the start of the current instruction + 8 and
6902       // the transform to adr is biased by that.
6903       MCSymbol *Dot = getContext().createTempSymbol();
6904       Out.EmitLabel(Dot);
6905       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6906       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6907                                                      MCSymbolRefExpr::VK_None,
6908                                                      getContext());
6909       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6910       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6911                                                      getContext());
6912       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6913                                                         getContext());
6914       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6915     }
6916     TmpInst.addOperand(Inst.getOperand(3));
6917     TmpInst.addOperand(Inst.getOperand(4));
6918     Inst = TmpInst;
6919     return true;
6920   }
6921   // Aliases for alternate PC+imm syntax of LDR instructions.
6922   case ARM::t2LDRpcrel:
6923     // Select the narrow version if the immediate will fit.
6924     if (Inst.getOperand(1).getImm() > 0 &&
6925         Inst.getOperand(1).getImm() <= 0xff &&
6926         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6927           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
6928       Inst.setOpcode(ARM::tLDRpci);
6929     else
6930       Inst.setOpcode(ARM::t2LDRpci);
6931     return true;
6932   case ARM::t2LDRBpcrel:
6933     Inst.setOpcode(ARM::t2LDRBpci);
6934     return true;
6935   case ARM::t2LDRHpcrel:
6936     Inst.setOpcode(ARM::t2LDRHpci);
6937     return true;
6938   case ARM::t2LDRSBpcrel:
6939     Inst.setOpcode(ARM::t2LDRSBpci);
6940     return true;
6941   case ARM::t2LDRSHpcrel:
6942     Inst.setOpcode(ARM::t2LDRSHpci);
6943     return true;
6944   case ARM::LDRConstPool:
6945   case ARM::tLDRConstPool:
6946   case ARM::t2LDRConstPool: {
6947     // Pseudo instruction ldr rt, =immediate is converted to a
6948     // MOV rt, immediate if immediate is known and representable
6949     // otherwise we create a constant pool entry that we load from.
6950     MCInst TmpInst;
6951     if (Inst.getOpcode() == ARM::LDRConstPool)
6952       TmpInst.setOpcode(ARM::LDRi12);
6953     else if (Inst.getOpcode() == ARM::tLDRConstPool)
6954       TmpInst.setOpcode(ARM::tLDRpci);
6955     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
6956       TmpInst.setOpcode(ARM::t2LDRpci);
6957     const ARMOperand &PoolOperand =
6958       (static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6959        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w") ?
6960       static_cast<ARMOperand &>(*Operands[4]) :
6961       static_cast<ARMOperand &>(*Operands[3]);
6962     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
6963     // If SubExprVal is a constant we may be able to use a MOV
6964     if (isa<MCConstantExpr>(SubExprVal) &&
6965         Inst.getOperand(0).getReg() != ARM::PC &&
6966         Inst.getOperand(0).getReg() != ARM::SP) {
6967       int64_t Value =
6968         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
6969       bool UseMov  = true;
6970       bool MovHasS = true;
6971       if (Inst.getOpcode() == ARM::LDRConstPool) {
6972         // ARM Constant
6973         if (ARM_AM::getSOImmVal(Value) != -1) {
6974           Value = ARM_AM::getSOImmVal(Value);
6975           TmpInst.setOpcode(ARM::MOVi);
6976         }
6977         else if (ARM_AM::getSOImmVal(~Value) != -1) {
6978           Value = ARM_AM::getSOImmVal(~Value);
6979           TmpInst.setOpcode(ARM::MVNi);
6980         }
6981         else if (hasV6T2Ops() &&
6982                  Value >=0 && Value < 65536) {
6983           TmpInst.setOpcode(ARM::MOVi16);
6984           MovHasS = false;
6985         }
6986         else
6987           UseMov = false;
6988       }
6989       else {
6990         // Thumb/Thumb2 Constant
6991         if (hasThumb2() &&
6992             ARM_AM::getT2SOImmVal(Value) != -1)
6993           TmpInst.setOpcode(ARM::t2MOVi);
6994         else if (hasThumb2() &&
6995                  ARM_AM::getT2SOImmVal(~Value) != -1) {
6996           TmpInst.setOpcode(ARM::t2MVNi);
6997           Value = ~Value;
6998         }
6999         else if (hasV8MBaseline() &&
7000                  Value >=0 && Value < 65536) {
7001           TmpInst.setOpcode(ARM::t2MOVi16);
7002           MovHasS = false;
7003         }
7004         else
7005           UseMov = false;
7006       }
7007       if (UseMov) {
7008         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7009         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7010         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7011         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7012         if (MovHasS)
7013           TmpInst.addOperand(MCOperand::createReg(0));    // S
7014         Inst = TmpInst;
7015         return true;
7016       }
7017     }
7018     // No opportunity to use MOV/MVN create constant pool
7019     const MCExpr *CPLoc =
7020       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7021                                                PoolOperand.getStartLoc());
7022     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7023     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7024     if (TmpInst.getOpcode() == ARM::LDRi12)
7025       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7026     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7027     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7028     Inst = TmpInst;
7029     return true;
7030   }
7031   // Handle NEON VST complex aliases.
7032   case ARM::VST1LNdWB_register_Asm_8:
7033   case ARM::VST1LNdWB_register_Asm_16:
7034   case ARM::VST1LNdWB_register_Asm_32: {
7035     MCInst TmpInst;
7036     // Shuffle the operands around so the lane index operand is in the
7037     // right place.
7038     unsigned Spacing;
7039     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7040     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7041     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7042     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7043     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7044     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7045     TmpInst.addOperand(Inst.getOperand(1)); // lane
7046     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7047     TmpInst.addOperand(Inst.getOperand(6));
7048     Inst = TmpInst;
7049     return true;
7050   }
7051 
7052   case ARM::VST2LNdWB_register_Asm_8:
7053   case ARM::VST2LNdWB_register_Asm_16:
7054   case ARM::VST2LNdWB_register_Asm_32:
7055   case ARM::VST2LNqWB_register_Asm_16:
7056   case ARM::VST2LNqWB_register_Asm_32: {
7057     MCInst TmpInst;
7058     // Shuffle the operands around so the lane index operand is in the
7059     // right place.
7060     unsigned Spacing;
7061     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7062     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7063     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7064     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7065     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7066     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7067     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7068                                             Spacing));
7069     TmpInst.addOperand(Inst.getOperand(1)); // lane
7070     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7071     TmpInst.addOperand(Inst.getOperand(6));
7072     Inst = TmpInst;
7073     return true;
7074   }
7075 
7076   case ARM::VST3LNdWB_register_Asm_8:
7077   case ARM::VST3LNdWB_register_Asm_16:
7078   case ARM::VST3LNdWB_register_Asm_32:
7079   case ARM::VST3LNqWB_register_Asm_16:
7080   case ARM::VST3LNqWB_register_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(Inst.getOperand(4)); // Rm
7090     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7091     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7092                                             Spacing));
7093     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7094                                             Spacing * 2));
7095     TmpInst.addOperand(Inst.getOperand(1)); // lane
7096     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7097     TmpInst.addOperand(Inst.getOperand(6));
7098     Inst = TmpInst;
7099     return true;
7100   }
7101 
7102   case ARM::VST4LNdWB_register_Asm_8:
7103   case ARM::VST4LNdWB_register_Asm_16:
7104   case ARM::VST4LNdWB_register_Asm_32:
7105   case ARM::VST4LNqWB_register_Asm_16:
7106   case ARM::VST4LNqWB_register_Asm_32: {
7107     MCInst TmpInst;
7108     // Shuffle the operands around so the lane index operand is in the
7109     // right place.
7110     unsigned Spacing;
7111     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7112     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7113     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7114     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7115     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7116     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7117     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7118                                             Spacing));
7119     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7120                                             Spacing * 2));
7121     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7122                                             Spacing * 3));
7123     TmpInst.addOperand(Inst.getOperand(1)); // lane
7124     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7125     TmpInst.addOperand(Inst.getOperand(6));
7126     Inst = TmpInst;
7127     return true;
7128   }
7129 
7130   case ARM::VST1LNdWB_fixed_Asm_8:
7131   case ARM::VST1LNdWB_fixed_Asm_16:
7132   case ARM::VST1LNdWB_fixed_Asm_32: {
7133     MCInst TmpInst;
7134     // Shuffle the operands around so the lane index operand is in the
7135     // right place.
7136     unsigned Spacing;
7137     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7138     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7139     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7140     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7141     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7142     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7143     TmpInst.addOperand(Inst.getOperand(1)); // lane
7144     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7145     TmpInst.addOperand(Inst.getOperand(5));
7146     Inst = TmpInst;
7147     return true;
7148   }
7149 
7150   case ARM::VST2LNdWB_fixed_Asm_8:
7151   case ARM::VST2LNdWB_fixed_Asm_16:
7152   case ARM::VST2LNdWB_fixed_Asm_32:
7153   case ARM::VST2LNqWB_fixed_Asm_16:
7154   case ARM::VST2LNqWB_fixed_Asm_32: {
7155     MCInst TmpInst;
7156     // Shuffle the operands around so the lane index operand is in the
7157     // right place.
7158     unsigned Spacing;
7159     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7160     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7161     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7162     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7163     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7164     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7165     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7166                                             Spacing));
7167     TmpInst.addOperand(Inst.getOperand(1)); // lane
7168     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7169     TmpInst.addOperand(Inst.getOperand(5));
7170     Inst = TmpInst;
7171     return true;
7172   }
7173 
7174   case ARM::VST3LNdWB_fixed_Asm_8:
7175   case ARM::VST3LNdWB_fixed_Asm_16:
7176   case ARM::VST3LNdWB_fixed_Asm_32:
7177   case ARM::VST3LNqWB_fixed_Asm_16:
7178   case ARM::VST3LNqWB_fixed_Asm_32: {
7179     MCInst TmpInst;
7180     // Shuffle the operands around so the lane index operand is in the
7181     // right place.
7182     unsigned Spacing;
7183     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7184     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7185     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7186     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7187     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7188     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7189     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7190                                             Spacing));
7191     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7192                                             Spacing * 2));
7193     TmpInst.addOperand(Inst.getOperand(1)); // lane
7194     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7195     TmpInst.addOperand(Inst.getOperand(5));
7196     Inst = TmpInst;
7197     return true;
7198   }
7199 
7200   case ARM::VST4LNdWB_fixed_Asm_8:
7201   case ARM::VST4LNdWB_fixed_Asm_16:
7202   case ARM::VST4LNdWB_fixed_Asm_32:
7203   case ARM::VST4LNqWB_fixed_Asm_16:
7204   case ARM::VST4LNqWB_fixed_Asm_32: {
7205     MCInst TmpInst;
7206     // Shuffle the operands around so the lane index operand is in the
7207     // right place.
7208     unsigned Spacing;
7209     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7210     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7211     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7212     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7213     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7214     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7215     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7216                                             Spacing));
7217     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7218                                             Spacing * 2));
7219     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7220                                             Spacing * 3));
7221     TmpInst.addOperand(Inst.getOperand(1)); // lane
7222     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7223     TmpInst.addOperand(Inst.getOperand(5));
7224     Inst = TmpInst;
7225     return true;
7226   }
7227 
7228   case ARM::VST1LNdAsm_8:
7229   case ARM::VST1LNdAsm_16:
7230   case ARM::VST1LNdAsm_32: {
7231     MCInst TmpInst;
7232     // Shuffle the operands around so the lane index operand is in the
7233     // right place.
7234     unsigned Spacing;
7235     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7236     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7237     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7238     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7239     TmpInst.addOperand(Inst.getOperand(1)); // lane
7240     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7241     TmpInst.addOperand(Inst.getOperand(5));
7242     Inst = TmpInst;
7243     return true;
7244   }
7245 
7246   case ARM::VST2LNdAsm_8:
7247   case ARM::VST2LNdAsm_16:
7248   case ARM::VST2LNdAsm_32:
7249   case ARM::VST2LNqAsm_16:
7250   case ARM::VST2LNqAsm_32: {
7251     MCInst TmpInst;
7252     // Shuffle the operands around so the lane index operand is in the
7253     // right place.
7254     unsigned Spacing;
7255     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7256     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7257     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7258     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7259     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7260                                             Spacing));
7261     TmpInst.addOperand(Inst.getOperand(1)); // lane
7262     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7263     TmpInst.addOperand(Inst.getOperand(5));
7264     Inst = TmpInst;
7265     return true;
7266   }
7267 
7268   case ARM::VST3LNdAsm_8:
7269   case ARM::VST3LNdAsm_16:
7270   case ARM::VST3LNdAsm_32:
7271   case ARM::VST3LNqAsm_16:
7272   case ARM::VST3LNqAsm_32: {
7273     MCInst TmpInst;
7274     // Shuffle the operands around so the lane index operand is in the
7275     // right place.
7276     unsigned Spacing;
7277     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7278     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7279     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7280     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7281     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7282                                             Spacing));
7283     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7284                                             Spacing * 2));
7285     TmpInst.addOperand(Inst.getOperand(1)); // lane
7286     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7287     TmpInst.addOperand(Inst.getOperand(5));
7288     Inst = TmpInst;
7289     return true;
7290   }
7291 
7292   case ARM::VST4LNdAsm_8:
7293   case ARM::VST4LNdAsm_16:
7294   case ARM::VST4LNdAsm_32:
7295   case ARM::VST4LNqAsm_16:
7296   case ARM::VST4LNqAsm_32: {
7297     MCInst TmpInst;
7298     // Shuffle the operands around so the lane index operand is in the
7299     // right place.
7300     unsigned Spacing;
7301     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7302     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7303     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7304     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7305     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7306                                             Spacing));
7307     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7308                                             Spacing * 2));
7309     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7310                                             Spacing * 3));
7311     TmpInst.addOperand(Inst.getOperand(1)); // lane
7312     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7313     TmpInst.addOperand(Inst.getOperand(5));
7314     Inst = TmpInst;
7315     return true;
7316   }
7317 
7318   // Handle NEON VLD complex aliases.
7319   case ARM::VLD1LNdWB_register_Asm_8:
7320   case ARM::VLD1LNdWB_register_Asm_16:
7321   case ARM::VLD1LNdWB_register_Asm_32: {
7322     MCInst TmpInst;
7323     // Shuffle the operands around so the lane index operand is in the
7324     // right place.
7325     unsigned Spacing;
7326     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7327     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7328     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7329     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7330     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7331     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7332     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7333     TmpInst.addOperand(Inst.getOperand(1)); // lane
7334     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7335     TmpInst.addOperand(Inst.getOperand(6));
7336     Inst = TmpInst;
7337     return true;
7338   }
7339 
7340   case ARM::VLD2LNdWB_register_Asm_8:
7341   case ARM::VLD2LNdWB_register_Asm_16:
7342   case ARM::VLD2LNdWB_register_Asm_32:
7343   case ARM::VLD2LNqWB_register_Asm_16:
7344   case ARM::VLD2LNqWB_register_Asm_32: {
7345     MCInst TmpInst;
7346     // Shuffle the operands around so the lane index operand is in the
7347     // right place.
7348     unsigned Spacing;
7349     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7350     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7351     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7352                                             Spacing));
7353     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7354     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7355     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7356     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7357     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7358     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7359                                             Spacing));
7360     TmpInst.addOperand(Inst.getOperand(1)); // lane
7361     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7362     TmpInst.addOperand(Inst.getOperand(6));
7363     Inst = TmpInst;
7364     return true;
7365   }
7366 
7367   case ARM::VLD3LNdWB_register_Asm_8:
7368   case ARM::VLD3LNdWB_register_Asm_16:
7369   case ARM::VLD3LNdWB_register_Asm_32:
7370   case ARM::VLD3LNqWB_register_Asm_16:
7371   case ARM::VLD3LNqWB_register_Asm_32: {
7372     MCInst TmpInst;
7373     // Shuffle the operands around so the lane index operand is in the
7374     // right place.
7375     unsigned Spacing;
7376     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7377     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7378     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7379                                             Spacing));
7380     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7381                                             Spacing * 2));
7382     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7383     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7384     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7385     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7386     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7387     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7388                                             Spacing));
7389     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7390                                             Spacing * 2));
7391     TmpInst.addOperand(Inst.getOperand(1)); // lane
7392     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7393     TmpInst.addOperand(Inst.getOperand(6));
7394     Inst = TmpInst;
7395     return true;
7396   }
7397 
7398   case ARM::VLD4LNdWB_register_Asm_8:
7399   case ARM::VLD4LNdWB_register_Asm_16:
7400   case ARM::VLD4LNdWB_register_Asm_32:
7401   case ARM::VLD4LNqWB_register_Asm_16:
7402   case ARM::VLD4LNqWB_register_Asm_32: {
7403     MCInst TmpInst;
7404     // Shuffle the operands around so the lane index operand is in the
7405     // right place.
7406     unsigned Spacing;
7407     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7408     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7409     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7410                                             Spacing));
7411     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7412                                             Spacing * 2));
7413     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7414                                             Spacing * 3));
7415     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7416     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7417     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7418     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7419     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7420     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7421                                             Spacing));
7422     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7423                                             Spacing * 2));
7424     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7425                                             Spacing * 3));
7426     TmpInst.addOperand(Inst.getOperand(1)); // lane
7427     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7428     TmpInst.addOperand(Inst.getOperand(6));
7429     Inst = TmpInst;
7430     return true;
7431   }
7432 
7433   case ARM::VLD1LNdWB_fixed_Asm_8:
7434   case ARM::VLD1LNdWB_fixed_Asm_16:
7435   case ARM::VLD1LNdWB_fixed_Asm_32: {
7436     MCInst TmpInst;
7437     // Shuffle the operands around so the lane index operand is in the
7438     // right place.
7439     unsigned Spacing;
7440     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7441     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7442     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7443     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7444     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7445     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7446     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7447     TmpInst.addOperand(Inst.getOperand(1)); // lane
7448     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7449     TmpInst.addOperand(Inst.getOperand(5));
7450     Inst = TmpInst;
7451     return true;
7452   }
7453 
7454   case ARM::VLD2LNdWB_fixed_Asm_8:
7455   case ARM::VLD2LNdWB_fixed_Asm_16:
7456   case ARM::VLD2LNdWB_fixed_Asm_32:
7457   case ARM::VLD2LNqWB_fixed_Asm_16:
7458   case ARM::VLD2LNqWB_fixed_Asm_32: {
7459     MCInst TmpInst;
7460     // Shuffle the operands around so the lane index operand is in the
7461     // right place.
7462     unsigned Spacing;
7463     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7464     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7465     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7466                                             Spacing));
7467     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7468     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7469     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7470     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7471     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7472     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7473                                             Spacing));
7474     TmpInst.addOperand(Inst.getOperand(1)); // lane
7475     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7476     TmpInst.addOperand(Inst.getOperand(5));
7477     Inst = TmpInst;
7478     return true;
7479   }
7480 
7481   case ARM::VLD3LNdWB_fixed_Asm_8:
7482   case ARM::VLD3LNdWB_fixed_Asm_16:
7483   case ARM::VLD3LNdWB_fixed_Asm_32:
7484   case ARM::VLD3LNqWB_fixed_Asm_16:
7485   case ARM::VLD3LNqWB_fixed_Asm_32: {
7486     MCInst TmpInst;
7487     // Shuffle the operands around so the lane index operand is in the
7488     // right place.
7489     unsigned Spacing;
7490     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7491     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7492     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7493                                             Spacing));
7494     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7495                                             Spacing * 2));
7496     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7497     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7498     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7499     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7500     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7501     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7502                                             Spacing));
7503     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7504                                             Spacing * 2));
7505     TmpInst.addOperand(Inst.getOperand(1)); // lane
7506     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7507     TmpInst.addOperand(Inst.getOperand(5));
7508     Inst = TmpInst;
7509     return true;
7510   }
7511 
7512   case ARM::VLD4LNdWB_fixed_Asm_8:
7513   case ARM::VLD4LNdWB_fixed_Asm_16:
7514   case ARM::VLD4LNdWB_fixed_Asm_32:
7515   case ARM::VLD4LNqWB_fixed_Asm_16:
7516   case ARM::VLD4LNqWB_fixed_Asm_32: {
7517     MCInst TmpInst;
7518     // Shuffle the operands around so the lane index operand is in the
7519     // right place.
7520     unsigned Spacing;
7521     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7522     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7523     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7524                                             Spacing));
7525     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7526                                             Spacing * 2));
7527     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7528                                             Spacing * 3));
7529     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7530     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7531     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7532     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7533     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7534     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7535                                             Spacing));
7536     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7537                                             Spacing * 2));
7538     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7539                                             Spacing * 3));
7540     TmpInst.addOperand(Inst.getOperand(1)); // lane
7541     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7542     TmpInst.addOperand(Inst.getOperand(5));
7543     Inst = TmpInst;
7544     return true;
7545   }
7546 
7547   case ARM::VLD1LNdAsm_8:
7548   case ARM::VLD1LNdAsm_16:
7549   case ARM::VLD1LNdAsm_32: {
7550     MCInst TmpInst;
7551     // Shuffle the operands around so the lane index operand is in the
7552     // right place.
7553     unsigned Spacing;
7554     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7555     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7556     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7557     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7558     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7559     TmpInst.addOperand(Inst.getOperand(1)); // lane
7560     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7561     TmpInst.addOperand(Inst.getOperand(5));
7562     Inst = TmpInst;
7563     return true;
7564   }
7565 
7566   case ARM::VLD2LNdAsm_8:
7567   case ARM::VLD2LNdAsm_16:
7568   case ARM::VLD2LNdAsm_32:
7569   case ARM::VLD2LNqAsm_16:
7570   case ARM::VLD2LNqAsm_32: {
7571     MCInst TmpInst;
7572     // Shuffle the operands around so the lane index operand is in the
7573     // right place.
7574     unsigned Spacing;
7575     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7576     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7577     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7578                                             Spacing));
7579     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7580     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7581     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7582     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7583                                             Spacing));
7584     TmpInst.addOperand(Inst.getOperand(1)); // lane
7585     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7586     TmpInst.addOperand(Inst.getOperand(5));
7587     Inst = TmpInst;
7588     return true;
7589   }
7590 
7591   case ARM::VLD3LNdAsm_8:
7592   case ARM::VLD3LNdAsm_16:
7593   case ARM::VLD3LNdAsm_32:
7594   case ARM::VLD3LNqAsm_16:
7595   case ARM::VLD3LNqAsm_32: {
7596     MCInst TmpInst;
7597     // Shuffle the operands around so the lane index operand is in the
7598     // right place.
7599     unsigned Spacing;
7600     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7601     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7602     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7603                                             Spacing));
7604     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7605                                             Spacing * 2));
7606     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7607     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7608     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7609     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7610                                             Spacing));
7611     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7612                                             Spacing * 2));
7613     TmpInst.addOperand(Inst.getOperand(1)); // lane
7614     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7615     TmpInst.addOperand(Inst.getOperand(5));
7616     Inst = TmpInst;
7617     return true;
7618   }
7619 
7620   case ARM::VLD4LNdAsm_8:
7621   case ARM::VLD4LNdAsm_16:
7622   case ARM::VLD4LNdAsm_32:
7623   case ARM::VLD4LNqAsm_16:
7624   case ARM::VLD4LNqAsm_32: {
7625     MCInst TmpInst;
7626     // Shuffle the operands around so the lane index operand is in the
7627     // right place.
7628     unsigned Spacing;
7629     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7630     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7631     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7632                                             Spacing));
7633     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7634                                             Spacing * 2));
7635     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7636                                             Spacing * 3));
7637     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7638     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7639     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7640     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7641                                             Spacing));
7642     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7643                                             Spacing * 2));
7644     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7645                                             Spacing * 3));
7646     TmpInst.addOperand(Inst.getOperand(1)); // lane
7647     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7648     TmpInst.addOperand(Inst.getOperand(5));
7649     Inst = TmpInst;
7650     return true;
7651   }
7652 
7653   // VLD3DUP single 3-element structure to all lanes instructions.
7654   case ARM::VLD3DUPdAsm_8:
7655   case ARM::VLD3DUPdAsm_16:
7656   case ARM::VLD3DUPdAsm_32:
7657   case ARM::VLD3DUPqAsm_8:
7658   case ARM::VLD3DUPqAsm_16:
7659   case ARM::VLD3DUPqAsm_32: {
7660     MCInst TmpInst;
7661     unsigned Spacing;
7662     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7663     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7664     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7665                                             Spacing));
7666     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7667                                             Spacing * 2));
7668     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7669     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7670     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7671     TmpInst.addOperand(Inst.getOperand(4));
7672     Inst = TmpInst;
7673     return true;
7674   }
7675 
7676   case ARM::VLD3DUPdWB_fixed_Asm_8:
7677   case ARM::VLD3DUPdWB_fixed_Asm_16:
7678   case ARM::VLD3DUPdWB_fixed_Asm_32:
7679   case ARM::VLD3DUPqWB_fixed_Asm_8:
7680   case ARM::VLD3DUPqWB_fixed_Asm_16:
7681   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7682     MCInst TmpInst;
7683     unsigned Spacing;
7684     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7685     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7686     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7687                                             Spacing));
7688     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7689                                             Spacing * 2));
7690     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7691     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7692     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7693     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7694     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7695     TmpInst.addOperand(Inst.getOperand(4));
7696     Inst = TmpInst;
7697     return true;
7698   }
7699 
7700   case ARM::VLD3DUPdWB_register_Asm_8:
7701   case ARM::VLD3DUPdWB_register_Asm_16:
7702   case ARM::VLD3DUPdWB_register_Asm_32:
7703   case ARM::VLD3DUPqWB_register_Asm_8:
7704   case ARM::VLD3DUPqWB_register_Asm_16:
7705   case ARM::VLD3DUPqWB_register_Asm_32: {
7706     MCInst TmpInst;
7707     unsigned Spacing;
7708     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7709     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7710     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7711                                             Spacing));
7712     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7713                                             Spacing * 2));
7714     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7715     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7716     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7717     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7718     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7719     TmpInst.addOperand(Inst.getOperand(5));
7720     Inst = TmpInst;
7721     return true;
7722   }
7723 
7724   // VLD3 multiple 3-element structure instructions.
7725   case ARM::VLD3dAsm_8:
7726   case ARM::VLD3dAsm_16:
7727   case ARM::VLD3dAsm_32:
7728   case ARM::VLD3qAsm_8:
7729   case ARM::VLD3qAsm_16:
7730   case ARM::VLD3qAsm_32: {
7731     MCInst TmpInst;
7732     unsigned Spacing;
7733     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7734     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7735     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7736                                             Spacing));
7737     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7738                                             Spacing * 2));
7739     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7740     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7741     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7742     TmpInst.addOperand(Inst.getOperand(4));
7743     Inst = TmpInst;
7744     return true;
7745   }
7746 
7747   case ARM::VLD3dWB_fixed_Asm_8:
7748   case ARM::VLD3dWB_fixed_Asm_16:
7749   case ARM::VLD3dWB_fixed_Asm_32:
7750   case ARM::VLD3qWB_fixed_Asm_8:
7751   case ARM::VLD3qWB_fixed_Asm_16:
7752   case ARM::VLD3qWB_fixed_Asm_32: {
7753     MCInst TmpInst;
7754     unsigned Spacing;
7755     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7756     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7757     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7758                                             Spacing));
7759     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7760                                             Spacing * 2));
7761     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7762     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7763     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7764     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7765     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7766     TmpInst.addOperand(Inst.getOperand(4));
7767     Inst = TmpInst;
7768     return true;
7769   }
7770 
7771   case ARM::VLD3dWB_register_Asm_8:
7772   case ARM::VLD3dWB_register_Asm_16:
7773   case ARM::VLD3dWB_register_Asm_32:
7774   case ARM::VLD3qWB_register_Asm_8:
7775   case ARM::VLD3qWB_register_Asm_16:
7776   case ARM::VLD3qWB_register_Asm_32: {
7777     MCInst TmpInst;
7778     unsigned Spacing;
7779     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7780     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7781     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7782                                             Spacing));
7783     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7784                                             Spacing * 2));
7785     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7786     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7787     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7788     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7789     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7790     TmpInst.addOperand(Inst.getOperand(5));
7791     Inst = TmpInst;
7792     return true;
7793   }
7794 
7795   // VLD4DUP single 3-element structure to all lanes instructions.
7796   case ARM::VLD4DUPdAsm_8:
7797   case ARM::VLD4DUPdAsm_16:
7798   case ARM::VLD4DUPdAsm_32:
7799   case ARM::VLD4DUPqAsm_8:
7800   case ARM::VLD4DUPqAsm_16:
7801   case ARM::VLD4DUPqAsm_32: {
7802     MCInst TmpInst;
7803     unsigned Spacing;
7804     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7805     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7806     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7807                                             Spacing));
7808     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7809                                             Spacing * 2));
7810     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7811                                             Spacing * 3));
7812     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7813     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7814     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7815     TmpInst.addOperand(Inst.getOperand(4));
7816     Inst = TmpInst;
7817     return true;
7818   }
7819 
7820   case ARM::VLD4DUPdWB_fixed_Asm_8:
7821   case ARM::VLD4DUPdWB_fixed_Asm_16:
7822   case ARM::VLD4DUPdWB_fixed_Asm_32:
7823   case ARM::VLD4DUPqWB_fixed_Asm_8:
7824   case ARM::VLD4DUPqWB_fixed_Asm_16:
7825   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7826     MCInst TmpInst;
7827     unsigned Spacing;
7828     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7829     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7830     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7831                                             Spacing));
7832     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7833                                             Spacing * 2));
7834     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7835                                             Spacing * 3));
7836     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7837     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7838     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7839     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7840     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7841     TmpInst.addOperand(Inst.getOperand(4));
7842     Inst = TmpInst;
7843     return true;
7844   }
7845 
7846   case ARM::VLD4DUPdWB_register_Asm_8:
7847   case ARM::VLD4DUPdWB_register_Asm_16:
7848   case ARM::VLD4DUPdWB_register_Asm_32:
7849   case ARM::VLD4DUPqWB_register_Asm_8:
7850   case ARM::VLD4DUPqWB_register_Asm_16:
7851   case ARM::VLD4DUPqWB_register_Asm_32: {
7852     MCInst TmpInst;
7853     unsigned Spacing;
7854     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7855     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7856     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7857                                             Spacing));
7858     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7859                                             Spacing * 2));
7860     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7861                                             Spacing * 3));
7862     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7863     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7864     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7865     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7866     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7867     TmpInst.addOperand(Inst.getOperand(5));
7868     Inst = TmpInst;
7869     return true;
7870   }
7871 
7872   // VLD4 multiple 4-element structure instructions.
7873   case ARM::VLD4dAsm_8:
7874   case ARM::VLD4dAsm_16:
7875   case ARM::VLD4dAsm_32:
7876   case ARM::VLD4qAsm_8:
7877   case ARM::VLD4qAsm_16:
7878   case ARM::VLD4qAsm_32: {
7879     MCInst TmpInst;
7880     unsigned Spacing;
7881     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7882     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7883     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7884                                             Spacing));
7885     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7886                                             Spacing * 2));
7887     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7888                                             Spacing * 3));
7889     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7890     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7891     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7892     TmpInst.addOperand(Inst.getOperand(4));
7893     Inst = TmpInst;
7894     return true;
7895   }
7896 
7897   case ARM::VLD4dWB_fixed_Asm_8:
7898   case ARM::VLD4dWB_fixed_Asm_16:
7899   case ARM::VLD4dWB_fixed_Asm_32:
7900   case ARM::VLD4qWB_fixed_Asm_8:
7901   case ARM::VLD4qWB_fixed_Asm_16:
7902   case ARM::VLD4qWB_fixed_Asm_32: {
7903     MCInst TmpInst;
7904     unsigned Spacing;
7905     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7906     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7907     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7908                                             Spacing));
7909     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7910                                             Spacing * 2));
7911     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7912                                             Spacing * 3));
7913     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7914     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7915     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7916     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7917     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7918     TmpInst.addOperand(Inst.getOperand(4));
7919     Inst = TmpInst;
7920     return true;
7921   }
7922 
7923   case ARM::VLD4dWB_register_Asm_8:
7924   case ARM::VLD4dWB_register_Asm_16:
7925   case ARM::VLD4dWB_register_Asm_32:
7926   case ARM::VLD4qWB_register_Asm_8:
7927   case ARM::VLD4qWB_register_Asm_16:
7928   case ARM::VLD4qWB_register_Asm_32: {
7929     MCInst TmpInst;
7930     unsigned Spacing;
7931     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7932     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7933     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7934                                             Spacing));
7935     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7936                                             Spacing * 2));
7937     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7938                                             Spacing * 3));
7939     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7940     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7941     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7942     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7943     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7944     TmpInst.addOperand(Inst.getOperand(5));
7945     Inst = TmpInst;
7946     return true;
7947   }
7948 
7949   // VST3 multiple 3-element structure instructions.
7950   case ARM::VST3dAsm_8:
7951   case ARM::VST3dAsm_16:
7952   case ARM::VST3dAsm_32:
7953   case ARM::VST3qAsm_8:
7954   case ARM::VST3qAsm_16:
7955   case ARM::VST3qAsm_32: {
7956     MCInst TmpInst;
7957     unsigned Spacing;
7958     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7959     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7960     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7961     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7962     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7963                                             Spacing));
7964     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7965                                             Spacing * 2));
7966     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7967     TmpInst.addOperand(Inst.getOperand(4));
7968     Inst = TmpInst;
7969     return true;
7970   }
7971 
7972   case ARM::VST3dWB_fixed_Asm_8:
7973   case ARM::VST3dWB_fixed_Asm_16:
7974   case ARM::VST3dWB_fixed_Asm_32:
7975   case ARM::VST3qWB_fixed_Asm_8:
7976   case ARM::VST3qWB_fixed_Asm_16:
7977   case ARM::VST3qWB_fixed_Asm_32: {
7978     MCInst TmpInst;
7979     unsigned Spacing;
7980     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7981     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7982     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7983     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7984     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7985     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7986     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7987                                             Spacing));
7988     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7989                                             Spacing * 2));
7990     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7991     TmpInst.addOperand(Inst.getOperand(4));
7992     Inst = TmpInst;
7993     return true;
7994   }
7995 
7996   case ARM::VST3dWB_register_Asm_8:
7997   case ARM::VST3dWB_register_Asm_16:
7998   case ARM::VST3dWB_register_Asm_32:
7999   case ARM::VST3qWB_register_Asm_8:
8000   case ARM::VST3qWB_register_Asm_16:
8001   case ARM::VST3qWB_register_Asm_32: {
8002     MCInst TmpInst;
8003     unsigned Spacing;
8004     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8005     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8006     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8007     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8008     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8009     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8010     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8011                                             Spacing));
8012     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8013                                             Spacing * 2));
8014     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8015     TmpInst.addOperand(Inst.getOperand(5));
8016     Inst = TmpInst;
8017     return true;
8018   }
8019 
8020   // VST4 multiple 3-element structure instructions.
8021   case ARM::VST4dAsm_8:
8022   case ARM::VST4dAsm_16:
8023   case ARM::VST4dAsm_32:
8024   case ARM::VST4qAsm_8:
8025   case ARM::VST4qAsm_16:
8026   case ARM::VST4qAsm_32: {
8027     MCInst TmpInst;
8028     unsigned Spacing;
8029     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8030     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8031     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8032     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8033     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8034                                             Spacing));
8035     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8036                                             Spacing * 2));
8037     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8038                                             Spacing * 3));
8039     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8040     TmpInst.addOperand(Inst.getOperand(4));
8041     Inst = TmpInst;
8042     return true;
8043   }
8044 
8045   case ARM::VST4dWB_fixed_Asm_8:
8046   case ARM::VST4dWB_fixed_Asm_16:
8047   case ARM::VST4dWB_fixed_Asm_32:
8048   case ARM::VST4qWB_fixed_Asm_8:
8049   case ARM::VST4qWB_fixed_Asm_16:
8050   case ARM::VST4qWB_fixed_Asm_32: {
8051     MCInst TmpInst;
8052     unsigned Spacing;
8053     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8054     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8055     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8056     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8057     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8058     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8059     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8060                                             Spacing));
8061     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8062                                             Spacing * 2));
8063     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8064                                             Spacing * 3));
8065     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8066     TmpInst.addOperand(Inst.getOperand(4));
8067     Inst = TmpInst;
8068     return true;
8069   }
8070 
8071   case ARM::VST4dWB_register_Asm_8:
8072   case ARM::VST4dWB_register_Asm_16:
8073   case ARM::VST4dWB_register_Asm_32:
8074   case ARM::VST4qWB_register_Asm_8:
8075   case ARM::VST4qWB_register_Asm_16:
8076   case ARM::VST4qWB_register_Asm_32: {
8077     MCInst TmpInst;
8078     unsigned Spacing;
8079     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8080     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8081     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8082     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8083     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8084     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8085     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8086                                             Spacing));
8087     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8088                                             Spacing * 2));
8089     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8090                                             Spacing * 3));
8091     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8092     TmpInst.addOperand(Inst.getOperand(5));
8093     Inst = TmpInst;
8094     return true;
8095   }
8096 
8097   // Handle encoding choice for the shift-immediate instructions.
8098   case ARM::t2LSLri:
8099   case ARM::t2LSRri:
8100   case ARM::t2ASRri: {
8101     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8102         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8103         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8104         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8105           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
8106       unsigned NewOpc;
8107       switch (Inst.getOpcode()) {
8108       default: llvm_unreachable("unexpected opcode");
8109       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8110       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8111       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8112       }
8113       // The Thumb1 operands aren't in the same order. Awesome, eh?
8114       MCInst TmpInst;
8115       TmpInst.setOpcode(NewOpc);
8116       TmpInst.addOperand(Inst.getOperand(0));
8117       TmpInst.addOperand(Inst.getOperand(5));
8118       TmpInst.addOperand(Inst.getOperand(1));
8119       TmpInst.addOperand(Inst.getOperand(2));
8120       TmpInst.addOperand(Inst.getOperand(3));
8121       TmpInst.addOperand(Inst.getOperand(4));
8122       Inst = TmpInst;
8123       return true;
8124     }
8125     return false;
8126   }
8127 
8128   // Handle the Thumb2 mode MOV complex aliases.
8129   case ARM::t2MOVsr:
8130   case ARM::t2MOVSsr: {
8131     // Which instruction to expand to depends on the CCOut operand and
8132     // whether we're in an IT block if the register operands are low
8133     // registers.
8134     bool isNarrow = false;
8135     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8136         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8137         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8138         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8139         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
8140       isNarrow = true;
8141     MCInst TmpInst;
8142     unsigned newOpc;
8143     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8144     default: llvm_unreachable("unexpected opcode!");
8145     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8146     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8147     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8148     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8149     }
8150     TmpInst.setOpcode(newOpc);
8151     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8152     if (isNarrow)
8153       TmpInst.addOperand(MCOperand::createReg(
8154           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8155     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8156     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8157     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8158     TmpInst.addOperand(Inst.getOperand(5));
8159     if (!isNarrow)
8160       TmpInst.addOperand(MCOperand::createReg(
8161           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8162     Inst = TmpInst;
8163     return true;
8164   }
8165   case ARM::t2MOVsi:
8166   case ARM::t2MOVSsi: {
8167     // Which instruction to expand to depends on the CCOut operand and
8168     // whether we're in an IT block if the register operands are low
8169     // registers.
8170     bool isNarrow = false;
8171     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8172         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8173         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
8174       isNarrow = true;
8175     MCInst TmpInst;
8176     unsigned newOpc;
8177     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8178     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8179     bool isMov = false;
8180     // MOV rd, rm, LSL #0 is actually a MOV instruction
8181     if (Shift == ARM_AM::lsl && Amount == 0) {
8182       isMov = true;
8183       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8184       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8185       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8186       // instead.
8187       if (inITBlock()) {
8188         isNarrow = false;
8189       }
8190       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8191     } else {
8192       switch(Shift) {
8193       default: llvm_unreachable("unexpected opcode!");
8194       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8195       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8196       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8197       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8198       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8199       }
8200     }
8201     if (Amount == 32) Amount = 0;
8202     TmpInst.setOpcode(newOpc);
8203     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8204     if (isNarrow && !isMov)
8205       TmpInst.addOperand(MCOperand::createReg(
8206           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8207     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8208     if (newOpc != ARM::t2RRX && !isMov)
8209       TmpInst.addOperand(MCOperand::createImm(Amount));
8210     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8211     TmpInst.addOperand(Inst.getOperand(4));
8212     if (!isNarrow)
8213       TmpInst.addOperand(MCOperand::createReg(
8214           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8215     Inst = TmpInst;
8216     return true;
8217   }
8218   // Handle the ARM mode MOV complex aliases.
8219   case ARM::ASRr:
8220   case ARM::LSRr:
8221   case ARM::LSLr:
8222   case ARM::RORr: {
8223     ARM_AM::ShiftOpc ShiftTy;
8224     switch(Inst.getOpcode()) {
8225     default: llvm_unreachable("unexpected opcode!");
8226     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8227     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8228     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8229     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8230     }
8231     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8232     MCInst TmpInst;
8233     TmpInst.setOpcode(ARM::MOVsr);
8234     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8235     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8236     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8237     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8238     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8239     TmpInst.addOperand(Inst.getOperand(4));
8240     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8241     Inst = TmpInst;
8242     return true;
8243   }
8244   case ARM::ASRi:
8245   case ARM::LSRi:
8246   case ARM::LSLi:
8247   case ARM::RORi: {
8248     ARM_AM::ShiftOpc ShiftTy;
8249     switch(Inst.getOpcode()) {
8250     default: llvm_unreachable("unexpected opcode!");
8251     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8252     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8253     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8254     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8255     }
8256     // A shift by zero is a plain MOVr, not a MOVsi.
8257     unsigned Amt = Inst.getOperand(2).getImm();
8258     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8259     // A shift by 32 should be encoded as 0 when permitted
8260     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8261       Amt = 0;
8262     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8263     MCInst TmpInst;
8264     TmpInst.setOpcode(Opc);
8265     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8266     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8267     if (Opc == ARM::MOVsi)
8268       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8269     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8270     TmpInst.addOperand(Inst.getOperand(4));
8271     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8272     Inst = TmpInst;
8273     return true;
8274   }
8275   case ARM::RRXi: {
8276     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8277     MCInst TmpInst;
8278     TmpInst.setOpcode(ARM::MOVsi);
8279     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8280     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8281     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8282     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8283     TmpInst.addOperand(Inst.getOperand(3));
8284     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8285     Inst = TmpInst;
8286     return true;
8287   }
8288   case ARM::t2LDMIA_UPD: {
8289     // If this is a load of a single register, then we should use
8290     // a post-indexed LDR instruction instead, per the ARM ARM.
8291     if (Inst.getNumOperands() != 5)
8292       return false;
8293     MCInst TmpInst;
8294     TmpInst.setOpcode(ARM::t2LDR_POST);
8295     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8296     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8297     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8298     TmpInst.addOperand(MCOperand::createImm(4));
8299     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8300     TmpInst.addOperand(Inst.getOperand(3));
8301     Inst = TmpInst;
8302     return true;
8303   }
8304   case ARM::t2STMDB_UPD: {
8305     // If this is a store of a single register, then we should use
8306     // a pre-indexed STR instruction instead, per the ARM ARM.
8307     if (Inst.getNumOperands() != 5)
8308       return false;
8309     MCInst TmpInst;
8310     TmpInst.setOpcode(ARM::t2STR_PRE);
8311     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8312     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8313     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8314     TmpInst.addOperand(MCOperand::createImm(-4));
8315     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8316     TmpInst.addOperand(Inst.getOperand(3));
8317     Inst = TmpInst;
8318     return true;
8319   }
8320   case ARM::LDMIA_UPD:
8321     // If this is a load of a single register via a 'pop', then we should use
8322     // a post-indexed LDR instruction instead, per the ARM ARM.
8323     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8324         Inst.getNumOperands() == 5) {
8325       MCInst TmpInst;
8326       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8327       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8328       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8329       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8330       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8331       TmpInst.addOperand(MCOperand::createImm(4));
8332       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8333       TmpInst.addOperand(Inst.getOperand(3));
8334       Inst = TmpInst;
8335       return true;
8336     }
8337     break;
8338   case ARM::STMDB_UPD:
8339     // If this is a store of a single register via a 'push', then we should use
8340     // a pre-indexed STR instruction instead, per the ARM ARM.
8341     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8342         Inst.getNumOperands() == 5) {
8343       MCInst TmpInst;
8344       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8345       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8346       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8347       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8348       TmpInst.addOperand(MCOperand::createImm(-4));
8349       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8350       TmpInst.addOperand(Inst.getOperand(3));
8351       Inst = TmpInst;
8352     }
8353     break;
8354   case ARM::t2ADDri12:
8355     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8356     // mnemonic was used (not "addw"), encoding T3 is preferred.
8357     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8358         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8359       break;
8360     Inst.setOpcode(ARM::t2ADDri);
8361     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8362     break;
8363   case ARM::t2SUBri12:
8364     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8365     // mnemonic was used (not "subw"), encoding T3 is preferred.
8366     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8367         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8368       break;
8369     Inst.setOpcode(ARM::t2SUBri);
8370     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8371     break;
8372   case ARM::tADDi8:
8373     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8374     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8375     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8376     // to encoding T1 if <Rd> is omitted."
8377     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8378       Inst.setOpcode(ARM::tADDi3);
8379       return true;
8380     }
8381     break;
8382   case ARM::tSUBi8:
8383     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8384     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8385     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8386     // to encoding T1 if <Rd> is omitted."
8387     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8388       Inst.setOpcode(ARM::tSUBi3);
8389       return true;
8390     }
8391     break;
8392   case ARM::t2ADDri:
8393   case ARM::t2SUBri: {
8394     // If the destination and first source operand are the same, and
8395     // the flags are compatible with the current IT status, use encoding T2
8396     // instead of T3. For compatibility with the system 'as'. Make sure the
8397     // wide encoding wasn't explicit.
8398     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8399         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8400         (unsigned)Inst.getOperand(2).getImm() > 255 ||
8401         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
8402          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
8403         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8404          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8405       break;
8406     MCInst TmpInst;
8407     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8408                       ARM::tADDi8 : ARM::tSUBi8);
8409     TmpInst.addOperand(Inst.getOperand(0));
8410     TmpInst.addOperand(Inst.getOperand(5));
8411     TmpInst.addOperand(Inst.getOperand(0));
8412     TmpInst.addOperand(Inst.getOperand(2));
8413     TmpInst.addOperand(Inst.getOperand(3));
8414     TmpInst.addOperand(Inst.getOperand(4));
8415     Inst = TmpInst;
8416     return true;
8417   }
8418   case ARM::t2ADDrr: {
8419     // If the destination and first source operand are the same, and
8420     // there's no setting of the flags, use encoding T2 instead of T3.
8421     // Note that this is only for ADD, not SUB. This mirrors the system
8422     // 'as' behaviour.  Also take advantage of ADD being commutative.
8423     // Make sure the wide encoding wasn't explicit.
8424     bool Swap = false;
8425     auto DestReg = Inst.getOperand(0).getReg();
8426     bool Transform = DestReg == Inst.getOperand(1).getReg();
8427     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8428       Transform = true;
8429       Swap = true;
8430     }
8431     if (!Transform ||
8432         Inst.getOperand(5).getReg() != 0 ||
8433         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8434          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8435       break;
8436     MCInst TmpInst;
8437     TmpInst.setOpcode(ARM::tADDhirr);
8438     TmpInst.addOperand(Inst.getOperand(0));
8439     TmpInst.addOperand(Inst.getOperand(0));
8440     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8441     TmpInst.addOperand(Inst.getOperand(3));
8442     TmpInst.addOperand(Inst.getOperand(4));
8443     Inst = TmpInst;
8444     return true;
8445   }
8446   case ARM::tADDrSP: {
8447     // If the non-SP source operand and the destination operand are not the
8448     // same, we need to use the 32-bit encoding if it's available.
8449     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8450       Inst.setOpcode(ARM::t2ADDrr);
8451       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8452       return true;
8453     }
8454     break;
8455   }
8456   case ARM::tB:
8457     // A Thumb conditional branch outside of an IT block is a tBcc.
8458     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8459       Inst.setOpcode(ARM::tBcc);
8460       return true;
8461     }
8462     break;
8463   case ARM::t2B:
8464     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8465     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8466       Inst.setOpcode(ARM::t2Bcc);
8467       return true;
8468     }
8469     break;
8470   case ARM::t2Bcc:
8471     // If the conditional is AL or we're in an IT block, we really want t2B.
8472     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8473       Inst.setOpcode(ARM::t2B);
8474       return true;
8475     }
8476     break;
8477   case ARM::tBcc:
8478     // If the conditional is AL, we really want tB.
8479     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8480       Inst.setOpcode(ARM::tB);
8481       return true;
8482     }
8483     break;
8484   case ARM::tLDMIA: {
8485     // If the register list contains any high registers, or if the writeback
8486     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8487     // instead if we're in Thumb2. Otherwise, this should have generated
8488     // an error in validateInstruction().
8489     unsigned Rn = Inst.getOperand(0).getReg();
8490     bool hasWritebackToken =
8491         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8492          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8493     bool listContainsBase;
8494     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8495         (!listContainsBase && !hasWritebackToken) ||
8496         (listContainsBase && hasWritebackToken)) {
8497       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8498       assert (isThumbTwo());
8499       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8500       // If we're switching to the updating version, we need to insert
8501       // the writeback tied operand.
8502       if (hasWritebackToken)
8503         Inst.insert(Inst.begin(),
8504                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8505       return true;
8506     }
8507     break;
8508   }
8509   case ARM::tSTMIA_UPD: {
8510     // If the register list contains any high registers, we need to use
8511     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8512     // should have generated an error in validateInstruction().
8513     unsigned Rn = Inst.getOperand(0).getReg();
8514     bool listContainsBase;
8515     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8516       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8517       assert (isThumbTwo());
8518       Inst.setOpcode(ARM::t2STMIA_UPD);
8519       return true;
8520     }
8521     break;
8522   }
8523   case ARM::tPOP: {
8524     bool listContainsBase;
8525     // If the register list contains any high registers, we need to use
8526     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8527     // should have generated an error in validateInstruction().
8528     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8529       return false;
8530     assert (isThumbTwo());
8531     Inst.setOpcode(ARM::t2LDMIA_UPD);
8532     // Add the base register and writeback operands.
8533     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8534     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8535     return true;
8536   }
8537   case ARM::tPUSH: {
8538     bool listContainsBase;
8539     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8540       return false;
8541     assert (isThumbTwo());
8542     Inst.setOpcode(ARM::t2STMDB_UPD);
8543     // Add the base register and writeback operands.
8544     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8545     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8546     return true;
8547   }
8548   case ARM::t2MOVi: {
8549     // If we can use the 16-bit encoding and the user didn't explicitly
8550     // request the 32-bit variant, transform it here.
8551     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8552         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8553         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8554           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8555          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8556         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8557          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8558       // The operands aren't in the same order for tMOVi8...
8559       MCInst TmpInst;
8560       TmpInst.setOpcode(ARM::tMOVi8);
8561       TmpInst.addOperand(Inst.getOperand(0));
8562       TmpInst.addOperand(Inst.getOperand(4));
8563       TmpInst.addOperand(Inst.getOperand(1));
8564       TmpInst.addOperand(Inst.getOperand(2));
8565       TmpInst.addOperand(Inst.getOperand(3));
8566       Inst = TmpInst;
8567       return true;
8568     }
8569     break;
8570   }
8571   case ARM::t2MOVr: {
8572     // If we can use the 16-bit encoding and the user didn't explicitly
8573     // request the 32-bit variant, transform it here.
8574     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8575         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8576         Inst.getOperand(2).getImm() == ARMCC::AL &&
8577         Inst.getOperand(4).getReg() == ARM::CPSR &&
8578         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8579          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8580       // The operands aren't the same for tMOV[S]r... (no cc_out)
8581       MCInst TmpInst;
8582       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8583       TmpInst.addOperand(Inst.getOperand(0));
8584       TmpInst.addOperand(Inst.getOperand(1));
8585       TmpInst.addOperand(Inst.getOperand(2));
8586       TmpInst.addOperand(Inst.getOperand(3));
8587       Inst = TmpInst;
8588       return true;
8589     }
8590     break;
8591   }
8592   case ARM::t2SXTH:
8593   case ARM::t2SXTB:
8594   case ARM::t2UXTH:
8595   case ARM::t2UXTB: {
8596     // If we can use the 16-bit encoding and the user didn't explicitly
8597     // request the 32-bit variant, transform it here.
8598     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8599         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8600         Inst.getOperand(2).getImm() == 0 &&
8601         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8602          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8603       unsigned NewOpc;
8604       switch (Inst.getOpcode()) {
8605       default: llvm_unreachable("Illegal opcode!");
8606       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8607       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8608       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8609       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8610       }
8611       // The operands aren't the same for thumb1 (no rotate operand).
8612       MCInst TmpInst;
8613       TmpInst.setOpcode(NewOpc);
8614       TmpInst.addOperand(Inst.getOperand(0));
8615       TmpInst.addOperand(Inst.getOperand(1));
8616       TmpInst.addOperand(Inst.getOperand(3));
8617       TmpInst.addOperand(Inst.getOperand(4));
8618       Inst = TmpInst;
8619       return true;
8620     }
8621     break;
8622   }
8623   case ARM::MOVsi: {
8624     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8625     // rrx shifts and asr/lsr of #32 is encoded as 0
8626     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8627       return false;
8628     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8629       // Shifting by zero is accepted as a vanilla 'MOVr'
8630       MCInst TmpInst;
8631       TmpInst.setOpcode(ARM::MOVr);
8632       TmpInst.addOperand(Inst.getOperand(0));
8633       TmpInst.addOperand(Inst.getOperand(1));
8634       TmpInst.addOperand(Inst.getOperand(3));
8635       TmpInst.addOperand(Inst.getOperand(4));
8636       TmpInst.addOperand(Inst.getOperand(5));
8637       Inst = TmpInst;
8638       return true;
8639     }
8640     return false;
8641   }
8642   case ARM::ANDrsi:
8643   case ARM::ORRrsi:
8644   case ARM::EORrsi:
8645   case ARM::BICrsi:
8646   case ARM::SUBrsi:
8647   case ARM::ADDrsi: {
8648     unsigned newOpc;
8649     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8650     if (SOpc == ARM_AM::rrx) return false;
8651     switch (Inst.getOpcode()) {
8652     default: llvm_unreachable("unexpected opcode!");
8653     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8654     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8655     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8656     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8657     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8658     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8659     }
8660     // If the shift is by zero, use the non-shifted instruction definition.
8661     // The exception is for right shifts, where 0 == 32
8662     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8663         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8664       MCInst TmpInst;
8665       TmpInst.setOpcode(newOpc);
8666       TmpInst.addOperand(Inst.getOperand(0));
8667       TmpInst.addOperand(Inst.getOperand(1));
8668       TmpInst.addOperand(Inst.getOperand(2));
8669       TmpInst.addOperand(Inst.getOperand(4));
8670       TmpInst.addOperand(Inst.getOperand(5));
8671       TmpInst.addOperand(Inst.getOperand(6));
8672       Inst = TmpInst;
8673       return true;
8674     }
8675     return false;
8676   }
8677   case ARM::ITasm:
8678   case ARM::t2IT: {
8679     MCOperand &MO = Inst.getOperand(1);
8680     unsigned Mask = MO.getImm();
8681     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8682 
8683     // Set up the IT block state according to the IT instruction we just
8684     // matched.
8685     assert(!inITBlock() && "nested IT blocks?!");
8686     startExplicitITBlock(Cond, Mask);
8687     MO.setImm(getITMaskEncoding());
8688     break;
8689   }
8690   case ARM::t2LSLrr:
8691   case ARM::t2LSRrr:
8692   case ARM::t2ASRrr:
8693   case ARM::t2SBCrr:
8694   case ARM::t2RORrr:
8695   case ARM::t2BICrr:
8696   {
8697     // Assemblers should use the narrow encodings of these instructions when permissible.
8698     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8699          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8700         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8701         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8702          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8703         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8704          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8705              ".w"))) {
8706       unsigned NewOpc;
8707       switch (Inst.getOpcode()) {
8708         default: llvm_unreachable("unexpected opcode");
8709         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8710         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8711         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8712         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8713         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8714         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8715       }
8716       MCInst TmpInst;
8717       TmpInst.setOpcode(NewOpc);
8718       TmpInst.addOperand(Inst.getOperand(0));
8719       TmpInst.addOperand(Inst.getOperand(5));
8720       TmpInst.addOperand(Inst.getOperand(1));
8721       TmpInst.addOperand(Inst.getOperand(2));
8722       TmpInst.addOperand(Inst.getOperand(3));
8723       TmpInst.addOperand(Inst.getOperand(4));
8724       Inst = TmpInst;
8725       return true;
8726     }
8727     return false;
8728   }
8729   case ARM::t2ANDrr:
8730   case ARM::t2EORrr:
8731   case ARM::t2ADCrr:
8732   case ARM::t2ORRrr:
8733   {
8734     // Assemblers should use the narrow encodings of these instructions when permissible.
8735     // These instructions are special in that they are commutable, so shorter encodings
8736     // are available more often.
8737     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8738          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8739         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8740          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8741         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8742          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8743         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8744          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8745              ".w"))) {
8746       unsigned NewOpc;
8747       switch (Inst.getOpcode()) {
8748         default: llvm_unreachable("unexpected opcode");
8749         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8750         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8751         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8752         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8753       }
8754       MCInst TmpInst;
8755       TmpInst.setOpcode(NewOpc);
8756       TmpInst.addOperand(Inst.getOperand(0));
8757       TmpInst.addOperand(Inst.getOperand(5));
8758       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8759         TmpInst.addOperand(Inst.getOperand(1));
8760         TmpInst.addOperand(Inst.getOperand(2));
8761       } else {
8762         TmpInst.addOperand(Inst.getOperand(2));
8763         TmpInst.addOperand(Inst.getOperand(1));
8764       }
8765       TmpInst.addOperand(Inst.getOperand(3));
8766       TmpInst.addOperand(Inst.getOperand(4));
8767       Inst = TmpInst;
8768       return true;
8769     }
8770     return false;
8771   }
8772   }
8773   return false;
8774 }
8775 
8776 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8777   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8778   // suffix depending on whether they're in an IT block or not.
8779   unsigned Opc = Inst.getOpcode();
8780   const MCInstrDesc &MCID = MII.get(Opc);
8781   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8782     assert(MCID.hasOptionalDef() &&
8783            "optionally flag setting instruction missing optional def operand");
8784     assert(MCID.NumOperands == Inst.getNumOperands() &&
8785            "operand count mismatch!");
8786     // Find the optional-def operand (cc_out).
8787     unsigned OpNo;
8788     for (OpNo = 0;
8789          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8790          ++OpNo)
8791       ;
8792     // If we're parsing Thumb1, reject it completely.
8793     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8794       return Match_RequiresFlagSetting;
8795     // If we're parsing Thumb2, which form is legal depends on whether we're
8796     // in an IT block.
8797     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8798         !inITBlock())
8799       return Match_RequiresITBlock;
8800     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8801         inITBlock())
8802       return Match_RequiresNotITBlock;
8803     // LSL with zero immediate is not allowed in an IT block
8804     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8805       return Match_RequiresNotITBlock;
8806   } else if (isThumbOne()) {
8807     // Some high-register supporting Thumb1 encodings only allow both registers
8808     // to be from r0-r7 when in Thumb2.
8809     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8810         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8811         isARMLowRegister(Inst.getOperand(2).getReg()))
8812       return Match_RequiresThumb2;
8813     // Others only require ARMv6 or later.
8814     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8815              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8816              isARMLowRegister(Inst.getOperand(1).getReg()))
8817       return Match_RequiresV6;
8818   }
8819 
8820   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8821   // than the loop below can handle, so it uses the GPRnopc register class and
8822   // we do SP handling here.
8823   if (Opc == ARM::t2MOVr && !hasV8Ops())
8824   {
8825     // SP as both source and destination is not allowed
8826     if (Inst.getOperand(0).getReg() == ARM::SP &&
8827         Inst.getOperand(1).getReg() == ARM::SP)
8828       return Match_RequiresV8;
8829     // When flags-setting SP as either source or destination is not allowed
8830     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8831         (Inst.getOperand(0).getReg() == ARM::SP ||
8832          Inst.getOperand(1).getReg() == ARM::SP))
8833       return Match_RequiresV8;
8834   }
8835 
8836   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8837     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8838       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8839       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8840         return Match_RequiresV8;
8841       else if (Inst.getOperand(I).getReg() == ARM::PC)
8842         return Match_InvalidOperand;
8843     }
8844 
8845   return Match_Success;
8846 }
8847 
8848 namespace llvm {
8849 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8850   return true; // In an assembly source, no need to second-guess
8851 }
8852 }
8853 
8854 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8855 // the last instruction in the block.
8856 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8857   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8858 
8859   // All branch & call instructions terminate IT blocks.
8860   if (MCID.isTerminator() || MCID.isCall() || MCID.isReturn() ||
8861       MCID.isBranch() || MCID.isIndirectBranch())
8862     return true;
8863 
8864   // Any arithmetic instruction which writes to the PC also terminates the IT
8865   // block.
8866   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8867     MCOperand &Op = Inst.getOperand(OpIdx);
8868     if (Op.isReg() && Op.getReg() == ARM::PC)
8869       return true;
8870   }
8871 
8872   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8873     return true;
8874 
8875   // Instructions with variable operand lists, which write to the variable
8876   // operands. We only care about Thumb instructions here, as ARM instructions
8877   // obviously can't be in an IT block.
8878   switch (Inst.getOpcode()) {
8879   case ARM::tLDMIA:
8880   case ARM::t2LDMIA:
8881   case ARM::t2LDMIA_UPD:
8882   case ARM::t2LDMDB:
8883   case ARM::t2LDMDB_UPD:
8884     if (listContainsReg(Inst, 3, ARM::PC))
8885       return true;
8886     break;
8887   case ARM::tPOP:
8888     if (listContainsReg(Inst, 2, ARM::PC))
8889       return true;
8890     break;
8891   }
8892 
8893   return false;
8894 }
8895 
8896 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8897                                           uint64_t &ErrorInfo,
8898                                           bool MatchingInlineAsm,
8899                                           bool &EmitInITBlock,
8900                                           MCStreamer &Out) {
8901   // If we can't use an implicit IT block here, just match as normal.
8902   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8903     return MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8904 
8905   // Try to match the instruction in an extension of the current IT block (if
8906   // there is one).
8907   if (inImplicitITBlock()) {
8908     extendImplicitITBlock(ITState.Cond);
8909     if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8910             Match_Success) {
8911       // The match succeded, but we still have to check that the instruction is
8912       // valid in this implicit IT block.
8913       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8914       if (MCID.isPredicable()) {
8915         ARMCC::CondCodes InstCond =
8916             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8917                 .getImm();
8918         ARMCC::CondCodes ITCond = currentITCond();
8919         if (InstCond == ITCond) {
8920           EmitInITBlock = true;
8921           return Match_Success;
8922         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
8923           invertCurrentITCondition();
8924           EmitInITBlock = true;
8925           return Match_Success;
8926         }
8927       }
8928     }
8929     rewindImplicitITPosition();
8930   }
8931 
8932   // Finish the current IT block, and try to match outside any IT block.
8933   flushPendingInstructions(Out);
8934   unsigned PlainMatchResult =
8935       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8936   if (PlainMatchResult == Match_Success) {
8937     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8938     if (MCID.isPredicable()) {
8939       ARMCC::CondCodes InstCond =
8940           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8941               .getImm();
8942       // Some forms of the branch instruction have their own condition code
8943       // fields, so can be conditionally executed without an IT block.
8944       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
8945         EmitInITBlock = false;
8946         return Match_Success;
8947       }
8948       if (InstCond == ARMCC::AL) {
8949         EmitInITBlock = false;
8950         return Match_Success;
8951       }
8952     } else {
8953       EmitInITBlock = false;
8954       return Match_Success;
8955     }
8956   }
8957 
8958   // Try to match in a new IT block. The matcher doesn't check the actual
8959   // condition, so we create an IT block with a dummy condition, and fix it up
8960   // once we know the actual condition.
8961   startImplicitITBlock();
8962   if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8963       Match_Success) {
8964     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8965     if (MCID.isPredicable()) {
8966       ITState.Cond =
8967           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8968               .getImm();
8969       EmitInITBlock = true;
8970       return Match_Success;
8971     }
8972   }
8973   discardImplicitITBlock();
8974 
8975   // If none of these succeed, return the error we got when trying to match
8976   // outside any IT blocks.
8977   EmitInITBlock = false;
8978   return PlainMatchResult;
8979 }
8980 
8981 static const char *getSubtargetFeatureName(uint64_t Val);
8982 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8983                                            OperandVector &Operands,
8984                                            MCStreamer &Out, uint64_t &ErrorInfo,
8985                                            bool MatchingInlineAsm) {
8986   MCInst Inst;
8987   unsigned MatchResult;
8988   bool PendConditionalInstruction = false;
8989 
8990   MatchResult = MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm,
8991                                  PendConditionalInstruction, Out);
8992 
8993   SMLoc ErrorLoc;
8994   if (ErrorInfo < Operands.size()) {
8995     ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8996     if (ErrorLoc == SMLoc())
8997       ErrorLoc = IDLoc;
8998   }
8999 
9000   switch (MatchResult) {
9001   case Match_Success:
9002     // Context sensitive operand constraints aren't handled by the matcher,
9003     // so check them here.
9004     if (validateInstruction(Inst, Operands)) {
9005       // Still progress the IT block, otherwise one wrong condition causes
9006       // nasty cascading errors.
9007       forwardITPosition();
9008       return true;
9009     }
9010 
9011     { // processInstruction() updates inITBlock state, we need to save it away
9012       bool wasInITBlock = inITBlock();
9013 
9014       // Some instructions need post-processing to, for example, tweak which
9015       // encoding is selected. Loop on it while changes happen so the
9016       // individual transformations can chain off each other. E.g.,
9017       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9018       while (processInstruction(Inst, Operands, Out))
9019         ;
9020 
9021       // Only after the instruction is fully processed, we can validate it
9022       if (wasInITBlock && hasV8Ops() && isThumb() &&
9023           !isV8EligibleForIT(&Inst)) {
9024         Warning(IDLoc, "deprecated instruction in IT block");
9025       }
9026     }
9027 
9028     // Only move forward at the very end so that everything in validate
9029     // and process gets a consistent answer about whether we're in an IT
9030     // block.
9031     forwardITPosition();
9032 
9033     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9034     // doesn't actually encode.
9035     if (Inst.getOpcode() == ARM::ITasm)
9036       return false;
9037 
9038     Inst.setLoc(IDLoc);
9039     if (PendConditionalInstruction) {
9040       PendingConditionalInsts.push_back(Inst);
9041       if (isITBlockFull() || isITBlockTerminator(Inst))
9042         flushPendingInstructions(Out);
9043     } else {
9044       Out.EmitInstruction(Inst, getSTI());
9045     }
9046     return false;
9047   case Match_MissingFeature: {
9048     assert(ErrorInfo && "Unknown missing feature!");
9049     // Special case the error message for the very common case where only
9050     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
9051     std::string Msg = "instruction requires:";
9052     uint64_t Mask = 1;
9053     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
9054       if (ErrorInfo & Mask) {
9055         Msg += " ";
9056         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
9057       }
9058       Mask <<= 1;
9059     }
9060     return Error(IDLoc, Msg);
9061   }
9062   case Match_InvalidOperand: {
9063     SMLoc ErrorLoc = IDLoc;
9064     if (ErrorInfo != ~0ULL) {
9065       if (ErrorInfo >= Operands.size())
9066         return Error(IDLoc, "too few operands for instruction");
9067 
9068       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9069       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9070     }
9071 
9072     return Error(ErrorLoc, "invalid operand for instruction");
9073   }
9074   case Match_MnemonicFail:
9075     return Error(IDLoc, "invalid instruction",
9076                  ((ARMOperand &)*Operands[0]).getLocRange());
9077   case Match_RequiresNotITBlock:
9078     return Error(IDLoc, "flag setting instruction only valid outside IT block");
9079   case Match_RequiresITBlock:
9080     return Error(IDLoc, "instruction only valid inside IT block");
9081   case Match_RequiresV6:
9082     return Error(IDLoc, "instruction variant requires ARMv6 or later");
9083   case Match_RequiresThumb2:
9084     return Error(IDLoc, "instruction variant requires Thumb2");
9085   case Match_RequiresV8:
9086     return Error(IDLoc, "instruction variant requires ARMv8 or later");
9087   case Match_RequiresFlagSetting:
9088     return Error(IDLoc, "no flag-preserving variant of this instruction available");
9089   case Match_ImmRange0_1:
9090     return Error(ErrorLoc, "immediate operand must be in the range [0,1]");
9091   case Match_ImmRange0_3:
9092     return Error(ErrorLoc, "immediate operand must be in the range [0,3]");
9093   case Match_ImmRange0_7:
9094     return Error(ErrorLoc, "immediate operand must be in the range [0,7]");
9095   case Match_ImmRange0_15:
9096     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
9097   case Match_ImmRange0_31:
9098     return Error(ErrorLoc, "immediate operand must be in the range [0,31]");
9099   case Match_ImmRange0_32:
9100     return Error(ErrorLoc, "immediate operand must be in the range [0,32]");
9101   case Match_ImmRange0_63:
9102     return Error(ErrorLoc, "immediate operand must be in the range [0,63]");
9103   case Match_ImmRange0_239:
9104     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
9105   case Match_ImmRange0_255:
9106     return Error(ErrorLoc, "immediate operand must be in the range [0,255]");
9107   case Match_ImmRange0_4095:
9108     return Error(ErrorLoc, "immediate operand must be in the range [0,4095]");
9109   case Match_ImmRange0_65535:
9110     return Error(ErrorLoc, "immediate operand must be in the range [0,65535]");
9111   case Match_ImmRange1_7:
9112     return Error(ErrorLoc, "immediate operand must be in the range [1,7]");
9113   case Match_ImmRange1_8:
9114     return Error(ErrorLoc, "immediate operand must be in the range [1,8]");
9115   case Match_ImmRange1_15:
9116     return Error(ErrorLoc, "immediate operand must be in the range [1,15]");
9117   case Match_ImmRange1_16:
9118     return Error(ErrorLoc, "immediate operand must be in the range [1,16]");
9119   case Match_ImmRange1_31:
9120     return Error(ErrorLoc, "immediate operand must be in the range [1,31]");
9121   case Match_ImmRange1_32:
9122     return Error(ErrorLoc, "immediate operand must be in the range [1,32]");
9123   case Match_ImmRange1_64:
9124     return Error(ErrorLoc, "immediate operand must be in the range [1,64]");
9125   case Match_ImmRange8_8:
9126     return Error(ErrorLoc, "immediate operand must be 8.");
9127   case Match_ImmRange16_16:
9128     return Error(ErrorLoc, "immediate operand must be 16.");
9129   case Match_ImmRange32_32:
9130     return Error(ErrorLoc, "immediate operand must be 32.");
9131   case Match_ImmRange256_65535:
9132     return Error(ErrorLoc, "immediate operand must be in the range [255,65535]");
9133   case Match_ImmRange0_16777215:
9134     return Error(ErrorLoc, "immediate operand must be in the range [0,0xffffff]");
9135   case Match_AlignedMemoryRequiresNone:
9136   case Match_DupAlignedMemoryRequiresNone:
9137   case Match_AlignedMemoryRequires16:
9138   case Match_DupAlignedMemoryRequires16:
9139   case Match_AlignedMemoryRequires32:
9140   case Match_DupAlignedMemoryRequires32:
9141   case Match_AlignedMemoryRequires64:
9142   case Match_DupAlignedMemoryRequires64:
9143   case Match_AlignedMemoryRequires64or128:
9144   case Match_DupAlignedMemoryRequires64or128:
9145   case Match_AlignedMemoryRequires64or128or256:
9146   {
9147     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
9148     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9149     switch (MatchResult) {
9150       default:
9151         llvm_unreachable("Missing Match_Aligned type");
9152       case Match_AlignedMemoryRequiresNone:
9153       case Match_DupAlignedMemoryRequiresNone:
9154         return Error(ErrorLoc, "alignment must be omitted");
9155       case Match_AlignedMemoryRequires16:
9156       case Match_DupAlignedMemoryRequires16:
9157         return Error(ErrorLoc, "alignment must be 16 or omitted");
9158       case Match_AlignedMemoryRequires32:
9159       case Match_DupAlignedMemoryRequires32:
9160         return Error(ErrorLoc, "alignment must be 32 or omitted");
9161       case Match_AlignedMemoryRequires64:
9162       case Match_DupAlignedMemoryRequires64:
9163         return Error(ErrorLoc, "alignment must be 64 or omitted");
9164       case Match_AlignedMemoryRequires64or128:
9165       case Match_DupAlignedMemoryRequires64or128:
9166         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
9167       case Match_AlignedMemoryRequires64or128or256:
9168         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
9169     }
9170   }
9171   }
9172 
9173   llvm_unreachable("Implement any new match types added!");
9174 }
9175 
9176 /// parseDirective parses the arm specific directives
9177 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9178   const MCObjectFileInfo::Environment Format =
9179     getContext().getObjectFileInfo()->getObjectFileType();
9180   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9181   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9182 
9183   StringRef IDVal = DirectiveID.getIdentifier();
9184   if (IDVal == ".word")
9185     parseLiteralValues(4, DirectiveID.getLoc());
9186   else if (IDVal == ".short" || IDVal == ".hword")
9187     parseLiteralValues(2, DirectiveID.getLoc());
9188   else if (IDVal == ".thumb")
9189     parseDirectiveThumb(DirectiveID.getLoc());
9190   else if (IDVal == ".arm")
9191     parseDirectiveARM(DirectiveID.getLoc());
9192   else if (IDVal == ".thumb_func")
9193     parseDirectiveThumbFunc(DirectiveID.getLoc());
9194   else if (IDVal == ".code")
9195     parseDirectiveCode(DirectiveID.getLoc());
9196   else if (IDVal == ".syntax")
9197     parseDirectiveSyntax(DirectiveID.getLoc());
9198   else if (IDVal == ".unreq")
9199     parseDirectiveUnreq(DirectiveID.getLoc());
9200   else if (IDVal == ".fnend")
9201     parseDirectiveFnEnd(DirectiveID.getLoc());
9202   else if (IDVal == ".cantunwind")
9203     parseDirectiveCantUnwind(DirectiveID.getLoc());
9204   else if (IDVal == ".personality")
9205     parseDirectivePersonality(DirectiveID.getLoc());
9206   else if (IDVal == ".handlerdata")
9207     parseDirectiveHandlerData(DirectiveID.getLoc());
9208   else if (IDVal == ".setfp")
9209     parseDirectiveSetFP(DirectiveID.getLoc());
9210   else if (IDVal == ".pad")
9211     parseDirectivePad(DirectiveID.getLoc());
9212   else if (IDVal == ".save")
9213     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9214   else if (IDVal == ".vsave")
9215     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9216   else if (IDVal == ".ltorg" || IDVal == ".pool")
9217     parseDirectiveLtorg(DirectiveID.getLoc());
9218   else if (IDVal == ".even")
9219     parseDirectiveEven(DirectiveID.getLoc());
9220   else if (IDVal == ".personalityindex")
9221     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9222   else if (IDVal == ".unwind_raw")
9223     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9224   else if (IDVal == ".movsp")
9225     parseDirectiveMovSP(DirectiveID.getLoc());
9226   else if (IDVal == ".arch_extension")
9227     parseDirectiveArchExtension(DirectiveID.getLoc());
9228   else if (IDVal == ".align")
9229     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9230   else if (IDVal == ".thumb_set")
9231     parseDirectiveThumbSet(DirectiveID.getLoc());
9232   else if (!IsMachO && !IsCOFF) {
9233     if (IDVal == ".arch")
9234       parseDirectiveArch(DirectiveID.getLoc());
9235     else if (IDVal == ".cpu")
9236       parseDirectiveCPU(DirectiveID.getLoc());
9237     else if (IDVal == ".eabi_attribute")
9238       parseDirectiveEabiAttr(DirectiveID.getLoc());
9239     else if (IDVal == ".fpu")
9240       parseDirectiveFPU(DirectiveID.getLoc());
9241     else if (IDVal == ".fnstart")
9242       parseDirectiveFnStart(DirectiveID.getLoc());
9243     else if (IDVal == ".inst")
9244       parseDirectiveInst(DirectiveID.getLoc());
9245     else if (IDVal == ".inst.n")
9246       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9247     else if (IDVal == ".inst.w")
9248       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9249     else if (IDVal == ".object_arch")
9250       parseDirectiveObjectArch(DirectiveID.getLoc());
9251     else if (IDVal == ".tlsdescseq")
9252       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9253     else
9254       return true;
9255   } else
9256     return true;
9257   return false;
9258 }
9259 
9260 /// parseLiteralValues
9261 ///  ::= .hword expression [, expression]*
9262 ///  ::= .short expression [, expression]*
9263 ///  ::= .word expression [, expression]*
9264 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9265   auto parseOne = [&]() -> bool {
9266     const MCExpr *Value;
9267     if (getParser().parseExpression(Value))
9268       return true;
9269     getParser().getStreamer().EmitValue(Value, Size, L);
9270     return false;
9271   };
9272   return (parseMany(parseOne));
9273 }
9274 
9275 /// parseDirectiveThumb
9276 ///  ::= .thumb
9277 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9278   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9279       check(!hasThumb(), L, "target does not support Thumb mode"))
9280     return true;
9281 
9282   if (!isThumb())
9283     SwitchMode();
9284 
9285   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9286   return false;
9287 }
9288 
9289 /// parseDirectiveARM
9290 ///  ::= .arm
9291 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9292   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9293       check(!hasARM(), L, "target does not support ARM mode"))
9294     return true;
9295 
9296   if (isThumb())
9297     SwitchMode();
9298   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9299   return false;
9300 }
9301 
9302 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9303   // We need to flush the current implicit IT block on a label, because it is
9304   // not legal to branch into an IT block.
9305   flushPendingInstructions(getStreamer());
9306   if (NextSymbolIsThumb) {
9307     getParser().getStreamer().EmitThumbFunc(Symbol);
9308     NextSymbolIsThumb = false;
9309   }
9310 }
9311 
9312 /// parseDirectiveThumbFunc
9313 ///  ::= .thumbfunc symbol_name
9314 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9315   MCAsmParser &Parser = getParser();
9316   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9317   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9318 
9319   // Darwin asm has (optionally) function name after .thumb_func direction
9320   // ELF doesn't
9321 
9322   if (IsMachO) {
9323     if (Parser.getTok().is(AsmToken::Identifier) ||
9324         Parser.getTok().is(AsmToken::String)) {
9325       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9326           Parser.getTok().getIdentifier());
9327       getParser().getStreamer().EmitThumbFunc(Func);
9328       Parser.Lex();
9329       if (parseToken(AsmToken::EndOfStatement,
9330                      "unexpected token in '.thumb_func' directive"))
9331         return true;
9332       return false;
9333     }
9334   }
9335 
9336   if (parseToken(AsmToken::EndOfStatement,
9337                  "unexpected token in '.thumb_func' directive"))
9338     return true;
9339 
9340   NextSymbolIsThumb = true;
9341   return false;
9342 }
9343 
9344 /// parseDirectiveSyntax
9345 ///  ::= .syntax unified | divided
9346 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9347   MCAsmParser &Parser = getParser();
9348   const AsmToken &Tok = Parser.getTok();
9349   if (Tok.isNot(AsmToken::Identifier)) {
9350     Error(L, "unexpected token in .syntax directive");
9351     return false;
9352   }
9353 
9354   StringRef Mode = Tok.getString();
9355   Parser.Lex();
9356   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9357             "'.syntax divided' arm assembly not supported") ||
9358       check(Mode != "unified" && Mode != "UNIFIED", L,
9359             "unrecognized syntax mode in .syntax directive") ||
9360       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9361     return true;
9362 
9363   // TODO tell the MC streamer the mode
9364   // getParser().getStreamer().Emit???();
9365   return false;
9366 }
9367 
9368 /// parseDirectiveCode
9369 ///  ::= .code 16 | 32
9370 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9371   MCAsmParser &Parser = getParser();
9372   const AsmToken &Tok = Parser.getTok();
9373   if (Tok.isNot(AsmToken::Integer))
9374     return Error(L, "unexpected token in .code directive");
9375   int64_t Val = Parser.getTok().getIntVal();
9376   if (Val != 16 && Val != 32) {
9377     Error(L, "invalid operand to .code directive");
9378     return false;
9379   }
9380   Parser.Lex();
9381 
9382   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9383     return true;
9384 
9385   if (Val == 16) {
9386     if (!hasThumb())
9387       return Error(L, "target does not support Thumb mode");
9388 
9389     if (!isThumb())
9390       SwitchMode();
9391     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9392   } else {
9393     if (!hasARM())
9394       return Error(L, "target does not support ARM mode");
9395 
9396     if (isThumb())
9397       SwitchMode();
9398     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9399   }
9400 
9401   return false;
9402 }
9403 
9404 /// parseDirectiveReq
9405 ///  ::= name .req registername
9406 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9407   MCAsmParser &Parser = getParser();
9408   Parser.Lex(); // Eat the '.req' token.
9409   unsigned Reg;
9410   SMLoc SRegLoc, ERegLoc;
9411   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9412             "register name expected") ||
9413       parseToken(AsmToken::EndOfStatement,
9414                  "unexpected input in .req directive."))
9415     return true;
9416 
9417   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9418     return Error(SRegLoc,
9419                  "redefinition of '" + Name + "' does not match original.");
9420 
9421   return false;
9422 }
9423 
9424 /// parseDirectiveUneq
9425 ///  ::= .unreq registername
9426 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9427   MCAsmParser &Parser = getParser();
9428   if (Parser.getTok().isNot(AsmToken::Identifier))
9429     return Error(L, "unexpected input in .unreq directive.");
9430   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9431   Parser.Lex(); // Eat the identifier.
9432   if (parseToken(AsmToken::EndOfStatement,
9433                  "unexpected input in '.unreq' directive"))
9434     return true;
9435   return false;
9436 }
9437 
9438 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9439 // before, if supported by the new target, or emit mapping symbols for the mode
9440 // switch.
9441 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9442   if (WasThumb != isThumb()) {
9443     if (WasThumb && hasThumb()) {
9444       // Stay in Thumb mode
9445       SwitchMode();
9446     } else if (!WasThumb && hasARM()) {
9447       // Stay in ARM mode
9448       SwitchMode();
9449     } else {
9450       // Mode switch forced, because the new arch doesn't support the old mode.
9451       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9452                                                             : MCAF_Code32);
9453       // Warn about the implcit mode switch. GAS does not switch modes here,
9454       // but instead stays in the old mode, reporting an error on any following
9455       // instructions as the mode does not exist on the target.
9456       Warning(Loc, Twine("new target does not support ") +
9457                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9458                        (!WasThumb ? "thumb" : "arm") + " mode");
9459     }
9460   }
9461 }
9462 
9463 /// parseDirectiveArch
9464 ///  ::= .arch token
9465 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9466   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9467   unsigned ID = ARM::parseArch(Arch);
9468 
9469   if (ID == ARM::AK_INVALID)
9470     return Error(L, "Unknown arch name");
9471 
9472   bool WasThumb = isThumb();
9473   Triple T;
9474   MCSubtargetInfo &STI = copySTI();
9475   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9476   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9477   FixModeAfterArchChange(WasThumb, L);
9478 
9479   getTargetStreamer().emitArch(ID);
9480   return false;
9481 }
9482 
9483 /// parseDirectiveEabiAttr
9484 ///  ::= .eabi_attribute int, int [, "str"]
9485 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9486 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9487   MCAsmParser &Parser = getParser();
9488   int64_t Tag;
9489   SMLoc TagLoc;
9490   TagLoc = Parser.getTok().getLoc();
9491   if (Parser.getTok().is(AsmToken::Identifier)) {
9492     StringRef Name = Parser.getTok().getIdentifier();
9493     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9494     if (Tag == -1) {
9495       Error(TagLoc, "attribute name not recognised: " + Name);
9496       return false;
9497     }
9498     Parser.Lex();
9499   } else {
9500     const MCExpr *AttrExpr;
9501 
9502     TagLoc = Parser.getTok().getLoc();
9503     if (Parser.parseExpression(AttrExpr))
9504       return true;
9505 
9506     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9507     if (check(!CE, TagLoc, "expected numeric constant"))
9508       return true;
9509 
9510     Tag = CE->getValue();
9511   }
9512 
9513   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9514     return true;
9515 
9516   StringRef StringValue = "";
9517   bool IsStringValue = false;
9518 
9519   int64_t IntegerValue = 0;
9520   bool IsIntegerValue = false;
9521 
9522   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9523     IsStringValue = true;
9524   else if (Tag == ARMBuildAttrs::compatibility) {
9525     IsStringValue = true;
9526     IsIntegerValue = true;
9527   } else if (Tag < 32 || Tag % 2 == 0)
9528     IsIntegerValue = true;
9529   else if (Tag % 2 == 1)
9530     IsStringValue = true;
9531   else
9532     llvm_unreachable("invalid tag type");
9533 
9534   if (IsIntegerValue) {
9535     const MCExpr *ValueExpr;
9536     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9537     if (Parser.parseExpression(ValueExpr))
9538       return true;
9539 
9540     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9541     if (!CE)
9542       return Error(ValueExprLoc, "expected numeric constant");
9543     IntegerValue = CE->getValue();
9544   }
9545 
9546   if (Tag == ARMBuildAttrs::compatibility) {
9547     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9548       return true;
9549   }
9550 
9551   if (IsStringValue) {
9552     if (Parser.getTok().isNot(AsmToken::String))
9553       return Error(Parser.getTok().getLoc(), "bad string constant");
9554 
9555     StringValue = Parser.getTok().getStringContents();
9556     Parser.Lex();
9557   }
9558 
9559   if (Parser.parseToken(AsmToken::EndOfStatement,
9560                         "unexpected token in '.eabi_attribute' directive"))
9561     return true;
9562 
9563   if (IsIntegerValue && IsStringValue) {
9564     assert(Tag == ARMBuildAttrs::compatibility);
9565     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9566   } else if (IsIntegerValue)
9567     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9568   else if (IsStringValue)
9569     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9570   return false;
9571 }
9572 
9573 /// parseDirectiveCPU
9574 ///  ::= .cpu str
9575 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9576   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9577   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9578 
9579   // FIXME: This is using table-gen data, but should be moved to
9580   // ARMTargetParser once that is table-gen'd.
9581   if (!getSTI().isCPUStringValid(CPU))
9582     return Error(L, "Unknown CPU name");
9583 
9584   bool WasThumb = isThumb();
9585   MCSubtargetInfo &STI = copySTI();
9586   STI.setDefaultFeatures(CPU, "");
9587   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9588   FixModeAfterArchChange(WasThumb, L);
9589 
9590   return false;
9591 }
9592 /// parseDirectiveFPU
9593 ///  ::= .fpu str
9594 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9595   SMLoc FPUNameLoc = getTok().getLoc();
9596   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9597 
9598   unsigned ID = ARM::parseFPU(FPU);
9599   std::vector<StringRef> Features;
9600   if (!ARM::getFPUFeatures(ID, Features))
9601     return Error(FPUNameLoc, "Unknown FPU name");
9602 
9603   MCSubtargetInfo &STI = copySTI();
9604   for (auto Feature : Features)
9605     STI.ApplyFeatureFlag(Feature);
9606   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9607 
9608   getTargetStreamer().emitFPU(ID);
9609   return false;
9610 }
9611 
9612 /// parseDirectiveFnStart
9613 ///  ::= .fnstart
9614 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9615   if (parseToken(AsmToken::EndOfStatement,
9616                  "unexpected token in '.fnstart' directive"))
9617     return true;
9618 
9619   if (UC.hasFnStart()) {
9620     Error(L, ".fnstart starts before the end of previous one");
9621     UC.emitFnStartLocNotes();
9622     return true;
9623   }
9624 
9625   // Reset the unwind directives parser state
9626   UC.reset();
9627 
9628   getTargetStreamer().emitFnStart();
9629 
9630   UC.recordFnStart(L);
9631   return false;
9632 }
9633 
9634 /// parseDirectiveFnEnd
9635 ///  ::= .fnend
9636 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9637   if (parseToken(AsmToken::EndOfStatement,
9638                  "unexpected token in '.fnend' directive"))
9639     return true;
9640   // Check the ordering of unwind directives
9641   if (!UC.hasFnStart())
9642     return Error(L, ".fnstart must precede .fnend directive");
9643 
9644   // Reset the unwind directives parser state
9645   getTargetStreamer().emitFnEnd();
9646 
9647   UC.reset();
9648   return false;
9649 }
9650 
9651 /// parseDirectiveCantUnwind
9652 ///  ::= .cantunwind
9653 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9654   if (parseToken(AsmToken::EndOfStatement,
9655                  "unexpected token in '.cantunwind' directive"))
9656     return true;
9657 
9658   UC.recordCantUnwind(L);
9659   // Check the ordering of unwind directives
9660   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9661     return true;
9662 
9663   if (UC.hasHandlerData()) {
9664     Error(L, ".cantunwind can't be used with .handlerdata directive");
9665     UC.emitHandlerDataLocNotes();
9666     return true;
9667   }
9668   if (UC.hasPersonality()) {
9669     Error(L, ".cantunwind can't be used with .personality directive");
9670     UC.emitPersonalityLocNotes();
9671     return true;
9672   }
9673 
9674   getTargetStreamer().emitCantUnwind();
9675   return false;
9676 }
9677 
9678 /// parseDirectivePersonality
9679 ///  ::= .personality name
9680 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9681   MCAsmParser &Parser = getParser();
9682   bool HasExistingPersonality = UC.hasPersonality();
9683 
9684   // Parse the name of the personality routine
9685   if (Parser.getTok().isNot(AsmToken::Identifier))
9686     return Error(L, "unexpected input in .personality directive.");
9687   StringRef Name(Parser.getTok().getIdentifier());
9688   Parser.Lex();
9689 
9690   if (parseToken(AsmToken::EndOfStatement,
9691                  "unexpected token in '.personality' directive"))
9692     return true;
9693 
9694   UC.recordPersonality(L);
9695 
9696   // Check the ordering of unwind directives
9697   if (!UC.hasFnStart())
9698     return Error(L, ".fnstart must precede .personality directive");
9699   if (UC.cantUnwind()) {
9700     Error(L, ".personality can't be used with .cantunwind directive");
9701     UC.emitCantUnwindLocNotes();
9702     return true;
9703   }
9704   if (UC.hasHandlerData()) {
9705     Error(L, ".personality must precede .handlerdata directive");
9706     UC.emitHandlerDataLocNotes();
9707     return true;
9708   }
9709   if (HasExistingPersonality) {
9710     Error(L, "multiple personality directives");
9711     UC.emitPersonalityLocNotes();
9712     return true;
9713   }
9714 
9715   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9716   getTargetStreamer().emitPersonality(PR);
9717   return false;
9718 }
9719 
9720 /// parseDirectiveHandlerData
9721 ///  ::= .handlerdata
9722 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9723   if (parseToken(AsmToken::EndOfStatement,
9724                  "unexpected token in '.handlerdata' directive"))
9725     return true;
9726 
9727   UC.recordHandlerData(L);
9728   // Check the ordering of unwind directives
9729   if (!UC.hasFnStart())
9730     return Error(L, ".fnstart must precede .personality directive");
9731   if (UC.cantUnwind()) {
9732     Error(L, ".handlerdata can't be used with .cantunwind directive");
9733     UC.emitCantUnwindLocNotes();
9734     return true;
9735   }
9736 
9737   getTargetStreamer().emitHandlerData();
9738   return false;
9739 }
9740 
9741 /// parseDirectiveSetFP
9742 ///  ::= .setfp fpreg, spreg [, offset]
9743 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9744   MCAsmParser &Parser = getParser();
9745   // Check the ordering of unwind directives
9746   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9747       check(UC.hasHandlerData(), L,
9748             ".setfp must precede .handlerdata directive"))
9749     return true;
9750 
9751   // Parse fpreg
9752   SMLoc FPRegLoc = Parser.getTok().getLoc();
9753   int FPReg = tryParseRegister();
9754 
9755   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9756       Parser.parseToken(AsmToken::Comma, "comma expected"))
9757     return true;
9758 
9759   // Parse spreg
9760   SMLoc SPRegLoc = Parser.getTok().getLoc();
9761   int SPReg = tryParseRegister();
9762   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9763       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9764             "register should be either $sp or the latest fp register"))
9765     return true;
9766 
9767   // Update the frame pointer register
9768   UC.saveFPReg(FPReg);
9769 
9770   // Parse offset
9771   int64_t Offset = 0;
9772   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9773     if (Parser.getTok().isNot(AsmToken::Hash) &&
9774         Parser.getTok().isNot(AsmToken::Dollar))
9775       return Error(Parser.getTok().getLoc(), "'#' expected");
9776     Parser.Lex(); // skip hash token.
9777 
9778     const MCExpr *OffsetExpr;
9779     SMLoc ExLoc = Parser.getTok().getLoc();
9780     SMLoc EndLoc;
9781     if (getParser().parseExpression(OffsetExpr, EndLoc))
9782       return Error(ExLoc, "malformed setfp offset");
9783     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9784     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9785       return true;
9786     Offset = CE->getValue();
9787   }
9788 
9789   if (Parser.parseToken(AsmToken::EndOfStatement))
9790     return true;
9791 
9792   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9793                                 static_cast<unsigned>(SPReg), Offset);
9794   return false;
9795 }
9796 
9797 /// parseDirective
9798 ///  ::= .pad offset
9799 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9800   MCAsmParser &Parser = getParser();
9801   // Check the ordering of unwind directives
9802   if (!UC.hasFnStart())
9803     return Error(L, ".fnstart must precede .pad directive");
9804   if (UC.hasHandlerData())
9805     return Error(L, ".pad must precede .handlerdata directive");
9806 
9807   // Parse the offset
9808   if (Parser.getTok().isNot(AsmToken::Hash) &&
9809       Parser.getTok().isNot(AsmToken::Dollar))
9810     return Error(Parser.getTok().getLoc(), "'#' expected");
9811   Parser.Lex(); // skip hash token.
9812 
9813   const MCExpr *OffsetExpr;
9814   SMLoc ExLoc = Parser.getTok().getLoc();
9815   SMLoc EndLoc;
9816   if (getParser().parseExpression(OffsetExpr, EndLoc))
9817     return Error(ExLoc, "malformed pad offset");
9818   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9819   if (!CE)
9820     return Error(ExLoc, "pad offset must be an immediate");
9821 
9822   if (parseToken(AsmToken::EndOfStatement,
9823                  "unexpected token in '.pad' directive"))
9824     return true;
9825 
9826   getTargetStreamer().emitPad(CE->getValue());
9827   return false;
9828 }
9829 
9830 /// parseDirectiveRegSave
9831 ///  ::= .save  { registers }
9832 ///  ::= .vsave { registers }
9833 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9834   // Check the ordering of unwind directives
9835   if (!UC.hasFnStart())
9836     return Error(L, ".fnstart must precede .save or .vsave directives");
9837   if (UC.hasHandlerData())
9838     return Error(L, ".save or .vsave must precede .handlerdata directive");
9839 
9840   // RAII object to make sure parsed operands are deleted.
9841   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9842 
9843   // Parse the register list
9844   if (parseRegisterList(Operands) ||
9845       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9846     return true;
9847   ARMOperand &Op = (ARMOperand &)*Operands[0];
9848   if (!IsVector && !Op.isRegList())
9849     return Error(L, ".save expects GPR registers");
9850   if (IsVector && !Op.isDPRRegList())
9851     return Error(L, ".vsave expects DPR registers");
9852 
9853   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9854   return false;
9855 }
9856 
9857 /// parseDirectiveInst
9858 ///  ::= .inst opcode [, ...]
9859 ///  ::= .inst.n opcode [, ...]
9860 ///  ::= .inst.w opcode [, ...]
9861 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9862   int Width = 4;
9863 
9864   if (isThumb()) {
9865     switch (Suffix) {
9866     case 'n':
9867       Width = 2;
9868       break;
9869     case 'w':
9870       break;
9871     default:
9872       return Error(Loc, "cannot determine Thumb instruction size, "
9873                         "use inst.n/inst.w instead");
9874     }
9875   } else {
9876     if (Suffix)
9877       return Error(Loc, "width suffixes are invalid in ARM mode");
9878   }
9879 
9880   auto parseOne = [&]() -> bool {
9881     const MCExpr *Expr;
9882     if (getParser().parseExpression(Expr))
9883       return true;
9884     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9885     if (!Value) {
9886       return Error(Loc, "expected constant expression");
9887     }
9888 
9889     switch (Width) {
9890     case 2:
9891       if (Value->getValue() > 0xffff)
9892         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9893       break;
9894     case 4:
9895       if (Value->getValue() > 0xffffffff)
9896         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9897                               " operand is too big");
9898       break;
9899     default:
9900       llvm_unreachable("only supported widths are 2 and 4");
9901     }
9902 
9903     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9904     return false;
9905   };
9906 
9907   if (parseOptionalToken(AsmToken::EndOfStatement))
9908     return Error(Loc, "expected expression following directive");
9909   if (parseMany(parseOne))
9910     return true;
9911   return false;
9912 }
9913 
9914 /// parseDirectiveLtorg
9915 ///  ::= .ltorg | .pool
9916 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9917   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9918     return true;
9919   getTargetStreamer().emitCurrentConstantPool();
9920   return false;
9921 }
9922 
9923 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9924   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9925 
9926   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9927     return true;
9928 
9929   if (!Section) {
9930     getStreamer().InitSections(false);
9931     Section = getStreamer().getCurrentSectionOnly();
9932   }
9933 
9934   assert(Section && "must have section to emit alignment");
9935   if (Section->UseCodeAlign())
9936     getStreamer().EmitCodeAlignment(2);
9937   else
9938     getStreamer().EmitValueToAlignment(2);
9939 
9940   return false;
9941 }
9942 
9943 /// parseDirectivePersonalityIndex
9944 ///   ::= .personalityindex index
9945 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9946   MCAsmParser &Parser = getParser();
9947   bool HasExistingPersonality = UC.hasPersonality();
9948 
9949   const MCExpr *IndexExpression;
9950   SMLoc IndexLoc = Parser.getTok().getLoc();
9951   if (Parser.parseExpression(IndexExpression) ||
9952       parseToken(AsmToken::EndOfStatement,
9953                  "unexpected token in '.personalityindex' directive")) {
9954     return true;
9955   }
9956 
9957   UC.recordPersonalityIndex(L);
9958 
9959   if (!UC.hasFnStart()) {
9960     return Error(L, ".fnstart must precede .personalityindex directive");
9961   }
9962   if (UC.cantUnwind()) {
9963     Error(L, ".personalityindex cannot be used with .cantunwind");
9964     UC.emitCantUnwindLocNotes();
9965     return true;
9966   }
9967   if (UC.hasHandlerData()) {
9968     Error(L, ".personalityindex must precede .handlerdata directive");
9969     UC.emitHandlerDataLocNotes();
9970     return true;
9971   }
9972   if (HasExistingPersonality) {
9973     Error(L, "multiple personality directives");
9974     UC.emitPersonalityLocNotes();
9975     return true;
9976   }
9977 
9978   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9979   if (!CE)
9980     return Error(IndexLoc, "index must be a constant number");
9981   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9982     return Error(IndexLoc,
9983                  "personality routine index should be in range [0-3]");
9984 
9985   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9986   return false;
9987 }
9988 
9989 /// parseDirectiveUnwindRaw
9990 ///   ::= .unwind_raw offset, opcode [, opcode...]
9991 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9992   MCAsmParser &Parser = getParser();
9993   int64_t StackOffset;
9994   const MCExpr *OffsetExpr;
9995   SMLoc OffsetLoc = getLexer().getLoc();
9996 
9997   if (!UC.hasFnStart())
9998     return Error(L, ".fnstart must precede .unwind_raw directives");
9999   if (getParser().parseExpression(OffsetExpr))
10000     return Error(OffsetLoc, "expected expression");
10001 
10002   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10003   if (!CE)
10004     return Error(OffsetLoc, "offset must be a constant");
10005 
10006   StackOffset = CE->getValue();
10007 
10008   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
10009     return true;
10010 
10011   SmallVector<uint8_t, 16> Opcodes;
10012 
10013   auto parseOne = [&]() -> bool {
10014     const MCExpr *OE;
10015     SMLoc OpcodeLoc = getLexer().getLoc();
10016     if (check(getLexer().is(AsmToken::EndOfStatement) ||
10017                   Parser.parseExpression(OE),
10018               OpcodeLoc, "expected opcode expression"))
10019       return true;
10020     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
10021     if (!OC)
10022       return Error(OpcodeLoc, "opcode value must be a constant");
10023     const int64_t Opcode = OC->getValue();
10024     if (Opcode & ~0xff)
10025       return Error(OpcodeLoc, "invalid opcode");
10026     Opcodes.push_back(uint8_t(Opcode));
10027     return false;
10028   };
10029 
10030   // Must have at least 1 element
10031   SMLoc OpcodeLoc = getLexer().getLoc();
10032   if (parseOptionalToken(AsmToken::EndOfStatement))
10033     return Error(OpcodeLoc, "expected opcode expression");
10034   if (parseMany(parseOne))
10035     return true;
10036 
10037   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
10038   return false;
10039 }
10040 
10041 /// parseDirectiveTLSDescSeq
10042 ///   ::= .tlsdescseq tls-variable
10043 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
10044   MCAsmParser &Parser = getParser();
10045 
10046   if (getLexer().isNot(AsmToken::Identifier))
10047     return TokError("expected variable after '.tlsdescseq' directive");
10048 
10049   const MCSymbolRefExpr *SRE =
10050     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10051                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10052   Lex();
10053 
10054   if (parseToken(AsmToken::EndOfStatement,
10055                  "unexpected token in '.tlsdescseq' directive"))
10056     return true;
10057 
10058   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10059   return false;
10060 }
10061 
10062 /// parseDirectiveMovSP
10063 ///  ::= .movsp reg [, #offset]
10064 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10065   MCAsmParser &Parser = getParser();
10066   if (!UC.hasFnStart())
10067     return Error(L, ".fnstart must precede .movsp directives");
10068   if (UC.getFPReg() != ARM::SP)
10069     return Error(L, "unexpected .movsp directive");
10070 
10071   SMLoc SPRegLoc = Parser.getTok().getLoc();
10072   int SPReg = tryParseRegister();
10073   if (SPReg == -1)
10074     return Error(SPRegLoc, "register expected");
10075   if (SPReg == ARM::SP || SPReg == ARM::PC)
10076     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10077 
10078   int64_t Offset = 0;
10079   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10080     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10081       return true;
10082 
10083     const MCExpr *OffsetExpr;
10084     SMLoc OffsetLoc = Parser.getTok().getLoc();
10085 
10086     if (Parser.parseExpression(OffsetExpr))
10087       return Error(OffsetLoc, "malformed offset expression");
10088 
10089     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10090     if (!CE)
10091       return Error(OffsetLoc, "offset must be an immediate constant");
10092 
10093     Offset = CE->getValue();
10094   }
10095 
10096   if (parseToken(AsmToken::EndOfStatement,
10097                  "unexpected token in '.movsp' directive"))
10098     return true;
10099 
10100   getTargetStreamer().emitMovSP(SPReg, Offset);
10101   UC.saveFPReg(SPReg);
10102 
10103   return false;
10104 }
10105 
10106 /// parseDirectiveObjectArch
10107 ///   ::= .object_arch name
10108 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10109   MCAsmParser &Parser = getParser();
10110   if (getLexer().isNot(AsmToken::Identifier))
10111     return Error(getLexer().getLoc(), "unexpected token");
10112 
10113   StringRef Arch = Parser.getTok().getString();
10114   SMLoc ArchLoc = Parser.getTok().getLoc();
10115   Lex();
10116 
10117   unsigned ID = ARM::parseArch(Arch);
10118 
10119   if (ID == ARM::AK_INVALID)
10120     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10121   if (parseToken(AsmToken::EndOfStatement))
10122     return true;
10123 
10124   getTargetStreamer().emitObjectArch(ID);
10125   return false;
10126 }
10127 
10128 /// parseDirectiveAlign
10129 ///   ::= .align
10130 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10131   // NOTE: if this is not the end of the statement, fall back to the target
10132   // agnostic handling for this directive which will correctly handle this.
10133   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10134     // '.align' is target specifically handled to mean 2**2 byte alignment.
10135     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10136     assert(Section && "must have section to emit alignment");
10137     if (Section->UseCodeAlign())
10138       getStreamer().EmitCodeAlignment(4, 0);
10139     else
10140       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10141     return false;
10142   }
10143   return true;
10144 }
10145 
10146 /// parseDirectiveThumbSet
10147 ///  ::= .thumb_set name, value
10148 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10149   MCAsmParser &Parser = getParser();
10150 
10151   StringRef Name;
10152   if (check(Parser.parseIdentifier(Name),
10153             "expected identifier after '.thumb_set'") ||
10154       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10155     return true;
10156 
10157   MCSymbol *Sym;
10158   const MCExpr *Value;
10159   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10160                                                Parser, Sym, Value))
10161     return true;
10162 
10163   getTargetStreamer().emitThumbSet(Sym, Value);
10164   return false;
10165 }
10166 
10167 /// Force static initialization.
10168 extern "C" void LLVMInitializeARMAsmParser() {
10169   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10170   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10171   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10172   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10173 }
10174 
10175 #define GET_REGISTER_MATCHER
10176 #define GET_SUBTARGET_FEATURE_NAME
10177 #define GET_MATCHER_IMPLEMENTATION
10178 #include "ARMGenAsmMatcher.inc"
10179 
10180 // FIXME: This structure should be moved inside ARMTargetParser
10181 // when we start to table-generate them, and we can use the ARM
10182 // flags below, that were generated by table-gen.
10183 static const struct {
10184   const unsigned Kind;
10185   const uint64_t ArchCheck;
10186   const FeatureBitset Features;
10187 } Extensions[] = {
10188   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10189   { ARM::AEK_CRYPTO,  Feature_HasV8,
10190     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10191   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10192   { (ARM::AEK_HWDIV | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10193     {ARM::FeatureHWDiv, ARM::FeatureHWDivARM} },
10194   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10195   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10196   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10197   // FIXME: Only available in A-class, isel not predicated
10198   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10199   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10200   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10201   // FIXME: Unsupported extensions.
10202   { ARM::AEK_OS, Feature_None, {} },
10203   { ARM::AEK_IWMMXT, Feature_None, {} },
10204   { ARM::AEK_IWMMXT2, Feature_None, {} },
10205   { ARM::AEK_MAVERICK, Feature_None, {} },
10206   { ARM::AEK_XSCALE, Feature_None, {} },
10207 };
10208 
10209 /// parseDirectiveArchExtension
10210 ///   ::= .arch_extension [no]feature
10211 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10212   MCAsmParser &Parser = getParser();
10213 
10214   if (getLexer().isNot(AsmToken::Identifier))
10215     return Error(getLexer().getLoc(), "expected architecture extension name");
10216 
10217   StringRef Name = Parser.getTok().getString();
10218   SMLoc ExtLoc = Parser.getTok().getLoc();
10219   Lex();
10220 
10221   if (parseToken(AsmToken::EndOfStatement,
10222                  "unexpected token in '.arch_extension' directive"))
10223     return true;
10224 
10225   bool EnableFeature = true;
10226   if (Name.startswith_lower("no")) {
10227     EnableFeature = false;
10228     Name = Name.substr(2);
10229   }
10230   unsigned FeatureKind = ARM::parseArchExt(Name);
10231   if (FeatureKind == ARM::AEK_INVALID)
10232     return Error(ExtLoc, "unknown architectural extension: " + Name);
10233 
10234   for (const auto &Extension : Extensions) {
10235     if (Extension.Kind != FeatureKind)
10236       continue;
10237 
10238     if (Extension.Features.none())
10239       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10240 
10241     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10242       return Error(ExtLoc, "architectural extension '" + Name +
10243                                "' is not "
10244                                "allowed for the current base architecture");
10245 
10246     MCSubtargetInfo &STI = copySTI();
10247     FeatureBitset ToggleFeatures = EnableFeature
10248       ? (~STI.getFeatureBits() & Extension.Features)
10249       : ( STI.getFeatureBits() & Extension.Features);
10250 
10251     uint64_t Features =
10252         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10253     setAvailableFeatures(Features);
10254     return false;
10255   }
10256 
10257   return Error(ExtLoc, "unknown architectural extension: " + Name);
10258 }
10259 
10260 // Define this matcher function after the auto-generated include so we
10261 // have the match class enum definitions.
10262 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10263                                                   unsigned Kind) {
10264   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10265   // If the kind is a token for a literal immediate, check if our asm
10266   // operand matches. This is for InstAliases which have a fixed-value
10267   // immediate in the syntax.
10268   switch (Kind) {
10269   default: break;
10270   case MCK__35_0:
10271     if (Op.isImm())
10272       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10273         if (CE->getValue() == 0)
10274           return Match_Success;
10275     break;
10276   case MCK_ModImm:
10277     if (Op.isImm()) {
10278       const MCExpr *SOExpr = Op.getImm();
10279       int64_t Value;
10280       if (!SOExpr->evaluateAsAbsolute(Value))
10281         return Match_Success;
10282       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
10283              "expression value must be representable in 32 bits");
10284     }
10285     break;
10286   case MCK_rGPR:
10287     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10288       return Match_Success;
10289     break;
10290   case MCK_GPRPair:
10291     if (Op.isReg() &&
10292         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10293       return Match_Success;
10294     break;
10295   }
10296   return Match_InvalidOperand;
10297 }
10298