]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/ARM/AsmParser/ARMAsmParser.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306325, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / ARM / AsmParser / ARMAsmParser.cpp
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/BinaryFormat/COFF.h"
21 #include "llvm/BinaryFormat/ELF.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCAssembler.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
26 #include "llvm/MC/MCELFStreamer.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstrDesc.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/MC/MCObjectFileInfo.h"
32 #include "llvm/MC/MCParser/MCAsmLexer.h"
33 #include "llvm/MC/MCParser/MCAsmParser.h"
34 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
35 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
36 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
37 #include "llvm/MC/MCRegisterInfo.h"
38 #include "llvm/MC/MCSection.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSubtargetInfo.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/Support/ARMBuildAttributes.h"
43 #include "llvm/Support/ARMEHABI.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.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 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
71                                         cl::init(false));
72
73 class ARMOperand;
74
75 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
76
77 class UnwindContext {
78   MCAsmParser &Parser;
79
80   typedef SmallVector<SMLoc, 4> Locs;
81
82   Locs FnStartLocs;
83   Locs CantUnwindLocs;
84   Locs PersonalityLocs;
85   Locs PersonalityIndexLocs;
86   Locs HandlerDataLocs;
87   int FPReg;
88
89 public:
90   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
91
92   bool hasFnStart() const { return !FnStartLocs.empty(); }
93   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
94   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
95   bool hasPersonality() const {
96     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
97   }
98
99   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
100   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
101   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
102   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
103   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
104
105   void saveFPReg(int Reg) { FPReg = Reg; }
106   int getFPReg() const { return FPReg; }
107
108   void emitFnStartLocNotes() const {
109     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
110          FI != FE; ++FI)
111       Parser.Note(*FI, ".fnstart was specified here");
112   }
113   void emitCantUnwindLocNotes() const {
114     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
115                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
116       Parser.Note(*UI, ".cantunwind was specified here");
117   }
118   void emitHandlerDataLocNotes() const {
119     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
120                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
121       Parser.Note(*HI, ".handlerdata was specified here");
122   }
123   void emitPersonalityLocNotes() const {
124     for (Locs::const_iterator PI = PersonalityLocs.begin(),
125                               PE = PersonalityLocs.end(),
126                               PII = PersonalityIndexLocs.begin(),
127                               PIE = PersonalityIndexLocs.end();
128          PI != PE || PII != PIE;) {
129       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
130         Parser.Note(*PI++, ".personality was specified here");
131       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
132         Parser.Note(*PII++, ".personalityindex was specified here");
133       else
134         llvm_unreachable(".personality and .personalityindex cannot be "
135                          "at the same location");
136     }
137   }
138
139   void reset() {
140     FnStartLocs = Locs();
141     CantUnwindLocs = Locs();
142     PersonalityLocs = Locs();
143     HandlerDataLocs = Locs();
144     PersonalityIndexLocs = Locs();
145     FPReg = ARM::SP;
146   }
147 };
148
149 class ARMAsmParser : public MCTargetAsmParser {
150   const MCInstrInfo &MII;
151   const MCRegisterInfo *MRI;
152   UnwindContext UC;
153
154   ARMTargetStreamer &getTargetStreamer() {
155     assert(getParser().getStreamer().getTargetStreamer() &&
156            "do not have a target streamer");
157     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
158     return static_cast<ARMTargetStreamer &>(TS);
159   }
160
161   // Map of register aliases registers via the .req directive.
162   StringMap<unsigned> RegisterReqs;
163
164   bool NextSymbolIsThumb;
165
166   bool useImplicitITThumb() const {
167     return ImplicitItMode == ImplicitItModeTy::Always ||
168            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
169   }
170
171   bool useImplicitITARM() const {
172     return ImplicitItMode == ImplicitItModeTy::Always ||
173            ImplicitItMode == ImplicitItModeTy::ARMOnly;
174   }
175
176   struct {
177     ARMCC::CondCodes Cond;    // Condition for IT block.
178     unsigned Mask:4;          // Condition mask for instructions.
179                               // Starting at first 1 (from lsb).
180                               //   '1'  condition as indicated in IT.
181                               //   '0'  inverse of condition (else).
182                               // Count of instructions in IT block is
183                               // 4 - trailingzeroes(mask)
184                               // Note that this does not have the same encoding
185                               // as in the IT instruction, which also depends
186                               // on the low bit of the condition code.
187
188     unsigned CurPosition;     // Current position in parsing of IT
189                               // block. In range [0,4], with 0 being the IT
190                               // instruction itself. Initialized according to
191                               // count of instructions in block.  ~0U if no
192                               // active IT block.
193
194     bool IsExplicit;          // true  - The IT instruction was present in the
195                               //         input, we should not modify it.
196                               // false - The IT instruction was added
197                               //         implicitly, we can extend it if that
198                               //         would be legal.
199   } ITState;
200
201   llvm::SmallVector<MCInst, 4> PendingConditionalInsts;
202
203   void flushPendingInstructions(MCStreamer &Out) override {
204     if (!inImplicitITBlock()) {
205       assert(PendingConditionalInsts.size() == 0);
206       return;
207     }
208
209     // Emit the IT instruction
210     unsigned Mask = getITMaskEncoding();
211     MCInst ITInst;
212     ITInst.setOpcode(ARM::t2IT);
213     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
214     ITInst.addOperand(MCOperand::createImm(Mask));
215     Out.EmitInstruction(ITInst, getSTI());
216
217     // Emit the conditonal instructions
218     assert(PendingConditionalInsts.size() <= 4);
219     for (const MCInst &Inst : PendingConditionalInsts) {
220       Out.EmitInstruction(Inst, getSTI());
221     }
222     PendingConditionalInsts.clear();
223
224     // Clear the IT state
225     ITState.Mask = 0;
226     ITState.CurPosition = ~0U;
227   }
228
229   bool inITBlock() { return ITState.CurPosition != ~0U; }
230   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
231   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
232   bool lastInITBlock() {
233     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
234   }
235   void forwardITPosition() {
236     if (!inITBlock()) return;
237     // Move to the next instruction in the IT block, if there is one. If not,
238     // mark the block as done, except for implicit IT blocks, which we leave
239     // open until we find an instruction that can't be added to it.
240     unsigned TZ = countTrailingZeros(ITState.Mask);
241     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
242       ITState.CurPosition = ~0U; // Done with the IT block after this.
243   }
244
245   // Rewind the state of the current IT block, removing the last slot from it.
246   void rewindImplicitITPosition() {
247     assert(inImplicitITBlock());
248     assert(ITState.CurPosition > 1);
249     ITState.CurPosition--;
250     unsigned TZ = countTrailingZeros(ITState.Mask);
251     unsigned NewMask = 0;
252     NewMask |= ITState.Mask & (0xC << TZ);
253     NewMask |= 0x2 << TZ;
254     ITState.Mask = NewMask;
255   }
256
257   // Rewind the state of the current IT block, removing the last slot from it.
258   // If we were at the first slot, this closes the IT block.
259   void discardImplicitITBlock() {
260     assert(inImplicitITBlock());
261     assert(ITState.CurPosition == 1);
262     ITState.CurPosition = ~0U;
263     return;
264   }
265
266   // Get the encoding of the IT mask, as it will appear in an IT instruction.
267   unsigned getITMaskEncoding() {
268     assert(inITBlock());
269     unsigned Mask = ITState.Mask;
270     unsigned TZ = countTrailingZeros(Mask);
271     if ((ITState.Cond & 1) == 0) {
272       assert(Mask && TZ <= 3 && "illegal IT mask value!");
273       Mask ^= (0xE << TZ) & 0xF;
274     }
275     return Mask;
276   }
277
278   // Get the condition code corresponding to the current IT block slot.
279   ARMCC::CondCodes currentITCond() {
280     unsigned MaskBit;
281     if (ITState.CurPosition == 1)
282       MaskBit = 1;
283     else
284       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
285
286     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
287   }
288
289   // Invert the condition of the current IT block slot without changing any
290   // other slots in the same block.
291   void invertCurrentITCondition() {
292     if (ITState.CurPosition == 1) {
293       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
294     } else {
295       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
296     }
297   }
298
299   // Returns true if the current IT block is full (all 4 slots used).
300   bool isITBlockFull() {
301     return inITBlock() && (ITState.Mask & 1);
302   }
303
304   // Extend the current implicit IT block to have one more slot with the given
305   // condition code.
306   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
307     assert(inImplicitITBlock());
308     assert(!isITBlockFull());
309     assert(Cond == ITState.Cond ||
310            Cond == ARMCC::getOppositeCondition(ITState.Cond));
311     unsigned TZ = countTrailingZeros(ITState.Mask);
312     unsigned NewMask = 0;
313     // Keep any existing condition bits.
314     NewMask |= ITState.Mask & (0xE << TZ);
315     // Insert the new condition bit.
316     NewMask |= (Cond == ITState.Cond) << TZ;
317     // Move the trailing 1 down one bit.
318     NewMask |= 1 << (TZ - 1);
319     ITState.Mask = NewMask;
320   }
321
322   // Create a new implicit IT block with a dummy condition code.
323   void startImplicitITBlock() {
324     assert(!inITBlock());
325     ITState.Cond = ARMCC::AL;
326     ITState.Mask = 8;
327     ITState.CurPosition = 1;
328     ITState.IsExplicit = false;
329     return;
330   }
331
332   // Create a new explicit IT block with the given condition and mask. The mask
333   // should be in the parsed format, with a 1 implying 't', regardless of the
334   // low bit of the condition.
335   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
336     assert(!inITBlock());
337     ITState.Cond = Cond;
338     ITState.Mask = Mask;
339     ITState.CurPosition = 0;
340     ITState.IsExplicit = true;
341     return;
342   }
343
344   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
345     return getParser().Note(L, Msg, Range);
346   }
347   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
348     return getParser().Warning(L, Msg, Range);
349   }
350   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
351     return getParser().Error(L, Msg, Range);
352   }
353
354   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
355                            unsigned ListNo, bool IsARPop = false);
356   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
357                            unsigned ListNo);
358
359   int tryParseRegister();
360   bool tryParseRegisterWithWriteBack(OperandVector &);
361   int tryParseShiftRegister(OperandVector &);
362   bool parseRegisterList(OperandVector &);
363   bool parseMemory(OperandVector &);
364   bool parseOperand(OperandVector &, StringRef Mnemonic);
365   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
366   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
367                               unsigned &ShiftAmount);
368   bool parseLiteralValues(unsigned Size, SMLoc L);
369   bool parseDirectiveThumb(SMLoc L);
370   bool parseDirectiveARM(SMLoc L);
371   bool parseDirectiveThumbFunc(SMLoc L);
372   bool parseDirectiveCode(SMLoc L);
373   bool parseDirectiveSyntax(SMLoc L);
374   bool parseDirectiveReq(StringRef Name, SMLoc L);
375   bool parseDirectiveUnreq(SMLoc L);
376   bool parseDirectiveArch(SMLoc L);
377   bool parseDirectiveEabiAttr(SMLoc L);
378   bool parseDirectiveCPU(SMLoc L);
379   bool parseDirectiveFPU(SMLoc L);
380   bool parseDirectiveFnStart(SMLoc L);
381   bool parseDirectiveFnEnd(SMLoc L);
382   bool parseDirectiveCantUnwind(SMLoc L);
383   bool parseDirectivePersonality(SMLoc L);
384   bool parseDirectiveHandlerData(SMLoc L);
385   bool parseDirectiveSetFP(SMLoc L);
386   bool parseDirectivePad(SMLoc L);
387   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
388   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
389   bool parseDirectiveLtorg(SMLoc L);
390   bool parseDirectiveEven(SMLoc L);
391   bool parseDirectivePersonalityIndex(SMLoc L);
392   bool parseDirectiveUnwindRaw(SMLoc L);
393   bool parseDirectiveTLSDescSeq(SMLoc L);
394   bool parseDirectiveMovSP(SMLoc L);
395   bool parseDirectiveObjectArch(SMLoc L);
396   bool parseDirectiveArchExtension(SMLoc L);
397   bool parseDirectiveAlign(SMLoc L);
398   bool parseDirectiveThumbSet(SMLoc L);
399
400   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
401                           bool &CarrySetting, unsigned &ProcessorIMod,
402                           StringRef &ITMask);
403   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
404                              bool &CanAcceptCarrySet,
405                              bool &CanAcceptPredicationCode);
406
407   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
408                                      OperandVector &Operands);
409   bool isThumb() const {
410     // FIXME: Can tablegen auto-generate this?
411     return getSTI().getFeatureBits()[ARM::ModeThumb];
412   }
413   bool isThumbOne() const {
414     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
415   }
416   bool isThumbTwo() const {
417     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
418   }
419   bool hasThumb() const {
420     return getSTI().getFeatureBits()[ARM::HasV4TOps];
421   }
422   bool hasThumb2() const {
423     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
424   }
425   bool hasV6Ops() const {
426     return getSTI().getFeatureBits()[ARM::HasV6Ops];
427   }
428   bool hasV6T2Ops() const {
429     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
430   }
431   bool hasV6MOps() const {
432     return getSTI().getFeatureBits()[ARM::HasV6MOps];
433   }
434   bool hasV7Ops() const {
435     return getSTI().getFeatureBits()[ARM::HasV7Ops];
436   }
437   bool hasV8Ops() const {
438     return getSTI().getFeatureBits()[ARM::HasV8Ops];
439   }
440   bool hasV8MBaseline() const {
441     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
442   }
443   bool hasV8MMainline() const {
444     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
445   }
446   bool has8MSecExt() const {
447     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
448   }
449   bool hasARM() const {
450     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
451   }
452   bool hasDSP() const {
453     return getSTI().getFeatureBits()[ARM::FeatureDSP];
454   }
455   bool hasD16() const {
456     return getSTI().getFeatureBits()[ARM::FeatureD16];
457   }
458   bool hasV8_1aOps() const {
459     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
460   }
461   bool hasRAS() const {
462     return getSTI().getFeatureBits()[ARM::FeatureRAS];
463   }
464
465   void SwitchMode() {
466     MCSubtargetInfo &STI = copySTI();
467     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
468     setAvailableFeatures(FB);
469   }
470   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
471   bool isMClass() const {
472     return getSTI().getFeatureBits()[ARM::FeatureMClass];
473   }
474
475   /// @name Auto-generated Match Functions
476   /// {
477
478 #define GET_ASSEMBLER_HEADER
479 #include "ARMGenAsmMatcher.inc"
480
481   /// }
482
483   OperandMatchResultTy parseITCondCode(OperandVector &);
484   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
485   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
486   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
487   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
488   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
489   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
490   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
491   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
492   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
493                                    int High);
494   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
495     return parsePKHImm(O, "lsl", 0, 31);
496   }
497   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
498     return parsePKHImm(O, "asr", 1, 32);
499   }
500   OperandMatchResultTy parseSetEndImm(OperandVector &);
501   OperandMatchResultTy parseShifterImm(OperandVector &);
502   OperandMatchResultTy parseRotImm(OperandVector &);
503   OperandMatchResultTy parseModImm(OperandVector &);
504   OperandMatchResultTy parseBitfield(OperandVector &);
505   OperandMatchResultTy parsePostIdxReg(OperandVector &);
506   OperandMatchResultTy parseAM3Offset(OperandVector &);
507   OperandMatchResultTy parseFPImm(OperandVector &);
508   OperandMatchResultTy parseVectorList(OperandVector &);
509   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
510                                        SMLoc &EndLoc);
511
512   // Asm Match Converter Methods
513   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
514   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
515
516   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
517   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
518   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
519   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
520   bool isITBlockTerminator(MCInst &Inst) const;
521
522 public:
523   enum ARMMatchResultTy {
524     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
525     Match_RequiresNotITBlock,
526     Match_RequiresV6,
527     Match_RequiresThumb2,
528     Match_RequiresV8,
529     Match_RequiresFlagSetting,
530 #define GET_OPERAND_DIAGNOSTIC_TYPES
531 #include "ARMGenAsmMatcher.inc"
532
533   };
534
535   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
536                const MCInstrInfo &MII, const MCTargetOptions &Options)
537     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
538     MCAsmParserExtension::Initialize(Parser);
539
540     // Cache the MCRegisterInfo.
541     MRI = getContext().getRegisterInfo();
542
543     // Initialize the set of available features.
544     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
545
546     // Add build attributes based on the selected target.
547     if (AddBuildAttributes)
548       getTargetStreamer().emitTargetAttributes(STI);
549
550     // Not in an ITBlock to start with.
551     ITState.CurPosition = ~0U;
552
553     NextSymbolIsThumb = false;
554   }
555
556   // Implementation of the MCTargetAsmParser interface:
557   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
558   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
559                         SMLoc NameLoc, OperandVector &Operands) override;
560   bool ParseDirective(AsmToken DirectiveID) override;
561
562   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
563                                       unsigned Kind) override;
564   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
565
566   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
567                                OperandVector &Operands, MCStreamer &Out,
568                                uint64_t &ErrorInfo,
569                                bool MatchingInlineAsm) override;
570   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
571                             uint64_t &ErrorInfo, bool MatchingInlineAsm,
572                             bool &EmitInITBlock, MCStreamer &Out);
573   void onLabelParsed(MCSymbol *Symbol) override;
574 };
575 } // end anonymous namespace
576
577 namespace {
578
579 /// ARMOperand - Instances of this class represent a parsed ARM machine
580 /// operand.
581 class ARMOperand : public MCParsedAsmOperand {
582   enum KindTy {
583     k_CondCode,
584     k_CCOut,
585     k_ITCondMask,
586     k_CoprocNum,
587     k_CoprocReg,
588     k_CoprocOption,
589     k_Immediate,
590     k_MemBarrierOpt,
591     k_InstSyncBarrierOpt,
592     k_Memory,
593     k_PostIndexRegister,
594     k_MSRMask,
595     k_BankedReg,
596     k_ProcIFlags,
597     k_VectorIndex,
598     k_Register,
599     k_RegisterList,
600     k_DPRRegisterList,
601     k_SPRRegisterList,
602     k_VectorList,
603     k_VectorListAllLanes,
604     k_VectorListIndexed,
605     k_ShiftedRegister,
606     k_ShiftedImmediate,
607     k_ShifterImmediate,
608     k_RotateImmediate,
609     k_ModifiedImmediate,
610     k_ConstantPoolImmediate,
611     k_BitfieldDescriptor,
612     k_Token,
613   } Kind;
614
615   SMLoc StartLoc, EndLoc, AlignmentLoc;
616   SmallVector<unsigned, 8> Registers;
617
618   struct CCOp {
619     ARMCC::CondCodes Val;
620   };
621
622   struct CopOp {
623     unsigned Val;
624   };
625
626   struct CoprocOptionOp {
627     unsigned Val;
628   };
629
630   struct ITMaskOp {
631     unsigned Mask:4;
632   };
633
634   struct MBOptOp {
635     ARM_MB::MemBOpt Val;
636   };
637
638   struct ISBOptOp {
639     ARM_ISB::InstSyncBOpt Val;
640   };
641
642   struct IFlagsOp {
643     ARM_PROC::IFlags Val;
644   };
645
646   struct MMaskOp {
647     unsigned Val;
648   };
649
650   struct BankedRegOp {
651     unsigned Val;
652   };
653
654   struct TokOp {
655     const char *Data;
656     unsigned Length;
657   };
658
659   struct RegOp {
660     unsigned RegNum;
661   };
662
663   // A vector register list is a sequential list of 1 to 4 registers.
664   struct VectorListOp {
665     unsigned RegNum;
666     unsigned Count;
667     unsigned LaneIndex;
668     bool isDoubleSpaced;
669   };
670
671   struct VectorIndexOp {
672     unsigned Val;
673   };
674
675   struct ImmOp {
676     const MCExpr *Val;
677   };
678
679   /// Combined record for all forms of ARM address expressions.
680   struct MemoryOp {
681     unsigned BaseRegNum;
682     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
683     // was specified.
684     const MCConstantExpr *OffsetImm;  // Offset immediate value
685     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
686     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
687     unsigned ShiftImm;        // shift for OffsetReg.
688     unsigned Alignment;       // 0 = no alignment specified
689     // n = alignment in bytes (2, 4, 8, 16, or 32)
690     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
691   };
692
693   struct PostIdxRegOp {
694     unsigned RegNum;
695     bool isAdd;
696     ARM_AM::ShiftOpc ShiftTy;
697     unsigned ShiftImm;
698   };
699
700   struct ShifterImmOp {
701     bool isASR;
702     unsigned Imm;
703   };
704
705   struct RegShiftedRegOp {
706     ARM_AM::ShiftOpc ShiftTy;
707     unsigned SrcReg;
708     unsigned ShiftReg;
709     unsigned ShiftImm;
710   };
711
712   struct RegShiftedImmOp {
713     ARM_AM::ShiftOpc ShiftTy;
714     unsigned SrcReg;
715     unsigned ShiftImm;
716   };
717
718   struct RotImmOp {
719     unsigned Imm;
720   };
721
722   struct ModImmOp {
723     unsigned Bits;
724     unsigned Rot;
725   };
726
727   struct BitfieldOp {
728     unsigned LSB;
729     unsigned Width;
730   };
731
732   union {
733     struct CCOp CC;
734     struct CopOp Cop;
735     struct CoprocOptionOp CoprocOption;
736     struct MBOptOp MBOpt;
737     struct ISBOptOp ISBOpt;
738     struct ITMaskOp ITMask;
739     struct IFlagsOp IFlags;
740     struct MMaskOp MMask;
741     struct BankedRegOp BankedReg;
742     struct TokOp Tok;
743     struct RegOp Reg;
744     struct VectorListOp VectorList;
745     struct VectorIndexOp VectorIndex;
746     struct ImmOp Imm;
747     struct MemoryOp Memory;
748     struct PostIdxRegOp PostIdxReg;
749     struct ShifterImmOp ShifterImm;
750     struct RegShiftedRegOp RegShiftedReg;
751     struct RegShiftedImmOp RegShiftedImm;
752     struct RotImmOp RotImm;
753     struct ModImmOp ModImm;
754     struct BitfieldOp Bitfield;
755   };
756
757 public:
758   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
759
760   /// getStartLoc - Get the location of the first token of this operand.
761   SMLoc getStartLoc() const override { return StartLoc; }
762   /// getEndLoc - Get the location of the last token of this operand.
763   SMLoc getEndLoc() const override { return EndLoc; }
764   /// getLocRange - Get the range between the first and last token of this
765   /// operand.
766   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
767
768   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
769   SMLoc getAlignmentLoc() const {
770     assert(Kind == k_Memory && "Invalid access!");
771     return AlignmentLoc;
772   }
773
774   ARMCC::CondCodes getCondCode() const {
775     assert(Kind == k_CondCode && "Invalid access!");
776     return CC.Val;
777   }
778
779   unsigned getCoproc() const {
780     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
781     return Cop.Val;
782   }
783
784   StringRef getToken() const {
785     assert(Kind == k_Token && "Invalid access!");
786     return StringRef(Tok.Data, Tok.Length);
787   }
788
789   unsigned getReg() const override {
790     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
791     return Reg.RegNum;
792   }
793
794   const SmallVectorImpl<unsigned> &getRegList() const {
795     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
796             Kind == k_SPRRegisterList) && "Invalid access!");
797     return Registers;
798   }
799
800   const MCExpr *getImm() const {
801     assert(isImm() && "Invalid access!");
802     return Imm.Val;
803   }
804
805   const MCExpr *getConstantPoolImm() const {
806     assert(isConstantPoolImm() && "Invalid access!");
807     return Imm.Val;
808   }
809
810   unsigned getVectorIndex() const {
811     assert(Kind == k_VectorIndex && "Invalid access!");
812     return VectorIndex.Val;
813   }
814
815   ARM_MB::MemBOpt getMemBarrierOpt() const {
816     assert(Kind == k_MemBarrierOpt && "Invalid access!");
817     return MBOpt.Val;
818   }
819
820   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
821     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
822     return ISBOpt.Val;
823   }
824
825   ARM_PROC::IFlags getProcIFlags() const {
826     assert(Kind == k_ProcIFlags && "Invalid access!");
827     return IFlags.Val;
828   }
829
830   unsigned getMSRMask() const {
831     assert(Kind == k_MSRMask && "Invalid access!");
832     return MMask.Val;
833   }
834
835   unsigned getBankedReg() const {
836     assert(Kind == k_BankedReg && "Invalid access!");
837     return BankedReg.Val;
838   }
839
840   bool isCoprocNum() const { return Kind == k_CoprocNum; }
841   bool isCoprocReg() const { return Kind == k_CoprocReg; }
842   bool isCoprocOption() const { return Kind == k_CoprocOption; }
843   bool isCondCode() const { return Kind == k_CondCode; }
844   bool isCCOut() const { return Kind == k_CCOut; }
845   bool isITMask() const { return Kind == k_ITCondMask; }
846   bool isITCondCode() const { return Kind == k_CondCode; }
847   bool isImm() const override {
848     return Kind == k_Immediate;
849   }
850
851   bool isARMBranchTarget() const {
852     if (!isImm()) return false;
853
854     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
855       return CE->getValue() % 4 == 0;
856     return true;
857   }
858
859
860   bool isThumbBranchTarget() const {
861     if (!isImm()) return false;
862
863     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
864       return CE->getValue() % 2 == 0;
865     return true;
866   }
867
868   // checks whether this operand is an unsigned offset which fits is a field
869   // of specified width and scaled by a specific number of bits
870   template<unsigned width, unsigned scale>
871   bool isUnsignedOffset() const {
872     if (!isImm()) return false;
873     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
874     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
875       int64_t Val = CE->getValue();
876       int64_t Align = 1LL << scale;
877       int64_t Max = Align * ((1LL << width) - 1);
878       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
879     }
880     return false;
881   }
882   // checks whether this operand is an signed offset which fits is a field
883   // of specified width and scaled by a specific number of bits
884   template<unsigned width, unsigned scale>
885   bool isSignedOffset() const {
886     if (!isImm()) return false;
887     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
888     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
889       int64_t Val = CE->getValue();
890       int64_t Align = 1LL << scale;
891       int64_t Max = Align * ((1LL << (width-1)) - 1);
892       int64_t Min = -Align * (1LL << (width-1));
893       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
894     }
895     return false;
896   }
897
898   // checks whether this operand is a memory operand computed as an offset
899   // applied to PC. the offset may have 8 bits of magnitude and is represented
900   // with two bits of shift. textually it may be either [pc, #imm], #imm or 
901   // relocable expression...
902   bool isThumbMemPC() const {
903     int64_t Val = 0;
904     if (isImm()) {
905       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
906       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
907       if (!CE) return false;
908       Val = CE->getValue();
909     }
910     else if (isMem()) {
911       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
912       if(Memory.BaseRegNum != ARM::PC) return false;
913       Val = Memory.OffsetImm->getValue();
914     }
915     else return false;
916     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
917   }
918   bool isFPImm() const {
919     if (!isImm()) return false;
920     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
921     if (!CE) return false;
922     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
923     return Val != -1;
924   }
925
926   template<int64_t N, int64_t M>
927   bool isImmediate() const {
928     if (!isImm()) return false;
929     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
930     if (!CE) return false;
931     int64_t Value = CE->getValue();
932     return Value >= N && Value <= M;
933   }
934   template<int64_t N, int64_t M>
935   bool isImmediateS4() const {
936     if (!isImm()) return false;
937     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
938     if (!CE) return false;
939     int64_t Value = CE->getValue();
940     return ((Value & 3) == 0) && Value >= N && Value <= M;
941   }
942   bool isFBits16() const {
943     return isImmediate<0, 17>();
944   }
945   bool isFBits32() const {
946     return isImmediate<1, 33>();
947   }
948   bool isImm8s4() const {
949     return isImmediateS4<-1020, 1020>();
950   }
951   bool isImm0_1020s4() const {
952     return isImmediateS4<0, 1020>();
953   }
954   bool isImm0_508s4() const {
955     return isImmediateS4<0, 508>();
956   }
957   bool isImm0_508s4Neg() const {
958     if (!isImm()) return false;
959     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
960     if (!CE) return false;
961     int64_t Value = -CE->getValue();
962     // explicitly exclude zero. we want that to use the normal 0_508 version.
963     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
964   }
965   bool isImm0_4095Neg() const {
966     if (!isImm()) return false;
967     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
968     if (!CE) return false;
969     int64_t Value = -CE->getValue();
970     return Value > 0 && Value < 4096;
971   }
972   bool isImm0_7() const {
973     return isImmediate<0, 7>();
974   }
975   bool isImm1_16() const {
976     return isImmediate<1, 16>();
977   }
978   bool isImm1_32() const {
979     return isImmediate<1, 32>();
980   }
981   bool isImm8_255() const {
982     return isImmediate<8, 255>();
983   }
984   bool isImm256_65535Expr() const {
985     if (!isImm()) return false;
986     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
987     // If it's not a constant expression, it'll generate a fixup and be
988     // handled later.
989     if (!CE) return true;
990     int64_t Value = CE->getValue();
991     return Value >= 256 && Value < 65536;
992   }
993   bool isImm0_65535Expr() const {
994     if (!isImm()) return false;
995     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
996     // If it's not a constant expression, it'll generate a fixup and be
997     // handled later.
998     if (!CE) return true;
999     int64_t Value = CE->getValue();
1000     return Value >= 0 && Value < 65536;
1001   }
1002   bool isImm24bit() const {
1003     return isImmediate<0, 0xffffff + 1>();
1004   }
1005   bool isImmThumbSR() const {
1006     return isImmediate<1, 33>();
1007   }
1008   bool isPKHLSLImm() const {
1009     return isImmediate<0, 32>();
1010   }
1011   bool isPKHASRImm() const {
1012     return isImmediate<0, 33>();
1013   }
1014   bool isAdrLabel() const {
1015     // If we have an immediate that's not a constant, treat it as a label
1016     // reference needing a fixup.
1017     if (isImm() && !isa<MCConstantExpr>(getImm()))
1018       return true;
1019
1020     // If it is a constant, it must fit into a modified immediate encoding.
1021     if (!isImm()) return false;
1022     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1023     if (!CE) return false;
1024     int64_t Value = CE->getValue();
1025     return (ARM_AM::getSOImmVal(Value) != -1 ||
1026             ARM_AM::getSOImmVal(-Value) != -1);
1027   }
1028   bool isT2SOImm() const {
1029     // If we have an immediate that's not a constant, treat it as an expression
1030     // needing a fixup.
1031     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1032       // We want to avoid matching :upper16: and :lower16: as we want these
1033       // expressions to match in isImm0_65535Expr()
1034       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1035       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1036                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1037     }
1038     if (!isImm()) return false;
1039     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1040     if (!CE) return false;
1041     int64_t Value = CE->getValue();
1042     return ARM_AM::getT2SOImmVal(Value) != -1;
1043   }
1044   bool isT2SOImmNot() const {
1045     if (!isImm()) return false;
1046     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1047     if (!CE) return false;
1048     int64_t Value = CE->getValue();
1049     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1050       ARM_AM::getT2SOImmVal(~Value) != -1;
1051   }
1052   bool isT2SOImmNeg() const {
1053     if (!isImm()) return false;
1054     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1055     if (!CE) return false;
1056     int64_t Value = CE->getValue();
1057     // Only use this when not representable as a plain so_imm.
1058     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1059       ARM_AM::getT2SOImmVal(-Value) != -1;
1060   }
1061   bool isSetEndImm() const {
1062     if (!isImm()) return false;
1063     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1064     if (!CE) return false;
1065     int64_t Value = CE->getValue();
1066     return Value == 1 || Value == 0;
1067   }
1068   bool isReg() const override { return Kind == k_Register; }
1069   bool isRegList() const { return Kind == k_RegisterList; }
1070   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1071   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1072   bool isToken() const override { return Kind == k_Token; }
1073   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1074   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1075   bool isMem() const override { return Kind == k_Memory; }
1076   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1077   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1078   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1079   bool isRotImm() const { return Kind == k_RotateImmediate; }
1080   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1081   bool isModImmNot() const {
1082     if (!isImm()) return false;
1083     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1084     if (!CE) return false;
1085     int64_t Value = CE->getValue();
1086     return ARM_AM::getSOImmVal(~Value) != -1;
1087   }
1088   bool isModImmNeg() const {
1089     if (!isImm()) return false;
1090     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1091     if (!CE) return false;
1092     int64_t Value = CE->getValue();
1093     return ARM_AM::getSOImmVal(Value) == -1 &&
1094       ARM_AM::getSOImmVal(-Value) != -1;
1095   }
1096   bool isThumbModImmNeg1_7() const {
1097     if (!isImm()) return false;
1098     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1099     if (!CE) return false;
1100     int32_t Value = -(int32_t)CE->getValue();
1101     return 0 < Value && Value < 8;
1102   }
1103   bool isThumbModImmNeg8_255() const {
1104     if (!isImm()) return false;
1105     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1106     if (!CE) return false;
1107     int32_t Value = -(int32_t)CE->getValue();
1108     return 7 < Value && Value < 256;
1109   }
1110   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1111   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1112   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1113   bool isPostIdxReg() const {
1114     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1115   }
1116   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1117     if (!isMem())
1118       return false;
1119     // No offset of any kind.
1120     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1121      (alignOK || Memory.Alignment == Alignment);
1122   }
1123   bool isMemPCRelImm12() const {
1124     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1125       return false;
1126     // Base register must be PC.
1127     if (Memory.BaseRegNum != ARM::PC)
1128       return false;
1129     // Immediate offset in range [-4095, 4095].
1130     if (!Memory.OffsetImm) return true;
1131     int64_t Val = Memory.OffsetImm->getValue();
1132     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1133   }
1134   bool isAlignedMemory() const {
1135     return isMemNoOffset(true);
1136   }
1137   bool isAlignedMemoryNone() const {
1138     return isMemNoOffset(false, 0);
1139   }
1140   bool isDupAlignedMemoryNone() const {
1141     return isMemNoOffset(false, 0);
1142   }
1143   bool isAlignedMemory16() const {
1144     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1145       return true;
1146     return isMemNoOffset(false, 0);
1147   }
1148   bool isDupAlignedMemory16() const {
1149     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1150       return true;
1151     return isMemNoOffset(false, 0);
1152   }
1153   bool isAlignedMemory32() const {
1154     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1155       return true;
1156     return isMemNoOffset(false, 0);
1157   }
1158   bool isDupAlignedMemory32() const {
1159     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1160       return true;
1161     return isMemNoOffset(false, 0);
1162   }
1163   bool isAlignedMemory64() const {
1164     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1165       return true;
1166     return isMemNoOffset(false, 0);
1167   }
1168   bool isDupAlignedMemory64() const {
1169     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1170       return true;
1171     return isMemNoOffset(false, 0);
1172   }
1173   bool isAlignedMemory64or128() const {
1174     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1175       return true;
1176     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1177       return true;
1178     return isMemNoOffset(false, 0);
1179   }
1180   bool isDupAlignedMemory64or128() const {
1181     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1182       return true;
1183     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1184       return true;
1185     return isMemNoOffset(false, 0);
1186   }
1187   bool isAlignedMemory64or128or256() const {
1188     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1189       return true;
1190     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1191       return true;
1192     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1193       return true;
1194     return isMemNoOffset(false, 0);
1195   }
1196   bool isAddrMode2() const {
1197     if (!isMem() || Memory.Alignment != 0) return false;
1198     // Check for register offset.
1199     if (Memory.OffsetRegNum) return true;
1200     // Immediate offset in range [-4095, 4095].
1201     if (!Memory.OffsetImm) return true;
1202     int64_t Val = Memory.OffsetImm->getValue();
1203     return Val > -4096 && Val < 4096;
1204   }
1205   bool isAM2OffsetImm() const {
1206     if (!isImm()) return false;
1207     // Immediate offset in range [-4095, 4095].
1208     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1209     if (!CE) return false;
1210     int64_t Val = CE->getValue();
1211     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1212   }
1213   bool isAddrMode3() const {
1214     // If we have an immediate that's not a constant, treat it as a label
1215     // reference needing a fixup. If it is a constant, it's something else
1216     // and we reject it.
1217     if (isImm() && !isa<MCConstantExpr>(getImm()))
1218       return true;
1219     if (!isMem() || Memory.Alignment != 0) return false;
1220     // No shifts are legal for AM3.
1221     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1222     // Check for register offset.
1223     if (Memory.OffsetRegNum) return true;
1224     // Immediate offset in range [-255, 255].
1225     if (!Memory.OffsetImm) return true;
1226     int64_t Val = Memory.OffsetImm->getValue();
1227     // The #-0 offset is encoded as INT32_MIN, and we have to check 
1228     // for this too.
1229     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1230   }
1231   bool isAM3Offset() const {
1232     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1233       return false;
1234     if (Kind == k_PostIndexRegister)
1235       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1236     // Immediate offset in range [-255, 255].
1237     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1238     if (!CE) return false;
1239     int64_t Val = CE->getValue();
1240     // Special case, #-0 is INT32_MIN.
1241     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1242   }
1243   bool isAddrMode5() const {
1244     // If we have an immediate that's not a constant, treat it as a label
1245     // reference needing a fixup. If it is a constant, it's something else
1246     // and we reject it.
1247     if (isImm() && !isa<MCConstantExpr>(getImm()))
1248       return true;
1249     if (!isMem() || Memory.Alignment != 0) return false;
1250     // Check for register offset.
1251     if (Memory.OffsetRegNum) return false;
1252     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1253     if (!Memory.OffsetImm) return true;
1254     int64_t Val = Memory.OffsetImm->getValue();
1255     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1256       Val == INT32_MIN;
1257   }
1258   bool isAddrMode5FP16() const {
1259     // If we have an immediate that's not a constant, treat it as a label
1260     // reference needing a fixup. If it is a constant, it's something else
1261     // and we reject it.
1262     if (isImm() && !isa<MCConstantExpr>(getImm()))
1263       return true;
1264     if (!isMem() || Memory.Alignment != 0) return false;
1265     // Check for register offset.
1266     if (Memory.OffsetRegNum) return false;
1267     // Immediate offset in range [-510, 510] and a multiple of 2.
1268     if (!Memory.OffsetImm) return true;
1269     int64_t Val = Memory.OffsetImm->getValue();
1270     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) || Val == INT32_MIN;
1271   }
1272   bool isMemTBB() const {
1273     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1274         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1275       return false;
1276     return true;
1277   }
1278   bool isMemTBH() const {
1279     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1280         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1281         Memory.Alignment != 0 )
1282       return false;
1283     return true;
1284   }
1285   bool isMemRegOffset() const {
1286     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1287       return false;
1288     return true;
1289   }
1290   bool isT2MemRegOffset() const {
1291     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1292         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1293       return false;
1294     // Only lsl #{0, 1, 2, 3} allowed.
1295     if (Memory.ShiftType == ARM_AM::no_shift)
1296       return true;
1297     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1298       return false;
1299     return true;
1300   }
1301   bool isMemThumbRR() const {
1302     // Thumb reg+reg addressing is simple. Just two registers, a base and
1303     // an offset. No shifts, negations or any other complicating factors.
1304     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1305         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1306       return false;
1307     return isARMLowRegister(Memory.BaseRegNum) &&
1308       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1309   }
1310   bool isMemThumbRIs4() const {
1311     if (!isMem() || Memory.OffsetRegNum != 0 ||
1312         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1313       return false;
1314     // Immediate offset, multiple of 4 in range [0, 124].
1315     if (!Memory.OffsetImm) return true;
1316     int64_t Val = Memory.OffsetImm->getValue();
1317     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1318   }
1319   bool isMemThumbRIs2() const {
1320     if (!isMem() || Memory.OffsetRegNum != 0 ||
1321         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1322       return false;
1323     // Immediate offset, multiple of 4 in range [0, 62].
1324     if (!Memory.OffsetImm) return true;
1325     int64_t Val = Memory.OffsetImm->getValue();
1326     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1327   }
1328   bool isMemThumbRIs1() const {
1329     if (!isMem() || Memory.OffsetRegNum != 0 ||
1330         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1331       return false;
1332     // Immediate offset in range [0, 31].
1333     if (!Memory.OffsetImm) return true;
1334     int64_t Val = Memory.OffsetImm->getValue();
1335     return Val >= 0 && Val <= 31;
1336   }
1337   bool isMemThumbSPI() const {
1338     if (!isMem() || Memory.OffsetRegNum != 0 ||
1339         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1340       return false;
1341     // Immediate offset, multiple of 4 in range [0, 1020].
1342     if (!Memory.OffsetImm) return true;
1343     int64_t Val = Memory.OffsetImm->getValue();
1344     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1345   }
1346   bool isMemImm8s4Offset() const {
1347     // If we have an immediate that's not a constant, treat it as a label
1348     // reference needing a fixup. If it is a constant, it's something else
1349     // and we reject it.
1350     if (isImm() && !isa<MCConstantExpr>(getImm()))
1351       return true;
1352     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1353       return false;
1354     // Immediate offset a multiple of 4 in range [-1020, 1020].
1355     if (!Memory.OffsetImm) return true;
1356     int64_t Val = Memory.OffsetImm->getValue();
1357     // Special case, #-0 is INT32_MIN.
1358     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1359   }
1360   bool isMemImm0_1020s4Offset() const {
1361     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1362       return false;
1363     // Immediate offset a multiple of 4 in range [0, 1020].
1364     if (!Memory.OffsetImm) return true;
1365     int64_t Val = Memory.OffsetImm->getValue();
1366     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1367   }
1368   bool isMemImm8Offset() const {
1369     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1370       return false;
1371     // Base reg of PC isn't allowed for these encodings.
1372     if (Memory.BaseRegNum == ARM::PC) return false;
1373     // Immediate offset in range [-255, 255].
1374     if (!Memory.OffsetImm) return true;
1375     int64_t Val = Memory.OffsetImm->getValue();
1376     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1377   }
1378   bool isMemPosImm8Offset() const {
1379     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1380       return false;
1381     // Immediate offset in range [0, 255].
1382     if (!Memory.OffsetImm) return true;
1383     int64_t Val = Memory.OffsetImm->getValue();
1384     return Val >= 0 && Val < 256;
1385   }
1386   bool isMemNegImm8Offset() const {
1387     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1388       return false;
1389     // Base reg of PC isn't allowed for these encodings.
1390     if (Memory.BaseRegNum == ARM::PC) return false;
1391     // Immediate offset in range [-255, -1].
1392     if (!Memory.OffsetImm) return false;
1393     int64_t Val = Memory.OffsetImm->getValue();
1394     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1395   }
1396   bool isMemUImm12Offset() const {
1397     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1398       return false;
1399     // Immediate offset in range [0, 4095].
1400     if (!Memory.OffsetImm) return true;
1401     int64_t Val = Memory.OffsetImm->getValue();
1402     return (Val >= 0 && Val < 4096);
1403   }
1404   bool isMemImm12Offset() const {
1405     // If we have an immediate that's not a constant, treat it as a label
1406     // reference needing a fixup. If it is a constant, it's something else
1407     // and we reject it.
1408
1409     if (isImm() && !isa<MCConstantExpr>(getImm()))
1410       return true;
1411
1412     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1413       return false;
1414     // Immediate offset in range [-4095, 4095].
1415     if (!Memory.OffsetImm) return true;
1416     int64_t Val = Memory.OffsetImm->getValue();
1417     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1418   }
1419   bool isConstPoolAsmImm() const {
1420     // Delay processing of Constant Pool Immediate, this will turn into
1421     // a constant. Match no other operand
1422     return (isConstantPoolImm());
1423   }
1424   bool isPostIdxImm8() const {
1425     if (!isImm()) return false;
1426     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1427     if (!CE) return false;
1428     int64_t Val = CE->getValue();
1429     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1430   }
1431   bool isPostIdxImm8s4() const {
1432     if (!isImm()) return false;
1433     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1434     if (!CE) return false;
1435     int64_t Val = CE->getValue();
1436     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1437       (Val == INT32_MIN);
1438   }
1439
1440   bool isMSRMask() const { return Kind == k_MSRMask; }
1441   bool isBankedReg() const { return Kind == k_BankedReg; }
1442   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1443
1444   // NEON operands.
1445   bool isSingleSpacedVectorList() const {
1446     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1447   }
1448   bool isDoubleSpacedVectorList() const {
1449     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1450   }
1451   bool isVecListOneD() const {
1452     if (!isSingleSpacedVectorList()) return false;
1453     return VectorList.Count == 1;
1454   }
1455
1456   bool isVecListDPair() const {
1457     if (!isSingleSpacedVectorList()) return false;
1458     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1459               .contains(VectorList.RegNum));
1460   }
1461
1462   bool isVecListThreeD() const {
1463     if (!isSingleSpacedVectorList()) return false;
1464     return VectorList.Count == 3;
1465   }
1466
1467   bool isVecListFourD() const {
1468     if (!isSingleSpacedVectorList()) return false;
1469     return VectorList.Count == 4;
1470   }
1471
1472   bool isVecListDPairSpaced() const {
1473     if (Kind != k_VectorList) return false;
1474     if (isSingleSpacedVectorList()) return false;
1475     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1476               .contains(VectorList.RegNum));
1477   }
1478
1479   bool isVecListThreeQ() const {
1480     if (!isDoubleSpacedVectorList()) return false;
1481     return VectorList.Count == 3;
1482   }
1483
1484   bool isVecListFourQ() const {
1485     if (!isDoubleSpacedVectorList()) return false;
1486     return VectorList.Count == 4;
1487   }
1488
1489   bool isSingleSpacedVectorAllLanes() const {
1490     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1491   }
1492   bool isDoubleSpacedVectorAllLanes() const {
1493     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1494   }
1495   bool isVecListOneDAllLanes() const {
1496     if (!isSingleSpacedVectorAllLanes()) return false;
1497     return VectorList.Count == 1;
1498   }
1499
1500   bool isVecListDPairAllLanes() const {
1501     if (!isSingleSpacedVectorAllLanes()) return false;
1502     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1503               .contains(VectorList.RegNum));
1504   }
1505
1506   bool isVecListDPairSpacedAllLanes() const {
1507     if (!isDoubleSpacedVectorAllLanes()) return false;
1508     return VectorList.Count == 2;
1509   }
1510
1511   bool isVecListThreeDAllLanes() const {
1512     if (!isSingleSpacedVectorAllLanes()) return false;
1513     return VectorList.Count == 3;
1514   }
1515
1516   bool isVecListThreeQAllLanes() const {
1517     if (!isDoubleSpacedVectorAllLanes()) return false;
1518     return VectorList.Count == 3;
1519   }
1520
1521   bool isVecListFourDAllLanes() const {
1522     if (!isSingleSpacedVectorAllLanes()) return false;
1523     return VectorList.Count == 4;
1524   }
1525
1526   bool isVecListFourQAllLanes() const {
1527     if (!isDoubleSpacedVectorAllLanes()) return false;
1528     return VectorList.Count == 4;
1529   }
1530
1531   bool isSingleSpacedVectorIndexed() const {
1532     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1533   }
1534   bool isDoubleSpacedVectorIndexed() const {
1535     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1536   }
1537   bool isVecListOneDByteIndexed() const {
1538     if (!isSingleSpacedVectorIndexed()) return false;
1539     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1540   }
1541
1542   bool isVecListOneDHWordIndexed() const {
1543     if (!isSingleSpacedVectorIndexed()) return false;
1544     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1545   }
1546
1547   bool isVecListOneDWordIndexed() const {
1548     if (!isSingleSpacedVectorIndexed()) return false;
1549     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1550   }
1551
1552   bool isVecListTwoDByteIndexed() const {
1553     if (!isSingleSpacedVectorIndexed()) return false;
1554     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1555   }
1556
1557   bool isVecListTwoDHWordIndexed() const {
1558     if (!isSingleSpacedVectorIndexed()) return false;
1559     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1560   }
1561
1562   bool isVecListTwoQWordIndexed() const {
1563     if (!isDoubleSpacedVectorIndexed()) return false;
1564     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1565   }
1566
1567   bool isVecListTwoQHWordIndexed() const {
1568     if (!isDoubleSpacedVectorIndexed()) return false;
1569     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1570   }
1571
1572   bool isVecListTwoDWordIndexed() const {
1573     if (!isSingleSpacedVectorIndexed()) return false;
1574     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1575   }
1576
1577   bool isVecListThreeDByteIndexed() const {
1578     if (!isSingleSpacedVectorIndexed()) return false;
1579     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1580   }
1581
1582   bool isVecListThreeDHWordIndexed() const {
1583     if (!isSingleSpacedVectorIndexed()) return false;
1584     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1585   }
1586
1587   bool isVecListThreeQWordIndexed() const {
1588     if (!isDoubleSpacedVectorIndexed()) return false;
1589     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1590   }
1591
1592   bool isVecListThreeQHWordIndexed() const {
1593     if (!isDoubleSpacedVectorIndexed()) return false;
1594     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1595   }
1596
1597   bool isVecListThreeDWordIndexed() const {
1598     if (!isSingleSpacedVectorIndexed()) return false;
1599     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1600   }
1601
1602   bool isVecListFourDByteIndexed() const {
1603     if (!isSingleSpacedVectorIndexed()) return false;
1604     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1605   }
1606
1607   bool isVecListFourDHWordIndexed() const {
1608     if (!isSingleSpacedVectorIndexed()) return false;
1609     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1610   }
1611
1612   bool isVecListFourQWordIndexed() const {
1613     if (!isDoubleSpacedVectorIndexed()) return false;
1614     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1615   }
1616
1617   bool isVecListFourQHWordIndexed() const {
1618     if (!isDoubleSpacedVectorIndexed()) return false;
1619     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1620   }
1621
1622   bool isVecListFourDWordIndexed() const {
1623     if (!isSingleSpacedVectorIndexed()) return false;
1624     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1625   }
1626
1627   bool isVectorIndex8() const {
1628     if (Kind != k_VectorIndex) return false;
1629     return VectorIndex.Val < 8;
1630   }
1631   bool isVectorIndex16() const {
1632     if (Kind != k_VectorIndex) return false;
1633     return VectorIndex.Val < 4;
1634   }
1635   bool isVectorIndex32() const {
1636     if (Kind != k_VectorIndex) return false;
1637     return VectorIndex.Val < 2;
1638   }
1639
1640   bool isNEONi8splat() const {
1641     if (!isImm()) return false;
1642     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1643     // Must be a constant.
1644     if (!CE) return false;
1645     int64_t Value = CE->getValue();
1646     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1647     // value.
1648     return Value >= 0 && Value < 256;
1649   }
1650
1651   bool isNEONi16splat() const {
1652     if (isNEONByteReplicate(2))
1653       return false; // Leave that for bytes replication and forbid by default.
1654     if (!isImm())
1655       return false;
1656     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1657     // Must be a constant.
1658     if (!CE) return false;
1659     unsigned Value = CE->getValue();
1660     return ARM_AM::isNEONi16splat(Value);
1661   }
1662
1663   bool isNEONi16splatNot() const {
1664     if (!isImm())
1665       return false;
1666     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1667     // Must be a constant.
1668     if (!CE) return false;
1669     unsigned Value = CE->getValue();
1670     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1671   }
1672
1673   bool isNEONi32splat() const {
1674     if (isNEONByteReplicate(4))
1675       return false; // Leave that for bytes replication and forbid by default.
1676     if (!isImm())
1677       return false;
1678     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1679     // Must be a constant.
1680     if (!CE) return false;
1681     unsigned Value = CE->getValue();
1682     return ARM_AM::isNEONi32splat(Value);
1683   }
1684
1685   bool isNEONi32splatNot() const {
1686     if (!isImm())
1687       return false;
1688     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1689     // Must be a constant.
1690     if (!CE) return false;
1691     unsigned Value = CE->getValue();
1692     return ARM_AM::isNEONi32splat(~Value);
1693   }
1694
1695   bool isNEONByteReplicate(unsigned NumBytes) const {
1696     if (!isImm())
1697       return false;
1698     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1699     // Must be a constant.
1700     if (!CE)
1701       return false;
1702     int64_t Value = CE->getValue();
1703     if (!Value)
1704       return false; // Don't bother with zero.
1705
1706     unsigned char B = Value & 0xff;
1707     for (unsigned i = 1; i < NumBytes; ++i) {
1708       Value >>= 8;
1709       if ((Value & 0xff) != B)
1710         return false;
1711     }
1712     return true;
1713   }
1714   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1715   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1716   bool isNEONi32vmov() const {
1717     if (isNEONByteReplicate(4))
1718       return false; // Let it to be classified as byte-replicate case.
1719     if (!isImm())
1720       return false;
1721     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1722     // Must be a constant.
1723     if (!CE)
1724       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   bool isNEONi32vmovNeg() const {
1737     if (!isImm()) return false;
1738     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1739     // Must be a constant.
1740     if (!CE) return false;
1741     int64_t Value = ~CE->getValue();
1742     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1743     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1744     // FIXME: This is probably wrong and a copy and paste from previous example
1745     return (Value >= 0 && Value < 256) ||
1746       (Value >= 0x0100 && Value <= 0xff00) ||
1747       (Value >= 0x010000 && Value <= 0xff0000) ||
1748       (Value >= 0x01000000 && Value <= 0xff000000) ||
1749       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1750       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1751   }
1752
1753   bool isNEONi64splat() const {
1754     if (!isImm()) return false;
1755     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1756     // Must be a constant.
1757     if (!CE) return false;
1758     uint64_t Value = CE->getValue();
1759     // i64 value with each byte being either 0 or 0xff.
1760     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1761       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1762     return true;
1763   }
1764
1765   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1766     // Add as immediates when possible.  Null MCExpr = 0.
1767     if (!Expr)
1768       Inst.addOperand(MCOperand::createImm(0));
1769     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1770       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1771     else
1772       Inst.addOperand(MCOperand::createExpr(Expr));
1773   }
1774
1775   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
1776     assert(N == 1 && "Invalid number of operands!");
1777     addExpr(Inst, getImm());
1778   }
1779
1780   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
1781     assert(N == 1 && "Invalid number of operands!");
1782     addExpr(Inst, getImm());
1783   }
1784
1785   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1786     assert(N == 2 && "Invalid number of operands!");
1787     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1788     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1789     Inst.addOperand(MCOperand::createReg(RegNum));
1790   }
1791
1792   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1793     assert(N == 1 && "Invalid number of operands!");
1794     Inst.addOperand(MCOperand::createImm(getCoproc()));
1795   }
1796
1797   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1798     assert(N == 1 && "Invalid number of operands!");
1799     Inst.addOperand(MCOperand::createImm(getCoproc()));
1800   }
1801
1802   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1803     assert(N == 1 && "Invalid number of operands!");
1804     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1805   }
1806
1807   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1808     assert(N == 1 && "Invalid number of operands!");
1809     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1810   }
1811
1812   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1813     assert(N == 1 && "Invalid number of operands!");
1814     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1815   }
1816
1817   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1818     assert(N == 1 && "Invalid number of operands!");
1819     Inst.addOperand(MCOperand::createReg(getReg()));
1820   }
1821
1822   void addRegOperands(MCInst &Inst, unsigned N) const {
1823     assert(N == 1 && "Invalid number of operands!");
1824     Inst.addOperand(MCOperand::createReg(getReg()));
1825   }
1826
1827   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1828     assert(N == 3 && "Invalid number of operands!");
1829     assert(isRegShiftedReg() &&
1830            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1831     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1832     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1833     Inst.addOperand(MCOperand::createImm(
1834       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1835   }
1836
1837   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1838     assert(N == 2 && "Invalid number of operands!");
1839     assert(isRegShiftedImm() &&
1840            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1841     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1842     // Shift of #32 is encoded as 0 where permitted
1843     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1844     Inst.addOperand(MCOperand::createImm(
1845       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1846   }
1847
1848   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1849     assert(N == 1 && "Invalid number of operands!");
1850     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1851                                          ShifterImm.Imm));
1852   }
1853
1854   void addRegListOperands(MCInst &Inst, unsigned N) const {
1855     assert(N == 1 && "Invalid number of operands!");
1856     const SmallVectorImpl<unsigned> &RegList = getRegList();
1857     for (SmallVectorImpl<unsigned>::const_iterator
1858            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1859       Inst.addOperand(MCOperand::createReg(*I));
1860   }
1861
1862   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1863     addRegListOperands(Inst, N);
1864   }
1865
1866   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1867     addRegListOperands(Inst, N);
1868   }
1869
1870   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1871     assert(N == 1 && "Invalid number of operands!");
1872     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1873     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1874   }
1875
1876   void addModImmOperands(MCInst &Inst, unsigned N) const {
1877     assert(N == 1 && "Invalid number of operands!");
1878
1879     // Support for fixups (MCFixup)
1880     if (isImm())
1881       return addImmOperands(Inst, N);
1882
1883     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
1884   }
1885
1886   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1887     assert(N == 1 && "Invalid number of operands!");
1888     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1889     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1890     Inst.addOperand(MCOperand::createImm(Enc));
1891   }
1892
1893   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1894     assert(N == 1 && "Invalid number of operands!");
1895     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1896     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1897     Inst.addOperand(MCOperand::createImm(Enc));
1898   }
1899
1900   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
1901     assert(N == 1 && "Invalid number of operands!");
1902     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1903     uint32_t Val = -CE->getValue();
1904     Inst.addOperand(MCOperand::createImm(Val));
1905   }
1906
1907   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
1908     assert(N == 1 && "Invalid number of operands!");
1909     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1910     uint32_t Val = -CE->getValue();
1911     Inst.addOperand(MCOperand::createImm(Val));
1912   }
1913
1914   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1915     assert(N == 1 && "Invalid number of operands!");
1916     // Munge the lsb/width into a bitfield mask.
1917     unsigned lsb = Bitfield.LSB;
1918     unsigned width = Bitfield.Width;
1919     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1920     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1921                       (32 - (lsb + width)));
1922     Inst.addOperand(MCOperand::createImm(Mask));
1923   }
1924
1925   void addImmOperands(MCInst &Inst, unsigned N) const {
1926     assert(N == 1 && "Invalid number of operands!");
1927     addExpr(Inst, getImm());
1928   }
1929
1930   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1931     assert(N == 1 && "Invalid number of operands!");
1932     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1933     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
1934   }
1935
1936   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1937     assert(N == 1 && "Invalid number of operands!");
1938     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1939     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
1940   }
1941
1942   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1943     assert(N == 1 && "Invalid number of operands!");
1944     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1945     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1946     Inst.addOperand(MCOperand::createImm(Val));
1947   }
1948
1949   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1950     assert(N == 1 && "Invalid number of operands!");
1951     // FIXME: We really want to scale the value here, but the LDRD/STRD
1952     // instruction don't encode operands that way yet.
1953     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1954     Inst.addOperand(MCOperand::createImm(CE->getValue()));
1955   }
1956
1957   void addImm0_1020s4Operands(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 addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1966     assert(N == 1 && "Invalid number of operands!");
1967     // The immediate is scaled by four in the encoding and is stored
1968     // in the MCInst as such. Lop off the low two bits here.
1969     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1970     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
1971   }
1972
1973   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1974     assert(N == 1 && "Invalid number of operands!");
1975     // The immediate is scaled by four in the encoding and is stored
1976     // in the MCInst as such. Lop off the low two bits here.
1977     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1978     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1979   }
1980
1981   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1982     assert(N == 1 && "Invalid number of operands!");
1983     // The constant encodes as the immediate-1, and we store in the instruction
1984     // the bits as encoded, so subtract off one here.
1985     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1986     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1987   }
1988
1989   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1990     assert(N == 1 && "Invalid number of operands!");
1991     // The constant encodes as the immediate-1, and we store in the instruction
1992     // the bits as encoded, so subtract off one here.
1993     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1994     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1995   }
1996
1997   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1998     assert(N == 1 && "Invalid number of operands!");
1999     // The constant encodes as the immediate, except for 32, which encodes as
2000     // zero.
2001     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2002     unsigned Imm = CE->getValue();
2003     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2004   }
2005
2006   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2007     assert(N == 1 && "Invalid number of operands!");
2008     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2009     // the instruction as well.
2010     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2011     int Val = CE->getValue();
2012     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2013   }
2014
2015   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2016     assert(N == 1 && "Invalid number of operands!");
2017     // The operand is actually a t2_so_imm, but we have its bitwise
2018     // negation in the assembly source, so twiddle it here.
2019     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2020     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2021   }
2022
2023   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2024     assert(N == 1 && "Invalid number of operands!");
2025     // The operand is actually a t2_so_imm, but we have its
2026     // negation in the assembly source, so twiddle it here.
2027     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2028     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2029   }
2030
2031   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2032     assert(N == 1 && "Invalid number of operands!");
2033     // The operand is actually an imm0_4095, but we have its
2034     // negation in the assembly source, so twiddle it here.
2035     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2036     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2037   }
2038
2039   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2040     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2041       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2042       return;
2043     }
2044
2045     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2046     assert(SR && "Unknown value type!");
2047     Inst.addOperand(MCOperand::createExpr(SR));
2048   }
2049
2050   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2051     assert(N == 1 && "Invalid number of operands!");
2052     if (isImm()) {
2053       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2054       if (CE) {
2055         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2056         return;
2057       }
2058
2059       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2060  
2061       assert(SR && "Unknown value type!");
2062       Inst.addOperand(MCOperand::createExpr(SR));
2063       return;
2064     }
2065
2066     assert(isMem()  && "Unknown value type!");
2067     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2068     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2069   }
2070
2071   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2072     assert(N == 1 && "Invalid number of operands!");
2073     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2074   }
2075
2076   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2077     assert(N == 1 && "Invalid number of operands!");
2078     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2079   }
2080
2081   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2082     assert(N == 1 && "Invalid number of operands!");
2083     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2084   }
2085
2086   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2087     assert(N == 1 && "Invalid number of operands!");
2088     int32_t Imm = Memory.OffsetImm->getValue();
2089     Inst.addOperand(MCOperand::createImm(Imm));
2090   }
2091
2092   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2093     assert(N == 1 && "Invalid number of operands!");
2094     assert(isImm() && "Not an immediate!");
2095
2096     // If we have an immediate that's not a constant, treat it as a label
2097     // reference needing a fixup. 
2098     if (!isa<MCConstantExpr>(getImm())) {
2099       Inst.addOperand(MCOperand::createExpr(getImm()));
2100       return;
2101     }
2102
2103     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2104     int Val = CE->getValue();
2105     Inst.addOperand(MCOperand::createImm(Val));
2106   }
2107
2108   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2109     assert(N == 2 && "Invalid number of operands!");
2110     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2111     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2112   }
2113
2114   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2115     addAlignedMemoryOperands(Inst, N);
2116   }
2117
2118   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2119     addAlignedMemoryOperands(Inst, N);
2120   }
2121
2122   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2123     addAlignedMemoryOperands(Inst, N);
2124   }
2125
2126   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2127     addAlignedMemoryOperands(Inst, N);
2128   }
2129
2130   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2131     addAlignedMemoryOperands(Inst, N);
2132   }
2133
2134   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2135     addAlignedMemoryOperands(Inst, N);
2136   }
2137
2138   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2139     addAlignedMemoryOperands(Inst, N);
2140   }
2141
2142   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2143     addAlignedMemoryOperands(Inst, N);
2144   }
2145
2146   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2147     addAlignedMemoryOperands(Inst, N);
2148   }
2149
2150   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2151     addAlignedMemoryOperands(Inst, N);
2152   }
2153
2154   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2155     addAlignedMemoryOperands(Inst, N);
2156   }
2157
2158   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2159     assert(N == 3 && "Invalid number of operands!");
2160     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2161     if (!Memory.OffsetRegNum) {
2162       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2163       // Special case for #-0
2164       if (Val == INT32_MIN) Val = 0;
2165       if (Val < 0) Val = -Val;
2166       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2167     } else {
2168       // For register offset, we encode the shift type and negation flag
2169       // here.
2170       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2171                               Memory.ShiftImm, Memory.ShiftType);
2172     }
2173     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2174     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2175     Inst.addOperand(MCOperand::createImm(Val));
2176   }
2177
2178   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2179     assert(N == 2 && "Invalid number of operands!");
2180     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2181     assert(CE && "non-constant AM2OffsetImm operand!");
2182     int32_t Val = CE->getValue();
2183     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2184     // Special case for #-0
2185     if (Val == INT32_MIN) Val = 0;
2186     if (Val < 0) Val = -Val;
2187     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2188     Inst.addOperand(MCOperand::createReg(0));
2189     Inst.addOperand(MCOperand::createImm(Val));
2190   }
2191
2192   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2193     assert(N == 3 && "Invalid number of operands!");
2194     // If we have an immediate that's not a constant, treat it as a label
2195     // reference needing a fixup. If it is a constant, it's something else
2196     // and we reject it.
2197     if (isImm()) {
2198       Inst.addOperand(MCOperand::createExpr(getImm()));
2199       Inst.addOperand(MCOperand::createReg(0));
2200       Inst.addOperand(MCOperand::createImm(0));
2201       return;
2202     }
2203
2204     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2205     if (!Memory.OffsetRegNum) {
2206       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2207       // Special case for #-0
2208       if (Val == INT32_MIN) Val = 0;
2209       if (Val < 0) Val = -Val;
2210       Val = ARM_AM::getAM3Opc(AddSub, Val);
2211     } else {
2212       // For register offset, we encode the shift type and negation flag
2213       // here.
2214       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2215     }
2216     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2217     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2218     Inst.addOperand(MCOperand::createImm(Val));
2219   }
2220
2221   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2222     assert(N == 2 && "Invalid number of operands!");
2223     if (Kind == k_PostIndexRegister) {
2224       int32_t Val =
2225         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2226       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2227       Inst.addOperand(MCOperand::createImm(Val));
2228       return;
2229     }
2230
2231     // Constant offset.
2232     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2233     int32_t Val = CE->getValue();
2234     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2235     // Special case for #-0
2236     if (Val == INT32_MIN) Val = 0;
2237     if (Val < 0) Val = -Val;
2238     Val = ARM_AM::getAM3Opc(AddSub, Val);
2239     Inst.addOperand(MCOperand::createReg(0));
2240     Inst.addOperand(MCOperand::createImm(Val));
2241   }
2242
2243   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2244     assert(N == 2 && "Invalid number of operands!");
2245     // If we have an immediate that's not a constant, treat it as a label
2246     // reference needing a fixup. If it is a constant, it's something else
2247     // and we reject it.
2248     if (isImm()) {
2249       Inst.addOperand(MCOperand::createExpr(getImm()));
2250       Inst.addOperand(MCOperand::createImm(0));
2251       return;
2252     }
2253
2254     // The lower two bits are always zero and as such are not encoded.
2255     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2256     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2257     // Special case for #-0
2258     if (Val == INT32_MIN) Val = 0;
2259     if (Val < 0) Val = -Val;
2260     Val = ARM_AM::getAM5Opc(AddSub, Val);
2261     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2262     Inst.addOperand(MCOperand::createImm(Val));
2263   }
2264
2265   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2266     assert(N == 2 && "Invalid number of operands!");
2267     // If we have an immediate that's not a constant, treat it as a label
2268     // reference needing a fixup. If it is a constant, it's something else
2269     // and we reject it.
2270     if (isImm()) {
2271       Inst.addOperand(MCOperand::createExpr(getImm()));
2272       Inst.addOperand(MCOperand::createImm(0));
2273       return;
2274     }
2275
2276     // The lower bit is always zero and as such is not encoded.
2277     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2278     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2279     // Special case for #-0
2280     if (Val == INT32_MIN) Val = 0;
2281     if (Val < 0) Val = -Val;
2282     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2283     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2284     Inst.addOperand(MCOperand::createImm(Val));
2285   }
2286
2287   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2288     assert(N == 2 && "Invalid number of operands!");
2289     // If we have an immediate that's not a constant, treat it as a label
2290     // reference needing a fixup. If it is a constant, it's something else
2291     // and we reject it.
2292     if (isImm()) {
2293       Inst.addOperand(MCOperand::createExpr(getImm()));
2294       Inst.addOperand(MCOperand::createImm(0));
2295       return;
2296     }
2297
2298     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2299     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2300     Inst.addOperand(MCOperand::createImm(Val));
2301   }
2302
2303   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2304     assert(N == 2 && "Invalid number of operands!");
2305     // The lower two bits are always zero and as such are not encoded.
2306     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2307     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2308     Inst.addOperand(MCOperand::createImm(Val));
2309   }
2310
2311   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2312     assert(N == 2 && "Invalid number of operands!");
2313     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2314     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2315     Inst.addOperand(MCOperand::createImm(Val));
2316   }
2317
2318   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2319     addMemImm8OffsetOperands(Inst, N);
2320   }
2321
2322   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2323     addMemImm8OffsetOperands(Inst, N);
2324   }
2325
2326   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2327     assert(N == 2 && "Invalid number of operands!");
2328     // If this is an immediate, it's a label reference.
2329     if (isImm()) {
2330       addExpr(Inst, getImm());
2331       Inst.addOperand(MCOperand::createImm(0));
2332       return;
2333     }
2334
2335     // Otherwise, it's a normal memory reg+offset.
2336     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2337     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2338     Inst.addOperand(MCOperand::createImm(Val));
2339   }
2340
2341   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2342     assert(N == 2 && "Invalid number of operands!");
2343     // If this is an immediate, it's a label reference.
2344     if (isImm()) {
2345       addExpr(Inst, getImm());
2346       Inst.addOperand(MCOperand::createImm(0));
2347       return;
2348     }
2349
2350     // Otherwise, it's a normal memory reg+offset.
2351     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2352     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2353     Inst.addOperand(MCOperand::createImm(Val));
2354   }
2355
2356   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2357     assert(N == 1 && "Invalid number of operands!");
2358     // This is container for the immediate that we will create the constant
2359     // pool from
2360     addExpr(Inst, getConstantPoolImm());
2361     return;
2362   }
2363
2364   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2365     assert(N == 2 && "Invalid number of operands!");
2366     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2367     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2368   }
2369
2370   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2371     assert(N == 2 && "Invalid number of operands!");
2372     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2373     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2374   }
2375
2376   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2377     assert(N == 3 && "Invalid number of operands!");
2378     unsigned Val =
2379       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2380                         Memory.ShiftImm, Memory.ShiftType);
2381     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2382     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2383     Inst.addOperand(MCOperand::createImm(Val));
2384   }
2385
2386   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2387     assert(N == 3 && "Invalid number of operands!");
2388     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2389     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2390     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2391   }
2392
2393   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2394     assert(N == 2 && "Invalid number of operands!");
2395     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2396     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2397   }
2398
2399   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2400     assert(N == 2 && "Invalid number of operands!");
2401     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2402     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2403     Inst.addOperand(MCOperand::createImm(Val));
2404   }
2405
2406   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2407     assert(N == 2 && "Invalid number of operands!");
2408     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2409     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2410     Inst.addOperand(MCOperand::createImm(Val));
2411   }
2412
2413   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2414     assert(N == 2 && "Invalid number of operands!");
2415     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2416     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2417     Inst.addOperand(MCOperand::createImm(Val));
2418   }
2419
2420   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2421     assert(N == 2 && "Invalid number of operands!");
2422     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2423     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2424     Inst.addOperand(MCOperand::createImm(Val));
2425   }
2426
2427   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2428     assert(N == 1 && "Invalid number of operands!");
2429     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2430     assert(CE && "non-constant post-idx-imm8 operand!");
2431     int Imm = CE->getValue();
2432     bool isAdd = Imm >= 0;
2433     if (Imm == INT32_MIN) Imm = 0;
2434     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2435     Inst.addOperand(MCOperand::createImm(Imm));
2436   }
2437
2438   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2439     assert(N == 1 && "Invalid number of operands!");
2440     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2441     assert(CE && "non-constant post-idx-imm8s4 operand!");
2442     int Imm = CE->getValue();
2443     bool isAdd = Imm >= 0;
2444     if (Imm == INT32_MIN) Imm = 0;
2445     // Immediate is scaled by 4.
2446     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2447     Inst.addOperand(MCOperand::createImm(Imm));
2448   }
2449
2450   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2451     assert(N == 2 && "Invalid number of operands!");
2452     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2453     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2454   }
2455
2456   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2457     assert(N == 2 && "Invalid number of operands!");
2458     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2459     // The sign, shift type, and shift amount are encoded in a single operand
2460     // using the AM2 encoding helpers.
2461     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2462     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2463                                      PostIdxReg.ShiftTy);
2464     Inst.addOperand(MCOperand::createImm(Imm));
2465   }
2466
2467   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2468     assert(N == 1 && "Invalid number of operands!");
2469     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2470   }
2471
2472   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2473     assert(N == 1 && "Invalid number of operands!");
2474     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2475   }
2476
2477   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2478     assert(N == 1 && "Invalid number of operands!");
2479     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2480   }
2481
2482   void addVecListOperands(MCInst &Inst, unsigned N) const {
2483     assert(N == 1 && "Invalid number of operands!");
2484     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2485   }
2486
2487   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2488     assert(N == 2 && "Invalid number of operands!");
2489     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2490     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2491   }
2492
2493   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2494     assert(N == 1 && "Invalid number of operands!");
2495     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2496   }
2497
2498   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2499     assert(N == 1 && "Invalid number of operands!");
2500     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2501   }
2502
2503   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2504     assert(N == 1 && "Invalid number of operands!");
2505     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2506   }
2507
2508   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2509     assert(N == 1 && "Invalid number of operands!");
2510     // The immediate encodes the type of constant as well as the value.
2511     // Mask in that this is an i8 splat.
2512     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2513     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2514   }
2515
2516   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2517     assert(N == 1 && "Invalid number of operands!");
2518     // The immediate encodes the type of constant as well as the value.
2519     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2520     unsigned Value = CE->getValue();
2521     Value = ARM_AM::encodeNEONi16splat(Value);
2522     Inst.addOperand(MCOperand::createImm(Value));
2523   }
2524
2525   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2526     assert(N == 1 && "Invalid number of operands!");
2527     // The immediate encodes the type of constant as well as the value.
2528     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2529     unsigned Value = CE->getValue();
2530     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2531     Inst.addOperand(MCOperand::createImm(Value));
2532   }
2533
2534   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2535     assert(N == 1 && "Invalid number of operands!");
2536     // The immediate encodes the type of constant as well as the value.
2537     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2538     unsigned Value = CE->getValue();
2539     Value = ARM_AM::encodeNEONi32splat(Value);
2540     Inst.addOperand(MCOperand::createImm(Value));
2541   }
2542
2543   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2544     assert(N == 1 && "Invalid number of operands!");
2545     // The immediate encodes the type of constant as well as the value.
2546     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2547     unsigned Value = CE->getValue();
2548     Value = ARM_AM::encodeNEONi32splat(~Value);
2549     Inst.addOperand(MCOperand::createImm(Value));
2550   }
2551
2552   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2553     assert(N == 1 && "Invalid number of operands!");
2554     // The immediate encodes the type of constant as well as the value.
2555     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2556     unsigned Value = CE->getValue();
2557     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2558             Inst.getOpcode() == ARM::VMOVv16i8) &&
2559            "All vmvn instructions that wants to replicate non-zero byte "
2560            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2561     unsigned B = ((~Value) & 0xff);
2562     B |= 0xe00; // cmode = 0b1110
2563     Inst.addOperand(MCOperand::createImm(B));
2564   }
2565   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2566     assert(N == 1 && "Invalid number of operands!");
2567     // The immediate encodes the type of constant as well as the value.
2568     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2569     unsigned Value = CE->getValue();
2570     if (Value >= 256 && Value <= 0xffff)
2571       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2572     else if (Value > 0xffff && Value <= 0xffffff)
2573       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2574     else if (Value > 0xffffff)
2575       Value = (Value >> 24) | 0x600;
2576     Inst.addOperand(MCOperand::createImm(Value));
2577   }
2578
2579   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2580     assert(N == 1 && "Invalid number of operands!");
2581     // The immediate encodes the type of constant as well as the value.
2582     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2583     unsigned Value = CE->getValue();
2584     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2585             Inst.getOpcode() == ARM::VMOVv16i8) &&
2586            "All instructions that wants to replicate non-zero byte "
2587            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2588     unsigned B = Value & 0xff;
2589     B |= 0xe00; // cmode = 0b1110
2590     Inst.addOperand(MCOperand::createImm(B));
2591   }
2592   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2593     assert(N == 1 && "Invalid number of operands!");
2594     // The immediate encodes the type of constant as well as the value.
2595     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2596     unsigned Value = ~CE->getValue();
2597     if (Value >= 256 && Value <= 0xffff)
2598       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2599     else if (Value > 0xffff && Value <= 0xffffff)
2600       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2601     else if (Value > 0xffffff)
2602       Value = (Value >> 24) | 0x600;
2603     Inst.addOperand(MCOperand::createImm(Value));
2604   }
2605
2606   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2607     assert(N == 1 && "Invalid number of operands!");
2608     // The immediate encodes the type of constant as well as the value.
2609     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2610     uint64_t Value = CE->getValue();
2611     unsigned Imm = 0;
2612     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2613       Imm |= (Value & 1) << i;
2614     }
2615     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2616   }
2617
2618   void print(raw_ostream &OS) const override;
2619
2620   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2621     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2622     Op->ITMask.Mask = Mask;
2623     Op->StartLoc = S;
2624     Op->EndLoc = S;
2625     return Op;
2626   }
2627
2628   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2629                                                     SMLoc S) {
2630     auto Op = make_unique<ARMOperand>(k_CondCode);
2631     Op->CC.Val = CC;
2632     Op->StartLoc = S;
2633     Op->EndLoc = S;
2634     return Op;
2635   }
2636
2637   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2638     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2639     Op->Cop.Val = CopVal;
2640     Op->StartLoc = S;
2641     Op->EndLoc = S;
2642     return Op;
2643   }
2644
2645   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2646     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2647     Op->Cop.Val = CopVal;
2648     Op->StartLoc = S;
2649     Op->EndLoc = S;
2650     return Op;
2651   }
2652
2653   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2654                                                         SMLoc E) {
2655     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2656     Op->Cop.Val = Val;
2657     Op->StartLoc = S;
2658     Op->EndLoc = E;
2659     return Op;
2660   }
2661
2662   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2663     auto Op = make_unique<ARMOperand>(k_CCOut);
2664     Op->Reg.RegNum = RegNum;
2665     Op->StartLoc = S;
2666     Op->EndLoc = S;
2667     return Op;
2668   }
2669
2670   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2671     auto Op = make_unique<ARMOperand>(k_Token);
2672     Op->Tok.Data = Str.data();
2673     Op->Tok.Length = Str.size();
2674     Op->StartLoc = S;
2675     Op->EndLoc = S;
2676     return Op;
2677   }
2678
2679   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2680                                                SMLoc E) {
2681     auto Op = make_unique<ARMOperand>(k_Register);
2682     Op->Reg.RegNum = RegNum;
2683     Op->StartLoc = S;
2684     Op->EndLoc = E;
2685     return Op;
2686   }
2687
2688   static std::unique_ptr<ARMOperand>
2689   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2690                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2691                         SMLoc E) {
2692     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2693     Op->RegShiftedReg.ShiftTy = ShTy;
2694     Op->RegShiftedReg.SrcReg = SrcReg;
2695     Op->RegShiftedReg.ShiftReg = ShiftReg;
2696     Op->RegShiftedReg.ShiftImm = ShiftImm;
2697     Op->StartLoc = S;
2698     Op->EndLoc = E;
2699     return Op;
2700   }
2701
2702   static std::unique_ptr<ARMOperand>
2703   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2704                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2705     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2706     Op->RegShiftedImm.ShiftTy = ShTy;
2707     Op->RegShiftedImm.SrcReg = SrcReg;
2708     Op->RegShiftedImm.ShiftImm = ShiftImm;
2709     Op->StartLoc = S;
2710     Op->EndLoc = E;
2711     return Op;
2712   }
2713
2714   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2715                                                       SMLoc S, SMLoc E) {
2716     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2717     Op->ShifterImm.isASR = isASR;
2718     Op->ShifterImm.Imm = Imm;
2719     Op->StartLoc = S;
2720     Op->EndLoc = E;
2721     return Op;
2722   }
2723
2724   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2725                                                   SMLoc E) {
2726     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2727     Op->RotImm.Imm = Imm;
2728     Op->StartLoc = S;
2729     Op->EndLoc = E;
2730     return Op;
2731   }
2732
2733   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2734                                                   SMLoc S, SMLoc E) {
2735     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2736     Op->ModImm.Bits = Bits;
2737     Op->ModImm.Rot = Rot;
2738     Op->StartLoc = S;
2739     Op->EndLoc = E;
2740     return Op;
2741   }
2742
2743   static std::unique_ptr<ARMOperand>
2744   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2745     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
2746     Op->Imm.Val = Val;
2747     Op->StartLoc = S;
2748     Op->EndLoc = E;
2749     return Op;
2750   }
2751
2752   static std::unique_ptr<ARMOperand>
2753   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2754     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2755     Op->Bitfield.LSB = LSB;
2756     Op->Bitfield.Width = Width;
2757     Op->StartLoc = S;
2758     Op->EndLoc = E;
2759     return Op;
2760   }
2761
2762   static std::unique_ptr<ARMOperand>
2763   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2764                 SMLoc StartLoc, SMLoc EndLoc) {
2765     assert (Regs.size() > 0 && "RegList contains no registers?");
2766     KindTy Kind = k_RegisterList;
2767
2768     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2769       Kind = k_DPRRegisterList;
2770     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2771              contains(Regs.front().second))
2772       Kind = k_SPRRegisterList;
2773
2774     // Sort based on the register encoding values.
2775     array_pod_sort(Regs.begin(), Regs.end());
2776
2777     auto Op = make_unique<ARMOperand>(Kind);
2778     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2779            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2780       Op->Registers.push_back(I->second);
2781     Op->StartLoc = StartLoc;
2782     Op->EndLoc = EndLoc;
2783     return Op;
2784   }
2785
2786   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2787                                                       unsigned Count,
2788                                                       bool isDoubleSpaced,
2789                                                       SMLoc S, SMLoc E) {
2790     auto Op = make_unique<ARMOperand>(k_VectorList);
2791     Op->VectorList.RegNum = RegNum;
2792     Op->VectorList.Count = Count;
2793     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2794     Op->StartLoc = S;
2795     Op->EndLoc = E;
2796     return Op;
2797   }
2798
2799   static std::unique_ptr<ARMOperand>
2800   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2801                            SMLoc S, SMLoc E) {
2802     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2803     Op->VectorList.RegNum = RegNum;
2804     Op->VectorList.Count = Count;
2805     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2806     Op->StartLoc = S;
2807     Op->EndLoc = E;
2808     return Op;
2809   }
2810
2811   static std::unique_ptr<ARMOperand>
2812   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2813                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2814     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2815     Op->VectorList.RegNum = RegNum;
2816     Op->VectorList.Count = Count;
2817     Op->VectorList.LaneIndex = Index;
2818     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2819     Op->StartLoc = S;
2820     Op->EndLoc = E;
2821     return Op;
2822   }
2823
2824   static std::unique_ptr<ARMOperand>
2825   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2826     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2827     Op->VectorIndex.Val = Idx;
2828     Op->StartLoc = S;
2829     Op->EndLoc = E;
2830     return Op;
2831   }
2832
2833   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2834                                                SMLoc E) {
2835     auto Op = make_unique<ARMOperand>(k_Immediate);
2836     Op->Imm.Val = Val;
2837     Op->StartLoc = S;
2838     Op->EndLoc = E;
2839     return Op;
2840   }
2841
2842   static std::unique_ptr<ARMOperand>
2843   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2844             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2845             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2846             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2847     auto Op = make_unique<ARMOperand>(k_Memory);
2848     Op->Memory.BaseRegNum = BaseRegNum;
2849     Op->Memory.OffsetImm = OffsetImm;
2850     Op->Memory.OffsetRegNum = OffsetRegNum;
2851     Op->Memory.ShiftType = ShiftType;
2852     Op->Memory.ShiftImm = ShiftImm;
2853     Op->Memory.Alignment = Alignment;
2854     Op->Memory.isNegative = isNegative;
2855     Op->StartLoc = S;
2856     Op->EndLoc = E;
2857     Op->AlignmentLoc = AlignmentLoc;
2858     return Op;
2859   }
2860
2861   static std::unique_ptr<ARMOperand>
2862   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2863                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2864     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2865     Op->PostIdxReg.RegNum = RegNum;
2866     Op->PostIdxReg.isAdd = isAdd;
2867     Op->PostIdxReg.ShiftTy = ShiftTy;
2868     Op->PostIdxReg.ShiftImm = ShiftImm;
2869     Op->StartLoc = S;
2870     Op->EndLoc = E;
2871     return Op;
2872   }
2873
2874   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2875                                                          SMLoc S) {
2876     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2877     Op->MBOpt.Val = Opt;
2878     Op->StartLoc = S;
2879     Op->EndLoc = S;
2880     return Op;
2881   }
2882
2883   static std::unique_ptr<ARMOperand>
2884   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2885     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2886     Op->ISBOpt.Val = Opt;
2887     Op->StartLoc = S;
2888     Op->EndLoc = S;
2889     return Op;
2890   }
2891
2892   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2893                                                       SMLoc S) {
2894     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2895     Op->IFlags.Val = IFlags;
2896     Op->StartLoc = S;
2897     Op->EndLoc = S;
2898     return Op;
2899   }
2900
2901   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2902     auto Op = make_unique<ARMOperand>(k_MSRMask);
2903     Op->MMask.Val = MMask;
2904     Op->StartLoc = S;
2905     Op->EndLoc = S;
2906     return Op;
2907   }
2908
2909   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2910     auto Op = make_unique<ARMOperand>(k_BankedReg);
2911     Op->BankedReg.Val = Reg;
2912     Op->StartLoc = S;
2913     Op->EndLoc = S;
2914     return Op;
2915   }
2916 };
2917
2918 } // end anonymous namespace.
2919
2920 void ARMOperand::print(raw_ostream &OS) const {
2921   switch (Kind) {
2922   case k_CondCode:
2923     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2924     break;
2925   case k_CCOut:
2926     OS << "<ccout " << getReg() << ">";
2927     break;
2928   case k_ITCondMask: {
2929     static const char *const MaskStr[] = {
2930       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2931       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2932     };
2933     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2934     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2935     break;
2936   }
2937   case k_CoprocNum:
2938     OS << "<coprocessor number: " << getCoproc() << ">";
2939     break;
2940   case k_CoprocReg:
2941     OS << "<coprocessor register: " << getCoproc() << ">";
2942     break;
2943   case k_CoprocOption:
2944     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2945     break;
2946   case k_MSRMask:
2947     OS << "<mask: " << getMSRMask() << ">";
2948     break;
2949   case k_BankedReg:
2950     OS << "<banked reg: " << getBankedReg() << ">";
2951     break;
2952   case k_Immediate:
2953     OS << *getImm();
2954     break;
2955   case k_MemBarrierOpt:
2956     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2957     break;
2958   case k_InstSyncBarrierOpt:
2959     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2960     break;
2961   case k_Memory:
2962     OS << "<memory "
2963        << " base:" << Memory.BaseRegNum;
2964     OS << ">";
2965     break;
2966   case k_PostIndexRegister:
2967     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2968        << PostIdxReg.RegNum;
2969     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2970       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2971          << PostIdxReg.ShiftImm;
2972     OS << ">";
2973     break;
2974   case k_ProcIFlags: {
2975     OS << "<ARM_PROC::";
2976     unsigned IFlags = getProcIFlags();
2977     for (int i=2; i >= 0; --i)
2978       if (IFlags & (1 << i))
2979         OS << ARM_PROC::IFlagsToString(1 << i);
2980     OS << ">";
2981     break;
2982   }
2983   case k_Register:
2984     OS << "<register " << getReg() << ">";
2985     break;
2986   case k_ShifterImmediate:
2987     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2988        << " #" << ShifterImm.Imm << ">";
2989     break;
2990   case k_ShiftedRegister:
2991     OS << "<so_reg_reg "
2992        << RegShiftedReg.SrcReg << " "
2993        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2994        << " " << RegShiftedReg.ShiftReg << ">";
2995     break;
2996   case k_ShiftedImmediate:
2997     OS << "<so_reg_imm "
2998        << RegShiftedImm.SrcReg << " "
2999        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
3000        << " #" << RegShiftedImm.ShiftImm << ">";
3001     break;
3002   case k_RotateImmediate:
3003     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3004     break;
3005   case k_ModifiedImmediate:
3006     OS << "<mod_imm #" << ModImm.Bits << ", #"
3007        <<  ModImm.Rot << ")>";
3008     break;
3009   case k_ConstantPoolImmediate:
3010     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3011     break;
3012   case k_BitfieldDescriptor:
3013     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3014        << ", width: " << Bitfield.Width << ">";
3015     break;
3016   case k_RegisterList:
3017   case k_DPRRegisterList:
3018   case k_SPRRegisterList: {
3019     OS << "<register_list ";
3020
3021     const SmallVectorImpl<unsigned> &RegList = getRegList();
3022     for (SmallVectorImpl<unsigned>::const_iterator
3023            I = RegList.begin(), E = RegList.end(); I != E; ) {
3024       OS << *I;
3025       if (++I < E) OS << ", ";
3026     }
3027
3028     OS << ">";
3029     break;
3030   }
3031   case k_VectorList:
3032     OS << "<vector_list " << VectorList.Count << " * "
3033        << VectorList.RegNum << ">";
3034     break;
3035   case k_VectorListAllLanes:
3036     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3037        << VectorList.RegNum << ">";
3038     break;
3039   case k_VectorListIndexed:
3040     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3041        << VectorList.Count << " * " << VectorList.RegNum << ">";
3042     break;
3043   case k_Token:
3044     OS << "'" << getToken() << "'";
3045     break;
3046   case k_VectorIndex:
3047     OS << "<vectorindex " << getVectorIndex() << ">";
3048     break;
3049   }
3050 }
3051
3052 /// @name Auto-generated Match Functions
3053 /// {
3054
3055 static unsigned MatchRegisterName(StringRef Name);
3056
3057 /// }
3058
3059 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3060                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3061   const AsmToken &Tok = getParser().getTok();
3062   StartLoc = Tok.getLoc();
3063   EndLoc = Tok.getEndLoc();
3064   RegNo = tryParseRegister();
3065
3066   return (RegNo == (unsigned)-1);
3067 }
3068
3069 /// Try to parse a register name.  The token must be an Identifier when called,
3070 /// and if it is a register name the token is eaten and the register number is
3071 /// returned.  Otherwise return -1.
3072 ///
3073 int ARMAsmParser::tryParseRegister() {
3074   MCAsmParser &Parser = getParser();
3075   const AsmToken &Tok = Parser.getTok();
3076   if (Tok.isNot(AsmToken::Identifier)) return -1;
3077
3078   std::string lowerCase = Tok.getString().lower();
3079   unsigned RegNum = MatchRegisterName(lowerCase);
3080   if (!RegNum) {
3081     RegNum = StringSwitch<unsigned>(lowerCase)
3082       .Case("r13", ARM::SP)
3083       .Case("r14", ARM::LR)
3084       .Case("r15", ARM::PC)
3085       .Case("ip", ARM::R12)
3086       // Additional register name aliases for 'gas' compatibility.
3087       .Case("a1", ARM::R0)
3088       .Case("a2", ARM::R1)
3089       .Case("a3", ARM::R2)
3090       .Case("a4", ARM::R3)
3091       .Case("v1", ARM::R4)
3092       .Case("v2", ARM::R5)
3093       .Case("v3", ARM::R6)
3094       .Case("v4", ARM::R7)
3095       .Case("v5", ARM::R8)
3096       .Case("v6", ARM::R9)
3097       .Case("v7", ARM::R10)
3098       .Case("v8", ARM::R11)
3099       .Case("sb", ARM::R9)
3100       .Case("sl", ARM::R10)
3101       .Case("fp", ARM::R11)
3102       .Default(0);
3103   }
3104   if (!RegNum) {
3105     // Check for aliases registered via .req. Canonicalize to lower case.
3106     // That's more consistent since register names are case insensitive, and
3107     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3108     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3109     // If no match, return failure.
3110     if (Entry == RegisterReqs.end())
3111       return -1;
3112     Parser.Lex(); // Eat identifier token.
3113     return Entry->getValue();
3114   }
3115
3116   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3117   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3118     return -1;
3119
3120   Parser.Lex(); // Eat identifier token.
3121
3122   return RegNum;
3123 }
3124
3125 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3126 // If a recoverable error occurs, return 1. If an irrecoverable error
3127 // occurs, return -1. An irrecoverable error is one where tokens have been
3128 // consumed in the process of trying to parse the shifter (i.e., when it is
3129 // indeed a shifter operand, but malformed).
3130 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3131   MCAsmParser &Parser = getParser();
3132   SMLoc S = Parser.getTok().getLoc();
3133   const AsmToken &Tok = Parser.getTok();
3134   if (Tok.isNot(AsmToken::Identifier))
3135     return -1; 
3136
3137   std::string lowerCase = Tok.getString().lower();
3138   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3139       .Case("asl", ARM_AM::lsl)
3140       .Case("lsl", ARM_AM::lsl)
3141       .Case("lsr", ARM_AM::lsr)
3142       .Case("asr", ARM_AM::asr)
3143       .Case("ror", ARM_AM::ror)
3144       .Case("rrx", ARM_AM::rrx)
3145       .Default(ARM_AM::no_shift);
3146
3147   if (ShiftTy == ARM_AM::no_shift)
3148     return 1;
3149
3150   Parser.Lex(); // Eat the operator.
3151
3152   // The source register for the shift has already been added to the
3153   // operand list, so we need to pop it off and combine it into the shifted
3154   // register operand instead.
3155   std::unique_ptr<ARMOperand> PrevOp(
3156       (ARMOperand *)Operands.pop_back_val().release());
3157   if (!PrevOp->isReg())
3158     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3159   int SrcReg = PrevOp->getReg();
3160
3161   SMLoc EndLoc;
3162   int64_t Imm = 0;
3163   int ShiftReg = 0;
3164   if (ShiftTy == ARM_AM::rrx) {
3165     // RRX Doesn't have an explicit shift amount. The encoder expects
3166     // the shift register to be the same as the source register. Seems odd,
3167     // but OK.
3168     ShiftReg = SrcReg;
3169   } else {
3170     // Figure out if this is shifted by a constant or a register (for non-RRX).
3171     if (Parser.getTok().is(AsmToken::Hash) ||
3172         Parser.getTok().is(AsmToken::Dollar)) {
3173       Parser.Lex(); // Eat hash.
3174       SMLoc ImmLoc = Parser.getTok().getLoc();
3175       const MCExpr *ShiftExpr = nullptr;
3176       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3177         Error(ImmLoc, "invalid immediate shift value");
3178         return -1;
3179       }
3180       // The expression must be evaluatable as an immediate.
3181       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3182       if (!CE) {
3183         Error(ImmLoc, "invalid immediate shift value");
3184         return -1;
3185       }
3186       // Range check the immediate.
3187       // lsl, ror: 0 <= imm <= 31
3188       // lsr, asr: 0 <= imm <= 32
3189       Imm = CE->getValue();
3190       if (Imm < 0 ||
3191           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3192           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3193         Error(ImmLoc, "immediate shift value out of range");
3194         return -1;
3195       }
3196       // shift by zero is a nop. Always send it through as lsl.
3197       // ('as' compatibility)
3198       if (Imm == 0)
3199         ShiftTy = ARM_AM::lsl;
3200     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3201       SMLoc L = Parser.getTok().getLoc();
3202       EndLoc = Parser.getTok().getEndLoc();
3203       ShiftReg = tryParseRegister();
3204       if (ShiftReg == -1) {
3205         Error(L, "expected immediate or register in shift operand");
3206         return -1;
3207       }
3208     } else {
3209       Error(Parser.getTok().getLoc(),
3210             "expected immediate or register in shift operand");
3211       return -1;
3212     }
3213   }
3214
3215   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3216     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3217                                                          ShiftReg, Imm,
3218                                                          S, EndLoc));
3219   else
3220     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3221                                                           S, EndLoc));
3222
3223   return 0;
3224 }
3225
3226
3227 /// Try to parse a register name.  The token must be an Identifier when called.
3228 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3229 /// if there is a "writeback". 'true' if it's not a register.
3230 ///
3231 /// TODO this is likely to change to allow different register types and or to
3232 /// parse for a specific register type.
3233 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3234   MCAsmParser &Parser = getParser();
3235   const AsmToken &RegTok = Parser.getTok();
3236   int RegNo = tryParseRegister();
3237   if (RegNo == -1)
3238     return true;
3239
3240   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3241                                            RegTok.getEndLoc()));
3242
3243   const AsmToken &ExclaimTok = Parser.getTok();
3244   if (ExclaimTok.is(AsmToken::Exclaim)) {
3245     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3246                                                ExclaimTok.getLoc()));
3247     Parser.Lex(); // Eat exclaim token
3248     return false;
3249   }
3250
3251   // Also check for an index operand. This is only legal for vector registers,
3252   // but that'll get caught OK in operand matching, so we don't need to
3253   // explicitly filter everything else out here.
3254   if (Parser.getTok().is(AsmToken::LBrac)) {
3255     SMLoc SIdx = Parser.getTok().getLoc();
3256     Parser.Lex(); // Eat left bracket token.
3257
3258     const MCExpr *ImmVal;
3259     if (getParser().parseExpression(ImmVal))
3260       return true;
3261     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3262     if (!MCE)
3263       return TokError("immediate value expected for vector index");
3264
3265     if (Parser.getTok().isNot(AsmToken::RBrac))
3266       return Error(Parser.getTok().getLoc(), "']' expected");
3267
3268     SMLoc E = Parser.getTok().getEndLoc();
3269     Parser.Lex(); // Eat right bracket token.
3270
3271     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3272                                                      SIdx, E,
3273                                                      getContext()));
3274   }
3275
3276   return false;
3277 }
3278
3279 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3280 /// instruction with a symbolic operand name.
3281 /// We accept "crN" syntax for GAS compatibility.
3282 /// <operand-name> ::= <prefix><number>
3283 /// If CoprocOp is 'c', then:
3284 ///   <prefix> ::= c | cr
3285 /// If CoprocOp is 'p', then :
3286 ///   <prefix> ::= p
3287 /// <number> ::= integer in range [0, 15]
3288 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3289   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3290   // but efficient.
3291   if (Name.size() < 2 || Name[0] != CoprocOp)
3292     return -1;
3293   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3294
3295   switch (Name.size()) {
3296   default: return -1;
3297   case 1:
3298     switch (Name[0]) {
3299     default:  return -1;
3300     case '0': return 0;
3301     case '1': return 1;
3302     case '2': return 2;
3303     case '3': return 3;
3304     case '4': return 4;
3305     case '5': return 5;
3306     case '6': return 6;
3307     case '7': return 7;
3308     case '8': return 8;
3309     case '9': return 9;
3310     }
3311   case 2:
3312     if (Name[0] != '1')
3313       return -1;
3314     switch (Name[1]) {
3315     default:  return -1;
3316     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3317     // However, old cores (v5/v6) did use them in that way.
3318     case '0': return 10;
3319     case '1': return 11;
3320     case '2': return 12;
3321     case '3': return 13;
3322     case '4': return 14;
3323     case '5': return 15;
3324     }
3325   }
3326 }
3327
3328 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3329 OperandMatchResultTy
3330 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3331   MCAsmParser &Parser = getParser();
3332   SMLoc S = Parser.getTok().getLoc();
3333   const AsmToken &Tok = Parser.getTok();
3334   if (!Tok.is(AsmToken::Identifier))
3335     return MatchOperand_NoMatch;
3336   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3337     .Case("eq", ARMCC::EQ)
3338     .Case("ne", ARMCC::NE)
3339     .Case("hs", ARMCC::HS)
3340     .Case("cs", ARMCC::HS)
3341     .Case("lo", ARMCC::LO)
3342     .Case("cc", ARMCC::LO)
3343     .Case("mi", ARMCC::MI)
3344     .Case("pl", ARMCC::PL)
3345     .Case("vs", ARMCC::VS)
3346     .Case("vc", ARMCC::VC)
3347     .Case("hi", ARMCC::HI)
3348     .Case("ls", ARMCC::LS)
3349     .Case("ge", ARMCC::GE)
3350     .Case("lt", ARMCC::LT)
3351     .Case("gt", ARMCC::GT)
3352     .Case("le", ARMCC::LE)
3353     .Case("al", ARMCC::AL)
3354     .Default(~0U);
3355   if (CC == ~0U)
3356     return MatchOperand_NoMatch;
3357   Parser.Lex(); // Eat the token.
3358
3359   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3360
3361   return MatchOperand_Success;
3362 }
3363
3364 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3365 /// token must be an Identifier when called, and if it is a coprocessor
3366 /// number, the token is eaten and the operand is added to the operand list.
3367 OperandMatchResultTy
3368 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3369   MCAsmParser &Parser = getParser();
3370   SMLoc S = Parser.getTok().getLoc();
3371   const AsmToken &Tok = Parser.getTok();
3372   if (Tok.isNot(AsmToken::Identifier))
3373     return MatchOperand_NoMatch;
3374
3375   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3376   if (Num == -1)
3377     return MatchOperand_NoMatch;
3378   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3379   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3380     return MatchOperand_NoMatch;
3381
3382   Parser.Lex(); // Eat identifier token.
3383   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3384   return MatchOperand_Success;
3385 }
3386
3387 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3388 /// token must be an Identifier when called, and if it is a coprocessor
3389 /// number, the token is eaten and the operand is added to the operand list.
3390 OperandMatchResultTy
3391 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3392   MCAsmParser &Parser = getParser();
3393   SMLoc S = Parser.getTok().getLoc();
3394   const AsmToken &Tok = Parser.getTok();
3395   if (Tok.isNot(AsmToken::Identifier))
3396     return MatchOperand_NoMatch;
3397
3398   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3399   if (Reg == -1)
3400     return MatchOperand_NoMatch;
3401
3402   Parser.Lex(); // Eat identifier token.
3403   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3404   return MatchOperand_Success;
3405 }
3406
3407 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3408 /// coproc_option : '{' imm0_255 '}'
3409 OperandMatchResultTy
3410 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3411   MCAsmParser &Parser = getParser();
3412   SMLoc S = Parser.getTok().getLoc();
3413
3414   // If this isn't a '{', this isn't a coprocessor immediate operand.
3415   if (Parser.getTok().isNot(AsmToken::LCurly))
3416     return MatchOperand_NoMatch;
3417   Parser.Lex(); // Eat the '{'
3418
3419   const MCExpr *Expr;
3420   SMLoc Loc = Parser.getTok().getLoc();
3421   if (getParser().parseExpression(Expr)) {
3422     Error(Loc, "illegal expression");
3423     return MatchOperand_ParseFail;
3424   }
3425   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3426   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3427     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3428     return MatchOperand_ParseFail;
3429   }
3430   int Val = CE->getValue();
3431
3432   // Check for and consume the closing '}'
3433   if (Parser.getTok().isNot(AsmToken::RCurly))
3434     return MatchOperand_ParseFail;
3435   SMLoc E = Parser.getTok().getEndLoc();
3436   Parser.Lex(); // Eat the '}'
3437
3438   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3439   return MatchOperand_Success;
3440 }
3441
3442 // For register list parsing, we need to map from raw GPR register numbering
3443 // to the enumeration values. The enumeration values aren't sorted by
3444 // register number due to our using "sp", "lr" and "pc" as canonical names.
3445 static unsigned getNextRegister(unsigned Reg) {
3446   // If this is a GPR, we need to do it manually, otherwise we can rely
3447   // on the sort ordering of the enumeration since the other reg-classes
3448   // are sane.
3449   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3450     return Reg + 1;
3451   switch(Reg) {
3452   default: llvm_unreachable("Invalid GPR number!");
3453   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3454   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3455   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3456   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3457   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3458   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3459   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3460   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3461   }
3462 }
3463
3464 // Return the low-subreg of a given Q register.
3465 static unsigned getDRegFromQReg(unsigned QReg) {
3466   switch (QReg) {
3467   default: llvm_unreachable("expected a Q register!");
3468   case ARM::Q0:  return ARM::D0;
3469   case ARM::Q1:  return ARM::D2;
3470   case ARM::Q2:  return ARM::D4;
3471   case ARM::Q3:  return ARM::D6;
3472   case ARM::Q4:  return ARM::D8;
3473   case ARM::Q5:  return ARM::D10;
3474   case ARM::Q6:  return ARM::D12;
3475   case ARM::Q7:  return ARM::D14;
3476   case ARM::Q8:  return ARM::D16;
3477   case ARM::Q9:  return ARM::D18;
3478   case ARM::Q10: return ARM::D20;
3479   case ARM::Q11: return ARM::D22;
3480   case ARM::Q12: return ARM::D24;
3481   case ARM::Q13: return ARM::D26;
3482   case ARM::Q14: return ARM::D28;
3483   case ARM::Q15: return ARM::D30;
3484   }
3485 }
3486
3487 /// Parse a register list.
3488 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3489   MCAsmParser &Parser = getParser();
3490   if (Parser.getTok().isNot(AsmToken::LCurly))
3491     return TokError("Token is not a Left Curly Brace");
3492   SMLoc S = Parser.getTok().getLoc();
3493   Parser.Lex(); // Eat '{' token.
3494   SMLoc RegLoc = Parser.getTok().getLoc();
3495
3496   // Check the first register in the list to see what register class
3497   // this is a list of.
3498   int Reg = tryParseRegister();
3499   if (Reg == -1)
3500     return Error(RegLoc, "register expected");
3501
3502   // The reglist instructions have at most 16 registers, so reserve
3503   // space for that many.
3504   int EReg = 0;
3505   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3506
3507   // Allow Q regs and just interpret them as the two D sub-registers.
3508   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3509     Reg = getDRegFromQReg(Reg);
3510     EReg = MRI->getEncodingValue(Reg);
3511     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3512     ++Reg;
3513   }
3514   const MCRegisterClass *RC;
3515   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3516     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3517   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3518     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3519   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3520     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3521   else
3522     return Error(RegLoc, "invalid register in register list");
3523
3524   // Store the register.
3525   EReg = MRI->getEncodingValue(Reg);
3526   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3527
3528   // This starts immediately after the first register token in the list,
3529   // so we can see either a comma or a minus (range separator) as a legal
3530   // next token.
3531   while (Parser.getTok().is(AsmToken::Comma) ||
3532          Parser.getTok().is(AsmToken::Minus)) {
3533     if (Parser.getTok().is(AsmToken::Minus)) {
3534       Parser.Lex(); // Eat the minus.
3535       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3536       int EndReg = tryParseRegister();
3537       if (EndReg == -1)
3538         return Error(AfterMinusLoc, "register expected");
3539       // Allow Q regs and just interpret them as the two D sub-registers.
3540       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3541         EndReg = getDRegFromQReg(EndReg) + 1;
3542       // If the register is the same as the start reg, there's nothing
3543       // more to do.
3544       if (Reg == EndReg)
3545         continue;
3546       // The register must be in the same register class as the first.
3547       if (!RC->contains(EndReg))
3548         return Error(AfterMinusLoc, "invalid register in register list");
3549       // Ranges must go from low to high.
3550       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3551         return Error(AfterMinusLoc, "bad range in register list");
3552
3553       // Add all the registers in the range to the register list.
3554       while (Reg != EndReg) {
3555         Reg = getNextRegister(Reg);
3556         EReg = MRI->getEncodingValue(Reg);
3557         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3558       }
3559       continue;
3560     }
3561     Parser.Lex(); // Eat the comma.
3562     RegLoc = Parser.getTok().getLoc();
3563     int OldReg = Reg;
3564     const AsmToken RegTok = Parser.getTok();
3565     Reg = tryParseRegister();
3566     if (Reg == -1)
3567       return Error(RegLoc, "register expected");
3568     // Allow Q regs and just interpret them as the two D sub-registers.
3569     bool isQReg = false;
3570     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3571       Reg = getDRegFromQReg(Reg);
3572       isQReg = true;
3573     }
3574     // The register must be in the same register class as the first.
3575     if (!RC->contains(Reg))
3576       return Error(RegLoc, "invalid register in register list");
3577     // List must be monotonically increasing.
3578     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3579       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3580         Warning(RegLoc, "register list not in ascending order");
3581       else
3582         return Error(RegLoc, "register list not in ascending order");
3583     }
3584     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3585       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3586               ") in register list");
3587       continue;
3588     }
3589     // VFP register lists must also be contiguous.
3590     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3591         Reg != OldReg + 1)
3592       return Error(RegLoc, "non-contiguous register range");
3593     EReg = MRI->getEncodingValue(Reg);
3594     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3595     if (isQReg) {
3596       EReg = MRI->getEncodingValue(++Reg);
3597       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3598     }
3599   }
3600
3601   if (Parser.getTok().isNot(AsmToken::RCurly))
3602     return Error(Parser.getTok().getLoc(), "'}' expected");
3603   SMLoc E = Parser.getTok().getEndLoc();
3604   Parser.Lex(); // Eat '}' token.
3605
3606   // Push the register list operand.
3607   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3608
3609   // The ARM system instruction variants for LDM/STM have a '^' token here.
3610   if (Parser.getTok().is(AsmToken::Caret)) {
3611     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3612     Parser.Lex(); // Eat '^' token.
3613   }
3614
3615   return false;
3616 }
3617
3618 // Helper function to parse the lane index for vector lists.
3619 OperandMatchResultTy ARMAsmParser::
3620 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3621   MCAsmParser &Parser = getParser();
3622   Index = 0; // Always return a defined index value.
3623   if (Parser.getTok().is(AsmToken::LBrac)) {
3624     Parser.Lex(); // Eat the '['.
3625     if (Parser.getTok().is(AsmToken::RBrac)) {
3626       // "Dn[]" is the 'all lanes' syntax.
3627       LaneKind = AllLanes;
3628       EndLoc = Parser.getTok().getEndLoc();
3629       Parser.Lex(); // Eat the ']'.
3630       return MatchOperand_Success;
3631     }
3632
3633     // There's an optional '#' token here. Normally there wouldn't be, but
3634     // inline assemble puts one in, and it's friendly to accept that.
3635     if (Parser.getTok().is(AsmToken::Hash))
3636       Parser.Lex(); // Eat '#' or '$'.
3637
3638     const MCExpr *LaneIndex;
3639     SMLoc Loc = Parser.getTok().getLoc();
3640     if (getParser().parseExpression(LaneIndex)) {
3641       Error(Loc, "illegal expression");
3642       return MatchOperand_ParseFail;
3643     }
3644     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3645     if (!CE) {
3646       Error(Loc, "lane index must be empty or an integer");
3647       return MatchOperand_ParseFail;
3648     }
3649     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3650       Error(Parser.getTok().getLoc(), "']' expected");
3651       return MatchOperand_ParseFail;
3652     }
3653     EndLoc = Parser.getTok().getEndLoc();
3654     Parser.Lex(); // Eat the ']'.
3655     int64_t Val = CE->getValue();
3656
3657     // FIXME: Make this range check context sensitive for .8, .16, .32.
3658     if (Val < 0 || Val > 7) {
3659       Error(Parser.getTok().getLoc(), "lane index out of range");
3660       return MatchOperand_ParseFail;
3661     }
3662     Index = Val;
3663     LaneKind = IndexedLane;
3664     return MatchOperand_Success;
3665   }
3666   LaneKind = NoLanes;
3667   return MatchOperand_Success;
3668 }
3669
3670 // parse a vector register list
3671 OperandMatchResultTy
3672 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3673   MCAsmParser &Parser = getParser();
3674   VectorLaneTy LaneKind;
3675   unsigned LaneIndex;
3676   SMLoc S = Parser.getTok().getLoc();
3677   // As an extension (to match gas), support a plain D register or Q register
3678   // (without encosing curly braces) as a single or double entry list,
3679   // respectively.
3680   if (Parser.getTok().is(AsmToken::Identifier)) {
3681     SMLoc E = Parser.getTok().getEndLoc();
3682     int Reg = tryParseRegister();
3683     if (Reg == -1)
3684       return MatchOperand_NoMatch;
3685     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3686       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3687       if (Res != MatchOperand_Success)
3688         return Res;
3689       switch (LaneKind) {
3690       case NoLanes:
3691         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3692         break;
3693       case AllLanes:
3694         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3695                                                                 S, E));
3696         break;
3697       case IndexedLane:
3698         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3699                                                                LaneIndex,
3700                                                                false, S, E));
3701         break;
3702       }
3703       return MatchOperand_Success;
3704     }
3705     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3706       Reg = getDRegFromQReg(Reg);
3707       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3708       if (Res != MatchOperand_Success)
3709         return Res;
3710       switch (LaneKind) {
3711       case NoLanes:
3712         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3713                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3714         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3715         break;
3716       case AllLanes:
3717         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3718                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3719         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3720                                                                 S, E));
3721         break;
3722       case IndexedLane:
3723         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3724                                                                LaneIndex,
3725                                                                false, S, E));
3726         break;
3727       }
3728       return MatchOperand_Success;
3729     }
3730     Error(S, "vector register expected");
3731     return MatchOperand_ParseFail;
3732   }
3733
3734   if (Parser.getTok().isNot(AsmToken::LCurly))
3735     return MatchOperand_NoMatch;
3736
3737   Parser.Lex(); // Eat '{' token.
3738   SMLoc RegLoc = Parser.getTok().getLoc();
3739
3740   int Reg = tryParseRegister();
3741   if (Reg == -1) {
3742     Error(RegLoc, "register expected");
3743     return MatchOperand_ParseFail;
3744   }
3745   unsigned Count = 1;
3746   int Spacing = 0;
3747   unsigned FirstReg = Reg;
3748   // The list is of D registers, but we also allow Q regs and just interpret
3749   // them as the two D sub-registers.
3750   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3751     FirstReg = Reg = getDRegFromQReg(Reg);
3752     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3753                  // it's ambiguous with four-register single spaced.
3754     ++Reg;
3755     ++Count;
3756   }
3757
3758   SMLoc E;
3759   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3760     return MatchOperand_ParseFail;
3761
3762   while (Parser.getTok().is(AsmToken::Comma) ||
3763          Parser.getTok().is(AsmToken::Minus)) {
3764     if (Parser.getTok().is(AsmToken::Minus)) {
3765       if (!Spacing)
3766         Spacing = 1; // Register range implies a single spaced list.
3767       else if (Spacing == 2) {
3768         Error(Parser.getTok().getLoc(),
3769               "sequential registers in double spaced list");
3770         return MatchOperand_ParseFail;
3771       }
3772       Parser.Lex(); // Eat the minus.
3773       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3774       int EndReg = tryParseRegister();
3775       if (EndReg == -1) {
3776         Error(AfterMinusLoc, "register expected");
3777         return MatchOperand_ParseFail;
3778       }
3779       // Allow Q regs and just interpret them as the two D sub-registers.
3780       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3781         EndReg = getDRegFromQReg(EndReg) + 1;
3782       // If the register is the same as the start reg, there's nothing
3783       // more to do.
3784       if (Reg == EndReg)
3785         continue;
3786       // The register must be in the same register class as the first.
3787       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3788         Error(AfterMinusLoc, "invalid register in register list");
3789         return MatchOperand_ParseFail;
3790       }
3791       // Ranges must go from low to high.
3792       if (Reg > EndReg) {
3793         Error(AfterMinusLoc, "bad range in register list");
3794         return MatchOperand_ParseFail;
3795       }
3796       // Parse the lane specifier if present.
3797       VectorLaneTy NextLaneKind;
3798       unsigned NextLaneIndex;
3799       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3800           MatchOperand_Success)
3801         return MatchOperand_ParseFail;
3802       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3803         Error(AfterMinusLoc, "mismatched lane index in register list");
3804         return MatchOperand_ParseFail;
3805       }
3806
3807       // Add all the registers in the range to the register list.
3808       Count += EndReg - Reg;
3809       Reg = EndReg;
3810       continue;
3811     }
3812     Parser.Lex(); // Eat the comma.
3813     RegLoc = Parser.getTok().getLoc();
3814     int OldReg = Reg;
3815     Reg = tryParseRegister();
3816     if (Reg == -1) {
3817       Error(RegLoc, "register expected");
3818       return MatchOperand_ParseFail;
3819     }
3820     // vector register lists must be contiguous.
3821     // It's OK to use the enumeration values directly here rather, as the
3822     // VFP register classes have the enum sorted properly.
3823     //
3824     // The list is of D registers, but we also allow Q regs and just interpret
3825     // them as the two D sub-registers.
3826     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3827       if (!Spacing)
3828         Spacing = 1; // Register range implies a single spaced list.
3829       else if (Spacing == 2) {
3830         Error(RegLoc,
3831               "invalid register in double-spaced list (must be 'D' register')");
3832         return MatchOperand_ParseFail;
3833       }
3834       Reg = getDRegFromQReg(Reg);
3835       if (Reg != OldReg + 1) {
3836         Error(RegLoc, "non-contiguous register range");
3837         return MatchOperand_ParseFail;
3838       }
3839       ++Reg;
3840       Count += 2;
3841       // Parse the lane specifier if present.
3842       VectorLaneTy NextLaneKind;
3843       unsigned NextLaneIndex;
3844       SMLoc LaneLoc = Parser.getTok().getLoc();
3845       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3846           MatchOperand_Success)
3847         return MatchOperand_ParseFail;
3848       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3849         Error(LaneLoc, "mismatched lane index in register list");
3850         return MatchOperand_ParseFail;
3851       }
3852       continue;
3853     }
3854     // Normal D register.
3855     // Figure out the register spacing (single or double) of the list if
3856     // we don't know it already.
3857     if (!Spacing)
3858       Spacing = 1 + (Reg == OldReg + 2);
3859
3860     // Just check that it's contiguous and keep going.
3861     if (Reg != OldReg + Spacing) {
3862       Error(RegLoc, "non-contiguous register range");
3863       return MatchOperand_ParseFail;
3864     }
3865     ++Count;
3866     // Parse the lane specifier if present.
3867     VectorLaneTy NextLaneKind;
3868     unsigned NextLaneIndex;
3869     SMLoc EndLoc = Parser.getTok().getLoc();
3870     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3871       return MatchOperand_ParseFail;
3872     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3873       Error(EndLoc, "mismatched lane index in register list");
3874       return MatchOperand_ParseFail;
3875     }
3876   }
3877
3878   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3879     Error(Parser.getTok().getLoc(), "'}' expected");
3880     return MatchOperand_ParseFail;
3881   }
3882   E = Parser.getTok().getEndLoc();
3883   Parser.Lex(); // Eat '}' token.
3884
3885   switch (LaneKind) {
3886   case NoLanes:
3887     // Two-register operands have been converted to the
3888     // composite register classes.
3889     if (Count == 2) {
3890       const MCRegisterClass *RC = (Spacing == 1) ?
3891         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3892         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3893       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3894     }
3895
3896     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3897                                                     (Spacing == 2), S, E));
3898     break;
3899   case AllLanes:
3900     // Two-register operands have been converted to the
3901     // composite register classes.
3902     if (Count == 2) {
3903       const MCRegisterClass *RC = (Spacing == 1) ?
3904         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3905         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3906       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3907     }
3908     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3909                                                             (Spacing == 2),
3910                                                             S, E));
3911     break;
3912   case IndexedLane:
3913     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3914                                                            LaneIndex,
3915                                                            (Spacing == 2),
3916                                                            S, E));
3917     break;
3918   }
3919   return MatchOperand_Success;
3920 }
3921
3922 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3923 OperandMatchResultTy
3924 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3925   MCAsmParser &Parser = getParser();
3926   SMLoc S = Parser.getTok().getLoc();
3927   const AsmToken &Tok = Parser.getTok();
3928   unsigned Opt;
3929
3930   if (Tok.is(AsmToken::Identifier)) {
3931     StringRef OptStr = Tok.getString();
3932
3933     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3934       .Case("sy",    ARM_MB::SY)
3935       .Case("st",    ARM_MB::ST)
3936       .Case("ld",    ARM_MB::LD)
3937       .Case("sh",    ARM_MB::ISH)
3938       .Case("ish",   ARM_MB::ISH)
3939       .Case("shst",  ARM_MB::ISHST)
3940       .Case("ishst", ARM_MB::ISHST)
3941       .Case("ishld", ARM_MB::ISHLD)
3942       .Case("nsh",   ARM_MB::NSH)
3943       .Case("un",    ARM_MB::NSH)
3944       .Case("nshst", ARM_MB::NSHST)
3945       .Case("nshld", ARM_MB::NSHLD)
3946       .Case("unst",  ARM_MB::NSHST)
3947       .Case("osh",   ARM_MB::OSH)
3948       .Case("oshst", ARM_MB::OSHST)
3949       .Case("oshld", ARM_MB::OSHLD)
3950       .Default(~0U);
3951
3952     // ishld, oshld, nshld and ld are only available from ARMv8.
3953     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3954                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3955       Opt = ~0U;
3956
3957     if (Opt == ~0U)
3958       return MatchOperand_NoMatch;
3959
3960     Parser.Lex(); // Eat identifier token.
3961   } else if (Tok.is(AsmToken::Hash) ||
3962              Tok.is(AsmToken::Dollar) ||
3963              Tok.is(AsmToken::Integer)) {
3964     if (Parser.getTok().isNot(AsmToken::Integer))
3965       Parser.Lex(); // Eat '#' or '$'.
3966     SMLoc Loc = Parser.getTok().getLoc();
3967
3968     const MCExpr *MemBarrierID;
3969     if (getParser().parseExpression(MemBarrierID)) {
3970       Error(Loc, "illegal expression");
3971       return MatchOperand_ParseFail;
3972     }
3973
3974     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3975     if (!CE) {
3976       Error(Loc, "constant expression expected");
3977       return MatchOperand_ParseFail;
3978     }
3979
3980     int Val = CE->getValue();
3981     if (Val & ~0xf) {
3982       Error(Loc, "immediate value out of range");
3983       return MatchOperand_ParseFail;
3984     }
3985
3986     Opt = ARM_MB::RESERVED_0 + Val;
3987   } else
3988     return MatchOperand_ParseFail;
3989
3990   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3991   return MatchOperand_Success;
3992 }
3993
3994 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3995 OperandMatchResultTy
3996 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3997   MCAsmParser &Parser = getParser();
3998   SMLoc S = Parser.getTok().getLoc();
3999   const AsmToken &Tok = Parser.getTok();
4000   unsigned Opt;
4001
4002   if (Tok.is(AsmToken::Identifier)) {
4003     StringRef OptStr = Tok.getString();
4004
4005     if (OptStr.equals_lower("sy"))
4006       Opt = ARM_ISB::SY;
4007     else
4008       return MatchOperand_NoMatch;
4009
4010     Parser.Lex(); // Eat identifier token.
4011   } else if (Tok.is(AsmToken::Hash) ||
4012              Tok.is(AsmToken::Dollar) ||
4013              Tok.is(AsmToken::Integer)) {
4014     if (Parser.getTok().isNot(AsmToken::Integer))
4015       Parser.Lex(); // Eat '#' or '$'.
4016     SMLoc Loc = Parser.getTok().getLoc();
4017
4018     const MCExpr *ISBarrierID;
4019     if (getParser().parseExpression(ISBarrierID)) {
4020       Error(Loc, "illegal expression");
4021       return MatchOperand_ParseFail;
4022     }
4023
4024     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4025     if (!CE) {
4026       Error(Loc, "constant expression expected");
4027       return MatchOperand_ParseFail;
4028     }
4029
4030     int Val = CE->getValue();
4031     if (Val & ~0xf) {
4032       Error(Loc, "immediate value out of range");
4033       return MatchOperand_ParseFail;
4034     }
4035
4036     Opt = ARM_ISB::RESERVED_0 + Val;
4037   } else
4038     return MatchOperand_ParseFail;
4039
4040   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4041           (ARM_ISB::InstSyncBOpt)Opt, S));
4042   return MatchOperand_Success;
4043 }
4044
4045
4046 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4047 OperandMatchResultTy
4048 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4049   MCAsmParser &Parser = getParser();
4050   SMLoc S = Parser.getTok().getLoc();
4051   const AsmToken &Tok = Parser.getTok();
4052   if (!Tok.is(AsmToken::Identifier)) 
4053     return MatchOperand_NoMatch;
4054   StringRef IFlagsStr = Tok.getString();
4055
4056   // An iflags string of "none" is interpreted to mean that none of the AIF
4057   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4058   unsigned IFlags = 0;
4059   if (IFlagsStr != "none") {
4060         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4061       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
4062         .Case("a", ARM_PROC::A)
4063         .Case("i", ARM_PROC::I)
4064         .Case("f", ARM_PROC::F)
4065         .Default(~0U);
4066
4067       // If some specific iflag is already set, it means that some letter is
4068       // present more than once, this is not acceptable.
4069       if (Flag == ~0U || (IFlags & Flag))
4070         return MatchOperand_NoMatch;
4071
4072       IFlags |= Flag;
4073     }
4074   }
4075
4076   Parser.Lex(); // Eat identifier token.
4077   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4078   return MatchOperand_Success;
4079 }
4080
4081 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4082 OperandMatchResultTy
4083 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4084   MCAsmParser &Parser = getParser();
4085   SMLoc S = Parser.getTok().getLoc();
4086   const AsmToken &Tok = Parser.getTok();
4087   if (!Tok.is(AsmToken::Identifier))
4088     return MatchOperand_NoMatch;
4089   StringRef Mask = Tok.getString();
4090
4091   if (isMClass()) {
4092     // See ARMv6-M 10.1.1
4093     std::string Name = Mask.lower();
4094     unsigned FlagsVal = StringSwitch<unsigned>(Name)
4095       // Note: in the documentation:
4096       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
4097       //  for MSR APSR_nzcvq.
4098       // but we do make it an alias here.  This is so to get the "mask encoding"
4099       // bits correct on MSR APSR writes.
4100       //
4101       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
4102       // should really only be allowed when writing a special register.  Note
4103       // they get dropped in the MRS instruction reading a special register as
4104       // the SYSm field is only 8 bits.
4105       .Case("apsr", 0x800)
4106       .Case("apsr_nzcvq", 0x800)
4107       .Case("apsr_g", 0x400)
4108       .Case("apsr_nzcvqg", 0xc00)
4109       .Case("iapsr", 0x801)
4110       .Case("iapsr_nzcvq", 0x801)
4111       .Case("iapsr_g", 0x401)
4112       .Case("iapsr_nzcvqg", 0xc01)
4113       .Case("eapsr", 0x802)
4114       .Case("eapsr_nzcvq", 0x802)
4115       .Case("eapsr_g", 0x402)
4116       .Case("eapsr_nzcvqg", 0xc02)
4117       .Case("xpsr", 0x803)
4118       .Case("xpsr_nzcvq", 0x803)
4119       .Case("xpsr_g", 0x403)
4120       .Case("xpsr_nzcvqg", 0xc03)
4121       .Case("ipsr", 0x805)
4122       .Case("epsr", 0x806)
4123       .Case("iepsr", 0x807)
4124       .Case("msp", 0x808)
4125       .Case("psp", 0x809)
4126       .Case("primask", 0x810)
4127       .Case("basepri", 0x811)
4128       .Case("basepri_max", 0x812)
4129       .Case("faultmask", 0x813)
4130       .Case("control", 0x814)
4131       .Case("msplim", 0x80a)
4132       .Case("psplim", 0x80b)
4133       .Case("msp_ns", 0x888)
4134       .Case("psp_ns", 0x889)
4135       .Case("msplim_ns", 0x88a)
4136       .Case("psplim_ns", 0x88b)
4137       .Case("primask_ns", 0x890)
4138       .Case("basepri_ns", 0x891)
4139       .Case("basepri_max_ns", 0x892)
4140       .Case("faultmask_ns", 0x893)
4141       .Case("control_ns", 0x894)
4142       .Case("sp_ns", 0x898)
4143       .Default(~0U);
4144
4145     if (FlagsVal == ~0U)
4146       return MatchOperand_NoMatch;
4147
4148     if (!hasDSP() && (FlagsVal & 0x400))
4149       // The _g and _nzcvqg versions are only valid if the DSP extension is
4150       // available.
4151       return MatchOperand_NoMatch;
4152
4153     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
4154       // basepri, basepri_max and faultmask only valid for V7m.
4155       return MatchOperand_NoMatch;
4156
4157     if (!has8MSecExt() && (FlagsVal == 0x80a || FlagsVal == 0x80b ||
4158                              (FlagsVal > 0x814 && FlagsVal < 0xc00)))
4159       return MatchOperand_NoMatch;
4160
4161     if (!hasV8MMainline() && (FlagsVal == 0x88a || FlagsVal == 0x88b ||
4162                               (FlagsVal > 0x890 && FlagsVal <= 0x893)))
4163       return MatchOperand_NoMatch;
4164
4165     Parser.Lex(); // Eat identifier token.
4166     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4167     return MatchOperand_Success;
4168   }
4169
4170   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4171   size_t Start = 0, Next = Mask.find('_');
4172   StringRef Flags = "";
4173   std::string SpecReg = Mask.slice(Start, Next).lower();
4174   if (Next != StringRef::npos)
4175     Flags = Mask.slice(Next+1, Mask.size());
4176
4177   // FlagsVal contains the complete mask:
4178   // 3-0: Mask
4179   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4180   unsigned FlagsVal = 0;
4181
4182   if (SpecReg == "apsr") {
4183     FlagsVal = StringSwitch<unsigned>(Flags)
4184     .Case("nzcvq",  0x8) // same as CPSR_f
4185     .Case("g",      0x4) // same as CPSR_s
4186     .Case("nzcvqg", 0xc) // same as CPSR_fs
4187     .Default(~0U);
4188
4189     if (FlagsVal == ~0U) {
4190       if (!Flags.empty())
4191         return MatchOperand_NoMatch;
4192       else
4193         FlagsVal = 8; // No flag
4194     }
4195   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4196     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4197     if (Flags == "all" || Flags == "")
4198       Flags = "fc";
4199     for (int i = 0, e = Flags.size(); i != e; ++i) {
4200       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4201       .Case("c", 1)
4202       .Case("x", 2)
4203       .Case("s", 4)
4204       .Case("f", 8)
4205       .Default(~0U);
4206
4207       // If some specific flag is already set, it means that some letter is
4208       // present more than once, this is not acceptable.
4209       if (Flag == ~0U || (FlagsVal & Flag))
4210         return MatchOperand_NoMatch;
4211       FlagsVal |= Flag;
4212     }
4213   } else // No match for special register.
4214     return MatchOperand_NoMatch;
4215
4216   // Special register without flags is NOT equivalent to "fc" flags.
4217   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4218   // two lines would enable gas compatibility at the expense of breaking
4219   // round-tripping.
4220   //
4221   // if (!FlagsVal)
4222   //  FlagsVal = 0x9;
4223
4224   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4225   if (SpecReg == "spsr")
4226     FlagsVal |= 16;
4227
4228   Parser.Lex(); // Eat identifier token.
4229   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4230   return MatchOperand_Success;
4231 }
4232
4233 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4234 /// use in the MRS/MSR instructions added to support virtualization.
4235 OperandMatchResultTy
4236 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4237   MCAsmParser &Parser = getParser();
4238   SMLoc S = Parser.getTok().getLoc();
4239   const AsmToken &Tok = Parser.getTok();
4240   if (!Tok.is(AsmToken::Identifier))
4241     return MatchOperand_NoMatch;
4242   StringRef RegName = Tok.getString();
4243
4244   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4245   // and bit 5 is R.
4246   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4247                           .Case("r8_usr", 0x00)
4248                           .Case("r9_usr", 0x01)
4249                           .Case("r10_usr", 0x02)
4250                           .Case("r11_usr", 0x03)
4251                           .Case("r12_usr", 0x04)
4252                           .Case("sp_usr", 0x05)
4253                           .Case("lr_usr", 0x06)
4254                           .Case("r8_fiq", 0x08)
4255                           .Case("r9_fiq", 0x09)
4256                           .Case("r10_fiq", 0x0a)
4257                           .Case("r11_fiq", 0x0b)
4258                           .Case("r12_fiq", 0x0c)
4259                           .Case("sp_fiq", 0x0d)
4260                           .Case("lr_fiq", 0x0e)
4261                           .Case("lr_irq", 0x10)
4262                           .Case("sp_irq", 0x11)
4263                           .Case("lr_svc", 0x12)
4264                           .Case("sp_svc", 0x13)
4265                           .Case("lr_abt", 0x14)
4266                           .Case("sp_abt", 0x15)
4267                           .Case("lr_und", 0x16)
4268                           .Case("sp_und", 0x17)
4269                           .Case("lr_mon", 0x1c)
4270                           .Case("sp_mon", 0x1d)
4271                           .Case("elr_hyp", 0x1e)
4272                           .Case("sp_hyp", 0x1f)
4273                           .Case("spsr_fiq", 0x2e)
4274                           .Case("spsr_irq", 0x30)
4275                           .Case("spsr_svc", 0x32)
4276                           .Case("spsr_abt", 0x34)
4277                           .Case("spsr_und", 0x36)
4278                           .Case("spsr_mon", 0x3c)
4279                           .Case("spsr_hyp", 0x3e)
4280                           .Default(~0U);
4281
4282   if (Encoding == ~0U)
4283     return MatchOperand_NoMatch;
4284
4285   Parser.Lex(); // Eat identifier token.
4286   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4287   return MatchOperand_Success;
4288 }
4289
4290 OperandMatchResultTy
4291 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4292                           int High) {
4293   MCAsmParser &Parser = getParser();
4294   const AsmToken &Tok = Parser.getTok();
4295   if (Tok.isNot(AsmToken::Identifier)) {
4296     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4297     return MatchOperand_ParseFail;
4298   }
4299   StringRef ShiftName = Tok.getString();
4300   std::string LowerOp = Op.lower();
4301   std::string UpperOp = Op.upper();
4302   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4303     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4304     return MatchOperand_ParseFail;
4305   }
4306   Parser.Lex(); // Eat shift type token.
4307
4308   // There must be a '#' and a shift amount.
4309   if (Parser.getTok().isNot(AsmToken::Hash) &&
4310       Parser.getTok().isNot(AsmToken::Dollar)) {
4311     Error(Parser.getTok().getLoc(), "'#' expected");
4312     return MatchOperand_ParseFail;
4313   }
4314   Parser.Lex(); // Eat hash token.
4315
4316   const MCExpr *ShiftAmount;
4317   SMLoc Loc = Parser.getTok().getLoc();
4318   SMLoc EndLoc;
4319   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4320     Error(Loc, "illegal expression");
4321     return MatchOperand_ParseFail;
4322   }
4323   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4324   if (!CE) {
4325     Error(Loc, "constant expression expected");
4326     return MatchOperand_ParseFail;
4327   }
4328   int Val = CE->getValue();
4329   if (Val < Low || Val > High) {
4330     Error(Loc, "immediate value out of range");
4331     return MatchOperand_ParseFail;
4332   }
4333
4334   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4335
4336   return MatchOperand_Success;
4337 }
4338
4339 OperandMatchResultTy
4340 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4341   MCAsmParser &Parser = getParser();
4342   const AsmToken &Tok = Parser.getTok();
4343   SMLoc S = Tok.getLoc();
4344   if (Tok.isNot(AsmToken::Identifier)) {
4345     Error(S, "'be' or 'le' operand expected");
4346     return MatchOperand_ParseFail;
4347   }
4348   int Val = StringSwitch<int>(Tok.getString().lower())
4349     .Case("be", 1)
4350     .Case("le", 0)
4351     .Default(-1);
4352   Parser.Lex(); // Eat the token.
4353
4354   if (Val == -1) {
4355     Error(S, "'be' or 'le' operand expected");
4356     return MatchOperand_ParseFail;
4357   }
4358   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4359                                                                   getContext()),
4360                                            S, Tok.getEndLoc()));
4361   return MatchOperand_Success;
4362 }
4363
4364 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4365 /// instructions. Legal values are:
4366 ///     lsl #n  'n' in [0,31]
4367 ///     asr #n  'n' in [1,32]
4368 ///             n == 32 encoded as n == 0.
4369 OperandMatchResultTy
4370 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4371   MCAsmParser &Parser = getParser();
4372   const AsmToken &Tok = Parser.getTok();
4373   SMLoc S = Tok.getLoc();
4374   if (Tok.isNot(AsmToken::Identifier)) {
4375     Error(S, "shift operator 'asr' or 'lsl' expected");
4376     return MatchOperand_ParseFail;
4377   }
4378   StringRef ShiftName = Tok.getString();
4379   bool isASR;
4380   if (ShiftName == "lsl" || ShiftName == "LSL")
4381     isASR = false;
4382   else if (ShiftName == "asr" || ShiftName == "ASR")
4383     isASR = true;
4384   else {
4385     Error(S, "shift operator 'asr' or 'lsl' expected");
4386     return MatchOperand_ParseFail;
4387   }
4388   Parser.Lex(); // Eat the operator.
4389
4390   // A '#' and a shift amount.
4391   if (Parser.getTok().isNot(AsmToken::Hash) &&
4392       Parser.getTok().isNot(AsmToken::Dollar)) {
4393     Error(Parser.getTok().getLoc(), "'#' expected");
4394     return MatchOperand_ParseFail;
4395   }
4396   Parser.Lex(); // Eat hash token.
4397   SMLoc ExLoc = Parser.getTok().getLoc();
4398
4399   const MCExpr *ShiftAmount;
4400   SMLoc EndLoc;
4401   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4402     Error(ExLoc, "malformed shift expression");
4403     return MatchOperand_ParseFail;
4404   }
4405   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4406   if (!CE) {
4407     Error(ExLoc, "shift amount must be an immediate");
4408     return MatchOperand_ParseFail;
4409   }
4410
4411   int64_t Val = CE->getValue();
4412   if (isASR) {
4413     // Shift amount must be in [1,32]
4414     if (Val < 1 || Val > 32) {
4415       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4416       return MatchOperand_ParseFail;
4417     }
4418     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4419     if (isThumb() && Val == 32) {
4420       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4421       return MatchOperand_ParseFail;
4422     }
4423     if (Val == 32) Val = 0;
4424   } else {
4425     // Shift amount must be in [1,32]
4426     if (Val < 0 || Val > 31) {
4427       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4428       return MatchOperand_ParseFail;
4429     }
4430   }
4431
4432   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4433
4434   return MatchOperand_Success;
4435 }
4436
4437 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4438 /// of instructions. Legal values are:
4439 ///     ror #n  'n' in {0, 8, 16, 24}
4440 OperandMatchResultTy
4441 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4442   MCAsmParser &Parser = getParser();
4443   const AsmToken &Tok = Parser.getTok();
4444   SMLoc S = Tok.getLoc();
4445   if (Tok.isNot(AsmToken::Identifier))
4446     return MatchOperand_NoMatch;
4447   StringRef ShiftName = Tok.getString();
4448   if (ShiftName != "ror" && ShiftName != "ROR")
4449     return MatchOperand_NoMatch;
4450   Parser.Lex(); // Eat the operator.
4451
4452   // A '#' and a rotate amount.
4453   if (Parser.getTok().isNot(AsmToken::Hash) &&
4454       Parser.getTok().isNot(AsmToken::Dollar)) {
4455     Error(Parser.getTok().getLoc(), "'#' expected");
4456     return MatchOperand_ParseFail;
4457   }
4458   Parser.Lex(); // Eat hash token.
4459   SMLoc ExLoc = Parser.getTok().getLoc();
4460
4461   const MCExpr *ShiftAmount;
4462   SMLoc EndLoc;
4463   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4464     Error(ExLoc, "malformed rotate expression");
4465     return MatchOperand_ParseFail;
4466   }
4467   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4468   if (!CE) {
4469     Error(ExLoc, "rotate amount must be an immediate");
4470     return MatchOperand_ParseFail;
4471   }
4472
4473   int64_t Val = CE->getValue();
4474   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4475   // normally, zero is represented in asm by omitting the rotate operand
4476   // entirely.
4477   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4478     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4479     return MatchOperand_ParseFail;
4480   }
4481
4482   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4483
4484   return MatchOperand_Success;
4485 }
4486
4487 OperandMatchResultTy
4488 ARMAsmParser::parseModImm(OperandVector &Operands) {
4489   MCAsmParser &Parser = getParser();
4490   MCAsmLexer &Lexer = getLexer();
4491   int64_t Imm1, Imm2;
4492
4493   SMLoc S = Parser.getTok().getLoc();
4494
4495   // 1) A mod_imm operand can appear in the place of a register name:
4496   //   add r0, #mod_imm
4497   //   add r0, r0, #mod_imm
4498   // to correctly handle the latter, we bail out as soon as we see an
4499   // identifier.
4500   //
4501   // 2) Similarly, we do not want to parse into complex operands:
4502   //   mov r0, #mod_imm
4503   //   mov r0, :lower16:(_foo)
4504   if (Parser.getTok().is(AsmToken::Identifier) ||
4505       Parser.getTok().is(AsmToken::Colon))
4506     return MatchOperand_NoMatch;
4507
4508   // Hash (dollar) is optional as per the ARMARM
4509   if (Parser.getTok().is(AsmToken::Hash) ||
4510       Parser.getTok().is(AsmToken::Dollar)) {
4511     // Avoid parsing into complex operands (#:)
4512     if (Lexer.peekTok().is(AsmToken::Colon))
4513       return MatchOperand_NoMatch;
4514
4515     // Eat the hash (dollar)
4516     Parser.Lex();
4517   }
4518
4519   SMLoc Sx1, Ex1;
4520   Sx1 = Parser.getTok().getLoc();
4521   const MCExpr *Imm1Exp;
4522   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4523     Error(Sx1, "malformed expression");
4524     return MatchOperand_ParseFail;
4525   }
4526
4527   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4528
4529   if (CE) {
4530     // Immediate must fit within 32-bits
4531     Imm1 = CE->getValue();
4532     int Enc = ARM_AM::getSOImmVal(Imm1);
4533     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4534       // We have a match!
4535       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4536                                                   (Enc & 0xF00) >> 7,
4537                                                   Sx1, Ex1));
4538       return MatchOperand_Success;
4539     }
4540
4541     // We have parsed an immediate which is not for us, fallback to a plain
4542     // immediate. This can happen for instruction aliases. For an example,
4543     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4544     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4545     // instruction with a mod_imm operand. The alias is defined such that the
4546     // parser method is shared, that's why we have to do this here.
4547     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4548       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4549       return MatchOperand_Success;
4550     }
4551   } else {
4552     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4553     // MCFixup). Fallback to a plain immediate.
4554     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4555     return MatchOperand_Success;
4556   }
4557
4558   // From this point onward, we expect the input to be a (#bits, #rot) pair
4559   if (Parser.getTok().isNot(AsmToken::Comma)) {
4560     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4561     return MatchOperand_ParseFail;
4562   }
4563
4564   if (Imm1 & ~0xFF) {
4565     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4566     return MatchOperand_ParseFail;
4567   }
4568
4569   // Eat the comma
4570   Parser.Lex();
4571
4572   // Repeat for #rot
4573   SMLoc Sx2, Ex2;
4574   Sx2 = Parser.getTok().getLoc();
4575
4576   // Eat the optional hash (dollar)
4577   if (Parser.getTok().is(AsmToken::Hash) ||
4578       Parser.getTok().is(AsmToken::Dollar))
4579     Parser.Lex();
4580
4581   const MCExpr *Imm2Exp;
4582   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4583     Error(Sx2, "malformed expression");
4584     return MatchOperand_ParseFail;
4585   }
4586
4587   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4588
4589   if (CE) {
4590     Imm2 = CE->getValue();
4591     if (!(Imm2 & ~0x1E)) {
4592       // We have a match!
4593       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4594       return MatchOperand_Success;
4595     }
4596     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4597     return MatchOperand_ParseFail;
4598   } else {
4599     Error(Sx2, "constant expression expected");
4600     return MatchOperand_ParseFail;
4601   }
4602 }
4603
4604 OperandMatchResultTy
4605 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4606   MCAsmParser &Parser = getParser();
4607   SMLoc S = Parser.getTok().getLoc();
4608   // The bitfield descriptor is really two operands, the LSB and the width.
4609   if (Parser.getTok().isNot(AsmToken::Hash) &&
4610       Parser.getTok().isNot(AsmToken::Dollar)) {
4611     Error(Parser.getTok().getLoc(), "'#' expected");
4612     return MatchOperand_ParseFail;
4613   }
4614   Parser.Lex(); // Eat hash token.
4615
4616   const MCExpr *LSBExpr;
4617   SMLoc E = Parser.getTok().getLoc();
4618   if (getParser().parseExpression(LSBExpr)) {
4619     Error(E, "malformed immediate expression");
4620     return MatchOperand_ParseFail;
4621   }
4622   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4623   if (!CE) {
4624     Error(E, "'lsb' operand must be an immediate");
4625     return MatchOperand_ParseFail;
4626   }
4627
4628   int64_t LSB = CE->getValue();
4629   // The LSB must be in the range [0,31]
4630   if (LSB < 0 || LSB > 31) {
4631     Error(E, "'lsb' operand must be in the range [0,31]");
4632     return MatchOperand_ParseFail;
4633   }
4634   E = Parser.getTok().getLoc();
4635
4636   // Expect another immediate operand.
4637   if (Parser.getTok().isNot(AsmToken::Comma)) {
4638     Error(Parser.getTok().getLoc(), "too few operands");
4639     return MatchOperand_ParseFail;
4640   }
4641   Parser.Lex(); // Eat hash token.
4642   if (Parser.getTok().isNot(AsmToken::Hash) &&
4643       Parser.getTok().isNot(AsmToken::Dollar)) {
4644     Error(Parser.getTok().getLoc(), "'#' expected");
4645     return MatchOperand_ParseFail;
4646   }
4647   Parser.Lex(); // Eat hash token.
4648
4649   const MCExpr *WidthExpr;
4650   SMLoc EndLoc;
4651   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4652     Error(E, "malformed immediate expression");
4653     return MatchOperand_ParseFail;
4654   }
4655   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4656   if (!CE) {
4657     Error(E, "'width' operand must be an immediate");
4658     return MatchOperand_ParseFail;
4659   }
4660
4661   int64_t Width = CE->getValue();
4662   // The LSB must be in the range [1,32-lsb]
4663   if (Width < 1 || Width > 32 - LSB) {
4664     Error(E, "'width' operand must be in the range [1,32-lsb]");
4665     return MatchOperand_ParseFail;
4666   }
4667
4668   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4669
4670   return MatchOperand_Success;
4671 }
4672
4673 OperandMatchResultTy
4674 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4675   // Check for a post-index addressing register operand. Specifically:
4676   // postidx_reg := '+' register {, shift}
4677   //              | '-' register {, shift}
4678   //              | register {, shift}
4679
4680   // This method must return MatchOperand_NoMatch without consuming any tokens
4681   // in the case where there is no match, as other alternatives take other
4682   // parse methods.
4683   MCAsmParser &Parser = getParser();
4684   AsmToken Tok = Parser.getTok();
4685   SMLoc S = Tok.getLoc();
4686   bool haveEaten = false;
4687   bool isAdd = true;
4688   if (Tok.is(AsmToken::Plus)) {
4689     Parser.Lex(); // Eat the '+' token.
4690     haveEaten = true;
4691   } else if (Tok.is(AsmToken::Minus)) {
4692     Parser.Lex(); // Eat the '-' token.
4693     isAdd = false;
4694     haveEaten = true;
4695   }
4696
4697   SMLoc E = Parser.getTok().getEndLoc();
4698   int Reg = tryParseRegister();
4699   if (Reg == -1) {
4700     if (!haveEaten)
4701       return MatchOperand_NoMatch;
4702     Error(Parser.getTok().getLoc(), "register expected");
4703     return MatchOperand_ParseFail;
4704   }
4705
4706   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4707   unsigned ShiftImm = 0;
4708   if (Parser.getTok().is(AsmToken::Comma)) {
4709     Parser.Lex(); // Eat the ','.
4710     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4711       return MatchOperand_ParseFail;
4712
4713     // FIXME: Only approximates end...may include intervening whitespace.
4714     E = Parser.getTok().getLoc();
4715   }
4716
4717   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4718                                                   ShiftImm, S, E));
4719
4720   return MatchOperand_Success;
4721 }
4722
4723 OperandMatchResultTy
4724 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4725   // Check for a post-index addressing register operand. Specifically:
4726   // am3offset := '+' register
4727   //              | '-' register
4728   //              | register
4729   //              | # imm
4730   //              | # + imm
4731   //              | # - imm
4732
4733   // This method must return MatchOperand_NoMatch without consuming any tokens
4734   // in the case where there is no match, as other alternatives take other
4735   // parse methods.
4736   MCAsmParser &Parser = getParser();
4737   AsmToken Tok = Parser.getTok();
4738   SMLoc S = Tok.getLoc();
4739
4740   // Do immediates first, as we always parse those if we have a '#'.
4741   if (Parser.getTok().is(AsmToken::Hash) ||
4742       Parser.getTok().is(AsmToken::Dollar)) {
4743     Parser.Lex(); // Eat '#' or '$'.
4744     // Explicitly look for a '-', as we need to encode negative zero
4745     // differently.
4746     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4747     const MCExpr *Offset;
4748     SMLoc E;
4749     if (getParser().parseExpression(Offset, E))
4750       return MatchOperand_ParseFail;
4751     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4752     if (!CE) {
4753       Error(S, "constant expression expected");
4754       return MatchOperand_ParseFail;
4755     }
4756     // Negative zero is encoded as the flag value INT32_MIN.
4757     int32_t Val = CE->getValue();
4758     if (isNegative && Val == 0)
4759       Val = INT32_MIN;
4760
4761     Operands.push_back(
4762       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4763
4764     return MatchOperand_Success;
4765   }
4766
4767
4768   bool haveEaten = false;
4769   bool isAdd = true;
4770   if (Tok.is(AsmToken::Plus)) {
4771     Parser.Lex(); // Eat the '+' token.
4772     haveEaten = true;
4773   } else if (Tok.is(AsmToken::Minus)) {
4774     Parser.Lex(); // Eat the '-' token.
4775     isAdd = false;
4776     haveEaten = true;
4777   }
4778
4779   Tok = Parser.getTok();
4780   int Reg = tryParseRegister();
4781   if (Reg == -1) {
4782     if (!haveEaten)
4783       return MatchOperand_NoMatch;
4784     Error(Tok.getLoc(), "register expected");
4785     return MatchOperand_ParseFail;
4786   }
4787
4788   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4789                                                   0, S, Tok.getEndLoc()));
4790
4791   return MatchOperand_Success;
4792 }
4793
4794 /// Convert parsed operands to MCInst.  Needed here because this instruction
4795 /// only has two register operands, but multiplication is commutative so
4796 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4797 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4798                                     const OperandVector &Operands) {
4799   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4800   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4801   // If we have a three-operand form, make sure to set Rn to be the operand
4802   // that isn't the same as Rd.
4803   unsigned RegOp = 4;
4804   if (Operands.size() == 6 &&
4805       ((ARMOperand &)*Operands[4]).getReg() ==
4806           ((ARMOperand &)*Operands[3]).getReg())
4807     RegOp = 5;
4808   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4809   Inst.addOperand(Inst.getOperand(0));
4810   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4811 }
4812
4813 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4814                                     const OperandVector &Operands) {
4815   int CondOp = -1, ImmOp = -1;
4816   switch(Inst.getOpcode()) {
4817     case ARM::tB:
4818     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4819
4820     case ARM::t2B:
4821     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4822
4823     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4824   }
4825   // first decide whether or not the branch should be conditional
4826   // by looking at it's location relative to an IT block
4827   if(inITBlock()) {
4828     // inside an IT block we cannot have any conditional branches. any 
4829     // such instructions needs to be converted to unconditional form
4830     switch(Inst.getOpcode()) {
4831       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4832       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4833     }
4834   } else {
4835     // outside IT blocks we can only have unconditional branches with AL
4836     // condition code or conditional branches with non-AL condition code
4837     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4838     switch(Inst.getOpcode()) {
4839       case ARM::tB:
4840       case ARM::tBcc: 
4841         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc); 
4842         break;
4843       case ARM::t2B:
4844       case ARM::t2Bcc: 
4845         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4846         break;
4847     }
4848   }
4849
4850   // now decide on encoding size based on branch target range
4851   switch(Inst.getOpcode()) {
4852     // classify tB as either t2B or t1B based on range of immediate operand
4853     case ARM::tB: {
4854       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4855       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4856         Inst.setOpcode(ARM::t2B);
4857       break;
4858     }
4859     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4860     case ARM::tBcc: {
4861       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4862       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4863         Inst.setOpcode(ARM::t2Bcc);
4864       break;
4865     }
4866   }
4867   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4868   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4869 }
4870
4871 /// Parse an ARM memory expression, return false if successful else return true
4872 /// or an error.  The first token must be a '[' when called.
4873 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4874   MCAsmParser &Parser = getParser();
4875   SMLoc S, E;
4876   if (Parser.getTok().isNot(AsmToken::LBrac))
4877     return TokError("Token is not a Left Bracket");
4878   S = Parser.getTok().getLoc();
4879   Parser.Lex(); // Eat left bracket token.
4880
4881   const AsmToken &BaseRegTok = Parser.getTok();
4882   int BaseRegNum = tryParseRegister();
4883   if (BaseRegNum == -1)
4884     return Error(BaseRegTok.getLoc(), "register expected");
4885
4886   // The next token must either be a comma, a colon or a closing bracket.
4887   const AsmToken &Tok = Parser.getTok();
4888   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4889       !Tok.is(AsmToken::RBrac))
4890     return Error(Tok.getLoc(), "malformed memory operand");
4891
4892   if (Tok.is(AsmToken::RBrac)) {
4893     E = Tok.getEndLoc();
4894     Parser.Lex(); // Eat right bracket token.
4895
4896     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4897                                              ARM_AM::no_shift, 0, 0, false,
4898                                              S, E));
4899
4900     // If there's a pre-indexing writeback marker, '!', just add it as a token
4901     // operand. It's rather odd, but syntactically valid.
4902     if (Parser.getTok().is(AsmToken::Exclaim)) {
4903       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4904       Parser.Lex(); // Eat the '!'.
4905     }
4906
4907     return false;
4908   }
4909
4910   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4911          "Lost colon or comma in memory operand?!");
4912   if (Tok.is(AsmToken::Comma)) {
4913     Parser.Lex(); // Eat the comma.
4914   }
4915
4916   // If we have a ':', it's an alignment specifier.
4917   if (Parser.getTok().is(AsmToken::Colon)) {
4918     Parser.Lex(); // Eat the ':'.
4919     E = Parser.getTok().getLoc();
4920     SMLoc AlignmentLoc = Tok.getLoc();
4921
4922     const MCExpr *Expr;
4923     if (getParser().parseExpression(Expr))
4924      return true;
4925
4926     // The expression has to be a constant. Memory references with relocations
4927     // don't come through here, as they use the <label> forms of the relevant
4928     // instructions.
4929     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4930     if (!CE)
4931       return Error (E, "constant expression expected");
4932
4933     unsigned Align = 0;
4934     switch (CE->getValue()) {
4935     default:
4936       return Error(E,
4937                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4938     case 16:  Align = 2; break;
4939     case 32:  Align = 4; break;
4940     case 64:  Align = 8; break;
4941     case 128: Align = 16; break;
4942     case 256: Align = 32; break;
4943     }
4944
4945     // Now we should have the closing ']'
4946     if (Parser.getTok().isNot(AsmToken::RBrac))
4947       return Error(Parser.getTok().getLoc(), "']' expected");
4948     E = Parser.getTok().getEndLoc();
4949     Parser.Lex(); // Eat right bracket token.
4950
4951     // Don't worry about range checking the value here. That's handled by
4952     // the is*() predicates.
4953     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4954                                              ARM_AM::no_shift, 0, Align,
4955                                              false, S, E, AlignmentLoc));
4956
4957     // If there's a pre-indexing writeback marker, '!', just add it as a token
4958     // operand.
4959     if (Parser.getTok().is(AsmToken::Exclaim)) {
4960       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4961       Parser.Lex(); // Eat the '!'.
4962     }
4963
4964     return false;
4965   }
4966
4967   // If we have a '#', it's an immediate offset, else assume it's a register
4968   // offset. Be friendly and also accept a plain integer (without a leading
4969   // hash) for gas compatibility.
4970   if (Parser.getTok().is(AsmToken::Hash) ||
4971       Parser.getTok().is(AsmToken::Dollar) ||
4972       Parser.getTok().is(AsmToken::Integer)) {
4973     if (Parser.getTok().isNot(AsmToken::Integer))
4974       Parser.Lex(); // Eat '#' or '$'.
4975     E = Parser.getTok().getLoc();
4976
4977     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4978     const MCExpr *Offset;
4979     if (getParser().parseExpression(Offset))
4980      return true;
4981
4982     // The expression has to be a constant. Memory references with relocations
4983     // don't come through here, as they use the <label> forms of the relevant
4984     // instructions.
4985     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4986     if (!CE)
4987       return Error (E, "constant expression expected");
4988
4989     // If the constant was #-0, represent it as INT32_MIN.
4990     int32_t Val = CE->getValue();
4991     if (isNegative && Val == 0)
4992       CE = MCConstantExpr::create(INT32_MIN, getContext());
4993
4994     // Now we should have the closing ']'
4995     if (Parser.getTok().isNot(AsmToken::RBrac))
4996       return Error(Parser.getTok().getLoc(), "']' expected");
4997     E = Parser.getTok().getEndLoc();
4998     Parser.Lex(); // Eat right bracket token.
4999
5000     // Don't worry about range checking the value here. That's handled by
5001     // the is*() predicates.
5002     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5003                                              ARM_AM::no_shift, 0, 0,
5004                                              false, S, E));
5005
5006     // If there's a pre-indexing writeback marker, '!', just add it as a token
5007     // operand.
5008     if (Parser.getTok().is(AsmToken::Exclaim)) {
5009       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5010       Parser.Lex(); // Eat the '!'.
5011     }
5012
5013     return false;
5014   }
5015
5016   // The register offset is optionally preceded by a '+' or '-'
5017   bool isNegative = false;
5018   if (Parser.getTok().is(AsmToken::Minus)) {
5019     isNegative = true;
5020     Parser.Lex(); // Eat the '-'.
5021   } else if (Parser.getTok().is(AsmToken::Plus)) {
5022     // Nothing to do.
5023     Parser.Lex(); // Eat the '+'.
5024   }
5025
5026   E = Parser.getTok().getLoc();
5027   int OffsetRegNum = tryParseRegister();
5028   if (OffsetRegNum == -1)
5029     return Error(E, "register expected");
5030
5031   // If there's a shift operator, handle it.
5032   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5033   unsigned ShiftImm = 0;
5034   if (Parser.getTok().is(AsmToken::Comma)) {
5035     Parser.Lex(); // Eat the ','.
5036     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5037       return true;
5038   }
5039
5040   // Now we should have the closing ']'
5041   if (Parser.getTok().isNot(AsmToken::RBrac))
5042     return Error(Parser.getTok().getLoc(), "']' expected");
5043   E = Parser.getTok().getEndLoc();
5044   Parser.Lex(); // Eat right bracket token.
5045
5046   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5047                                            ShiftType, ShiftImm, 0, isNegative,
5048                                            S, E));
5049
5050   // If there's a pre-indexing writeback marker, '!', just add it as a token
5051   // operand.
5052   if (Parser.getTok().is(AsmToken::Exclaim)) {
5053     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5054     Parser.Lex(); // Eat the '!'.
5055   }
5056
5057   return false;
5058 }
5059
5060 /// parseMemRegOffsetShift - one of these two:
5061 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5062 ///   rrx
5063 /// return true if it parses a shift otherwise it returns false.
5064 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5065                                           unsigned &Amount) {
5066   MCAsmParser &Parser = getParser();
5067   SMLoc Loc = Parser.getTok().getLoc();
5068   const AsmToken &Tok = Parser.getTok();
5069   if (Tok.isNot(AsmToken::Identifier))
5070     return true;
5071   StringRef ShiftName = Tok.getString();
5072   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5073       ShiftName == "asl" || ShiftName == "ASL")
5074     St = ARM_AM::lsl;
5075   else if (ShiftName == "lsr" || ShiftName == "LSR")
5076     St = ARM_AM::lsr;
5077   else if (ShiftName == "asr" || ShiftName == "ASR")
5078     St = ARM_AM::asr;
5079   else if (ShiftName == "ror" || ShiftName == "ROR")
5080     St = ARM_AM::ror;
5081   else if (ShiftName == "rrx" || ShiftName == "RRX")
5082     St = ARM_AM::rrx;
5083   else
5084     return Error(Loc, "illegal shift operator");
5085   Parser.Lex(); // Eat shift type token.
5086
5087   // rrx stands alone.
5088   Amount = 0;
5089   if (St != ARM_AM::rrx) {
5090     Loc = Parser.getTok().getLoc();
5091     // A '#' and a shift amount.
5092     const AsmToken &HashTok = Parser.getTok();
5093     if (HashTok.isNot(AsmToken::Hash) &&
5094         HashTok.isNot(AsmToken::Dollar))
5095       return Error(HashTok.getLoc(), "'#' expected");
5096     Parser.Lex(); // Eat hash token.
5097
5098     const MCExpr *Expr;
5099     if (getParser().parseExpression(Expr))
5100       return true;
5101     // Range check the immediate.
5102     // lsl, ror: 0 <= imm <= 31
5103     // lsr, asr: 0 <= imm <= 32
5104     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5105     if (!CE)
5106       return Error(Loc, "shift amount must be an immediate");
5107     int64_t Imm = CE->getValue();
5108     if (Imm < 0 ||
5109         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5110         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5111       return Error(Loc, "immediate shift value out of range");
5112     // If <ShiftTy> #0, turn it into a no_shift.
5113     if (Imm == 0)
5114       St = ARM_AM::lsl;
5115     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5116     if (Imm == 32)
5117       Imm = 0;
5118     Amount = Imm;
5119   }
5120
5121   return false;
5122 }
5123
5124 /// parseFPImm - A floating point immediate expression operand.
5125 OperandMatchResultTy
5126 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5127   MCAsmParser &Parser = getParser();
5128   // Anything that can accept a floating point constant as an operand
5129   // needs to go through here, as the regular parseExpression is
5130   // integer only.
5131   //
5132   // This routine still creates a generic Immediate operand, containing
5133   // a bitcast of the 64-bit floating point value. The various operands
5134   // that accept floats can check whether the value is valid for them
5135   // via the standard is*() predicates.
5136
5137   SMLoc S = Parser.getTok().getLoc();
5138
5139   if (Parser.getTok().isNot(AsmToken::Hash) &&
5140       Parser.getTok().isNot(AsmToken::Dollar))
5141     return MatchOperand_NoMatch;
5142
5143   // Disambiguate the VMOV forms that can accept an FP immediate.
5144   // vmov.f32 <sreg>, #imm
5145   // vmov.f64 <dreg>, #imm
5146   // vmov.f32 <dreg>, #imm  @ vector f32x2
5147   // vmov.f32 <qreg>, #imm  @ vector f32x4
5148   //
5149   // There are also the NEON VMOV instructions which expect an
5150   // integer constant. Make sure we don't try to parse an FPImm
5151   // for these:
5152   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5153   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5154   bool isVmovf = TyOp.isToken() &&
5155                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5156                   TyOp.getToken() == ".f16");
5157   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5158   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5159                                          Mnemonic.getToken() == "fconsts");
5160   if (!(isVmovf || isFconst))
5161     return MatchOperand_NoMatch;
5162
5163   Parser.Lex(); // Eat '#' or '$'.
5164
5165   // Handle negation, as that still comes through as a separate token.
5166   bool isNegative = false;
5167   if (Parser.getTok().is(AsmToken::Minus)) {
5168     isNegative = true;
5169     Parser.Lex();
5170   }
5171   const AsmToken &Tok = Parser.getTok();
5172   SMLoc Loc = Tok.getLoc();
5173   if (Tok.is(AsmToken::Real) && isVmovf) {
5174     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5175     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5176     // If we had a '-' in front, toggle the sign bit.
5177     IntVal ^= (uint64_t)isNegative << 31;
5178     Parser.Lex(); // Eat the token.
5179     Operands.push_back(ARMOperand::CreateImm(
5180           MCConstantExpr::create(IntVal, getContext()),
5181           S, Parser.getTok().getLoc()));
5182     return MatchOperand_Success;
5183   }
5184   // Also handle plain integers. Instructions which allow floating point
5185   // immediates also allow a raw encoded 8-bit value.
5186   if (Tok.is(AsmToken::Integer) && isFconst) {
5187     int64_t Val = Tok.getIntVal();
5188     Parser.Lex(); // Eat the token.
5189     if (Val > 255 || Val < 0) {
5190       Error(Loc, "encoded floating point value out of range");
5191       return MatchOperand_ParseFail;
5192     }
5193     float RealVal = ARM_AM::getFPImmFloat(Val);
5194     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5195
5196     Operands.push_back(ARMOperand::CreateImm(
5197         MCConstantExpr::create(Val, getContext()), S,
5198         Parser.getTok().getLoc()));
5199     return MatchOperand_Success;
5200   }
5201
5202   Error(Loc, "invalid floating point immediate");
5203   return MatchOperand_ParseFail;
5204 }
5205
5206 /// Parse a arm instruction operand.  For now this parses the operand regardless
5207 /// of the mnemonic.
5208 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5209   MCAsmParser &Parser = getParser();
5210   SMLoc S, E;
5211
5212   // Check if the current operand has a custom associated parser, if so, try to
5213   // custom parse the operand, or fallback to the general approach.
5214   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5215   if (ResTy == MatchOperand_Success)
5216     return false;
5217   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5218   // there was a match, but an error occurred, in which case, just return that
5219   // the operand parsing failed.
5220   if (ResTy == MatchOperand_ParseFail)
5221     return true;
5222
5223   switch (getLexer().getKind()) {
5224   default:
5225     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5226     return true;
5227   case AsmToken::Identifier: {
5228     // If we've seen a branch mnemonic, the next operand must be a label.  This
5229     // is true even if the label is a register name.  So "br r1" means branch to
5230     // label "r1".
5231     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5232     if (!ExpectLabel) {
5233       if (!tryParseRegisterWithWriteBack(Operands))
5234         return false;
5235       int Res = tryParseShiftRegister(Operands);
5236       if (Res == 0) // success
5237         return false;
5238       else if (Res == -1) // irrecoverable error
5239         return true;
5240       // If this is VMRS, check for the apsr_nzcv operand.
5241       if (Mnemonic == "vmrs" &&
5242           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5243         S = Parser.getTok().getLoc();
5244         Parser.Lex();
5245         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5246         return false;
5247       }
5248     }
5249
5250     // Fall though for the Identifier case that is not a register or a
5251     // special name.
5252   }
5253   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5254   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5255   case AsmToken::String:  // quoted label names.
5256   case AsmToken::Dot: {   // . as a branch target
5257     // This was not a register so parse other operands that start with an
5258     // identifier (like labels) as expressions and create them as immediates.
5259     const MCExpr *IdVal;
5260     S = Parser.getTok().getLoc();
5261     if (getParser().parseExpression(IdVal))
5262       return true;
5263     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5264     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5265     return false;
5266   }
5267   case AsmToken::LBrac:
5268     return parseMemory(Operands);
5269   case AsmToken::LCurly:
5270     return parseRegisterList(Operands);
5271   case AsmToken::Dollar:
5272   case AsmToken::Hash: {
5273     // #42 -> immediate.
5274     S = Parser.getTok().getLoc();
5275     Parser.Lex();
5276
5277     if (Parser.getTok().isNot(AsmToken::Colon)) {
5278       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5279       const MCExpr *ImmVal;
5280       if (getParser().parseExpression(ImmVal))
5281         return true;
5282       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5283       if (CE) {
5284         int32_t Val = CE->getValue();
5285         if (isNegative && Val == 0)
5286           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5287       }
5288       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5289       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5290
5291       // There can be a trailing '!' on operands that we want as a separate
5292       // '!' Token operand. Handle that here. For example, the compatibility
5293       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5294       if (Parser.getTok().is(AsmToken::Exclaim)) {
5295         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5296                                                    Parser.getTok().getLoc()));
5297         Parser.Lex(); // Eat exclaim token
5298       }
5299       return false;
5300     }
5301     // w/ a ':' after the '#', it's just like a plain ':'.
5302     LLVM_FALLTHROUGH;
5303   }
5304   case AsmToken::Colon: {
5305     S = Parser.getTok().getLoc();
5306     // ":lower16:" and ":upper16:" expression prefixes
5307     // FIXME: Check it's an expression prefix,
5308     // e.g. (FOO - :lower16:BAR) isn't legal.
5309     ARMMCExpr::VariantKind RefKind;
5310     if (parsePrefix(RefKind))
5311       return true;
5312
5313     const MCExpr *SubExprVal;
5314     if (getParser().parseExpression(SubExprVal))
5315       return true;
5316
5317     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5318                                               getContext());
5319     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5320     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5321     return false;
5322   }
5323   case AsmToken::Equal: {
5324     S = Parser.getTok().getLoc();
5325     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5326       return Error(S, "unexpected token in operand");
5327     Parser.Lex(); // Eat '='
5328     const MCExpr *SubExprVal;
5329     if (getParser().parseExpression(SubExprVal))
5330       return true;
5331     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5332
5333     // execute-only: we assume that assembly programmers know what they are
5334     // doing and allow literal pool creation here
5335     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5336     return false;
5337   }
5338   }
5339 }
5340
5341 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5342 //  :lower16: and :upper16:.
5343 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5344   MCAsmParser &Parser = getParser();
5345   RefKind = ARMMCExpr::VK_ARM_None;
5346
5347   // consume an optional '#' (GNU compatibility)
5348   if (getLexer().is(AsmToken::Hash))
5349     Parser.Lex();
5350
5351   // :lower16: and :upper16: modifiers
5352   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5353   Parser.Lex(); // Eat ':'
5354
5355   if (getLexer().isNot(AsmToken::Identifier)) {
5356     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5357     return true;
5358   }
5359
5360   enum {
5361     COFF = (1 << MCObjectFileInfo::IsCOFF),
5362     ELF = (1 << MCObjectFileInfo::IsELF),
5363     MACHO = (1 << MCObjectFileInfo::IsMachO),
5364     WASM = (1 << MCObjectFileInfo::IsWasm),
5365   };
5366   static const struct PrefixEntry {
5367     const char *Spelling;
5368     ARMMCExpr::VariantKind VariantKind;
5369     uint8_t SupportedFormats;
5370   } PrefixEntries[] = {
5371     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5372     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5373   };
5374
5375   StringRef IDVal = Parser.getTok().getIdentifier();
5376
5377   const auto &Prefix =
5378       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5379                    [&IDVal](const PrefixEntry &PE) {
5380                       return PE.Spelling == IDVal;
5381                    });
5382   if (Prefix == std::end(PrefixEntries)) {
5383     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5384     return true;
5385   }
5386
5387   uint8_t CurrentFormat;
5388   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5389   case MCObjectFileInfo::IsMachO:
5390     CurrentFormat = MACHO;
5391     break;
5392   case MCObjectFileInfo::IsELF:
5393     CurrentFormat = ELF;
5394     break;
5395   case MCObjectFileInfo::IsCOFF:
5396     CurrentFormat = COFF;
5397     break;
5398   case MCObjectFileInfo::IsWasm:
5399     CurrentFormat = WASM;
5400     break;
5401   }
5402
5403   if (~Prefix->SupportedFormats & CurrentFormat) {
5404     Error(Parser.getTok().getLoc(),
5405           "cannot represent relocation in the current file format");
5406     return true;
5407   }
5408
5409   RefKind = Prefix->VariantKind;
5410   Parser.Lex();
5411
5412   if (getLexer().isNot(AsmToken::Colon)) {
5413     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5414     return true;
5415   }
5416   Parser.Lex(); // Eat the last ':'
5417
5418   return false;
5419 }
5420
5421 /// \brief Given a mnemonic, split out possible predication code and carry
5422 /// setting letters to form a canonical mnemonic and flags.
5423 //
5424 // FIXME: Would be nice to autogen this.
5425 // FIXME: This is a bit of a maze of special cases.
5426 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5427                                       unsigned &PredicationCode,
5428                                       bool &CarrySetting,
5429                                       unsigned &ProcessorIMod,
5430                                       StringRef &ITMask) {
5431   PredicationCode = ARMCC::AL;
5432   CarrySetting = false;
5433   ProcessorIMod = 0;
5434
5435   // Ignore some mnemonics we know aren't predicated forms.
5436   //
5437   // FIXME: Would be nice to autogen this.
5438   if ((Mnemonic == "movs" && isThumb()) ||
5439       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5440       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5441       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5442       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5443       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5444       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5445       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5446       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5447       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5448       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5449       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5450       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5451       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5452       Mnemonic == "bxns"  || Mnemonic == "blxns")
5453     return Mnemonic;
5454
5455   // First, split out any predication code. Ignore mnemonics we know aren't
5456   // predicated but do have a carry-set and so weren't caught above.
5457   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5458       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5459       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5460       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5461     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5462       .Case("eq", ARMCC::EQ)
5463       .Case("ne", ARMCC::NE)
5464       .Case("hs", ARMCC::HS)
5465       .Case("cs", ARMCC::HS)
5466       .Case("lo", ARMCC::LO)
5467       .Case("cc", ARMCC::LO)
5468       .Case("mi", ARMCC::MI)
5469       .Case("pl", ARMCC::PL)
5470       .Case("vs", ARMCC::VS)
5471       .Case("vc", ARMCC::VC)
5472       .Case("hi", ARMCC::HI)
5473       .Case("ls", ARMCC::LS)
5474       .Case("ge", ARMCC::GE)
5475       .Case("lt", ARMCC::LT)
5476       .Case("gt", ARMCC::GT)
5477       .Case("le", ARMCC::LE)
5478       .Case("al", ARMCC::AL)
5479       .Default(~0U);
5480     if (CC != ~0U) {
5481       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5482       PredicationCode = CC;
5483     }
5484   }
5485
5486   // Next, determine if we have a carry setting bit. We explicitly ignore all
5487   // the instructions we know end in 's'.
5488   if (Mnemonic.endswith("s") &&
5489       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5490         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5491         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5492         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5493         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5494         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5495         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5496         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5497         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5498         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5499         (Mnemonic == "movs" && isThumb()))) {
5500     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5501     CarrySetting = true;
5502   }
5503
5504   // The "cps" instruction can have a interrupt mode operand which is glued into
5505   // the mnemonic. Check if this is the case, split it and parse the imod op
5506   if (Mnemonic.startswith("cps")) {
5507     // Split out any imod code.
5508     unsigned IMod =
5509       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5510       .Case("ie", ARM_PROC::IE)
5511       .Case("id", ARM_PROC::ID)
5512       .Default(~0U);
5513     if (IMod != ~0U) {
5514       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5515       ProcessorIMod = IMod;
5516     }
5517   }
5518
5519   // The "it" instruction has the condition mask on the end of the mnemonic.
5520   if (Mnemonic.startswith("it")) {
5521     ITMask = Mnemonic.slice(2, Mnemonic.size());
5522     Mnemonic = Mnemonic.slice(0, 2);
5523   }
5524
5525   return Mnemonic;
5526 }
5527
5528 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5529 /// inclusion of carry set or predication code operands.
5530 //
5531 // FIXME: It would be nice to autogen this.
5532 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5533                                          bool &CanAcceptCarrySet,
5534                                          bool &CanAcceptPredicationCode) {
5535   CanAcceptCarrySet =
5536       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5537       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5538       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5539       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5540       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5541       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5542       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5543       (!isThumb() &&
5544        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5545         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5546
5547   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5548       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5549       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5550       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5551       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5552       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5553       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5554       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5555       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5556       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5557       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5558       Mnemonic == "vmovx" || Mnemonic == "vins") {
5559     // These mnemonics are never predicable
5560     CanAcceptPredicationCode = false;
5561   } else if (!isThumb()) {
5562     // Some instructions are only predicable in Thumb mode
5563     CanAcceptPredicationCode =
5564         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5565         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5566         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5567         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5568         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5569         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5570         !Mnemonic.startswith("srs");
5571   } else if (isThumbOne()) {
5572     if (hasV6MOps())
5573       CanAcceptPredicationCode = Mnemonic != "movs";
5574     else
5575       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5576   } else
5577     CanAcceptPredicationCode = true;
5578 }
5579
5580 // \brief Some Thumb instructions have two operand forms that are not
5581 // available as three operand, convert to two operand form if possible.
5582 //
5583 // FIXME: We would really like to be able to tablegen'erate this.
5584 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5585                                                  bool CarrySetting,
5586                                                  OperandVector &Operands) {
5587   if (Operands.size() != 6)
5588     return;
5589
5590   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5591         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5592   if (!Op3.isReg() || !Op4.isReg())
5593     return;
5594
5595   auto Op3Reg = Op3.getReg();
5596   auto Op4Reg = Op4.getReg();
5597
5598   // For most Thumb2 cases we just generate the 3 operand form and reduce
5599   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5600   // won't accept SP or PC so we do the transformation here taking care
5601   // with immediate range in the 'add sp, sp #imm' case.
5602   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5603   if (isThumbTwo()) {
5604     if (Mnemonic != "add")
5605       return;
5606     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5607                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5608     if (!TryTransform) {
5609       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5610                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5611                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5612                        Op5.isImm() && !Op5.isImm0_508s4());
5613     }
5614     if (!TryTransform)
5615       return;
5616   } else if (!isThumbOne())
5617     return;
5618
5619   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5620         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5621         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5622         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5623     return;
5624
5625   // If first 2 operands of a 3 operand instruction are the same
5626   // then transform to 2 operand version of the same instruction
5627   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5628   bool Transform = Op3Reg == Op4Reg;
5629
5630   // For communtative operations, we might be able to transform if we swap
5631   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5632   // as tADDrsp.
5633   const ARMOperand *LastOp = &Op5;
5634   bool Swap = false;
5635   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5636       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5637        Mnemonic == "and" || Mnemonic == "eor" ||
5638        Mnemonic == "adc" || Mnemonic == "orr")) {
5639     Swap = true;
5640     LastOp = &Op4;
5641     Transform = true;
5642   }
5643
5644   // If both registers are the same then remove one of them from
5645   // the operand list, with certain exceptions.
5646   if (Transform) {
5647     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5648     // 2 operand forms don't exist.
5649     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5650         LastOp->isReg())
5651       Transform = false;
5652
5653     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5654     // 3-bits because the ARMARM says not to.
5655     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5656       Transform = false;
5657   }
5658
5659   if (Transform) {
5660     if (Swap)
5661       std::swap(Op4, Op5);
5662     Operands.erase(Operands.begin() + 3);
5663   }
5664 }
5665
5666 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5667                                           OperandVector &Operands) {
5668   // FIXME: This is all horribly hacky. We really need a better way to deal
5669   // with optional operands like this in the matcher table.
5670
5671   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5672   // another does not. Specifically, the MOVW instruction does not. So we
5673   // special case it here and remove the defaulted (non-setting) cc_out
5674   // operand if that's the instruction we're trying to match.
5675   //
5676   // We do this as post-processing of the explicit operands rather than just
5677   // conditionally adding the cc_out in the first place because we need
5678   // to check the type of the parsed immediate operand.
5679   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5680       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5681       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5682       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5683     return true;
5684
5685   // Register-register 'add' for thumb does not have a cc_out operand
5686   // when there are only two register operands.
5687   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5688       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5689       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5690       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5691     return true;
5692   // Register-register 'add' for thumb does not have a cc_out operand
5693   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5694   // have to check the immediate range here since Thumb2 has a variant
5695   // that can handle a different range and has a cc_out operand.
5696   if (((isThumb() && Mnemonic == "add") ||
5697        (isThumbTwo() && Mnemonic == "sub")) &&
5698       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5699       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5700       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5701       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5702       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5703        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5704     return true;
5705   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5706   // imm0_4095 variant. That's the least-preferred variant when
5707   // selecting via the generic "add" mnemonic, so to know that we
5708   // should remove the cc_out operand, we have to explicitly check that
5709   // it's not one of the other variants. Ugh.
5710   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5711       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5712       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5713       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5714     // Nest conditions rather than one big 'if' statement for readability.
5715     //
5716     // If both registers are low, we're in an IT block, and the immediate is
5717     // in range, we should use encoding T1 instead, which has a cc_out.
5718     if (inITBlock() &&
5719         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5720         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5721         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5722       return false;
5723     // Check against T3. If the second register is the PC, this is an
5724     // alternate form of ADR, which uses encoding T4, so check for that too.
5725     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5726         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5727       return false;
5728
5729     // Otherwise, we use encoding T4, which does not have a cc_out
5730     // operand.
5731     return true;
5732   }
5733
5734   // The thumb2 multiply instruction doesn't have a CCOut register, so
5735   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5736   // use the 16-bit encoding or not.
5737   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5738       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5739       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5740       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5741       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5742       // If the registers aren't low regs, the destination reg isn't the
5743       // same as one of the source regs, or the cc_out operand is zero
5744       // outside of an IT block, we have to use the 32-bit encoding, so
5745       // remove the cc_out operand.
5746       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5747        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5748        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5749        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5750                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5751                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5752                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5753     return true;
5754
5755   // Also check the 'mul' syntax variant that doesn't specify an explicit
5756   // destination register.
5757   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5758       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5759       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5760       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5761       // If the registers aren't low regs  or the cc_out operand is zero
5762       // outside of an IT block, we have to use the 32-bit encoding, so
5763       // remove the cc_out operand.
5764       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5765        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5766        !inITBlock()))
5767     return true;
5768
5769
5770
5771   // Register-register 'add/sub' for thumb does not have a cc_out operand
5772   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5773   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5774   // right, this will result in better diagnostics (which operand is off)
5775   // anyway.
5776   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5777       (Operands.size() == 5 || Operands.size() == 6) &&
5778       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5779       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5780       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5781       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5782        (Operands.size() == 6 &&
5783         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5784     return true;
5785
5786   return false;
5787 }
5788
5789 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5790                                               OperandVector &Operands) {
5791   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5792   unsigned RegIdx = 3;
5793   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5794       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5795        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5796     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5797         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5798          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5799       RegIdx = 4;
5800
5801     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5802         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5803              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5804          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5805              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5806       return true;
5807   }
5808   return false;
5809 }
5810
5811 static bool isDataTypeToken(StringRef Tok) {
5812   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5813     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5814     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5815     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5816     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5817     Tok == ".f" || Tok == ".d";
5818 }
5819
5820 // FIXME: This bit should probably be handled via an explicit match class
5821 // in the .td files that matches the suffix instead of having it be
5822 // a literal string token the way it is now.
5823 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5824   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5825 }
5826 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5827                                  unsigned VariantID);
5828
5829 static bool RequiresVFPRegListValidation(StringRef Inst,
5830                                          bool &AcceptSinglePrecisionOnly,
5831                                          bool &AcceptDoublePrecisionOnly) {
5832   if (Inst.size() < 7)
5833     return false;
5834
5835   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5836     StringRef AddressingMode = Inst.substr(4, 2);
5837     if (AddressingMode == "ia" || AddressingMode == "db" ||
5838         AddressingMode == "ea" || AddressingMode == "fd") {
5839       AcceptSinglePrecisionOnly = Inst[6] == 's';
5840       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5841       return true;
5842     }
5843   }
5844
5845   return false;
5846 }
5847
5848 /// Parse an arm instruction mnemonic followed by its operands.
5849 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5850                                     SMLoc NameLoc, OperandVector &Operands) {
5851   MCAsmParser &Parser = getParser();
5852   // FIXME: Can this be done via tablegen in some fashion?
5853   bool RequireVFPRegisterListCheck;
5854   bool AcceptSinglePrecisionOnly;
5855   bool AcceptDoublePrecisionOnly;
5856   RequireVFPRegisterListCheck =
5857     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5858                                  AcceptDoublePrecisionOnly);
5859
5860   // Apply mnemonic aliases before doing anything else, as the destination
5861   // mnemonic may include suffices and we want to handle them normally.
5862   // The generic tblgen'erated code does this later, at the start of
5863   // MatchInstructionImpl(), but that's too late for aliases that include
5864   // any sort of suffix.
5865   uint64_t AvailableFeatures = getAvailableFeatures();
5866   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5867   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5868
5869   // First check for the ARM-specific .req directive.
5870   if (Parser.getTok().is(AsmToken::Identifier) &&
5871       Parser.getTok().getIdentifier() == ".req") {
5872     parseDirectiveReq(Name, NameLoc);
5873     // We always return 'error' for this, as we're done with this
5874     // statement and don't need to match the 'instruction."
5875     return true;
5876   }
5877
5878   // Create the leading tokens for the mnemonic, split by '.' characters.
5879   size_t Start = 0, Next = Name.find('.');
5880   StringRef Mnemonic = Name.slice(Start, Next);
5881
5882   // Split out the predication code and carry setting flag from the mnemonic.
5883   unsigned PredicationCode;
5884   unsigned ProcessorIMod;
5885   bool CarrySetting;
5886   StringRef ITMask;
5887   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5888                            ProcessorIMod, ITMask);
5889
5890   // In Thumb1, only the branch (B) instruction can be predicated.
5891   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5892     return Error(NameLoc, "conditional execution not supported in Thumb1");
5893   }
5894
5895   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5896
5897   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5898   // is the mask as it will be for the IT encoding if the conditional
5899   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5900   // where the conditional bit0 is zero, the instruction post-processing
5901   // will adjust the mask accordingly.
5902   if (Mnemonic == "it") {
5903     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5904     if (ITMask.size() > 3) {
5905       return Error(Loc, "too many conditions on IT instruction");
5906     }
5907     unsigned Mask = 8;
5908     for (unsigned i = ITMask.size(); i != 0; --i) {
5909       char pos = ITMask[i - 1];
5910       if (pos != 't' && pos != 'e') {
5911         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5912       }
5913       Mask >>= 1;
5914       if (ITMask[i - 1] == 't')
5915         Mask |= 8;
5916     }
5917     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5918   }
5919
5920   // FIXME: This is all a pretty gross hack. We should automatically handle
5921   // optional operands like this via tblgen.
5922
5923   // Next, add the CCOut and ConditionCode operands, if needed.
5924   //
5925   // For mnemonics which can ever incorporate a carry setting bit or predication
5926   // code, our matching model involves us always generating CCOut and
5927   // ConditionCode operands to match the mnemonic "as written" and then we let
5928   // the matcher deal with finding the right instruction or generating an
5929   // appropriate error.
5930   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5931   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5932
5933   // If we had a carry-set on an instruction that can't do that, issue an
5934   // error.
5935   if (!CanAcceptCarrySet && CarrySetting) {
5936     return Error(NameLoc, "instruction '" + Mnemonic +
5937                  "' can not set flags, but 's' suffix specified");
5938   }
5939   // If we had a predication code on an instruction that can't do that, issue an
5940   // error.
5941   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5942     return Error(NameLoc, "instruction '" + Mnemonic +
5943                  "' is not predicable, but condition code specified");
5944   }
5945
5946   // Add the carry setting operand, if necessary.
5947   if (CanAcceptCarrySet) {
5948     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5949     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5950                                                Loc));
5951   }
5952
5953   // Add the predication code operand, if necessary.
5954   if (CanAcceptPredicationCode) {
5955     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5956                                       CarrySetting);
5957     Operands.push_back(ARMOperand::CreateCondCode(
5958                          ARMCC::CondCodes(PredicationCode), Loc));
5959   }
5960
5961   // Add the processor imod operand, if necessary.
5962   if (ProcessorIMod) {
5963     Operands.push_back(ARMOperand::CreateImm(
5964           MCConstantExpr::create(ProcessorIMod, getContext()),
5965                                  NameLoc, NameLoc));
5966   } else if (Mnemonic == "cps" && isMClass()) {
5967     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5968   }
5969
5970   // Add the remaining tokens in the mnemonic.
5971   while (Next != StringRef::npos) {
5972     Start = Next;
5973     Next = Name.find('.', Start + 1);
5974     StringRef ExtraToken = Name.slice(Start, Next);
5975
5976     // Some NEON instructions have an optional datatype suffix that is
5977     // completely ignored. Check for that.
5978     if (isDataTypeToken(ExtraToken) &&
5979         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5980       continue;
5981
5982     // For for ARM mode generate an error if the .n qualifier is used.
5983     if (ExtraToken == ".n" && !isThumb()) {
5984       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5985       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5986                    "arm mode");
5987     }
5988
5989     // The .n qualifier is always discarded as that is what the tables
5990     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5991     // so discard it to avoid errors that can be caused by the matcher.
5992     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5993       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5994       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5995     }
5996   }
5997
5998   // Read the remaining operands.
5999   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6000     // Read the first operand.
6001     if (parseOperand(Operands, Mnemonic)) {
6002       return true;
6003     }
6004
6005     while (parseOptionalToken(AsmToken::Comma)) {
6006       // Parse and remember the operand.
6007       if (parseOperand(Operands, Mnemonic)) {
6008         return true;
6009       }
6010     }
6011   }
6012
6013   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6014     return true;
6015
6016   if (RequireVFPRegisterListCheck) {
6017     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
6018     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
6019       return Error(Op.getStartLoc(),
6020                    "VFP/Neon single precision register expected");
6021     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
6022       return Error(Op.getStartLoc(),
6023                    "VFP/Neon double precision register expected");
6024   }
6025
6026   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6027
6028   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6029   // do and don't have a cc_out optional-def operand. With some spot-checks
6030   // of the operand list, we can figure out which variant we're trying to
6031   // parse and adjust accordingly before actually matching. We shouldn't ever
6032   // try to remove a cc_out operand that was explicitly set on the
6033   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6034   // table driven matcher doesn't fit well with the ARM instruction set.
6035   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6036     Operands.erase(Operands.begin() + 1);
6037
6038   // Some instructions have the same mnemonic, but don't always
6039   // have a predicate. Distinguish them here and delete the
6040   // predicate if needed.
6041   if (shouldOmitPredicateOperand(Mnemonic, Operands))
6042     Operands.erase(Operands.begin() + 1);
6043
6044   // ARM mode 'blx' need special handling, as the register operand version
6045   // is predicable, but the label operand version is not. So, we can't rely
6046   // on the Mnemonic based checking to correctly figure out when to put
6047   // a k_CondCode operand in the list. If we're trying to match the label
6048   // version, remove the k_CondCode operand here.
6049   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6050       static_cast<ARMOperand &>(*Operands[2]).isImm())
6051     Operands.erase(Operands.begin() + 1);
6052
6053   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6054   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6055   // a single GPRPair reg operand is used in the .td file to replace the two
6056   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6057   // expressed as a GPRPair, so we have to manually merge them.
6058   // FIXME: We would really like to be able to tablegen'erate this.
6059   if (!isThumb() && Operands.size() > 4 &&
6060       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6061        Mnemonic == "stlexd")) {
6062     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6063     unsigned Idx = isLoad ? 2 : 3;
6064     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6065     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6066
6067     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6068     // Adjust only if Op1 and Op2 are GPRs.
6069     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6070         MRC.contains(Op2.getReg())) {
6071       unsigned Reg1 = Op1.getReg();
6072       unsigned Reg2 = Op2.getReg();
6073       unsigned Rt = MRI->getEncodingValue(Reg1);
6074       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6075
6076       // Rt2 must be Rt + 1 and Rt must be even.
6077       if (Rt + 1 != Rt2 || (Rt & 1)) {
6078         return Error(Op2.getStartLoc(),
6079                      isLoad ? "destination operands must be sequential"
6080                             : "source operands must be sequential");
6081       }
6082       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6083           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6084       Operands[Idx] =
6085           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6086       Operands.erase(Operands.begin() + Idx + 1);
6087     }
6088   }
6089
6090   // GNU Assembler extension (compatibility)
6091   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
6092     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6093     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6094     if (Op3.isMem()) {
6095       assert(Op2.isReg() && "expected register argument");
6096
6097       unsigned SuperReg = MRI->getMatchingSuperReg(
6098           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
6099
6100       assert(SuperReg && "expected register pair");
6101
6102       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
6103
6104       Operands.insert(
6105           Operands.begin() + 3,
6106           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6107     }
6108   }
6109
6110   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6111   // does not fit with other "subs" and tblgen.
6112   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6113   // so the Mnemonic is the original name "subs" and delete the predicate
6114   // operand so it will match the table entry.
6115   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6116       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6117       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6118       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6119       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6120       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6121     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6122     Operands.erase(Operands.begin() + 1);
6123   }
6124   return false;
6125 }
6126
6127 // Validate context-sensitive operand constraints.
6128
6129 // return 'true' if register list contains non-low GPR registers,
6130 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6131 // 'containsReg' to true.
6132 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6133                                  unsigned Reg, unsigned HiReg,
6134                                  bool &containsReg) {
6135   containsReg = false;
6136   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6137     unsigned OpReg = Inst.getOperand(i).getReg();
6138     if (OpReg == Reg)
6139       containsReg = true;
6140     // Anything other than a low register isn't legal here.
6141     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6142       return true;
6143   }
6144   return false;
6145 }
6146
6147 // Check if the specified regisgter is in the register list of the inst,
6148 // starting at the indicated operand number.
6149 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6150   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6151     unsigned OpReg = Inst.getOperand(i).getReg();
6152     if (OpReg == Reg)
6153       return true;
6154   }
6155   return false;
6156 }
6157
6158 // Return true if instruction has the interesting property of being
6159 // allowed in IT blocks, but not being predicable.
6160 static bool instIsBreakpoint(const MCInst &Inst) {
6161     return Inst.getOpcode() == ARM::tBKPT ||
6162            Inst.getOpcode() == ARM::BKPT ||
6163            Inst.getOpcode() == ARM::tHLT ||
6164            Inst.getOpcode() == ARM::HLT;
6165
6166 }
6167
6168 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6169                                        const OperandVector &Operands,
6170                                        unsigned ListNo, bool IsARPop) {
6171   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6172   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6173
6174   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6175   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6176   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6177
6178   if (!IsARPop && ListContainsSP)
6179     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6180                  "SP may not be in the register list");
6181   else if (ListContainsPC && ListContainsLR)
6182     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6183                  "PC and LR may not be in the register list simultaneously");
6184   return false;
6185 }
6186
6187 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6188                                        const OperandVector &Operands,
6189                                        unsigned ListNo) {
6190   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6191   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6192
6193   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6194   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6195
6196   if (ListContainsSP && ListContainsPC)
6197     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6198                  "SP and PC may not be in the register list");
6199   else if (ListContainsSP)
6200     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6201                  "SP may not be in the register list");
6202   else if (ListContainsPC)
6203     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6204                  "PC may not be in the register list");
6205   return false;
6206 }
6207
6208 // FIXME: We would really like to be able to tablegen'erate this.
6209 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6210                                        const OperandVector &Operands) {
6211   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6212   SMLoc Loc = Operands[0]->getStartLoc();
6213
6214   // Check the IT block state first.
6215   // NOTE: BKPT and HLT instructions have the interesting property of being
6216   // allowed in IT blocks, but not being predicable. They just always execute.
6217   if (inITBlock() && !instIsBreakpoint(Inst)) {
6218     // The instruction must be predicable.
6219     if (!MCID.isPredicable())
6220       return Error(Loc, "instructions in IT block must be predicable");
6221     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6222     if (Cond != currentITCond()) {
6223       // Find the condition code Operand to get its SMLoc information.
6224       SMLoc CondLoc;
6225       for (unsigned I = 1; I < Operands.size(); ++I)
6226         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6227           CondLoc = Operands[I]->getStartLoc();
6228       return Error(CondLoc, "incorrect condition in IT block; got '" +
6229                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6230                    "', but expected '" +
6231                    ARMCondCodeToString(ARMCC::CondCodes(currentITCond())) + "'");
6232     }
6233   // Check for non-'al' condition codes outside of the IT block.
6234   } else if (isThumbTwo() && MCID.isPredicable() &&
6235              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6236              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6237              Inst.getOpcode() != ARM::t2Bcc) {
6238     return Error(Loc, "predicated instructions must be in IT block");
6239   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6240              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6241                  ARMCC::AL) {
6242     return Warning(Loc, "predicated instructions should be in IT block");
6243   }
6244
6245   // PC-setting instructions in an IT block, but not the last instruction of
6246   // the block, are UNPREDICTABLE.
6247   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6248     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6249   }
6250
6251   const unsigned Opcode = Inst.getOpcode();
6252   switch (Opcode) {
6253   case ARM::LDRD:
6254   case ARM::LDRD_PRE:
6255   case ARM::LDRD_POST: {
6256     const unsigned RtReg = Inst.getOperand(0).getReg();
6257
6258     // Rt can't be R14.
6259     if (RtReg == ARM::LR)
6260       return Error(Operands[3]->getStartLoc(),
6261                    "Rt can't be R14");
6262
6263     const unsigned Rt = MRI->getEncodingValue(RtReg);
6264     // Rt must be even-numbered.
6265     if ((Rt & 1) == 1)
6266       return Error(Operands[3]->getStartLoc(),
6267                    "Rt must be even-numbered");
6268
6269     // Rt2 must be Rt + 1.
6270     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6271     if (Rt2 != Rt + 1)
6272       return Error(Operands[3]->getStartLoc(),
6273                    "destination operands must be sequential");
6274
6275     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6276       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6277       // For addressing modes with writeback, the base register needs to be
6278       // different from the destination registers.
6279       if (Rn == Rt || Rn == Rt2)
6280         return Error(Operands[3]->getStartLoc(),
6281                      "base register needs to be different from destination "
6282                      "registers");
6283     }
6284
6285     return false;
6286   }
6287   case ARM::t2LDRDi8:
6288   case ARM::t2LDRD_PRE:
6289   case ARM::t2LDRD_POST: {
6290     // Rt2 must be different from Rt.
6291     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6292     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6293     if (Rt2 == Rt)
6294       return Error(Operands[3]->getStartLoc(),
6295                    "destination operands can't be identical");
6296     return false;
6297   }
6298   case ARM::t2BXJ: {
6299     const unsigned RmReg = Inst.getOperand(0).getReg();
6300     // Rm = SP is no longer unpredictable in v8-A
6301     if (RmReg == ARM::SP && !hasV8Ops())
6302       return Error(Operands[2]->getStartLoc(),
6303                    "r13 (SP) is an unpredictable operand to BXJ");
6304     return false;
6305   }
6306   case ARM::STRD: {
6307     // Rt2 must be Rt + 1.
6308     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6309     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6310     if (Rt2 != Rt + 1)
6311       return Error(Operands[3]->getStartLoc(),
6312                    "source operands must be sequential");
6313     return false;
6314   }
6315   case ARM::STRD_PRE:
6316   case ARM::STRD_POST: {
6317     // Rt2 must be Rt + 1.
6318     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6319     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6320     if (Rt2 != Rt + 1)
6321       return Error(Operands[3]->getStartLoc(),
6322                    "source operands must be sequential");
6323     return false;
6324   }
6325   case ARM::STR_PRE_IMM:
6326   case ARM::STR_PRE_REG:
6327   case ARM::STR_POST_IMM:
6328   case ARM::STR_POST_REG:
6329   case ARM::STRH_PRE:
6330   case ARM::STRH_POST:
6331   case ARM::STRB_PRE_IMM:
6332   case ARM::STRB_PRE_REG:
6333   case ARM::STRB_POST_IMM:
6334   case ARM::STRB_POST_REG: {
6335     // Rt must be different from Rn.
6336     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6337     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6338
6339     if (Rt == Rn)
6340       return Error(Operands[3]->getStartLoc(),
6341                    "source register and base register can't be identical");
6342     return false;
6343   }
6344   case ARM::LDR_PRE_IMM:
6345   case ARM::LDR_PRE_REG:
6346   case ARM::LDR_POST_IMM:
6347   case ARM::LDR_POST_REG:
6348   case ARM::LDRH_PRE:
6349   case ARM::LDRH_POST:
6350   case ARM::LDRSH_PRE:
6351   case ARM::LDRSH_POST:
6352   case ARM::LDRB_PRE_IMM:
6353   case ARM::LDRB_PRE_REG:
6354   case ARM::LDRB_POST_IMM:
6355   case ARM::LDRB_POST_REG:
6356   case ARM::LDRSB_PRE:
6357   case ARM::LDRSB_POST: {
6358     // Rt must be different from Rn.
6359     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6360     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6361
6362     if (Rt == Rn)
6363       return Error(Operands[3]->getStartLoc(),
6364                    "destination register and base register can't be identical");
6365     return false;
6366   }
6367   case ARM::SBFX:
6368   case ARM::UBFX: {
6369     // Width must be in range [1, 32-lsb].
6370     unsigned LSB = Inst.getOperand(2).getImm();
6371     unsigned Widthm1 = Inst.getOperand(3).getImm();
6372     if (Widthm1 >= 32 - LSB)
6373       return Error(Operands[5]->getStartLoc(),
6374                    "bitfield width must be in range [1,32-lsb]");
6375     return false;
6376   }
6377   // Notionally handles ARM::tLDMIA_UPD too.
6378   case ARM::tLDMIA: {
6379     // If we're parsing Thumb2, the .w variant is available and handles
6380     // most cases that are normally illegal for a Thumb1 LDM instruction.
6381     // We'll make the transformation in processInstruction() if necessary.
6382     //
6383     // Thumb LDM instructions are writeback iff the base register is not
6384     // in the register list.
6385     unsigned Rn = Inst.getOperand(0).getReg();
6386     bool HasWritebackToken =
6387         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6388          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6389     bool ListContainsBase;
6390     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6391       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6392                    "registers must be in range r0-r7");
6393     // If we should have writeback, then there should be a '!' token.
6394     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6395       return Error(Operands[2]->getStartLoc(),
6396                    "writeback operator '!' expected");
6397     // If we should not have writeback, there must not be a '!'. This is
6398     // true even for the 32-bit wide encodings.
6399     if (ListContainsBase && HasWritebackToken)
6400       return Error(Operands[3]->getStartLoc(),
6401                    "writeback operator '!' not allowed when base register "
6402                    "in register list");
6403
6404     if (validatetLDMRegList(Inst, Operands, 3))
6405       return true;
6406     break;
6407   }
6408   case ARM::LDMIA_UPD:
6409   case ARM::LDMDB_UPD:
6410   case ARM::LDMIB_UPD:
6411   case ARM::LDMDA_UPD:
6412     // ARM variants loading and updating the same register are only officially
6413     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6414     if (!hasV7Ops())
6415       break;
6416     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6417       return Error(Operands.back()->getStartLoc(),
6418                    "writeback register not allowed in register list");
6419     break;
6420   case ARM::t2LDMIA:
6421   case ARM::t2LDMDB:
6422     if (validatetLDMRegList(Inst, Operands, 3))
6423       return true;
6424     break;
6425   case ARM::t2STMIA:
6426   case ARM::t2STMDB:
6427     if (validatetSTMRegList(Inst, Operands, 3))
6428       return true;
6429     break;
6430   case ARM::t2LDMIA_UPD:
6431   case ARM::t2LDMDB_UPD:
6432   case ARM::t2STMIA_UPD:
6433   case ARM::t2STMDB_UPD: {
6434     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6435       return Error(Operands.back()->getStartLoc(),
6436                    "writeback register not allowed in register list");
6437
6438     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6439       if (validatetLDMRegList(Inst, Operands, 3))
6440         return true;
6441     } else {
6442       if (validatetSTMRegList(Inst, Operands, 3))
6443         return true;
6444     }
6445     break;
6446   }
6447   case ARM::sysLDMIA_UPD:
6448   case ARM::sysLDMDA_UPD:
6449   case ARM::sysLDMDB_UPD:
6450   case ARM::sysLDMIB_UPD:
6451     if (!listContainsReg(Inst, 3, ARM::PC))
6452       return Error(Operands[4]->getStartLoc(),
6453                    "writeback register only allowed on system LDM "
6454                    "if PC in register-list");
6455     break;
6456   case ARM::sysSTMIA_UPD:
6457   case ARM::sysSTMDA_UPD:
6458   case ARM::sysSTMDB_UPD:
6459   case ARM::sysSTMIB_UPD:
6460     return Error(Operands[2]->getStartLoc(),
6461                  "system STM cannot have writeback register");
6462   case ARM::tMUL: {
6463     // The second source operand must be the same register as the destination
6464     // operand.
6465     //
6466     // In this case, we must directly check the parsed operands because the
6467     // cvtThumbMultiply() function is written in such a way that it guarantees
6468     // this first statement is always true for the new Inst.  Essentially, the
6469     // destination is unconditionally copied into the second source operand
6470     // without checking to see if it matches what we actually parsed.
6471     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6472                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6473         (((ARMOperand &)*Operands[3]).getReg() !=
6474          ((ARMOperand &)*Operands[4]).getReg())) {
6475       return Error(Operands[3]->getStartLoc(),
6476                    "destination register must match source register");
6477     }
6478     break;
6479   }
6480   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6481   // so only issue a diagnostic for thumb1. The instructions will be
6482   // switched to the t2 encodings in processInstruction() if necessary.
6483   case ARM::tPOP: {
6484     bool ListContainsBase;
6485     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6486         !isThumbTwo())
6487       return Error(Operands[2]->getStartLoc(),
6488                    "registers must be in range r0-r7 or pc");
6489     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6490       return true;
6491     break;
6492   }
6493   case ARM::tPUSH: {
6494     bool ListContainsBase;
6495     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6496         !isThumbTwo())
6497       return Error(Operands[2]->getStartLoc(),
6498                    "registers must be in range r0-r7 or lr");
6499     if (validatetSTMRegList(Inst, Operands, 2))
6500       return true;
6501     break;
6502   }
6503   case ARM::tSTMIA_UPD: {
6504     bool ListContainsBase, InvalidLowList;
6505     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6506                                           0, ListContainsBase);
6507     if (InvalidLowList && !isThumbTwo())
6508       return Error(Operands[4]->getStartLoc(),
6509                    "registers must be in range r0-r7");
6510
6511     // This would be converted to a 32-bit stm, but that's not valid if the
6512     // writeback register is in the list.
6513     if (InvalidLowList && ListContainsBase)
6514       return Error(Operands[4]->getStartLoc(),
6515                    "writeback operator '!' not allowed when base register "
6516                    "in register list");
6517
6518     if (validatetSTMRegList(Inst, Operands, 4))
6519       return true;
6520     break;
6521   }
6522   case ARM::tADDrSP: {
6523     // If the non-SP source operand and the destination operand are not the
6524     // same, we need thumb2 (for the wide encoding), or we have an error.
6525     if (!isThumbTwo() &&
6526         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6527       return Error(Operands[4]->getStartLoc(),
6528                    "source register must be the same as destination");
6529     }
6530     break;
6531   }
6532   // Final range checking for Thumb unconditional branch instructions.
6533   case ARM::tB:
6534     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6535       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6536     break;
6537   case ARM::t2B: {
6538     int op = (Operands[2]->isImm()) ? 2 : 3;
6539     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6540       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6541     break;
6542   }
6543   // Final range checking for Thumb conditional branch instructions.
6544   case ARM::tBcc:
6545     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6546       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6547     break;
6548   case ARM::t2Bcc: {
6549     int Op = (Operands[2]->isImm()) ? 2 : 3;
6550     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6551       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6552     break;
6553   }
6554   case ARM::tCBZ:
6555   case ARM::tCBNZ: {
6556     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6557       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6558     break;
6559   }
6560   case ARM::MOVi16:
6561   case ARM::MOVTi16:
6562   case ARM::t2MOVi16:
6563   case ARM::t2MOVTi16:
6564     {
6565     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6566     // especially when we turn it into a movw and the expression <symbol> does
6567     // not have a :lower16: or :upper16 as part of the expression.  We don't
6568     // want the behavior of silently truncating, which can be unexpected and
6569     // lead to bugs that are difficult to find since this is an easy mistake
6570     // to make.
6571     int i = (Operands[3]->isImm()) ? 3 : 4;
6572     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6573     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6574     if (CE) break;
6575     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6576     if (!E) break;
6577     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6578     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6579                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6580       return Error(
6581           Op.getStartLoc(),
6582           "immediate expression for mov requires :lower16: or :upper16");
6583     break;
6584   }
6585   case ARM::HINT:
6586   case ARM::t2HINT: {
6587     if (hasRAS()) {
6588       // ESB is not predicable (pred must be AL)
6589       unsigned Imm8 = Inst.getOperand(0).getImm();
6590       unsigned Pred = Inst.getOperand(1).getImm();
6591       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6592         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6593                                                  "predicable, but condition "
6594                                                  "code specified");
6595     }
6596     // Without the RAS extension, this behaves as any other unallocated hint.
6597     break;
6598   }
6599   }
6600
6601   return false;
6602 }
6603
6604 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6605   switch(Opc) {
6606   default: llvm_unreachable("unexpected opcode!");
6607   // VST1LN
6608   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6609   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6610   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6611   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6612   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6613   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6614   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6615   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6616   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6617
6618   // VST2LN
6619   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6620   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6621   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6622   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6623   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6624
6625   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6626   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6627   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6628   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6629   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6630
6631   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6632   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6633   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6634   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6635   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6636
6637   // VST3LN
6638   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6639   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6640   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6641   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6642   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6643   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6644   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6645   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6646   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6647   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6648   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6649   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6650   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6651   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6652   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6653
6654   // VST3
6655   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6656   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6657   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6658   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6659   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6660   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6661   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6662   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6663   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6664   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6665   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6666   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6667   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6668   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6669   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6670   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6671   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6672   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6673
6674   // VST4LN
6675   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6676   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6677   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6678   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6679   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6680   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6681   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6682   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6683   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6684   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6685   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6686   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6687   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6688   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6689   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6690
6691   // VST4
6692   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6693   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6694   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6695   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6696   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6697   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6698   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6699   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6700   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6701   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6702   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6703   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6704   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6705   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6706   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6707   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6708   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6709   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6710   }
6711 }
6712
6713 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6714   switch(Opc) {
6715   default: llvm_unreachable("unexpected opcode!");
6716   // VLD1LN
6717   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6718   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6719   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6720   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6721   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6722   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6723   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6724   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6725   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6726
6727   // VLD2LN
6728   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6729   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6730   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6731   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6732   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6733   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6734   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6735   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6736   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6737   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6738   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6739   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6740   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6741   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6742   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6743
6744   // VLD3DUP
6745   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6746   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6747   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6748   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6749   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6750   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6751   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6752   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6753   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6754   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6755   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6756   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6757   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6758   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6759   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6760   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6761   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6762   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6763
6764   // VLD3LN
6765   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6766   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6767   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6768   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6769   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6770   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6771   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6772   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6773   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6774   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6775   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6776   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6777   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6778   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6779   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6780
6781   // VLD3
6782   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6783   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6784   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6785   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6786   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6787   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6788   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6789   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6790   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6791   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6792   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6793   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6794   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6795   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6796   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6797   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6798   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6799   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6800
6801   // VLD4LN
6802   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6803   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6804   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6805   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6806   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6807   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6808   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6809   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6810   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6811   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6812   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6813   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6814   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6815   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6816   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6817
6818   // VLD4DUP
6819   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6820   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6821   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6822   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6823   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6824   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6825   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6826   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6827   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6828   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6829   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6830   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6831   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6832   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6833   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6834   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6835   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6836   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6837
6838   // VLD4
6839   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6840   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6841   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6842   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6843   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6844   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6845   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6846   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6847   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6848   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6849   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6850   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6851   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6852   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6853   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6854   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6855   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6856   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6857   }
6858 }
6859
6860 bool ARMAsmParser::processInstruction(MCInst &Inst,
6861                                       const OperandVector &Operands,
6862                                       MCStreamer &Out) {
6863   // Check if we have the wide qualifier, because if it's present we
6864   // must avoid selecting a 16-bit thumb instruction.
6865   bool HasWideQualifier = false;
6866   for (auto &Op : Operands) {
6867     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
6868     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
6869       HasWideQualifier = true;
6870       break;
6871     }
6872   }
6873
6874   switch (Inst.getOpcode()) {
6875   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6876   case ARM::LDRT_POST:
6877   case ARM::LDRBT_POST: {
6878     const unsigned Opcode =
6879       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6880                                            : ARM::LDRBT_POST_IMM;
6881     MCInst TmpInst;
6882     TmpInst.setOpcode(Opcode);
6883     TmpInst.addOperand(Inst.getOperand(0));
6884     TmpInst.addOperand(Inst.getOperand(1));
6885     TmpInst.addOperand(Inst.getOperand(1));
6886     TmpInst.addOperand(MCOperand::createReg(0));
6887     TmpInst.addOperand(MCOperand::createImm(0));
6888     TmpInst.addOperand(Inst.getOperand(2));
6889     TmpInst.addOperand(Inst.getOperand(3));
6890     Inst = TmpInst;
6891     return true;
6892   }
6893   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6894   case ARM::STRT_POST:
6895   case ARM::STRBT_POST: {
6896     const unsigned Opcode =
6897       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6898                                            : ARM::STRBT_POST_IMM;
6899     MCInst TmpInst;
6900     TmpInst.setOpcode(Opcode);
6901     TmpInst.addOperand(Inst.getOperand(1));
6902     TmpInst.addOperand(Inst.getOperand(0));
6903     TmpInst.addOperand(Inst.getOperand(1));
6904     TmpInst.addOperand(MCOperand::createReg(0));
6905     TmpInst.addOperand(MCOperand::createImm(0));
6906     TmpInst.addOperand(Inst.getOperand(2));
6907     TmpInst.addOperand(Inst.getOperand(3));
6908     Inst = TmpInst;
6909     return true;
6910   }
6911   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6912   case ARM::ADDri: {
6913     if (Inst.getOperand(1).getReg() != ARM::PC ||
6914         Inst.getOperand(5).getReg() != 0 ||
6915         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6916       return false;
6917     MCInst TmpInst;
6918     TmpInst.setOpcode(ARM::ADR);
6919     TmpInst.addOperand(Inst.getOperand(0));
6920     if (Inst.getOperand(2).isImm()) {
6921       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6922       // before passing it to the ADR instruction.
6923       unsigned Enc = Inst.getOperand(2).getImm();
6924       TmpInst.addOperand(MCOperand::createImm(
6925         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6926     } else {
6927       // Turn PC-relative expression into absolute expression.
6928       // Reading PC provides the start of the current instruction + 8 and
6929       // the transform to adr is biased by that.
6930       MCSymbol *Dot = getContext().createTempSymbol();
6931       Out.EmitLabel(Dot);
6932       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6933       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6934                                                      MCSymbolRefExpr::VK_None,
6935                                                      getContext());
6936       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6937       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6938                                                      getContext());
6939       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6940                                                         getContext());
6941       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6942     }
6943     TmpInst.addOperand(Inst.getOperand(3));
6944     TmpInst.addOperand(Inst.getOperand(4));
6945     Inst = TmpInst;
6946     return true;
6947   }
6948   // Aliases for alternate PC+imm syntax of LDR instructions.
6949   case ARM::t2LDRpcrel:
6950     // Select the narrow version if the immediate will fit.
6951     if (Inst.getOperand(1).getImm() > 0 &&
6952         Inst.getOperand(1).getImm() <= 0xff &&
6953         !HasWideQualifier)
6954       Inst.setOpcode(ARM::tLDRpci);
6955     else
6956       Inst.setOpcode(ARM::t2LDRpci);
6957     return true;
6958   case ARM::t2LDRBpcrel:
6959     Inst.setOpcode(ARM::t2LDRBpci);
6960     return true;
6961   case ARM::t2LDRHpcrel:
6962     Inst.setOpcode(ARM::t2LDRHpci);
6963     return true;
6964   case ARM::t2LDRSBpcrel:
6965     Inst.setOpcode(ARM::t2LDRSBpci);
6966     return true;
6967   case ARM::t2LDRSHpcrel:
6968     Inst.setOpcode(ARM::t2LDRSHpci);
6969     return true;
6970   case ARM::LDRConstPool:
6971   case ARM::tLDRConstPool:
6972   case ARM::t2LDRConstPool: {
6973     // Pseudo instruction ldr rt, =immediate is converted to a
6974     // MOV rt, immediate if immediate is known and representable
6975     // otherwise we create a constant pool entry that we load from.
6976     MCInst TmpInst;
6977     if (Inst.getOpcode() == ARM::LDRConstPool)
6978       TmpInst.setOpcode(ARM::LDRi12);
6979     else if (Inst.getOpcode() == ARM::tLDRConstPool)
6980       TmpInst.setOpcode(ARM::tLDRpci);
6981     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
6982       TmpInst.setOpcode(ARM::t2LDRpci);
6983     const ARMOperand &PoolOperand =
6984       (HasWideQualifier ?
6985        static_cast<ARMOperand &>(*Operands[4]) :
6986        static_cast<ARMOperand &>(*Operands[3]));
6987     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
6988     // If SubExprVal is a constant we may be able to use a MOV
6989     if (isa<MCConstantExpr>(SubExprVal) &&
6990         Inst.getOperand(0).getReg() != ARM::PC &&
6991         Inst.getOperand(0).getReg() != ARM::SP) {
6992       int64_t Value =
6993         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
6994       bool UseMov  = true;
6995       bool MovHasS = true;
6996       if (Inst.getOpcode() == ARM::LDRConstPool) {
6997         // ARM Constant
6998         if (ARM_AM::getSOImmVal(Value) != -1) {
6999           Value = ARM_AM::getSOImmVal(Value);
7000           TmpInst.setOpcode(ARM::MOVi);
7001         }
7002         else if (ARM_AM::getSOImmVal(~Value) != -1) {
7003           Value = ARM_AM::getSOImmVal(~Value);
7004           TmpInst.setOpcode(ARM::MVNi);
7005         }
7006         else if (hasV6T2Ops() &&
7007                  Value >=0 && Value < 65536) {
7008           TmpInst.setOpcode(ARM::MOVi16);
7009           MovHasS = false;
7010         }
7011         else
7012           UseMov = false;
7013       }
7014       else {
7015         // Thumb/Thumb2 Constant
7016         if (hasThumb2() &&
7017             ARM_AM::getT2SOImmVal(Value) != -1)
7018           TmpInst.setOpcode(ARM::t2MOVi);
7019         else if (hasThumb2() &&
7020                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7021           TmpInst.setOpcode(ARM::t2MVNi);
7022           Value = ~Value;
7023         }
7024         else if (hasV8MBaseline() &&
7025                  Value >=0 && Value < 65536) {
7026           TmpInst.setOpcode(ARM::t2MOVi16);
7027           MovHasS = false;
7028         }
7029         else
7030           UseMov = false;
7031       }
7032       if (UseMov) {
7033         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7034         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7035         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7036         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7037         if (MovHasS)
7038           TmpInst.addOperand(MCOperand::createReg(0));    // S
7039         Inst = TmpInst;
7040         return true;
7041       }
7042     }
7043     // No opportunity to use MOV/MVN create constant pool
7044     const MCExpr *CPLoc =
7045       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7046                                                PoolOperand.getStartLoc());
7047     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7048     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7049     if (TmpInst.getOpcode() == ARM::LDRi12)
7050       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7051     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7052     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7053     Inst = TmpInst;
7054     return true;
7055   }
7056   // Handle NEON VST complex aliases.
7057   case ARM::VST1LNdWB_register_Asm_8:
7058   case ARM::VST1LNdWB_register_Asm_16:
7059   case ARM::VST1LNdWB_register_Asm_32: {
7060     MCInst TmpInst;
7061     // Shuffle the operands around so the lane index operand is in the
7062     // right place.
7063     unsigned Spacing;
7064     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7065     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7066     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7067     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7068     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7069     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7070     TmpInst.addOperand(Inst.getOperand(1)); // lane
7071     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7072     TmpInst.addOperand(Inst.getOperand(6));
7073     Inst = TmpInst;
7074     return true;
7075   }
7076
7077   case ARM::VST2LNdWB_register_Asm_8:
7078   case ARM::VST2LNdWB_register_Asm_16:
7079   case ARM::VST2LNdWB_register_Asm_32:
7080   case ARM::VST2LNqWB_register_Asm_16:
7081   case ARM::VST2LNqWB_register_Asm_32: {
7082     MCInst TmpInst;
7083     // Shuffle the operands around so the lane index operand is in the
7084     // right place.
7085     unsigned Spacing;
7086     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7087     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7088     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7089     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7090     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7091     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7092     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7093                                             Spacing));
7094     TmpInst.addOperand(Inst.getOperand(1)); // lane
7095     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7096     TmpInst.addOperand(Inst.getOperand(6));
7097     Inst = TmpInst;
7098     return true;
7099   }
7100
7101   case ARM::VST3LNdWB_register_Asm_8:
7102   case ARM::VST3LNdWB_register_Asm_16:
7103   case ARM::VST3LNdWB_register_Asm_32:
7104   case ARM::VST3LNqWB_register_Asm_16:
7105   case ARM::VST3LNqWB_register_Asm_32: {
7106     MCInst TmpInst;
7107     // Shuffle the operands around so the lane index operand is in the
7108     // right place.
7109     unsigned Spacing;
7110     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7111     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7112     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7113     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7114     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7115     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7116     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7117                                             Spacing));
7118     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7119                                             Spacing * 2));
7120     TmpInst.addOperand(Inst.getOperand(1)); // lane
7121     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7122     TmpInst.addOperand(Inst.getOperand(6));
7123     Inst = TmpInst;
7124     return true;
7125   }
7126
7127   case ARM::VST4LNdWB_register_Asm_8:
7128   case ARM::VST4LNdWB_register_Asm_16:
7129   case ARM::VST4LNdWB_register_Asm_32:
7130   case ARM::VST4LNqWB_register_Asm_16:
7131   case ARM::VST4LNqWB_register_Asm_32: {
7132     MCInst TmpInst;
7133     // Shuffle the operands around so the lane index operand is in the
7134     // right place.
7135     unsigned Spacing;
7136     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7137     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7138     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7139     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7140     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7141     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7142     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7143                                             Spacing));
7144     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7145                                             Spacing * 2));
7146     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7147                                             Spacing * 3));
7148     TmpInst.addOperand(Inst.getOperand(1)); // lane
7149     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7150     TmpInst.addOperand(Inst.getOperand(6));
7151     Inst = TmpInst;
7152     return true;
7153   }
7154
7155   case ARM::VST1LNdWB_fixed_Asm_8:
7156   case ARM::VST1LNdWB_fixed_Asm_16:
7157   case ARM::VST1LNdWB_fixed_Asm_32: {
7158     MCInst TmpInst;
7159     // Shuffle the operands around so the lane index operand is in the
7160     // right place.
7161     unsigned Spacing;
7162     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7163     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7164     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7165     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7166     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7167     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7168     TmpInst.addOperand(Inst.getOperand(1)); // lane
7169     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7170     TmpInst.addOperand(Inst.getOperand(5));
7171     Inst = TmpInst;
7172     return true;
7173   }
7174
7175   case ARM::VST2LNdWB_fixed_Asm_8:
7176   case ARM::VST2LNdWB_fixed_Asm_16:
7177   case ARM::VST2LNdWB_fixed_Asm_32:
7178   case ARM::VST2LNqWB_fixed_Asm_16:
7179   case ARM::VST2LNqWB_fixed_Asm_32: {
7180     MCInst TmpInst;
7181     // Shuffle the operands around so the lane index operand is in the
7182     // right place.
7183     unsigned Spacing;
7184     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7185     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7186     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7187     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7188     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7189     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7190     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7191                                             Spacing));
7192     TmpInst.addOperand(Inst.getOperand(1)); // lane
7193     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7194     TmpInst.addOperand(Inst.getOperand(5));
7195     Inst = TmpInst;
7196     return true;
7197   }
7198
7199   case ARM::VST3LNdWB_fixed_Asm_8:
7200   case ARM::VST3LNdWB_fixed_Asm_16:
7201   case ARM::VST3LNdWB_fixed_Asm_32:
7202   case ARM::VST3LNqWB_fixed_Asm_16:
7203   case ARM::VST3LNqWB_fixed_Asm_32: {
7204     MCInst TmpInst;
7205     // Shuffle the operands around so the lane index operand is in the
7206     // right place.
7207     unsigned Spacing;
7208     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7209     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7210     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7211     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7212     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7213     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7214     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7215                                             Spacing));
7216     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7217                                             Spacing * 2));
7218     TmpInst.addOperand(Inst.getOperand(1)); // lane
7219     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7220     TmpInst.addOperand(Inst.getOperand(5));
7221     Inst = TmpInst;
7222     return true;
7223   }
7224
7225   case ARM::VST4LNdWB_fixed_Asm_8:
7226   case ARM::VST4LNdWB_fixed_Asm_16:
7227   case ARM::VST4LNdWB_fixed_Asm_32:
7228   case ARM::VST4LNqWB_fixed_Asm_16:
7229   case ARM::VST4LNqWB_fixed_Asm_32: {
7230     MCInst TmpInst;
7231     // Shuffle the operands around so the lane index operand is in the
7232     // right place.
7233     unsigned Spacing;
7234     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7235     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7236     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7237     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7238     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7239     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7240     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7241                                             Spacing));
7242     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7243                                             Spacing * 2));
7244     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7245                                             Spacing * 3));
7246     TmpInst.addOperand(Inst.getOperand(1)); // lane
7247     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7248     TmpInst.addOperand(Inst.getOperand(5));
7249     Inst = TmpInst;
7250     return true;
7251   }
7252
7253   case ARM::VST1LNdAsm_8:
7254   case ARM::VST1LNdAsm_16:
7255   case ARM::VST1LNdAsm_32: {
7256     MCInst TmpInst;
7257     // Shuffle the operands around so the lane index operand is in the
7258     // right place.
7259     unsigned Spacing;
7260     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7261     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7262     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7263     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7264     TmpInst.addOperand(Inst.getOperand(1)); // lane
7265     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7266     TmpInst.addOperand(Inst.getOperand(5));
7267     Inst = TmpInst;
7268     return true;
7269   }
7270
7271   case ARM::VST2LNdAsm_8:
7272   case ARM::VST2LNdAsm_16:
7273   case ARM::VST2LNdAsm_32:
7274   case ARM::VST2LNqAsm_16:
7275   case ARM::VST2LNqAsm_32: {
7276     MCInst TmpInst;
7277     // Shuffle the operands around so the lane index operand is in the
7278     // right place.
7279     unsigned Spacing;
7280     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7281     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7282     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7283     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7284     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7285                                             Spacing));
7286     TmpInst.addOperand(Inst.getOperand(1)); // lane
7287     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7288     TmpInst.addOperand(Inst.getOperand(5));
7289     Inst = TmpInst;
7290     return true;
7291   }
7292
7293   case ARM::VST3LNdAsm_8:
7294   case ARM::VST3LNdAsm_16:
7295   case ARM::VST3LNdAsm_32:
7296   case ARM::VST3LNqAsm_16:
7297   case ARM::VST3LNqAsm_32: {
7298     MCInst TmpInst;
7299     // Shuffle the operands around so the lane index operand is in the
7300     // right place.
7301     unsigned Spacing;
7302     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7303     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7304     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7305     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7306     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7307                                             Spacing));
7308     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7309                                             Spacing * 2));
7310     TmpInst.addOperand(Inst.getOperand(1)); // lane
7311     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7312     TmpInst.addOperand(Inst.getOperand(5));
7313     Inst = TmpInst;
7314     return true;
7315   }
7316
7317   case ARM::VST4LNdAsm_8:
7318   case ARM::VST4LNdAsm_16:
7319   case ARM::VST4LNdAsm_32:
7320   case ARM::VST4LNqAsm_16:
7321   case ARM::VST4LNqAsm_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(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7327     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7328     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7329     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7330     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7331                                             Spacing));
7332     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7333                                             Spacing * 2));
7334     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7335                                             Spacing * 3));
7336     TmpInst.addOperand(Inst.getOperand(1)); // lane
7337     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7338     TmpInst.addOperand(Inst.getOperand(5));
7339     Inst = TmpInst;
7340     return true;
7341   }
7342
7343   // Handle NEON VLD complex aliases.
7344   case ARM::VLD1LNdWB_register_Asm_8:
7345   case ARM::VLD1LNdWB_register_Asm_16:
7346   case ARM::VLD1LNdWB_register_Asm_32: {
7347     MCInst TmpInst;
7348     // Shuffle the operands around so the lane index operand is in the
7349     // right place.
7350     unsigned Spacing;
7351     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7352     TmpInst.addOperand(Inst.getOperand(0)); // Vd
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(Inst.getOperand(1)); // lane
7359     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7360     TmpInst.addOperand(Inst.getOperand(6));
7361     Inst = TmpInst;
7362     return true;
7363   }
7364
7365   case ARM::VLD2LNdWB_register_Asm_8:
7366   case ARM::VLD2LNdWB_register_Asm_16:
7367   case ARM::VLD2LNdWB_register_Asm_32:
7368   case ARM::VLD2LNqWB_register_Asm_16:
7369   case ARM::VLD2LNqWB_register_Asm_32: {
7370     MCInst TmpInst;
7371     // Shuffle the operands around so the lane index operand is in the
7372     // right place.
7373     unsigned Spacing;
7374     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7375     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7376     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7377                                             Spacing));
7378     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7379     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7380     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7381     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7382     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7383     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7384                                             Spacing));
7385     TmpInst.addOperand(Inst.getOperand(1)); // lane
7386     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7387     TmpInst.addOperand(Inst.getOperand(6));
7388     Inst = TmpInst;
7389     return true;
7390   }
7391
7392   case ARM::VLD3LNdWB_register_Asm_8:
7393   case ARM::VLD3LNdWB_register_Asm_16:
7394   case ARM::VLD3LNdWB_register_Asm_32:
7395   case ARM::VLD3LNqWB_register_Asm_16:
7396   case ARM::VLD3LNqWB_register_Asm_32: {
7397     MCInst TmpInst;
7398     // Shuffle the operands around so the lane index operand is in the
7399     // right place.
7400     unsigned Spacing;
7401     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7402     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7403     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7404                                             Spacing));
7405     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7406                                             Spacing * 2));
7407     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7408     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7409     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7410     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7411     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7412     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7413                                             Spacing));
7414     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7415                                             Spacing * 2));
7416     TmpInst.addOperand(Inst.getOperand(1)); // lane
7417     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7418     TmpInst.addOperand(Inst.getOperand(6));
7419     Inst = TmpInst;
7420     return true;
7421   }
7422
7423   case ARM::VLD4LNdWB_register_Asm_8:
7424   case ARM::VLD4LNdWB_register_Asm_16:
7425   case ARM::VLD4LNdWB_register_Asm_32:
7426   case ARM::VLD4LNqWB_register_Asm_16:
7427   case ARM::VLD4LNqWB_register_Asm_32: {
7428     MCInst TmpInst;
7429     // Shuffle the operands around so the lane index operand is in the
7430     // right place.
7431     unsigned Spacing;
7432     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7433     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7434     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7435                                             Spacing));
7436     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7437                                             Spacing * 2));
7438     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7439                                             Spacing * 3));
7440     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7441     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7442     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7443     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7444     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7445     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7446                                             Spacing));
7447     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7448                                             Spacing * 2));
7449     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7450                                             Spacing * 3));
7451     TmpInst.addOperand(Inst.getOperand(1)); // lane
7452     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7453     TmpInst.addOperand(Inst.getOperand(6));
7454     Inst = TmpInst;
7455     return true;
7456   }
7457
7458   case ARM::VLD1LNdWB_fixed_Asm_8:
7459   case ARM::VLD1LNdWB_fixed_Asm_16:
7460   case ARM::VLD1LNdWB_fixed_Asm_32: {
7461     MCInst TmpInst;
7462     // Shuffle the operands around so the lane index operand is in the
7463     // right place.
7464     unsigned Spacing;
7465     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7466     TmpInst.addOperand(Inst.getOperand(0)); // Vd
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(Inst.getOperand(1)); // lane
7473     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7474     TmpInst.addOperand(Inst.getOperand(5));
7475     Inst = TmpInst;
7476     return true;
7477   }
7478
7479   case ARM::VLD2LNdWB_fixed_Asm_8:
7480   case ARM::VLD2LNdWB_fixed_Asm_16:
7481   case ARM::VLD2LNdWB_fixed_Asm_32:
7482   case ARM::VLD2LNqWB_fixed_Asm_16:
7483   case ARM::VLD2LNqWB_fixed_Asm_32: {
7484     MCInst TmpInst;
7485     // Shuffle the operands around so the lane index operand is in the
7486     // right place.
7487     unsigned Spacing;
7488     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7489     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7490     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7491                                             Spacing));
7492     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7493     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7494     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7495     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7496     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7497     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7498                                             Spacing));
7499     TmpInst.addOperand(Inst.getOperand(1)); // lane
7500     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7501     TmpInst.addOperand(Inst.getOperand(5));
7502     Inst = TmpInst;
7503     return true;
7504   }
7505
7506   case ARM::VLD3LNdWB_fixed_Asm_8:
7507   case ARM::VLD3LNdWB_fixed_Asm_16:
7508   case ARM::VLD3LNdWB_fixed_Asm_32:
7509   case ARM::VLD3LNqWB_fixed_Asm_16:
7510   case ARM::VLD3LNqWB_fixed_Asm_32: {
7511     MCInst TmpInst;
7512     // Shuffle the operands around so the lane index operand is in the
7513     // right place.
7514     unsigned Spacing;
7515     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7516     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7517     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7518                                             Spacing));
7519     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7520                                             Spacing * 2));
7521     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7522     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7523     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7524     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7525     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7526     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7527                                             Spacing));
7528     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7529                                             Spacing * 2));
7530     TmpInst.addOperand(Inst.getOperand(1)); // lane
7531     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7532     TmpInst.addOperand(Inst.getOperand(5));
7533     Inst = TmpInst;
7534     return true;
7535   }
7536
7537   case ARM::VLD4LNdWB_fixed_Asm_8:
7538   case ARM::VLD4LNdWB_fixed_Asm_16:
7539   case ARM::VLD4LNdWB_fixed_Asm_32:
7540   case ARM::VLD4LNqWB_fixed_Asm_16:
7541   case ARM::VLD4LNqWB_fixed_Asm_32: {
7542     MCInst TmpInst;
7543     // Shuffle the operands around so the lane index operand is in the
7544     // right place.
7545     unsigned Spacing;
7546     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7547     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7548     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7549                                             Spacing));
7550     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7551                                             Spacing * 2));
7552     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7553                                             Spacing * 3));
7554     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7555     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7556     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7557     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7558     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7559     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7560                                             Spacing));
7561     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7562                                             Spacing * 2));
7563     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7564                                             Spacing * 3));
7565     TmpInst.addOperand(Inst.getOperand(1)); // lane
7566     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7567     TmpInst.addOperand(Inst.getOperand(5));
7568     Inst = TmpInst;
7569     return true;
7570   }
7571
7572   case ARM::VLD1LNdAsm_8:
7573   case ARM::VLD1LNdAsm_16:
7574   case ARM::VLD1LNdAsm_32: {
7575     MCInst TmpInst;
7576     // Shuffle the operands around so the lane index operand is in the
7577     // right place.
7578     unsigned Spacing;
7579     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7580     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7581     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7582     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7583     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
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::VLD2LNdAsm_8:
7592   case ARM::VLD2LNdAsm_16:
7593   case ARM::VLD2LNdAsm_32:
7594   case ARM::VLD2LNqAsm_16:
7595   case ARM::VLD2LNqAsm_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(Inst.getOperand(2)); // Rn
7605     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7606     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7607     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7608                                             Spacing));
7609     TmpInst.addOperand(Inst.getOperand(1)); // lane
7610     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7611     TmpInst.addOperand(Inst.getOperand(5));
7612     Inst = TmpInst;
7613     return true;
7614   }
7615
7616   case ARM::VLD3LNdAsm_8:
7617   case ARM::VLD3LNdAsm_16:
7618   case ARM::VLD3LNdAsm_32:
7619   case ARM::VLD3LNqAsm_16:
7620   case ARM::VLD3LNqAsm_32: {
7621     MCInst TmpInst;
7622     // Shuffle the operands around so the lane index operand is in the
7623     // right place.
7624     unsigned Spacing;
7625     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7626     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7627     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7628                                             Spacing));
7629     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7630                                             Spacing * 2));
7631     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7632     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7633     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7634     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7635                                             Spacing));
7636     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7637                                             Spacing * 2));
7638     TmpInst.addOperand(Inst.getOperand(1)); // lane
7639     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7640     TmpInst.addOperand(Inst.getOperand(5));
7641     Inst = TmpInst;
7642     return true;
7643   }
7644
7645   case ARM::VLD4LNdAsm_8:
7646   case ARM::VLD4LNdAsm_16:
7647   case ARM::VLD4LNdAsm_32:
7648   case ARM::VLD4LNqAsm_16:
7649   case ARM::VLD4LNqAsm_32: {
7650     MCInst TmpInst;
7651     // Shuffle the operands around so the lane index operand is in the
7652     // right place.
7653     unsigned Spacing;
7654     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7655     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7656     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7657                                             Spacing));
7658     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7659                                             Spacing * 2));
7660     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7661                                             Spacing * 3));
7662     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7663     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7664     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7665     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7666                                             Spacing));
7667     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7668                                             Spacing * 2));
7669     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7670                                             Spacing * 3));
7671     TmpInst.addOperand(Inst.getOperand(1)); // lane
7672     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7673     TmpInst.addOperand(Inst.getOperand(5));
7674     Inst = TmpInst;
7675     return true;
7676   }
7677
7678   // VLD3DUP single 3-element structure to all lanes instructions.
7679   case ARM::VLD3DUPdAsm_8:
7680   case ARM::VLD3DUPdAsm_16:
7681   case ARM::VLD3DUPdAsm_32:
7682   case ARM::VLD3DUPqAsm_8:
7683   case ARM::VLD3DUPqAsm_16:
7684   case ARM::VLD3DUPqAsm_32: {
7685     MCInst TmpInst;
7686     unsigned Spacing;
7687     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7688     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7689     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7690                                             Spacing));
7691     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7692                                             Spacing * 2));
7693     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7694     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7695     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7696     TmpInst.addOperand(Inst.getOperand(4));
7697     Inst = TmpInst;
7698     return true;
7699   }
7700
7701   case ARM::VLD3DUPdWB_fixed_Asm_8:
7702   case ARM::VLD3DUPdWB_fixed_Asm_16:
7703   case ARM::VLD3DUPdWB_fixed_Asm_32:
7704   case ARM::VLD3DUPqWB_fixed_Asm_8:
7705   case ARM::VLD3DUPqWB_fixed_Asm_16:
7706   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7707     MCInst TmpInst;
7708     unsigned Spacing;
7709     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7710     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7711     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7712                                             Spacing));
7713     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7714                                             Spacing * 2));
7715     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7716     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7717     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7718     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7719     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7720     TmpInst.addOperand(Inst.getOperand(4));
7721     Inst = TmpInst;
7722     return true;
7723   }
7724
7725   case ARM::VLD3DUPdWB_register_Asm_8:
7726   case ARM::VLD3DUPdWB_register_Asm_16:
7727   case ARM::VLD3DUPdWB_register_Asm_32:
7728   case ARM::VLD3DUPqWB_register_Asm_8:
7729   case ARM::VLD3DUPqWB_register_Asm_16:
7730   case ARM::VLD3DUPqWB_register_Asm_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(1)); // Rn_wb == tied Rn
7741     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7742     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7743     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7744     TmpInst.addOperand(Inst.getOperand(5));
7745     Inst = TmpInst;
7746     return true;
7747   }
7748
7749   // VLD3 multiple 3-element structure instructions.
7750   case ARM::VLD3dAsm_8:
7751   case ARM::VLD3dAsm_16:
7752   case ARM::VLD3dAsm_32:
7753   case ARM::VLD3qAsm_8:
7754   case ARM::VLD3qAsm_16:
7755   case ARM::VLD3qAsm_32: {
7756     MCInst TmpInst;
7757     unsigned Spacing;
7758     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7759     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7760     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7761                                             Spacing));
7762     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7763                                             Spacing * 2));
7764     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7765     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7766     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7767     TmpInst.addOperand(Inst.getOperand(4));
7768     Inst = TmpInst;
7769     return true;
7770   }
7771
7772   case ARM::VLD3dWB_fixed_Asm_8:
7773   case ARM::VLD3dWB_fixed_Asm_16:
7774   case ARM::VLD3dWB_fixed_Asm_32:
7775   case ARM::VLD3qWB_fixed_Asm_8:
7776   case ARM::VLD3qWB_fixed_Asm_16:
7777   case ARM::VLD3qWB_fixed_Asm_32: {
7778     MCInst TmpInst;
7779     unsigned Spacing;
7780     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7781     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7782     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7783                                             Spacing));
7784     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7785                                             Spacing * 2));
7786     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7787     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7788     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7789     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7790     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7791     TmpInst.addOperand(Inst.getOperand(4));
7792     Inst = TmpInst;
7793     return true;
7794   }
7795
7796   case ARM::VLD3dWB_register_Asm_8:
7797   case ARM::VLD3dWB_register_Asm_16:
7798   case ARM::VLD3dWB_register_Asm_32:
7799   case ARM::VLD3qWB_register_Asm_8:
7800   case ARM::VLD3qWB_register_Asm_16:
7801   case ARM::VLD3qWB_register_Asm_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(Inst.getOperand(1)); // Rn
7811     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7812     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7813     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7814     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7815     TmpInst.addOperand(Inst.getOperand(5));
7816     Inst = TmpInst;
7817     return true;
7818   }
7819
7820   // VLD4DUP single 3-element structure to all lanes instructions.
7821   case ARM::VLD4DUPdAsm_8:
7822   case ARM::VLD4DUPdAsm_16:
7823   case ARM::VLD4DUPdAsm_32:
7824   case ARM::VLD4DUPqAsm_8:
7825   case ARM::VLD4DUPqAsm_16:
7826   case ARM::VLD4DUPqAsm_32: {
7827     MCInst TmpInst;
7828     unsigned Spacing;
7829     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7830     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7831     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7832                                             Spacing));
7833     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7834                                             Spacing * 2));
7835     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7836                                             Spacing * 3));
7837     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7838     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7839     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7840     TmpInst.addOperand(Inst.getOperand(4));
7841     Inst = TmpInst;
7842     return true;
7843   }
7844
7845   case ARM::VLD4DUPdWB_fixed_Asm_8:
7846   case ARM::VLD4DUPdWB_fixed_Asm_16:
7847   case ARM::VLD4DUPdWB_fixed_Asm_32:
7848   case ARM::VLD4DUPqWB_fixed_Asm_8:
7849   case ARM::VLD4DUPqWB_fixed_Asm_16:
7850   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7851     MCInst TmpInst;
7852     unsigned Spacing;
7853     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7854     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7855     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7856                                             Spacing));
7857     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7858                                             Spacing * 2));
7859     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7860                                             Spacing * 3));
7861     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7862     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7863     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7864     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7865     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7866     TmpInst.addOperand(Inst.getOperand(4));
7867     Inst = TmpInst;
7868     return true;
7869   }
7870
7871   case ARM::VLD4DUPdWB_register_Asm_8:
7872   case ARM::VLD4DUPdWB_register_Asm_16:
7873   case ARM::VLD4DUPdWB_register_Asm_32:
7874   case ARM::VLD4DUPqWB_register_Asm_8:
7875   case ARM::VLD4DUPqWB_register_Asm_16:
7876   case ARM::VLD4DUPqWB_register_Asm_32: {
7877     MCInst TmpInst;
7878     unsigned Spacing;
7879     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7880     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7881     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7882                                             Spacing));
7883     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7884                                             Spacing * 2));
7885     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7886                                             Spacing * 3));
7887     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7888     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7889     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7890     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7891     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7892     TmpInst.addOperand(Inst.getOperand(5));
7893     Inst = TmpInst;
7894     return true;
7895   }
7896
7897   // VLD4 multiple 4-element structure instructions.
7898   case ARM::VLD4dAsm_8:
7899   case ARM::VLD4dAsm_16:
7900   case ARM::VLD4dAsm_32:
7901   case ARM::VLD4qAsm_8:
7902   case ARM::VLD4qAsm_16:
7903   case ARM::VLD4qAsm_32: {
7904     MCInst TmpInst;
7905     unsigned Spacing;
7906     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7907     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7908     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7909                                             Spacing));
7910     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7911                                             Spacing * 2));
7912     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7913                                             Spacing * 3));
7914     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7915     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7916     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7917     TmpInst.addOperand(Inst.getOperand(4));
7918     Inst = TmpInst;
7919     return true;
7920   }
7921
7922   case ARM::VLD4dWB_fixed_Asm_8:
7923   case ARM::VLD4dWB_fixed_Asm_16:
7924   case ARM::VLD4dWB_fixed_Asm_32:
7925   case ARM::VLD4qWB_fixed_Asm_8:
7926   case ARM::VLD4qWB_fixed_Asm_16:
7927   case ARM::VLD4qWB_fixed_Asm_32: {
7928     MCInst TmpInst;
7929     unsigned Spacing;
7930     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7931     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7932     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7933                                             Spacing));
7934     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7935                                             Spacing * 2));
7936     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7937                                             Spacing * 3));
7938     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7939     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7940     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7941     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7942     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7943     TmpInst.addOperand(Inst.getOperand(4));
7944     Inst = TmpInst;
7945     return true;
7946   }
7947
7948   case ARM::VLD4dWB_register_Asm_8:
7949   case ARM::VLD4dWB_register_Asm_16:
7950   case ARM::VLD4dWB_register_Asm_32:
7951   case ARM::VLD4qWB_register_Asm_8:
7952   case ARM::VLD4qWB_register_Asm_16:
7953   case ARM::VLD4qWB_register_Asm_32: {
7954     MCInst TmpInst;
7955     unsigned Spacing;
7956     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7957     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7958     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7959                                             Spacing));
7960     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7961                                             Spacing * 2));
7962     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7963                                             Spacing * 3));
7964     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7965     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7966     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7967     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7968     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7969     TmpInst.addOperand(Inst.getOperand(5));
7970     Inst = TmpInst;
7971     return true;
7972   }
7973
7974   // VST3 multiple 3-element structure instructions.
7975   case ARM::VST3dAsm_8:
7976   case ARM::VST3dAsm_16:
7977   case ARM::VST3dAsm_32:
7978   case ARM::VST3qAsm_8:
7979   case ARM::VST3qAsm_16:
7980   case ARM::VST3qAsm_32: {
7981     MCInst TmpInst;
7982     unsigned Spacing;
7983     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7984     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7985     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7986     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7987     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7988                                             Spacing));
7989     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7990                                             Spacing * 2));
7991     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7992     TmpInst.addOperand(Inst.getOperand(4));
7993     Inst = TmpInst;
7994     return true;
7995   }
7996
7997   case ARM::VST3dWB_fixed_Asm_8:
7998   case ARM::VST3dWB_fixed_Asm_16:
7999   case ARM::VST3dWB_fixed_Asm_32:
8000   case ARM::VST3qWB_fixed_Asm_8:
8001   case ARM::VST3qWB_fixed_Asm_16:
8002   case ARM::VST3qWB_fixed_Asm_32: {
8003     MCInst TmpInst;
8004     unsigned Spacing;
8005     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8006     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8007     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8008     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8009     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8010     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8011     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8012                                             Spacing));
8013     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8014                                             Spacing * 2));
8015     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8016     TmpInst.addOperand(Inst.getOperand(4));
8017     Inst = TmpInst;
8018     return true;
8019   }
8020
8021   case ARM::VST3dWB_register_Asm_8:
8022   case ARM::VST3dWB_register_Asm_16:
8023   case ARM::VST3dWB_register_Asm_32:
8024   case ARM::VST3qWB_register_Asm_8:
8025   case ARM::VST3qWB_register_Asm_16:
8026   case ARM::VST3qWB_register_Asm_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(1)); // Rn_wb == tied Rn
8032     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8033     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8034     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8035     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8036                                             Spacing));
8037     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8038                                             Spacing * 2));
8039     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8040     TmpInst.addOperand(Inst.getOperand(5));
8041     Inst = TmpInst;
8042     return true;
8043   }
8044
8045   // VST4 multiple 3-element structure instructions.
8046   case ARM::VST4dAsm_8:
8047   case ARM::VST4dAsm_16:
8048   case ARM::VST4dAsm_32:
8049   case ARM::VST4qAsm_8:
8050   case ARM::VST4qAsm_16:
8051   case ARM::VST4qAsm_32: {
8052     MCInst TmpInst;
8053     unsigned Spacing;
8054     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8055     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8056     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8057     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8058     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8059                                             Spacing));
8060     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8061                                             Spacing * 2));
8062     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8063                                             Spacing * 3));
8064     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8065     TmpInst.addOperand(Inst.getOperand(4));
8066     Inst = TmpInst;
8067     return true;
8068   }
8069
8070   case ARM::VST4dWB_fixed_Asm_8:
8071   case ARM::VST4dWB_fixed_Asm_16:
8072   case ARM::VST4dWB_fixed_Asm_32:
8073   case ARM::VST4qWB_fixed_Asm_8:
8074   case ARM::VST4qWB_fixed_Asm_16:
8075   case ARM::VST4qWB_fixed_Asm_32: {
8076     MCInst TmpInst;
8077     unsigned Spacing;
8078     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8079     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8080     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8081     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8082     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8083     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8084     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8085                                             Spacing));
8086     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8087                                             Spacing * 2));
8088     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8089                                             Spacing * 3));
8090     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8091     TmpInst.addOperand(Inst.getOperand(4));
8092     Inst = TmpInst;
8093     return true;
8094   }
8095
8096   case ARM::VST4dWB_register_Asm_8:
8097   case ARM::VST4dWB_register_Asm_16:
8098   case ARM::VST4dWB_register_Asm_32:
8099   case ARM::VST4qWB_register_Asm_8:
8100   case ARM::VST4qWB_register_Asm_16:
8101   case ARM::VST4qWB_register_Asm_32: {
8102     MCInst TmpInst;
8103     unsigned Spacing;
8104     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8105     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8106     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8107     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8108     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8109     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8110     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8111                                             Spacing));
8112     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8113                                             Spacing * 2));
8114     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8115                                             Spacing * 3));
8116     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8117     TmpInst.addOperand(Inst.getOperand(5));
8118     Inst = TmpInst;
8119     return true;
8120   }
8121
8122   // Handle encoding choice for the shift-immediate instructions.
8123   case ARM::t2LSLri:
8124   case ARM::t2LSRri:
8125   case ARM::t2ASRri: {
8126     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8127         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8128         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8129         !HasWideQualifier) {
8130       unsigned NewOpc;
8131       switch (Inst.getOpcode()) {
8132       default: llvm_unreachable("unexpected opcode");
8133       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8134       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8135       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8136       }
8137       // The Thumb1 operands aren't in the same order. Awesome, eh?
8138       MCInst TmpInst;
8139       TmpInst.setOpcode(NewOpc);
8140       TmpInst.addOperand(Inst.getOperand(0));
8141       TmpInst.addOperand(Inst.getOperand(5));
8142       TmpInst.addOperand(Inst.getOperand(1));
8143       TmpInst.addOperand(Inst.getOperand(2));
8144       TmpInst.addOperand(Inst.getOperand(3));
8145       TmpInst.addOperand(Inst.getOperand(4));
8146       Inst = TmpInst;
8147       return true;
8148     }
8149     return false;
8150   }
8151
8152   // Handle the Thumb2 mode MOV complex aliases.
8153   case ARM::t2MOVsr:
8154   case ARM::t2MOVSsr: {
8155     // Which instruction to expand to depends on the CCOut operand and
8156     // whether we're in an IT block if the register operands are low
8157     // registers.
8158     bool isNarrow = false;
8159     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8160         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8161         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8162         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8163         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8164         !HasWideQualifier)
8165       isNarrow = true;
8166     MCInst TmpInst;
8167     unsigned newOpc;
8168     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8169     default: llvm_unreachable("unexpected opcode!");
8170     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8171     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8172     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8173     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8174     }
8175     TmpInst.setOpcode(newOpc);
8176     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8177     if (isNarrow)
8178       TmpInst.addOperand(MCOperand::createReg(
8179           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8180     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8181     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8182     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8183     TmpInst.addOperand(Inst.getOperand(5));
8184     if (!isNarrow)
8185       TmpInst.addOperand(MCOperand::createReg(
8186           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8187     Inst = TmpInst;
8188     return true;
8189   }
8190   case ARM::t2MOVsi:
8191   case ARM::t2MOVSsi: {
8192     // Which instruction to expand to depends on the CCOut operand and
8193     // whether we're in an IT block if the register operands are low
8194     // registers.
8195     bool isNarrow = false;
8196     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8197         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8198         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8199         !HasWideQualifier)
8200       isNarrow = true;
8201     MCInst TmpInst;
8202     unsigned newOpc;
8203     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8204     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8205     bool isMov = false;
8206     // MOV rd, rm, LSL #0 is actually a MOV instruction
8207     if (Shift == ARM_AM::lsl && Amount == 0) {
8208       isMov = true;
8209       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8210       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8211       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8212       // instead.
8213       if (inITBlock()) {
8214         isNarrow = false;
8215       }
8216       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8217     } else {
8218       switch(Shift) {
8219       default: llvm_unreachable("unexpected opcode!");
8220       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8221       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8222       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8223       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8224       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8225       }
8226     }
8227     if (Amount == 32) Amount = 0;
8228     TmpInst.setOpcode(newOpc);
8229     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8230     if (isNarrow && !isMov)
8231       TmpInst.addOperand(MCOperand::createReg(
8232           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8233     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8234     if (newOpc != ARM::t2RRX && !isMov)
8235       TmpInst.addOperand(MCOperand::createImm(Amount));
8236     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8237     TmpInst.addOperand(Inst.getOperand(4));
8238     if (!isNarrow)
8239       TmpInst.addOperand(MCOperand::createReg(
8240           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8241     Inst = TmpInst;
8242     return true;
8243   }
8244   // Handle the ARM mode MOV complex aliases.
8245   case ARM::ASRr:
8246   case ARM::LSRr:
8247   case ARM::LSLr:
8248   case ARM::RORr: {
8249     ARM_AM::ShiftOpc ShiftTy;
8250     switch(Inst.getOpcode()) {
8251     default: llvm_unreachable("unexpected opcode!");
8252     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8253     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8254     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8255     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8256     }
8257     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8258     MCInst TmpInst;
8259     TmpInst.setOpcode(ARM::MOVsr);
8260     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8261     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8262     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8263     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8264     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8265     TmpInst.addOperand(Inst.getOperand(4));
8266     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8267     Inst = TmpInst;
8268     return true;
8269   }
8270   case ARM::ASRi:
8271   case ARM::LSRi:
8272   case ARM::LSLi:
8273   case ARM::RORi: {
8274     ARM_AM::ShiftOpc ShiftTy;
8275     switch(Inst.getOpcode()) {
8276     default: llvm_unreachable("unexpected opcode!");
8277     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8278     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8279     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8280     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8281     }
8282     // A shift by zero is a plain MOVr, not a MOVsi.
8283     unsigned Amt = Inst.getOperand(2).getImm();
8284     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8285     // A shift by 32 should be encoded as 0 when permitted
8286     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8287       Amt = 0;
8288     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8289     MCInst TmpInst;
8290     TmpInst.setOpcode(Opc);
8291     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8292     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8293     if (Opc == ARM::MOVsi)
8294       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8295     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8296     TmpInst.addOperand(Inst.getOperand(4));
8297     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8298     Inst = TmpInst;
8299     return true;
8300   }
8301   case ARM::RRXi: {
8302     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8303     MCInst TmpInst;
8304     TmpInst.setOpcode(ARM::MOVsi);
8305     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8306     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8307     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8308     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8309     TmpInst.addOperand(Inst.getOperand(3));
8310     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8311     Inst = TmpInst;
8312     return true;
8313   }
8314   case ARM::t2LDMIA_UPD: {
8315     // If this is a load of a single register, then we should use
8316     // a post-indexed LDR instruction instead, per the ARM ARM.
8317     if (Inst.getNumOperands() != 5)
8318       return false;
8319     MCInst TmpInst;
8320     TmpInst.setOpcode(ARM::t2LDR_POST);
8321     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8322     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8323     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8324     TmpInst.addOperand(MCOperand::createImm(4));
8325     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8326     TmpInst.addOperand(Inst.getOperand(3));
8327     Inst = TmpInst;
8328     return true;
8329   }
8330   case ARM::t2STMDB_UPD: {
8331     // If this is a store of a single register, then we should use
8332     // a pre-indexed STR instruction instead, per the ARM ARM.
8333     if (Inst.getNumOperands() != 5)
8334       return false;
8335     MCInst TmpInst;
8336     TmpInst.setOpcode(ARM::t2STR_PRE);
8337     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8338     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8339     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8340     TmpInst.addOperand(MCOperand::createImm(-4));
8341     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8342     TmpInst.addOperand(Inst.getOperand(3));
8343     Inst = TmpInst;
8344     return true;
8345   }
8346   case ARM::LDMIA_UPD:
8347     // If this is a load of a single register via a 'pop', then we should use
8348     // a post-indexed LDR instruction instead, per the ARM ARM.
8349     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8350         Inst.getNumOperands() == 5) {
8351       MCInst TmpInst;
8352       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8353       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8354       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8355       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8356       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8357       TmpInst.addOperand(MCOperand::createImm(4));
8358       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8359       TmpInst.addOperand(Inst.getOperand(3));
8360       Inst = TmpInst;
8361       return true;
8362     }
8363     break;
8364   case ARM::STMDB_UPD:
8365     // If this is a store of a single register via a 'push', then we should use
8366     // a pre-indexed STR instruction instead, per the ARM ARM.
8367     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8368         Inst.getNumOperands() == 5) {
8369       MCInst TmpInst;
8370       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8371       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8372       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8373       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8374       TmpInst.addOperand(MCOperand::createImm(-4));
8375       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8376       TmpInst.addOperand(Inst.getOperand(3));
8377       Inst = TmpInst;
8378     }
8379     break;
8380   case ARM::t2ADDri12:
8381     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8382     // mnemonic was used (not "addw"), encoding T3 is preferred.
8383     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8384         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8385       break;
8386     Inst.setOpcode(ARM::t2ADDri);
8387     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8388     break;
8389   case ARM::t2SUBri12:
8390     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8391     // mnemonic was used (not "subw"), encoding T3 is preferred.
8392     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8393         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8394       break;
8395     Inst.setOpcode(ARM::t2SUBri);
8396     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8397     break;
8398   case ARM::tADDi8:
8399     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8400     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8401     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8402     // to encoding T1 if <Rd> is omitted."
8403     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8404       Inst.setOpcode(ARM::tADDi3);
8405       return true;
8406     }
8407     break;
8408   case ARM::tSUBi8:
8409     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8410     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8411     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8412     // to encoding T1 if <Rd> is omitted."
8413     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8414       Inst.setOpcode(ARM::tSUBi3);
8415       return true;
8416     }
8417     break;
8418   case ARM::t2ADDri:
8419   case ARM::t2SUBri: {
8420     // If the destination and first source operand are the same, and
8421     // the flags are compatible with the current IT status, use encoding T2
8422     // instead of T3. For compatibility with the system 'as'. Make sure the
8423     // wide encoding wasn't explicit.
8424     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8425         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8426         (Inst.getOperand(2).isImm() &&
8427          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8428         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8429         HasWideQualifier)
8430       break;
8431     MCInst TmpInst;
8432     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8433                       ARM::tADDi8 : ARM::tSUBi8);
8434     TmpInst.addOperand(Inst.getOperand(0));
8435     TmpInst.addOperand(Inst.getOperand(5));
8436     TmpInst.addOperand(Inst.getOperand(0));
8437     TmpInst.addOperand(Inst.getOperand(2));
8438     TmpInst.addOperand(Inst.getOperand(3));
8439     TmpInst.addOperand(Inst.getOperand(4));
8440     Inst = TmpInst;
8441     return true;
8442   }
8443   case ARM::t2ADDrr: {
8444     // If the destination and first source operand are the same, and
8445     // there's no setting of the flags, use encoding T2 instead of T3.
8446     // Note that this is only for ADD, not SUB. This mirrors the system
8447     // 'as' behaviour.  Also take advantage of ADD being commutative.
8448     // Make sure the wide encoding wasn't explicit.
8449     bool Swap = false;
8450     auto DestReg = Inst.getOperand(0).getReg();
8451     bool Transform = DestReg == Inst.getOperand(1).getReg();
8452     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8453       Transform = true;
8454       Swap = true;
8455     }
8456     if (!Transform ||
8457         Inst.getOperand(5).getReg() != 0 ||
8458         HasWideQualifier)
8459       break;
8460     MCInst TmpInst;
8461     TmpInst.setOpcode(ARM::tADDhirr);
8462     TmpInst.addOperand(Inst.getOperand(0));
8463     TmpInst.addOperand(Inst.getOperand(0));
8464     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8465     TmpInst.addOperand(Inst.getOperand(3));
8466     TmpInst.addOperand(Inst.getOperand(4));
8467     Inst = TmpInst;
8468     return true;
8469   }
8470   case ARM::tADDrSP: {
8471     // If the non-SP source operand and the destination operand are not the
8472     // same, we need to use the 32-bit encoding if it's available.
8473     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8474       Inst.setOpcode(ARM::t2ADDrr);
8475       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8476       return true;
8477     }
8478     break;
8479   }
8480   case ARM::tB:
8481     // A Thumb conditional branch outside of an IT block is a tBcc.
8482     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8483       Inst.setOpcode(ARM::tBcc);
8484       return true;
8485     }
8486     break;
8487   case ARM::t2B:
8488     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8489     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8490       Inst.setOpcode(ARM::t2Bcc);
8491       return true;
8492     }
8493     break;
8494   case ARM::t2Bcc:
8495     // If the conditional is AL or we're in an IT block, we really want t2B.
8496     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8497       Inst.setOpcode(ARM::t2B);
8498       return true;
8499     }
8500     break;
8501   case ARM::tBcc:
8502     // If the conditional is AL, we really want tB.
8503     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8504       Inst.setOpcode(ARM::tB);
8505       return true;
8506     }
8507     break;
8508   case ARM::tLDMIA: {
8509     // If the register list contains any high registers, or if the writeback
8510     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8511     // instead if we're in Thumb2. Otherwise, this should have generated
8512     // an error in validateInstruction().
8513     unsigned Rn = Inst.getOperand(0).getReg();
8514     bool hasWritebackToken =
8515         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8516          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8517     bool listContainsBase;
8518     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8519         (!listContainsBase && !hasWritebackToken) ||
8520         (listContainsBase && hasWritebackToken)) {
8521       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8522       assert (isThumbTwo());
8523       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8524       // If we're switching to the updating version, we need to insert
8525       // the writeback tied operand.
8526       if (hasWritebackToken)
8527         Inst.insert(Inst.begin(),
8528                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8529       return true;
8530     }
8531     break;
8532   }
8533   case ARM::tSTMIA_UPD: {
8534     // If the register list contains any high registers, we need to use
8535     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8536     // should have generated an error in validateInstruction().
8537     unsigned Rn = Inst.getOperand(0).getReg();
8538     bool listContainsBase;
8539     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8540       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8541       assert (isThumbTwo());
8542       Inst.setOpcode(ARM::t2STMIA_UPD);
8543       return true;
8544     }
8545     break;
8546   }
8547   case ARM::tPOP: {
8548     bool listContainsBase;
8549     // If the register list contains any high registers, we need to use
8550     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8551     // should have generated an error in validateInstruction().
8552     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8553       return false;
8554     assert (isThumbTwo());
8555     Inst.setOpcode(ARM::t2LDMIA_UPD);
8556     // Add the base register and writeback operands.
8557     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8558     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8559     return true;
8560   }
8561   case ARM::tPUSH: {
8562     bool listContainsBase;
8563     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8564       return false;
8565     assert (isThumbTwo());
8566     Inst.setOpcode(ARM::t2STMDB_UPD);
8567     // Add the base register and writeback operands.
8568     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8569     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8570     return true;
8571   }
8572   case ARM::t2MOVi: {
8573     // If we can use the 16-bit encoding and the user didn't explicitly
8574     // request the 32-bit variant, transform it here.
8575     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8576         (Inst.getOperand(1).isImm() &&
8577          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8578         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8579         !HasWideQualifier) {
8580       // The operands aren't in the same order for tMOVi8...
8581       MCInst TmpInst;
8582       TmpInst.setOpcode(ARM::tMOVi8);
8583       TmpInst.addOperand(Inst.getOperand(0));
8584       TmpInst.addOperand(Inst.getOperand(4));
8585       TmpInst.addOperand(Inst.getOperand(1));
8586       TmpInst.addOperand(Inst.getOperand(2));
8587       TmpInst.addOperand(Inst.getOperand(3));
8588       Inst = TmpInst;
8589       return true;
8590     }
8591     break;
8592   }
8593   case ARM::t2MOVr: {
8594     // If we can use the 16-bit encoding and the user didn't explicitly
8595     // request the 32-bit variant, transform it here.
8596     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8597         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8598         Inst.getOperand(2).getImm() == ARMCC::AL &&
8599         Inst.getOperand(4).getReg() == ARM::CPSR &&
8600         !HasWideQualifier) {
8601       // The operands aren't the same for tMOV[S]r... (no cc_out)
8602       MCInst TmpInst;
8603       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8604       TmpInst.addOperand(Inst.getOperand(0));
8605       TmpInst.addOperand(Inst.getOperand(1));
8606       TmpInst.addOperand(Inst.getOperand(2));
8607       TmpInst.addOperand(Inst.getOperand(3));
8608       Inst = TmpInst;
8609       return true;
8610     }
8611     break;
8612   }
8613   case ARM::t2SXTH:
8614   case ARM::t2SXTB:
8615   case ARM::t2UXTH:
8616   case ARM::t2UXTB: {
8617     // If we can use the 16-bit encoding and the user didn't explicitly
8618     // request the 32-bit variant, transform it here.
8619     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8620         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8621         Inst.getOperand(2).getImm() == 0 &&
8622         !HasWideQualifier) {
8623       unsigned NewOpc;
8624       switch (Inst.getOpcode()) {
8625       default: llvm_unreachable("Illegal opcode!");
8626       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8627       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8628       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8629       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8630       }
8631       // The operands aren't the same for thumb1 (no rotate operand).
8632       MCInst TmpInst;
8633       TmpInst.setOpcode(NewOpc);
8634       TmpInst.addOperand(Inst.getOperand(0));
8635       TmpInst.addOperand(Inst.getOperand(1));
8636       TmpInst.addOperand(Inst.getOperand(3));
8637       TmpInst.addOperand(Inst.getOperand(4));
8638       Inst = TmpInst;
8639       return true;
8640     }
8641     break;
8642   }
8643   case ARM::MOVsi: {
8644     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8645     // rrx shifts and asr/lsr of #32 is encoded as 0
8646     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr) 
8647       return false;
8648     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8649       // Shifting by zero is accepted as a vanilla 'MOVr'
8650       MCInst TmpInst;
8651       TmpInst.setOpcode(ARM::MOVr);
8652       TmpInst.addOperand(Inst.getOperand(0));
8653       TmpInst.addOperand(Inst.getOperand(1));
8654       TmpInst.addOperand(Inst.getOperand(3));
8655       TmpInst.addOperand(Inst.getOperand(4));
8656       TmpInst.addOperand(Inst.getOperand(5));
8657       Inst = TmpInst;
8658       return true;
8659     }
8660     return false;
8661   }
8662   case ARM::ANDrsi:
8663   case ARM::ORRrsi:
8664   case ARM::EORrsi:
8665   case ARM::BICrsi:
8666   case ARM::SUBrsi:
8667   case ARM::ADDrsi: {
8668     unsigned newOpc;
8669     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8670     if (SOpc == ARM_AM::rrx) return false;
8671     switch (Inst.getOpcode()) {
8672     default: llvm_unreachable("unexpected opcode!");
8673     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8674     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8675     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8676     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8677     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8678     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8679     }
8680     // If the shift is by zero, use the non-shifted instruction definition.
8681     // The exception is for right shifts, where 0 == 32
8682     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8683         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8684       MCInst TmpInst;
8685       TmpInst.setOpcode(newOpc);
8686       TmpInst.addOperand(Inst.getOperand(0));
8687       TmpInst.addOperand(Inst.getOperand(1));
8688       TmpInst.addOperand(Inst.getOperand(2));
8689       TmpInst.addOperand(Inst.getOperand(4));
8690       TmpInst.addOperand(Inst.getOperand(5));
8691       TmpInst.addOperand(Inst.getOperand(6));
8692       Inst = TmpInst;
8693       return true;
8694     }
8695     return false;
8696   }
8697   case ARM::ITasm:
8698   case ARM::t2IT: {
8699     MCOperand &MO = Inst.getOperand(1);
8700     unsigned Mask = MO.getImm();
8701     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8702
8703     // Set up the IT block state according to the IT instruction we just
8704     // matched.
8705     assert(!inITBlock() && "nested IT blocks?!");
8706     startExplicitITBlock(Cond, Mask);
8707     MO.setImm(getITMaskEncoding());
8708     break;
8709   }
8710   case ARM::t2LSLrr:
8711   case ARM::t2LSRrr:
8712   case ARM::t2ASRrr:
8713   case ARM::t2SBCrr:
8714   case ARM::t2RORrr:
8715   case ARM::t2BICrr:
8716   {
8717     // Assemblers should use the narrow encodings of these instructions when permissible.
8718     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8719          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8720         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8721         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8722         !HasWideQualifier) {
8723       unsigned NewOpc;
8724       switch (Inst.getOpcode()) {
8725         default: llvm_unreachable("unexpected opcode");
8726         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8727         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8728         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8729         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8730         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8731         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8732       }
8733       MCInst TmpInst;
8734       TmpInst.setOpcode(NewOpc);
8735       TmpInst.addOperand(Inst.getOperand(0));
8736       TmpInst.addOperand(Inst.getOperand(5));
8737       TmpInst.addOperand(Inst.getOperand(1));
8738       TmpInst.addOperand(Inst.getOperand(2));
8739       TmpInst.addOperand(Inst.getOperand(3));
8740       TmpInst.addOperand(Inst.getOperand(4));
8741       Inst = TmpInst;
8742       return true;
8743     }
8744     return false;
8745   }
8746   case ARM::t2ANDrr:
8747   case ARM::t2EORrr:
8748   case ARM::t2ADCrr:
8749   case ARM::t2ORRrr:
8750   {
8751     // Assemblers should use the narrow encodings of these instructions when permissible.
8752     // These instructions are special in that they are commutable, so shorter encodings
8753     // are available more often.
8754     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8755          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8756         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8757          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8758         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8759         !HasWideQualifier) {
8760       unsigned NewOpc;
8761       switch (Inst.getOpcode()) {
8762         default: llvm_unreachable("unexpected opcode");
8763         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8764         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8765         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8766         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8767       }
8768       MCInst TmpInst;
8769       TmpInst.setOpcode(NewOpc);
8770       TmpInst.addOperand(Inst.getOperand(0));
8771       TmpInst.addOperand(Inst.getOperand(5));
8772       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8773         TmpInst.addOperand(Inst.getOperand(1));
8774         TmpInst.addOperand(Inst.getOperand(2));
8775       } else {
8776         TmpInst.addOperand(Inst.getOperand(2));
8777         TmpInst.addOperand(Inst.getOperand(1));
8778       }
8779       TmpInst.addOperand(Inst.getOperand(3));
8780       TmpInst.addOperand(Inst.getOperand(4));
8781       Inst = TmpInst;
8782       return true;
8783     }
8784     return false;
8785   }
8786   }
8787   return false;
8788 }
8789
8790 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8791   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8792   // suffix depending on whether they're in an IT block or not.
8793   unsigned Opc = Inst.getOpcode();
8794   const MCInstrDesc &MCID = MII.get(Opc);
8795   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8796     assert(MCID.hasOptionalDef() &&
8797            "optionally flag setting instruction missing optional def operand");
8798     assert(MCID.NumOperands == Inst.getNumOperands() &&
8799            "operand count mismatch!");
8800     // Find the optional-def operand (cc_out).
8801     unsigned OpNo;
8802     for (OpNo = 0;
8803          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8804          ++OpNo)
8805       ;
8806     // If we're parsing Thumb1, reject it completely.
8807     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8808       return Match_RequiresFlagSetting;
8809     // If we're parsing Thumb2, which form is legal depends on whether we're
8810     // in an IT block.
8811     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8812         !inITBlock())
8813       return Match_RequiresITBlock;
8814     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8815         inITBlock())
8816       return Match_RequiresNotITBlock;
8817     // LSL with zero immediate is not allowed in an IT block
8818     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8819       return Match_RequiresNotITBlock;
8820   } else if (isThumbOne()) {
8821     // Some high-register supporting Thumb1 encodings only allow both registers
8822     // to be from r0-r7 when in Thumb2.
8823     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8824         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8825         isARMLowRegister(Inst.getOperand(2).getReg()))
8826       return Match_RequiresThumb2;
8827     // Others only require ARMv6 or later.
8828     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8829              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8830              isARMLowRegister(Inst.getOperand(1).getReg()))
8831       return Match_RequiresV6;
8832   }
8833
8834   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8835   // than the loop below can handle, so it uses the GPRnopc register class and
8836   // we do SP handling here.
8837   if (Opc == ARM::t2MOVr && !hasV8Ops())
8838   {
8839     // SP as both source and destination is not allowed
8840     if (Inst.getOperand(0).getReg() == ARM::SP &&
8841         Inst.getOperand(1).getReg() == ARM::SP)
8842       return Match_RequiresV8;
8843     // When flags-setting SP as either source or destination is not allowed
8844     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8845         (Inst.getOperand(0).getReg() == ARM::SP ||
8846          Inst.getOperand(1).getReg() == ARM::SP))
8847       return Match_RequiresV8;
8848   }
8849
8850   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8851     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8852       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8853       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8854         return Match_RequiresV8;
8855       else if (Inst.getOperand(I).getReg() == ARM::PC)
8856         return Match_InvalidOperand;
8857     }
8858
8859   return Match_Success;
8860 }
8861
8862 namespace llvm {
8863 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8864   return true; // In an assembly source, no need to second-guess
8865 }
8866 }
8867
8868 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8869 // the last instruction in the block.
8870 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8871   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8872
8873   // All branch & call instructions terminate IT blocks.
8874   if (MCID.isTerminator() || MCID.isCall() || MCID.isReturn() ||
8875       MCID.isBranch() || MCID.isIndirectBranch())
8876     return true;
8877
8878   // Any arithmetic instruction which writes to the PC also terminates the IT
8879   // block.
8880   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8881     MCOperand &Op = Inst.getOperand(OpIdx);
8882     if (Op.isReg() && Op.getReg() == ARM::PC)
8883       return true;
8884   }
8885
8886   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8887     return true;
8888
8889   // Instructions with variable operand lists, which write to the variable
8890   // operands. We only care about Thumb instructions here, as ARM instructions
8891   // obviously can't be in an IT block.
8892   switch (Inst.getOpcode()) {
8893   case ARM::tLDMIA:
8894   case ARM::t2LDMIA:
8895   case ARM::t2LDMIA_UPD:
8896   case ARM::t2LDMDB:
8897   case ARM::t2LDMDB_UPD:
8898     if (listContainsReg(Inst, 3, ARM::PC))
8899       return true;
8900     break;
8901   case ARM::tPOP:
8902     if (listContainsReg(Inst, 2, ARM::PC))
8903       return true;
8904     break;
8905   }
8906
8907   return false;
8908 }
8909
8910 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8911                                           uint64_t &ErrorInfo,
8912                                           bool MatchingInlineAsm,
8913                                           bool &EmitInITBlock,
8914                                           MCStreamer &Out) {
8915   // If we can't use an implicit IT block here, just match as normal.
8916   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8917     return MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8918
8919   // Try to match the instruction in an extension of the current IT block (if
8920   // there is one).
8921   if (inImplicitITBlock()) {
8922     extendImplicitITBlock(ITState.Cond);
8923     if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8924             Match_Success) {
8925       // The match succeded, but we still have to check that the instruction is
8926       // valid in this implicit IT block.
8927       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8928       if (MCID.isPredicable()) {
8929         ARMCC::CondCodes InstCond =
8930             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8931                 .getImm();
8932         ARMCC::CondCodes ITCond = currentITCond();
8933         if (InstCond == ITCond) {
8934           EmitInITBlock = true;
8935           return Match_Success;
8936         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
8937           invertCurrentITCondition();
8938           EmitInITBlock = true;
8939           return Match_Success;
8940         }
8941       }
8942     }
8943     rewindImplicitITPosition();
8944   }
8945
8946   // Finish the current IT block, and try to match outside any IT block.
8947   flushPendingInstructions(Out);
8948   unsigned PlainMatchResult =
8949       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8950   if (PlainMatchResult == Match_Success) {
8951     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8952     if (MCID.isPredicable()) {
8953       ARMCC::CondCodes InstCond =
8954           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8955               .getImm();
8956       // Some forms of the branch instruction have their own condition code
8957       // fields, so can be conditionally executed without an IT block.
8958       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
8959         EmitInITBlock = false;
8960         return Match_Success;
8961       }
8962       if (InstCond == ARMCC::AL) {
8963         EmitInITBlock = false;
8964         return Match_Success;
8965       }
8966     } else {
8967       EmitInITBlock = false;
8968       return Match_Success;
8969     }
8970   }
8971
8972   // Try to match in a new IT block. The matcher doesn't check the actual
8973   // condition, so we create an IT block with a dummy condition, and fix it up
8974   // once we know the actual condition.
8975   startImplicitITBlock();
8976   if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8977       Match_Success) {
8978     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8979     if (MCID.isPredicable()) {
8980       ITState.Cond =
8981           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8982               .getImm();
8983       EmitInITBlock = true;
8984       return Match_Success;
8985     }
8986   }
8987   discardImplicitITBlock();
8988
8989   // If none of these succeed, return the error we got when trying to match
8990   // outside any IT blocks.
8991   EmitInITBlock = false;
8992   return PlainMatchResult;
8993 }
8994
8995 static const char *getSubtargetFeatureName(uint64_t Val);
8996 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8997                                            OperandVector &Operands,
8998                                            MCStreamer &Out, uint64_t &ErrorInfo,
8999                                            bool MatchingInlineAsm) {
9000   MCInst Inst;
9001   unsigned MatchResult;
9002   bool PendConditionalInstruction = false;
9003
9004   MatchResult = MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm,
9005                                  PendConditionalInstruction, Out);
9006
9007   SMLoc ErrorLoc;
9008   if (ErrorInfo < Operands.size()) {
9009     ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9010     if (ErrorLoc == SMLoc())
9011       ErrorLoc = IDLoc;
9012   }
9013
9014   switch (MatchResult) {
9015   case Match_Success:
9016     // Context sensitive operand constraints aren't handled by the matcher,
9017     // so check them here.
9018     if (validateInstruction(Inst, Operands)) {
9019       // Still progress the IT block, otherwise one wrong condition causes
9020       // nasty cascading errors.
9021       forwardITPosition();
9022       return true;
9023     }
9024
9025     { // processInstruction() updates inITBlock state, we need to save it away
9026       bool wasInITBlock = inITBlock();
9027
9028       // Some instructions need post-processing to, for example, tweak which
9029       // encoding is selected. Loop on it while changes happen so the
9030       // individual transformations can chain off each other. E.g.,
9031       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9032       while (processInstruction(Inst, Operands, Out))
9033         ;
9034
9035       // Only after the instruction is fully processed, we can validate it
9036       if (wasInITBlock && hasV8Ops() && isThumb() &&
9037           !isV8EligibleForIT(&Inst)) {
9038         Warning(IDLoc, "deprecated instruction in IT block");
9039       }
9040     }
9041
9042     // Only move forward at the very end so that everything in validate
9043     // and process gets a consistent answer about whether we're in an IT
9044     // block.
9045     forwardITPosition();
9046
9047     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9048     // doesn't actually encode.
9049     if (Inst.getOpcode() == ARM::ITasm)
9050       return false;
9051
9052     Inst.setLoc(IDLoc);
9053     if (PendConditionalInstruction) {
9054       PendingConditionalInsts.push_back(Inst);
9055       if (isITBlockFull() || isITBlockTerminator(Inst))
9056         flushPendingInstructions(Out);
9057     } else {
9058       Out.EmitInstruction(Inst, getSTI());
9059     }
9060     return false;
9061   case Match_MissingFeature: {
9062     assert(ErrorInfo && "Unknown missing feature!");
9063     // Special case the error message for the very common case where only
9064     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
9065     std::string Msg = "instruction requires:";
9066     uint64_t Mask = 1;
9067     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
9068       if (ErrorInfo & Mask) {
9069         Msg += " ";
9070         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
9071       }
9072       Mask <<= 1;
9073     }
9074     return Error(IDLoc, Msg);
9075   }
9076   case Match_InvalidOperand: {
9077     SMLoc ErrorLoc = IDLoc;
9078     if (ErrorInfo != ~0ULL) {
9079       if (ErrorInfo >= Operands.size())
9080         return Error(IDLoc, "too few operands for instruction");
9081
9082       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9083       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9084     }
9085
9086     return Error(ErrorLoc, "invalid operand for instruction");
9087   }
9088   case Match_MnemonicFail:
9089     return Error(IDLoc, "invalid instruction",
9090                  ((ARMOperand &)*Operands[0]).getLocRange());
9091   case Match_RequiresNotITBlock:
9092     return Error(IDLoc, "flag setting instruction only valid outside IT block");
9093   case Match_RequiresITBlock:
9094     return Error(IDLoc, "instruction only valid inside IT block");
9095   case Match_RequiresV6:
9096     return Error(IDLoc, "instruction variant requires ARMv6 or later");
9097   case Match_RequiresThumb2:
9098     return Error(IDLoc, "instruction variant requires Thumb2");
9099   case Match_RequiresV8:
9100     return Error(IDLoc, "instruction variant requires ARMv8 or later");
9101   case Match_RequiresFlagSetting:
9102     return Error(IDLoc, "no flag-preserving variant of this instruction available");
9103   case Match_ImmRange0_1:
9104     return Error(ErrorLoc, "immediate operand must be in the range [0,1]");
9105   case Match_ImmRange0_3:
9106     return Error(ErrorLoc, "immediate operand must be in the range [0,3]");
9107   case Match_ImmRange0_7:
9108     return Error(ErrorLoc, "immediate operand must be in the range [0,7]");
9109   case Match_ImmRange0_15:
9110     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
9111   case Match_ImmRange0_31:
9112     return Error(ErrorLoc, "immediate operand must be in the range [0,31]");
9113   case Match_ImmRange0_32:
9114     return Error(ErrorLoc, "immediate operand must be in the range [0,32]");
9115   case Match_ImmRange0_63:
9116     return Error(ErrorLoc, "immediate operand must be in the range [0,63]");
9117   case Match_ImmRange0_239:
9118     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
9119   case Match_ImmRange0_255:
9120     return Error(ErrorLoc, "immediate operand must be in the range [0,255]");
9121   case Match_ImmRange0_4095:
9122     return Error(ErrorLoc, "immediate operand must be in the range [0,4095]");
9123   case Match_ImmRange0_65535:
9124     return Error(ErrorLoc, "immediate operand must be in the range [0,65535]");
9125   case Match_ImmRange1_7:
9126     return Error(ErrorLoc, "immediate operand must be in the range [1,7]");
9127   case Match_ImmRange1_8:
9128     return Error(ErrorLoc, "immediate operand must be in the range [1,8]");
9129   case Match_ImmRange1_15:
9130     return Error(ErrorLoc, "immediate operand must be in the range [1,15]");
9131   case Match_ImmRange1_16:
9132     return Error(ErrorLoc, "immediate operand must be in the range [1,16]");
9133   case Match_ImmRange1_31:
9134     return Error(ErrorLoc, "immediate operand must be in the range [1,31]");
9135   case Match_ImmRange1_32:
9136     return Error(ErrorLoc, "immediate operand must be in the range [1,32]");
9137   case Match_ImmRange1_64:
9138     return Error(ErrorLoc, "immediate operand must be in the range [1,64]");
9139   case Match_ImmRange8_8:
9140     return Error(ErrorLoc, "immediate operand must be 8.");
9141   case Match_ImmRange16_16:
9142     return Error(ErrorLoc, "immediate operand must be 16.");
9143   case Match_ImmRange32_32:
9144     return Error(ErrorLoc, "immediate operand must be 32.");
9145   case Match_ImmRange256_65535:
9146     return Error(ErrorLoc, "immediate operand must be in the range [255,65535]");
9147   case Match_ImmRange0_16777215:
9148     return Error(ErrorLoc, "immediate operand must be in the range [0,0xffffff]");
9149   case Match_AlignedMemoryRequiresNone:
9150   case Match_DupAlignedMemoryRequiresNone:
9151   case Match_AlignedMemoryRequires16:
9152   case Match_DupAlignedMemoryRequires16:
9153   case Match_AlignedMemoryRequires32:
9154   case Match_DupAlignedMemoryRequires32:
9155   case Match_AlignedMemoryRequires64:
9156   case Match_DupAlignedMemoryRequires64:
9157   case Match_AlignedMemoryRequires64or128:
9158   case Match_DupAlignedMemoryRequires64or128:
9159   case Match_AlignedMemoryRequires64or128or256:
9160   {
9161     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
9162     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9163     switch (MatchResult) {
9164       default:
9165         llvm_unreachable("Missing Match_Aligned type");
9166       case Match_AlignedMemoryRequiresNone:
9167       case Match_DupAlignedMemoryRequiresNone:
9168         return Error(ErrorLoc, "alignment must be omitted");
9169       case Match_AlignedMemoryRequires16:
9170       case Match_DupAlignedMemoryRequires16:
9171         return Error(ErrorLoc, "alignment must be 16 or omitted");
9172       case Match_AlignedMemoryRequires32:
9173       case Match_DupAlignedMemoryRequires32:
9174         return Error(ErrorLoc, "alignment must be 32 or omitted");
9175       case Match_AlignedMemoryRequires64:
9176       case Match_DupAlignedMemoryRequires64:
9177         return Error(ErrorLoc, "alignment must be 64 or omitted");
9178       case Match_AlignedMemoryRequires64or128:
9179       case Match_DupAlignedMemoryRequires64or128:
9180         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
9181       case Match_AlignedMemoryRequires64or128or256:
9182         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
9183     }
9184   }
9185   }
9186
9187   llvm_unreachable("Implement any new match types added!");
9188 }
9189
9190 /// parseDirective parses the arm specific directives
9191 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9192   const MCObjectFileInfo::Environment Format =
9193     getContext().getObjectFileInfo()->getObjectFileType();
9194   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9195   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9196
9197   StringRef IDVal = DirectiveID.getIdentifier();
9198   if (IDVal == ".word")
9199     parseLiteralValues(4, DirectiveID.getLoc());
9200   else if (IDVal == ".short" || IDVal == ".hword")
9201     parseLiteralValues(2, DirectiveID.getLoc());
9202   else if (IDVal == ".thumb")
9203     parseDirectiveThumb(DirectiveID.getLoc());
9204   else if (IDVal == ".arm")
9205     parseDirectiveARM(DirectiveID.getLoc());
9206   else if (IDVal == ".thumb_func")
9207     parseDirectiveThumbFunc(DirectiveID.getLoc());
9208   else if (IDVal == ".code")
9209     parseDirectiveCode(DirectiveID.getLoc());
9210   else if (IDVal == ".syntax")
9211     parseDirectiveSyntax(DirectiveID.getLoc());
9212   else if (IDVal == ".unreq")
9213     parseDirectiveUnreq(DirectiveID.getLoc());
9214   else if (IDVal == ".fnend")
9215     parseDirectiveFnEnd(DirectiveID.getLoc());
9216   else if (IDVal == ".cantunwind")
9217     parseDirectiveCantUnwind(DirectiveID.getLoc());
9218   else if (IDVal == ".personality")
9219     parseDirectivePersonality(DirectiveID.getLoc());
9220   else if (IDVal == ".handlerdata")
9221     parseDirectiveHandlerData(DirectiveID.getLoc());
9222   else if (IDVal == ".setfp")
9223     parseDirectiveSetFP(DirectiveID.getLoc());
9224   else if (IDVal == ".pad")
9225     parseDirectivePad(DirectiveID.getLoc());
9226   else if (IDVal == ".save")
9227     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9228   else if (IDVal == ".vsave")
9229     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9230   else if (IDVal == ".ltorg" || IDVal == ".pool")
9231     parseDirectiveLtorg(DirectiveID.getLoc());
9232   else if (IDVal == ".even")
9233     parseDirectiveEven(DirectiveID.getLoc());
9234   else if (IDVal == ".personalityindex")
9235     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9236   else if (IDVal == ".unwind_raw")
9237     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9238   else if (IDVal == ".movsp")
9239     parseDirectiveMovSP(DirectiveID.getLoc());
9240   else if (IDVal == ".arch_extension")
9241     parseDirectiveArchExtension(DirectiveID.getLoc());
9242   else if (IDVal == ".align")
9243     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9244   else if (IDVal == ".thumb_set")
9245     parseDirectiveThumbSet(DirectiveID.getLoc());
9246   else if (!IsMachO && !IsCOFF) {
9247     if (IDVal == ".arch")
9248       parseDirectiveArch(DirectiveID.getLoc());
9249     else if (IDVal == ".cpu")
9250       parseDirectiveCPU(DirectiveID.getLoc());
9251     else if (IDVal == ".eabi_attribute")
9252       parseDirectiveEabiAttr(DirectiveID.getLoc());
9253     else if (IDVal == ".fpu")
9254       parseDirectiveFPU(DirectiveID.getLoc());
9255     else if (IDVal == ".fnstart")
9256       parseDirectiveFnStart(DirectiveID.getLoc());
9257     else if (IDVal == ".inst")
9258       parseDirectiveInst(DirectiveID.getLoc());
9259     else if (IDVal == ".inst.n")
9260       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9261     else if (IDVal == ".inst.w")
9262       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9263     else if (IDVal == ".object_arch")
9264       parseDirectiveObjectArch(DirectiveID.getLoc());
9265     else if (IDVal == ".tlsdescseq")
9266       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9267     else
9268       return true;
9269   } else
9270     return true;
9271   return false;
9272 }
9273
9274 /// parseLiteralValues
9275 ///  ::= .hword expression [, expression]*
9276 ///  ::= .short expression [, expression]*
9277 ///  ::= .word expression [, expression]*
9278 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9279   auto parseOne = [&]() -> bool {
9280     const MCExpr *Value;
9281     if (getParser().parseExpression(Value))
9282       return true;
9283     getParser().getStreamer().EmitValue(Value, Size, L);
9284     return false;
9285   };
9286   return (parseMany(parseOne));
9287 }
9288
9289 /// parseDirectiveThumb
9290 ///  ::= .thumb
9291 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9292   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9293       check(!hasThumb(), L, "target does not support Thumb mode"))
9294     return true;
9295
9296   if (!isThumb())
9297     SwitchMode();
9298
9299   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9300   return false;
9301 }
9302
9303 /// parseDirectiveARM
9304 ///  ::= .arm
9305 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9306   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9307       check(!hasARM(), L, "target does not support ARM mode"))
9308     return true;
9309
9310   if (isThumb())
9311     SwitchMode();
9312   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9313   return false;
9314 }
9315
9316 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9317   // We need to flush the current implicit IT block on a label, because it is
9318   // not legal to branch into an IT block.
9319   flushPendingInstructions(getStreamer());
9320   if (NextSymbolIsThumb) {
9321     getParser().getStreamer().EmitThumbFunc(Symbol);
9322     NextSymbolIsThumb = false;
9323   }
9324 }
9325
9326 /// parseDirectiveThumbFunc
9327 ///  ::= .thumbfunc symbol_name
9328 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9329   MCAsmParser &Parser = getParser();
9330   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9331   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9332
9333   // Darwin asm has (optionally) function name after .thumb_func direction
9334   // ELF doesn't
9335
9336   if (IsMachO) {
9337     if (Parser.getTok().is(AsmToken::Identifier) ||
9338         Parser.getTok().is(AsmToken::String)) {
9339       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9340           Parser.getTok().getIdentifier());
9341       getParser().getStreamer().EmitThumbFunc(Func);
9342       Parser.Lex();
9343       if (parseToken(AsmToken::EndOfStatement,
9344                      "unexpected token in '.thumb_func' directive"))
9345         return true;
9346       return false;
9347     }
9348   }
9349
9350   if (parseToken(AsmToken::EndOfStatement,
9351                  "unexpected token in '.thumb_func' directive"))
9352     return true;
9353
9354   NextSymbolIsThumb = true;
9355   return false;
9356 }
9357
9358 /// parseDirectiveSyntax
9359 ///  ::= .syntax unified | divided
9360 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9361   MCAsmParser &Parser = getParser();
9362   const AsmToken &Tok = Parser.getTok();
9363   if (Tok.isNot(AsmToken::Identifier)) {
9364     Error(L, "unexpected token in .syntax directive");
9365     return false;
9366   }
9367
9368   StringRef Mode = Tok.getString();
9369   Parser.Lex();
9370   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9371             "'.syntax divided' arm assembly not supported") ||
9372       check(Mode != "unified" && Mode != "UNIFIED", L,
9373             "unrecognized syntax mode in .syntax directive") ||
9374       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9375     return true;
9376
9377   // TODO tell the MC streamer the mode
9378   // getParser().getStreamer().Emit???();
9379   return false;
9380 }
9381
9382 /// parseDirectiveCode
9383 ///  ::= .code 16 | 32
9384 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9385   MCAsmParser &Parser = getParser();
9386   const AsmToken &Tok = Parser.getTok();
9387   if (Tok.isNot(AsmToken::Integer))
9388     return Error(L, "unexpected token in .code directive");
9389   int64_t Val = Parser.getTok().getIntVal();
9390   if (Val != 16 && Val != 32) {
9391     Error(L, "invalid operand to .code directive");
9392     return false;
9393   }
9394   Parser.Lex();
9395
9396   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9397     return true;
9398
9399   if (Val == 16) {
9400     if (!hasThumb())
9401       return Error(L, "target does not support Thumb mode");
9402
9403     if (!isThumb())
9404       SwitchMode();
9405     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9406   } else {
9407     if (!hasARM())
9408       return Error(L, "target does not support ARM mode");
9409
9410     if (isThumb())
9411       SwitchMode();
9412     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9413   }
9414
9415   return false;
9416 }
9417
9418 /// parseDirectiveReq
9419 ///  ::= name .req registername
9420 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9421   MCAsmParser &Parser = getParser();
9422   Parser.Lex(); // Eat the '.req' token.
9423   unsigned Reg;
9424   SMLoc SRegLoc, ERegLoc;
9425   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9426             "register name expected") ||
9427       parseToken(AsmToken::EndOfStatement,
9428                  "unexpected input in .req directive."))
9429     return true;
9430
9431   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9432     return Error(SRegLoc,
9433                  "redefinition of '" + Name + "' does not match original.");
9434
9435   return false;
9436 }
9437
9438 /// parseDirectiveUneq
9439 ///  ::= .unreq registername
9440 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9441   MCAsmParser &Parser = getParser();
9442   if (Parser.getTok().isNot(AsmToken::Identifier))
9443     return Error(L, "unexpected input in .unreq directive.");
9444   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9445   Parser.Lex(); // Eat the identifier.
9446   if (parseToken(AsmToken::EndOfStatement,
9447                  "unexpected input in '.unreq' directive"))
9448     return true;
9449   return false;
9450 }
9451
9452 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9453 // before, if supported by the new target, or emit mapping symbols for the mode
9454 // switch.
9455 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9456   if (WasThumb != isThumb()) {
9457     if (WasThumb && hasThumb()) {
9458       // Stay in Thumb mode
9459       SwitchMode();
9460     } else if (!WasThumb && hasARM()) {
9461       // Stay in ARM mode
9462       SwitchMode();
9463     } else {
9464       // Mode switch forced, because the new arch doesn't support the old mode.
9465       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9466                                                             : MCAF_Code32);
9467       // Warn about the implcit mode switch. GAS does not switch modes here,
9468       // but instead stays in the old mode, reporting an error on any following
9469       // instructions as the mode does not exist on the target.
9470       Warning(Loc, Twine("new target does not support ") +
9471                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9472                        (!WasThumb ? "thumb" : "arm") + " mode");
9473     }
9474   }
9475 }
9476
9477 /// parseDirectiveArch
9478 ///  ::= .arch token
9479 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9480   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9481   unsigned ID = ARM::parseArch(Arch);
9482
9483   if (ID == ARM::AK_INVALID)
9484     return Error(L, "Unknown arch name");
9485
9486   bool WasThumb = isThumb();
9487   Triple T;
9488   MCSubtargetInfo &STI = copySTI();
9489   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9490   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9491   FixModeAfterArchChange(WasThumb, L);
9492
9493   getTargetStreamer().emitArch(ID);
9494   return false;
9495 }
9496
9497 /// parseDirectiveEabiAttr
9498 ///  ::= .eabi_attribute int, int [, "str"]
9499 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9500 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9501   MCAsmParser &Parser = getParser();
9502   int64_t Tag;
9503   SMLoc TagLoc;
9504   TagLoc = Parser.getTok().getLoc();
9505   if (Parser.getTok().is(AsmToken::Identifier)) {
9506     StringRef Name = Parser.getTok().getIdentifier();
9507     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9508     if (Tag == -1) {
9509       Error(TagLoc, "attribute name not recognised: " + Name);
9510       return false;
9511     }
9512     Parser.Lex();
9513   } else {
9514     const MCExpr *AttrExpr;
9515
9516     TagLoc = Parser.getTok().getLoc();
9517     if (Parser.parseExpression(AttrExpr))
9518       return true;
9519
9520     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9521     if (check(!CE, TagLoc, "expected numeric constant"))
9522       return true;
9523
9524     Tag = CE->getValue();
9525   }
9526
9527   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9528     return true;
9529
9530   StringRef StringValue = "";
9531   bool IsStringValue = false;
9532
9533   int64_t IntegerValue = 0;
9534   bool IsIntegerValue = false;
9535
9536   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9537     IsStringValue = true;
9538   else if (Tag == ARMBuildAttrs::compatibility) {
9539     IsStringValue = true;
9540     IsIntegerValue = true;
9541   } else if (Tag < 32 || Tag % 2 == 0)
9542     IsIntegerValue = true;
9543   else if (Tag % 2 == 1)
9544     IsStringValue = true;
9545   else
9546     llvm_unreachable("invalid tag type");
9547
9548   if (IsIntegerValue) {
9549     const MCExpr *ValueExpr;
9550     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9551     if (Parser.parseExpression(ValueExpr))
9552       return true;
9553
9554     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9555     if (!CE)
9556       return Error(ValueExprLoc, "expected numeric constant");
9557     IntegerValue = CE->getValue();
9558   }
9559
9560   if (Tag == ARMBuildAttrs::compatibility) {
9561     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9562       return true;
9563   }
9564
9565   if (IsStringValue) {
9566     if (Parser.getTok().isNot(AsmToken::String))
9567       return Error(Parser.getTok().getLoc(), "bad string constant");
9568
9569     StringValue = Parser.getTok().getStringContents();
9570     Parser.Lex();
9571   }
9572
9573   if (Parser.parseToken(AsmToken::EndOfStatement,
9574                         "unexpected token in '.eabi_attribute' directive"))
9575     return true;
9576
9577   if (IsIntegerValue && IsStringValue) {
9578     assert(Tag == ARMBuildAttrs::compatibility);
9579     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9580   } else if (IsIntegerValue)
9581     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9582   else if (IsStringValue)
9583     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9584   return false;
9585 }
9586
9587 /// parseDirectiveCPU
9588 ///  ::= .cpu str
9589 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9590   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9591   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9592
9593   // FIXME: This is using table-gen data, but should be moved to
9594   // ARMTargetParser once that is table-gen'd.
9595   if (!getSTI().isCPUStringValid(CPU))
9596     return Error(L, "Unknown CPU name");
9597
9598   bool WasThumb = isThumb();
9599   MCSubtargetInfo &STI = copySTI();
9600   STI.setDefaultFeatures(CPU, "");
9601   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9602   FixModeAfterArchChange(WasThumb, L);
9603
9604   return false;
9605 }
9606 /// parseDirectiveFPU
9607 ///  ::= .fpu str
9608 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9609   SMLoc FPUNameLoc = getTok().getLoc();
9610   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9611
9612   unsigned ID = ARM::parseFPU(FPU);
9613   std::vector<StringRef> Features;
9614   if (!ARM::getFPUFeatures(ID, Features))
9615     return Error(FPUNameLoc, "Unknown FPU name");
9616
9617   MCSubtargetInfo &STI = copySTI();
9618   for (auto Feature : Features)
9619     STI.ApplyFeatureFlag(Feature);
9620   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9621
9622   getTargetStreamer().emitFPU(ID);
9623   return false;
9624 }
9625
9626 /// parseDirectiveFnStart
9627 ///  ::= .fnstart
9628 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9629   if (parseToken(AsmToken::EndOfStatement,
9630                  "unexpected token in '.fnstart' directive"))
9631     return true;
9632
9633   if (UC.hasFnStart()) {
9634     Error(L, ".fnstart starts before the end of previous one");
9635     UC.emitFnStartLocNotes();
9636     return true;
9637   }
9638
9639   // Reset the unwind directives parser state
9640   UC.reset();
9641
9642   getTargetStreamer().emitFnStart();
9643
9644   UC.recordFnStart(L);
9645   return false;
9646 }
9647
9648 /// parseDirectiveFnEnd
9649 ///  ::= .fnend
9650 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9651   if (parseToken(AsmToken::EndOfStatement,
9652                  "unexpected token in '.fnend' directive"))
9653     return true;
9654   // Check the ordering of unwind directives
9655   if (!UC.hasFnStart())
9656     return Error(L, ".fnstart must precede .fnend directive");
9657
9658   // Reset the unwind directives parser state
9659   getTargetStreamer().emitFnEnd();
9660
9661   UC.reset();
9662   return false;
9663 }
9664
9665 /// parseDirectiveCantUnwind
9666 ///  ::= .cantunwind
9667 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9668   if (parseToken(AsmToken::EndOfStatement,
9669                  "unexpected token in '.cantunwind' directive"))
9670     return true;
9671
9672   UC.recordCantUnwind(L);
9673   // Check the ordering of unwind directives
9674   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9675     return true;
9676
9677   if (UC.hasHandlerData()) {
9678     Error(L, ".cantunwind can't be used with .handlerdata directive");
9679     UC.emitHandlerDataLocNotes();
9680     return true;
9681   }
9682   if (UC.hasPersonality()) {
9683     Error(L, ".cantunwind can't be used with .personality directive");
9684     UC.emitPersonalityLocNotes();
9685     return true;
9686   }
9687
9688   getTargetStreamer().emitCantUnwind();
9689   return false;
9690 }
9691
9692 /// parseDirectivePersonality
9693 ///  ::= .personality name
9694 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9695   MCAsmParser &Parser = getParser();
9696   bool HasExistingPersonality = UC.hasPersonality();
9697
9698   // Parse the name of the personality routine
9699   if (Parser.getTok().isNot(AsmToken::Identifier))
9700     return Error(L, "unexpected input in .personality directive.");
9701   StringRef Name(Parser.getTok().getIdentifier());
9702   Parser.Lex();
9703
9704   if (parseToken(AsmToken::EndOfStatement,
9705                  "unexpected token in '.personality' directive"))
9706     return true;
9707
9708   UC.recordPersonality(L);
9709
9710   // Check the ordering of unwind directives
9711   if (!UC.hasFnStart())
9712     return Error(L, ".fnstart must precede .personality directive");
9713   if (UC.cantUnwind()) {
9714     Error(L, ".personality can't be used with .cantunwind directive");
9715     UC.emitCantUnwindLocNotes();
9716     return true;
9717   }
9718   if (UC.hasHandlerData()) {
9719     Error(L, ".personality must precede .handlerdata directive");
9720     UC.emitHandlerDataLocNotes();
9721     return true;
9722   }
9723   if (HasExistingPersonality) {
9724     Error(L, "multiple personality directives");
9725     UC.emitPersonalityLocNotes();
9726     return true;
9727   }
9728
9729   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9730   getTargetStreamer().emitPersonality(PR);
9731   return false;
9732 }
9733
9734 /// parseDirectiveHandlerData
9735 ///  ::= .handlerdata
9736 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9737   if (parseToken(AsmToken::EndOfStatement,
9738                  "unexpected token in '.handlerdata' directive"))
9739     return true;
9740
9741   UC.recordHandlerData(L);
9742   // Check the ordering of unwind directives
9743   if (!UC.hasFnStart())
9744     return Error(L, ".fnstart must precede .personality directive");
9745   if (UC.cantUnwind()) {
9746     Error(L, ".handlerdata can't be used with .cantunwind directive");
9747     UC.emitCantUnwindLocNotes();
9748     return true;
9749   }
9750
9751   getTargetStreamer().emitHandlerData();
9752   return false;
9753 }
9754
9755 /// parseDirectiveSetFP
9756 ///  ::= .setfp fpreg, spreg [, offset]
9757 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9758   MCAsmParser &Parser = getParser();
9759   // Check the ordering of unwind directives
9760   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9761       check(UC.hasHandlerData(), L,
9762             ".setfp must precede .handlerdata directive"))
9763     return true;
9764
9765   // Parse fpreg
9766   SMLoc FPRegLoc = Parser.getTok().getLoc();
9767   int FPReg = tryParseRegister();
9768
9769   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9770       Parser.parseToken(AsmToken::Comma, "comma expected"))
9771     return true;
9772
9773   // Parse spreg
9774   SMLoc SPRegLoc = Parser.getTok().getLoc();
9775   int SPReg = tryParseRegister();
9776   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9777       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9778             "register should be either $sp or the latest fp register"))
9779     return true;
9780
9781   // Update the frame pointer register
9782   UC.saveFPReg(FPReg);
9783
9784   // Parse offset
9785   int64_t Offset = 0;
9786   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9787     if (Parser.getTok().isNot(AsmToken::Hash) &&
9788         Parser.getTok().isNot(AsmToken::Dollar))
9789       return Error(Parser.getTok().getLoc(), "'#' expected");
9790     Parser.Lex(); // skip hash token.
9791
9792     const MCExpr *OffsetExpr;
9793     SMLoc ExLoc = Parser.getTok().getLoc();
9794     SMLoc EndLoc;
9795     if (getParser().parseExpression(OffsetExpr, EndLoc))
9796       return Error(ExLoc, "malformed setfp offset");
9797     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9798     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9799       return true;
9800     Offset = CE->getValue();
9801   }
9802
9803   if (Parser.parseToken(AsmToken::EndOfStatement))
9804     return true;
9805
9806   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9807                                 static_cast<unsigned>(SPReg), Offset);
9808   return false;
9809 }
9810
9811 /// parseDirective
9812 ///  ::= .pad offset
9813 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9814   MCAsmParser &Parser = getParser();
9815   // Check the ordering of unwind directives
9816   if (!UC.hasFnStart())
9817     return Error(L, ".fnstart must precede .pad directive");
9818   if (UC.hasHandlerData())
9819     return Error(L, ".pad must precede .handlerdata directive");
9820
9821   // Parse the offset
9822   if (Parser.getTok().isNot(AsmToken::Hash) &&
9823       Parser.getTok().isNot(AsmToken::Dollar))
9824     return Error(Parser.getTok().getLoc(), "'#' expected");
9825   Parser.Lex(); // skip hash token.
9826
9827   const MCExpr *OffsetExpr;
9828   SMLoc ExLoc = Parser.getTok().getLoc();
9829   SMLoc EndLoc;
9830   if (getParser().parseExpression(OffsetExpr, EndLoc))
9831     return Error(ExLoc, "malformed pad offset");
9832   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9833   if (!CE)
9834     return Error(ExLoc, "pad offset must be an immediate");
9835
9836   if (parseToken(AsmToken::EndOfStatement,
9837                  "unexpected token in '.pad' directive"))
9838     return true;
9839
9840   getTargetStreamer().emitPad(CE->getValue());
9841   return false;
9842 }
9843
9844 /// parseDirectiveRegSave
9845 ///  ::= .save  { registers }
9846 ///  ::= .vsave { registers }
9847 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9848   // Check the ordering of unwind directives
9849   if (!UC.hasFnStart())
9850     return Error(L, ".fnstart must precede .save or .vsave directives");
9851   if (UC.hasHandlerData())
9852     return Error(L, ".save or .vsave must precede .handlerdata directive");
9853
9854   // RAII object to make sure parsed operands are deleted.
9855   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9856
9857   // Parse the register list
9858   if (parseRegisterList(Operands) ||
9859       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9860     return true;
9861   ARMOperand &Op = (ARMOperand &)*Operands[0];
9862   if (!IsVector && !Op.isRegList())
9863     return Error(L, ".save expects GPR registers");
9864   if (IsVector && !Op.isDPRRegList())
9865     return Error(L, ".vsave expects DPR registers");
9866
9867   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9868   return false;
9869 }
9870
9871 /// parseDirectiveInst
9872 ///  ::= .inst opcode [, ...]
9873 ///  ::= .inst.n opcode [, ...]
9874 ///  ::= .inst.w opcode [, ...]
9875 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9876   int Width = 4;
9877
9878   if (isThumb()) {
9879     switch (Suffix) {
9880     case 'n':
9881       Width = 2;
9882       break;
9883     case 'w':
9884       break;
9885     default:
9886       return Error(Loc, "cannot determine Thumb instruction size, "
9887                         "use inst.n/inst.w instead");
9888     }
9889   } else {
9890     if (Suffix)
9891       return Error(Loc, "width suffixes are invalid in ARM mode");
9892   }
9893
9894   auto parseOne = [&]() -> bool {
9895     const MCExpr *Expr;
9896     if (getParser().parseExpression(Expr))
9897       return true;
9898     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9899     if (!Value) {
9900       return Error(Loc, "expected constant expression");
9901     }
9902
9903     switch (Width) {
9904     case 2:
9905       if (Value->getValue() > 0xffff)
9906         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9907       break;
9908     case 4:
9909       if (Value->getValue() > 0xffffffff)
9910         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9911                               " operand is too big");
9912       break;
9913     default:
9914       llvm_unreachable("only supported widths are 2 and 4");
9915     }
9916
9917     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9918     return false;
9919   };
9920
9921   if (parseOptionalToken(AsmToken::EndOfStatement))
9922     return Error(Loc, "expected expression following directive");
9923   if (parseMany(parseOne))
9924     return true;
9925   return false;
9926 }
9927
9928 /// parseDirectiveLtorg
9929 ///  ::= .ltorg | .pool
9930 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9931   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9932     return true;
9933   getTargetStreamer().emitCurrentConstantPool();
9934   return false;
9935 }
9936
9937 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9938   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9939
9940   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9941     return true;
9942
9943   if (!Section) {
9944     getStreamer().InitSections(false);
9945     Section = getStreamer().getCurrentSectionOnly();
9946   }
9947
9948   assert(Section && "must have section to emit alignment");
9949   if (Section->UseCodeAlign())
9950     getStreamer().EmitCodeAlignment(2);
9951   else
9952     getStreamer().EmitValueToAlignment(2);
9953
9954   return false;
9955 }
9956
9957 /// parseDirectivePersonalityIndex
9958 ///   ::= .personalityindex index
9959 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9960   MCAsmParser &Parser = getParser();
9961   bool HasExistingPersonality = UC.hasPersonality();
9962
9963   const MCExpr *IndexExpression;
9964   SMLoc IndexLoc = Parser.getTok().getLoc();
9965   if (Parser.parseExpression(IndexExpression) ||
9966       parseToken(AsmToken::EndOfStatement,
9967                  "unexpected token in '.personalityindex' directive")) {
9968     return true;
9969   }
9970
9971   UC.recordPersonalityIndex(L);
9972
9973   if (!UC.hasFnStart()) {
9974     return Error(L, ".fnstart must precede .personalityindex directive");
9975   }
9976   if (UC.cantUnwind()) {
9977     Error(L, ".personalityindex cannot be used with .cantunwind");
9978     UC.emitCantUnwindLocNotes();
9979     return true;
9980   }
9981   if (UC.hasHandlerData()) {
9982     Error(L, ".personalityindex must precede .handlerdata directive");
9983     UC.emitHandlerDataLocNotes();
9984     return true;
9985   }
9986   if (HasExistingPersonality) {
9987     Error(L, "multiple personality directives");
9988     UC.emitPersonalityLocNotes();
9989     return true;
9990   }
9991
9992   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9993   if (!CE)
9994     return Error(IndexLoc, "index must be a constant number");
9995   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9996     return Error(IndexLoc,
9997                  "personality routine index should be in range [0-3]");
9998
9999   getTargetStreamer().emitPersonalityIndex(CE->getValue());
10000   return false;
10001 }
10002
10003 /// parseDirectiveUnwindRaw
10004 ///   ::= .unwind_raw offset, opcode [, opcode...]
10005 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
10006   MCAsmParser &Parser = getParser();
10007   int64_t StackOffset;
10008   const MCExpr *OffsetExpr;
10009   SMLoc OffsetLoc = getLexer().getLoc();
10010
10011   if (!UC.hasFnStart())
10012     return Error(L, ".fnstart must precede .unwind_raw directives");
10013   if (getParser().parseExpression(OffsetExpr))
10014     return Error(OffsetLoc, "expected expression");
10015
10016   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10017   if (!CE)
10018     return Error(OffsetLoc, "offset must be a constant");
10019
10020   StackOffset = CE->getValue();
10021
10022   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
10023     return true;
10024
10025   SmallVector<uint8_t, 16> Opcodes;
10026
10027   auto parseOne = [&]() -> bool {
10028     const MCExpr *OE;
10029     SMLoc OpcodeLoc = getLexer().getLoc();
10030     if (check(getLexer().is(AsmToken::EndOfStatement) ||
10031                   Parser.parseExpression(OE),
10032               OpcodeLoc, "expected opcode expression"))
10033       return true;
10034     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
10035     if (!OC)
10036       return Error(OpcodeLoc, "opcode value must be a constant");
10037     const int64_t Opcode = OC->getValue();
10038     if (Opcode & ~0xff)
10039       return Error(OpcodeLoc, "invalid opcode");
10040     Opcodes.push_back(uint8_t(Opcode));
10041     return false;
10042   };
10043
10044   // Must have at least 1 element
10045   SMLoc OpcodeLoc = getLexer().getLoc();
10046   if (parseOptionalToken(AsmToken::EndOfStatement))
10047     return Error(OpcodeLoc, "expected opcode expression");
10048   if (parseMany(parseOne))
10049     return true;
10050
10051   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
10052   return false;
10053 }
10054
10055 /// parseDirectiveTLSDescSeq
10056 ///   ::= .tlsdescseq tls-variable
10057 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
10058   MCAsmParser &Parser = getParser();
10059
10060   if (getLexer().isNot(AsmToken::Identifier))
10061     return TokError("expected variable after '.tlsdescseq' directive");
10062
10063   const MCSymbolRefExpr *SRE =
10064     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10065                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10066   Lex();
10067
10068   if (parseToken(AsmToken::EndOfStatement,
10069                  "unexpected token in '.tlsdescseq' directive"))
10070     return true;
10071
10072   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10073   return false;
10074 }
10075
10076 /// parseDirectiveMovSP
10077 ///  ::= .movsp reg [, #offset]
10078 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10079   MCAsmParser &Parser = getParser();
10080   if (!UC.hasFnStart())
10081     return Error(L, ".fnstart must precede .movsp directives");
10082   if (UC.getFPReg() != ARM::SP)
10083     return Error(L, "unexpected .movsp directive");
10084
10085   SMLoc SPRegLoc = Parser.getTok().getLoc();
10086   int SPReg = tryParseRegister();
10087   if (SPReg == -1)
10088     return Error(SPRegLoc, "register expected");
10089   if (SPReg == ARM::SP || SPReg == ARM::PC)
10090     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10091
10092   int64_t Offset = 0;
10093   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10094     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10095       return true;
10096
10097     const MCExpr *OffsetExpr;
10098     SMLoc OffsetLoc = Parser.getTok().getLoc();
10099
10100     if (Parser.parseExpression(OffsetExpr))
10101       return Error(OffsetLoc, "malformed offset expression");
10102
10103     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10104     if (!CE)
10105       return Error(OffsetLoc, "offset must be an immediate constant");
10106
10107     Offset = CE->getValue();
10108   }
10109
10110   if (parseToken(AsmToken::EndOfStatement,
10111                  "unexpected token in '.movsp' directive"))
10112     return true;
10113
10114   getTargetStreamer().emitMovSP(SPReg, Offset);
10115   UC.saveFPReg(SPReg);
10116
10117   return false;
10118 }
10119
10120 /// parseDirectiveObjectArch
10121 ///   ::= .object_arch name
10122 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10123   MCAsmParser &Parser = getParser();
10124   if (getLexer().isNot(AsmToken::Identifier))
10125     return Error(getLexer().getLoc(), "unexpected token");
10126
10127   StringRef Arch = Parser.getTok().getString();
10128   SMLoc ArchLoc = Parser.getTok().getLoc();
10129   Lex();
10130
10131   unsigned ID = ARM::parseArch(Arch);
10132
10133   if (ID == ARM::AK_INVALID)
10134     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10135   if (parseToken(AsmToken::EndOfStatement))
10136     return true;
10137
10138   getTargetStreamer().emitObjectArch(ID);
10139   return false;
10140 }
10141
10142 /// parseDirectiveAlign
10143 ///   ::= .align
10144 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10145   // NOTE: if this is not the end of the statement, fall back to the target
10146   // agnostic handling for this directive which will correctly handle this.
10147   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10148     // '.align' is target specifically handled to mean 2**2 byte alignment.
10149     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10150     assert(Section && "must have section to emit alignment");
10151     if (Section->UseCodeAlign())
10152       getStreamer().EmitCodeAlignment(4, 0);
10153     else
10154       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10155     return false;
10156   }
10157   return true;
10158 }
10159
10160 /// parseDirectiveThumbSet
10161 ///  ::= .thumb_set name, value
10162 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10163   MCAsmParser &Parser = getParser();
10164
10165   StringRef Name;
10166   if (check(Parser.parseIdentifier(Name),
10167             "expected identifier after '.thumb_set'") ||
10168       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10169     return true;
10170
10171   MCSymbol *Sym;
10172   const MCExpr *Value;
10173   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10174                                                Parser, Sym, Value))
10175     return true;
10176
10177   getTargetStreamer().emitThumbSet(Sym, Value);
10178   return false;
10179 }
10180
10181 /// Force static initialization.
10182 extern "C" void LLVMInitializeARMAsmParser() {
10183   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10184   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10185   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10186   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10187 }
10188
10189 #define GET_REGISTER_MATCHER
10190 #define GET_SUBTARGET_FEATURE_NAME
10191 #define GET_MATCHER_IMPLEMENTATION
10192 #include "ARMGenAsmMatcher.inc"
10193
10194 // FIXME: This structure should be moved inside ARMTargetParser
10195 // when we start to table-generate them, and we can use the ARM
10196 // flags below, that were generated by table-gen.
10197 static const struct {
10198   const unsigned Kind;
10199   const uint64_t ArchCheck;
10200   const FeatureBitset Features;
10201 } Extensions[] = {
10202   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10203   { ARM::AEK_CRYPTO,  Feature_HasV8,
10204     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10205   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10206   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10207     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10208   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10209   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10210   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10211   // FIXME: Only available in A-class, isel not predicated
10212   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10213   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10214   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10215   // FIXME: Unsupported extensions.
10216   { ARM::AEK_OS, Feature_None, {} },
10217   { ARM::AEK_IWMMXT, Feature_None, {} },
10218   { ARM::AEK_IWMMXT2, Feature_None, {} },
10219   { ARM::AEK_MAVERICK, Feature_None, {} },
10220   { ARM::AEK_XSCALE, Feature_None, {} },
10221 };
10222
10223 /// parseDirectiveArchExtension
10224 ///   ::= .arch_extension [no]feature
10225 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10226   MCAsmParser &Parser = getParser();
10227
10228   if (getLexer().isNot(AsmToken::Identifier))
10229     return Error(getLexer().getLoc(), "expected architecture extension name");
10230
10231   StringRef Name = Parser.getTok().getString();
10232   SMLoc ExtLoc = Parser.getTok().getLoc();
10233   Lex();
10234
10235   if (parseToken(AsmToken::EndOfStatement,
10236                  "unexpected token in '.arch_extension' directive"))
10237     return true;
10238
10239   bool EnableFeature = true;
10240   if (Name.startswith_lower("no")) {
10241     EnableFeature = false;
10242     Name = Name.substr(2);
10243   }
10244   unsigned FeatureKind = ARM::parseArchExt(Name);
10245   if (FeatureKind == ARM::AEK_INVALID)
10246     return Error(ExtLoc, "unknown architectural extension: " + Name);
10247
10248   for (const auto &Extension : Extensions) {
10249     if (Extension.Kind != FeatureKind)
10250       continue;
10251
10252     if (Extension.Features.none())
10253       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10254
10255     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10256       return Error(ExtLoc, "architectural extension '" + Name +
10257                                "' is not "
10258                                "allowed for the current base architecture");
10259
10260     MCSubtargetInfo &STI = copySTI();
10261     FeatureBitset ToggleFeatures = EnableFeature
10262       ? (~STI.getFeatureBits() & Extension.Features)
10263       : ( STI.getFeatureBits() & Extension.Features);
10264
10265     uint64_t Features =
10266         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10267     setAvailableFeatures(Features);
10268     return false;
10269   }
10270
10271   return Error(ExtLoc, "unknown architectural extension: " + Name);
10272 }
10273
10274 // Define this matcher function after the auto-generated include so we
10275 // have the match class enum definitions.
10276 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10277                                                   unsigned Kind) {
10278   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10279   // If the kind is a token for a literal immediate, check if our asm
10280   // operand matches. This is for InstAliases which have a fixed-value
10281   // immediate in the syntax.
10282   switch (Kind) {
10283   default: break;
10284   case MCK__35_0:
10285     if (Op.isImm())
10286       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10287         if (CE->getValue() == 0)
10288           return Match_Success;
10289     break;
10290   case MCK_ModImm:
10291     if (Op.isImm()) {
10292       const MCExpr *SOExpr = Op.getImm();
10293       int64_t Value;
10294       if (!SOExpr->evaluateAsAbsolute(Value))
10295         return Match_Success;
10296       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
10297              "expression value must be representable in 32 bits");
10298     }
10299     break;
10300   case MCK_rGPR:
10301     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10302       return Match_Success;
10303     break;
10304   case MCK_GPRPair:
10305     if (Op.isReg() &&
10306         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10307       return Match_Success;
10308     break;
10309   }
10310   return Match_InvalidOperand;
10311 }