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/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDisassembler.h"
23 #include "llvm/MC/MCELFStreamer.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCObjectFileInfo.h"
29 #include "llvm/MC/MCParser/MCAsmLexer.h"
30 #include "llvm/MC/MCParser/MCAsmParser.h"
31 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
32 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/MC/MCTargetAsmParser.h"
39 #include "llvm/Support/ARMBuildAttributes.h"
40 #include "llvm/Support/ARMEHABI.h"
41 #include "llvm/Support/TargetParser.h"
42 #include "llvm/Support/COFF.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/raw_ostream.h"
49 
50 using namespace llvm;
51 
52 namespace {
53 
54 class ARMOperand;
55 
56 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
57 
58 class UnwindContext {
59   MCAsmParser &Parser;
60 
61   typedef SmallVector<SMLoc, 4> Locs;
62 
63   Locs FnStartLocs;
64   Locs CantUnwindLocs;
65   Locs PersonalityLocs;
66   Locs PersonalityIndexLocs;
67   Locs HandlerDataLocs;
68   int FPReg;
69 
70 public:
71   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
72 
73   bool hasFnStart() const { return !FnStartLocs.empty(); }
74   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
75   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
76   bool hasPersonality() const {
77     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
78   }
79 
80   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
81   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
82   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
83   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
84   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
85 
86   void saveFPReg(int Reg) { FPReg = Reg; }
87   int getFPReg() const { return FPReg; }
88 
89   void emitFnStartLocNotes() const {
90     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
91          FI != FE; ++FI)
92       Parser.Note(*FI, ".fnstart was specified here");
93   }
94   void emitCantUnwindLocNotes() const {
95     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
96                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
97       Parser.Note(*UI, ".cantunwind was specified here");
98   }
99   void emitHandlerDataLocNotes() const {
100     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
101                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
102       Parser.Note(*HI, ".handlerdata was specified here");
103   }
104   void emitPersonalityLocNotes() const {
105     for (Locs::const_iterator PI = PersonalityLocs.begin(),
106                               PE = PersonalityLocs.end(),
107                               PII = PersonalityIndexLocs.begin(),
108                               PIE = PersonalityIndexLocs.end();
109          PI != PE || PII != PIE;) {
110       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
111         Parser.Note(*PI++, ".personality was specified here");
112       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
113         Parser.Note(*PII++, ".personalityindex was specified here");
114       else
115         llvm_unreachable(".personality and .personalityindex cannot be "
116                          "at the same location");
117     }
118   }
119 
120   void reset() {
121     FnStartLocs = Locs();
122     CantUnwindLocs = Locs();
123     PersonalityLocs = Locs();
124     HandlerDataLocs = Locs();
125     PersonalityIndexLocs = Locs();
126     FPReg = ARM::SP;
127   }
128 };
129 
130 class ARMAsmParser : public MCTargetAsmParser {
131   MCSubtargetInfo &STI;
132   const MCInstrInfo &MII;
133   const MCRegisterInfo *MRI;
134   UnwindContext UC;
135 
136   ARMTargetStreamer &getTargetStreamer() {
137     assert(getParser().getStreamer().getTargetStreamer() &&
138            "do not have a target streamer");
139     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
140     return static_cast<ARMTargetStreamer &>(TS);
141   }
142 
143   // Map of register aliases registers via the .req directive.
144   StringMap<unsigned> RegisterReqs;
145 
146   bool NextSymbolIsThumb;
147 
148   struct {
149     ARMCC::CondCodes Cond;    // Condition for IT block.
150     unsigned Mask:4;          // Condition mask for instructions.
151                               // Starting at first 1 (from lsb).
152                               //   '1'  condition as indicated in IT.
153                               //   '0'  inverse of condition (else).
154                               // Count of instructions in IT block is
155                               // 4 - trailingzeroes(mask)
156 
157     bool FirstCond;           // Explicit flag for when we're parsing the
158                               // First instruction in the IT block. It's
159                               // implied in the mask, so needs special
160                               // handling.
161 
162     unsigned CurPosition;     // Current position in parsing of IT
163                               // block. In range [0,3]. Initialized
164                               // according to count of instructions in block.
165                               // ~0U if no active IT block.
166   } ITState;
167   bool inITBlock() { return ITState.CurPosition != ~0U; }
168   bool lastInITBlock() {
169     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
170   }
171   void forwardITPosition() {
172     if (!inITBlock()) return;
173     // Move to the next instruction in the IT block, if there is one. If not,
174     // mark the block as done.
175     unsigned TZ = countTrailingZeros(ITState.Mask);
176     if (++ITState.CurPosition == 5 - TZ)
177       ITState.CurPosition = ~0U; // Done with the IT block after this.
178   }
179 
180   void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None) {
181     return getParser().Note(L, Msg, Ranges);
182   }
183   bool Warning(SMLoc L, const Twine &Msg,
184                ArrayRef<SMRange> Ranges = None) {
185     return getParser().Warning(L, Msg, Ranges);
186   }
187   bool Error(SMLoc L, const Twine &Msg,
188              ArrayRef<SMRange> Ranges = None) {
189     return getParser().Error(L, Msg, Ranges);
190   }
191 
192   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
193                            unsigned ListNo, bool IsARPop = false);
194   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
195                            unsigned ListNo);
196 
197   int tryParseRegister();
198   bool tryParseRegisterWithWriteBack(OperandVector &);
199   int tryParseShiftRegister(OperandVector &);
200   bool parseRegisterList(OperandVector &);
201   bool parseMemory(OperandVector &);
202   bool parseOperand(OperandVector &, StringRef Mnemonic);
203   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
204   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
205                               unsigned &ShiftAmount);
206   bool parseLiteralValues(unsigned Size, SMLoc L);
207   bool parseDirectiveThumb(SMLoc L);
208   bool parseDirectiveARM(SMLoc L);
209   bool parseDirectiveThumbFunc(SMLoc L);
210   bool parseDirectiveCode(SMLoc L);
211   bool parseDirectiveSyntax(SMLoc L);
212   bool parseDirectiveReq(StringRef Name, SMLoc L);
213   bool parseDirectiveUnreq(SMLoc L);
214   bool parseDirectiveArch(SMLoc L);
215   bool parseDirectiveEabiAttr(SMLoc L);
216   bool parseDirectiveCPU(SMLoc L);
217   bool parseDirectiveFPU(SMLoc L);
218   bool parseDirectiveFnStart(SMLoc L);
219   bool parseDirectiveFnEnd(SMLoc L);
220   bool parseDirectiveCantUnwind(SMLoc L);
221   bool parseDirectivePersonality(SMLoc L);
222   bool parseDirectiveHandlerData(SMLoc L);
223   bool parseDirectiveSetFP(SMLoc L);
224   bool parseDirectivePad(SMLoc L);
225   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
226   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
227   bool parseDirectiveLtorg(SMLoc L);
228   bool parseDirectiveEven(SMLoc L);
229   bool parseDirectivePersonalityIndex(SMLoc L);
230   bool parseDirectiveUnwindRaw(SMLoc L);
231   bool parseDirectiveTLSDescSeq(SMLoc L);
232   bool parseDirectiveMovSP(SMLoc L);
233   bool parseDirectiveObjectArch(SMLoc L);
234   bool parseDirectiveArchExtension(SMLoc L);
235   bool parseDirectiveAlign(SMLoc L);
236   bool parseDirectiveThumbSet(SMLoc L);
237 
238   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
239                           bool &CarrySetting, unsigned &ProcessorIMod,
240                           StringRef &ITMask);
241   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
242                              bool &CanAcceptCarrySet,
243                              bool &CanAcceptPredicationCode);
244 
245   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
246                                      OperandVector &Operands);
247   bool isThumb() const {
248     // FIXME: Can tablegen auto-generate this?
249     return STI.getFeatureBits()[ARM::ModeThumb];
250   }
251   bool isThumbOne() const {
252     return isThumb() && !STI.getFeatureBits()[ARM::FeatureThumb2];
253   }
254   bool isThumbTwo() const {
255     return isThumb() && STI.getFeatureBits()[ARM::FeatureThumb2];
256   }
257   bool hasThumb() const {
258     return STI.getFeatureBits()[ARM::HasV4TOps];
259   }
260   bool hasV6Ops() const {
261     return STI.getFeatureBits()[ARM::HasV6Ops];
262   }
263   bool hasV6MOps() const {
264     return STI.getFeatureBits()[ARM::HasV6MOps];
265   }
266   bool hasV7Ops() const {
267     return STI.getFeatureBits()[ARM::HasV7Ops];
268   }
269   bool hasV8Ops() const {
270     return STI.getFeatureBits()[ARM::HasV8Ops];
271   }
272   bool hasARM() const {
273     return !STI.getFeatureBits()[ARM::FeatureNoARM];
274   }
275   bool hasThumb2DSP() const {
276     return STI.getFeatureBits()[ARM::FeatureDSPThumb2];
277   }
278   bool hasD16() const {
279     return STI.getFeatureBits()[ARM::FeatureD16];
280   }
281   bool hasV8_1aOps() const {
282     return STI.getFeatureBits()[ARM::HasV8_1aOps];
283   }
284 
285   void SwitchMode() {
286     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
287     setAvailableFeatures(FB);
288   }
289   bool isMClass() const {
290     return STI.getFeatureBits()[ARM::FeatureMClass];
291   }
292 
293   /// @name Auto-generated Match Functions
294   /// {
295 
296 #define GET_ASSEMBLER_HEADER
297 #include "ARMGenAsmMatcher.inc"
298 
299   /// }
300 
301   OperandMatchResultTy parseITCondCode(OperandVector &);
302   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
303   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
304   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
305   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
306   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
307   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
308   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
309   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
310   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
311                                    int High);
312   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
313     return parsePKHImm(O, "lsl", 0, 31);
314   }
315   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
316     return parsePKHImm(O, "asr", 1, 32);
317   }
318   OperandMatchResultTy parseSetEndImm(OperandVector &);
319   OperandMatchResultTy parseShifterImm(OperandVector &);
320   OperandMatchResultTy parseRotImm(OperandVector &);
321   OperandMatchResultTy parseModImm(OperandVector &);
322   OperandMatchResultTy parseBitfield(OperandVector &);
323   OperandMatchResultTy parsePostIdxReg(OperandVector &);
324   OperandMatchResultTy parseAM3Offset(OperandVector &);
325   OperandMatchResultTy parseFPImm(OperandVector &);
326   OperandMatchResultTy parseVectorList(OperandVector &);
327   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
328                                        SMLoc &EndLoc);
329 
330   // Asm Match Converter Methods
331   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
332   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
333 
334   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
335   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
336   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
337   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
338 
339 public:
340   enum ARMMatchResultTy {
341     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
342     Match_RequiresNotITBlock,
343     Match_RequiresV6,
344     Match_RequiresThumb2,
345 #define GET_OPERAND_DIAGNOSTIC_TYPES
346 #include "ARMGenAsmMatcher.inc"
347 
348   };
349 
350   ARMAsmParser(MCSubtargetInfo &STI, MCAsmParser &Parser,
351                const MCInstrInfo &MII, const MCTargetOptions &Options)
352       : MCTargetAsmParser(Options), STI(STI), MII(MII), UC(Parser) {
353     MCAsmParserExtension::Initialize(Parser);
354 
355     // Cache the MCRegisterInfo.
356     MRI = getContext().getRegisterInfo();
357 
358     // Initialize the set of available features.
359     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
360 
361     // Not in an ITBlock to start with.
362     ITState.CurPosition = ~0U;
363 
364     NextSymbolIsThumb = false;
365   }
366 
367   // Implementation of the MCTargetAsmParser interface:
368   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
369   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
370                         SMLoc NameLoc, OperandVector &Operands) override;
371   bool ParseDirective(AsmToken DirectiveID) override;
372 
373   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
374                                       unsigned Kind) override;
375   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
376 
377   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
378                                OperandVector &Operands, MCStreamer &Out,
379                                uint64_t &ErrorInfo,
380                                bool MatchingInlineAsm) override;
381   void onLabelParsed(MCSymbol *Symbol) override;
382 };
383 } // end anonymous namespace
384 
385 namespace {
386 
387 /// ARMOperand - Instances of this class represent a parsed ARM machine
388 /// operand.
389 class ARMOperand : public MCParsedAsmOperand {
390   enum KindTy {
391     k_CondCode,
392     k_CCOut,
393     k_ITCondMask,
394     k_CoprocNum,
395     k_CoprocReg,
396     k_CoprocOption,
397     k_Immediate,
398     k_MemBarrierOpt,
399     k_InstSyncBarrierOpt,
400     k_Memory,
401     k_PostIndexRegister,
402     k_MSRMask,
403     k_BankedReg,
404     k_ProcIFlags,
405     k_VectorIndex,
406     k_Register,
407     k_RegisterList,
408     k_DPRRegisterList,
409     k_SPRRegisterList,
410     k_VectorList,
411     k_VectorListAllLanes,
412     k_VectorListIndexed,
413     k_ShiftedRegister,
414     k_ShiftedImmediate,
415     k_ShifterImmediate,
416     k_RotateImmediate,
417     k_ModifiedImmediate,
418     k_BitfieldDescriptor,
419     k_Token
420   } Kind;
421 
422   SMLoc StartLoc, EndLoc, AlignmentLoc;
423   SmallVector<unsigned, 8> Registers;
424 
425   struct CCOp {
426     ARMCC::CondCodes Val;
427   };
428 
429   struct CopOp {
430     unsigned Val;
431   };
432 
433   struct CoprocOptionOp {
434     unsigned Val;
435   };
436 
437   struct ITMaskOp {
438     unsigned Mask:4;
439   };
440 
441   struct MBOptOp {
442     ARM_MB::MemBOpt Val;
443   };
444 
445   struct ISBOptOp {
446     ARM_ISB::InstSyncBOpt Val;
447   };
448 
449   struct IFlagsOp {
450     ARM_PROC::IFlags Val;
451   };
452 
453   struct MMaskOp {
454     unsigned Val;
455   };
456 
457   struct BankedRegOp {
458     unsigned Val;
459   };
460 
461   struct TokOp {
462     const char *Data;
463     unsigned Length;
464   };
465 
466   struct RegOp {
467     unsigned RegNum;
468   };
469 
470   // A vector register list is a sequential list of 1 to 4 registers.
471   struct VectorListOp {
472     unsigned RegNum;
473     unsigned Count;
474     unsigned LaneIndex;
475     bool isDoubleSpaced;
476   };
477 
478   struct VectorIndexOp {
479     unsigned Val;
480   };
481 
482   struct ImmOp {
483     const MCExpr *Val;
484   };
485 
486   /// Combined record for all forms of ARM address expressions.
487   struct MemoryOp {
488     unsigned BaseRegNum;
489     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
490     // was specified.
491     const MCConstantExpr *OffsetImm;  // Offset immediate value
492     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
493     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
494     unsigned ShiftImm;        // shift for OffsetReg.
495     unsigned Alignment;       // 0 = no alignment specified
496     // n = alignment in bytes (2, 4, 8, 16, or 32)
497     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
498   };
499 
500   struct PostIdxRegOp {
501     unsigned RegNum;
502     bool isAdd;
503     ARM_AM::ShiftOpc ShiftTy;
504     unsigned ShiftImm;
505   };
506 
507   struct ShifterImmOp {
508     bool isASR;
509     unsigned Imm;
510   };
511 
512   struct RegShiftedRegOp {
513     ARM_AM::ShiftOpc ShiftTy;
514     unsigned SrcReg;
515     unsigned ShiftReg;
516     unsigned ShiftImm;
517   };
518 
519   struct RegShiftedImmOp {
520     ARM_AM::ShiftOpc ShiftTy;
521     unsigned SrcReg;
522     unsigned ShiftImm;
523   };
524 
525   struct RotImmOp {
526     unsigned Imm;
527   };
528 
529   struct ModImmOp {
530     unsigned Bits;
531     unsigned Rot;
532   };
533 
534   struct BitfieldOp {
535     unsigned LSB;
536     unsigned Width;
537   };
538 
539   union {
540     struct CCOp CC;
541     struct CopOp Cop;
542     struct CoprocOptionOp CoprocOption;
543     struct MBOptOp MBOpt;
544     struct ISBOptOp ISBOpt;
545     struct ITMaskOp ITMask;
546     struct IFlagsOp IFlags;
547     struct MMaskOp MMask;
548     struct BankedRegOp BankedReg;
549     struct TokOp Tok;
550     struct RegOp Reg;
551     struct VectorListOp VectorList;
552     struct VectorIndexOp VectorIndex;
553     struct ImmOp Imm;
554     struct MemoryOp Memory;
555     struct PostIdxRegOp PostIdxReg;
556     struct ShifterImmOp ShifterImm;
557     struct RegShiftedRegOp RegShiftedReg;
558     struct RegShiftedImmOp RegShiftedImm;
559     struct RotImmOp RotImm;
560     struct ModImmOp ModImm;
561     struct BitfieldOp Bitfield;
562   };
563 
564 public:
565   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
566 
567   /// getStartLoc - Get the location of the first token of this operand.
568   SMLoc getStartLoc() const override { return StartLoc; }
569   /// getEndLoc - Get the location of the last token of this operand.
570   SMLoc getEndLoc() const override { return EndLoc; }
571   /// getLocRange - Get the range between the first and last token of this
572   /// operand.
573   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
574 
575   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
576   SMLoc getAlignmentLoc() const {
577     assert(Kind == k_Memory && "Invalid access!");
578     return AlignmentLoc;
579   }
580 
581   ARMCC::CondCodes getCondCode() const {
582     assert(Kind == k_CondCode && "Invalid access!");
583     return CC.Val;
584   }
585 
586   unsigned getCoproc() const {
587     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
588     return Cop.Val;
589   }
590 
591   StringRef getToken() const {
592     assert(Kind == k_Token && "Invalid access!");
593     return StringRef(Tok.Data, Tok.Length);
594   }
595 
596   unsigned getReg() const override {
597     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
598     return Reg.RegNum;
599   }
600 
601   const SmallVectorImpl<unsigned> &getRegList() const {
602     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
603             Kind == k_SPRRegisterList) && "Invalid access!");
604     return Registers;
605   }
606 
607   const MCExpr *getImm() const {
608     assert(isImm() && "Invalid access!");
609     return Imm.Val;
610   }
611 
612   unsigned getVectorIndex() const {
613     assert(Kind == k_VectorIndex && "Invalid access!");
614     return VectorIndex.Val;
615   }
616 
617   ARM_MB::MemBOpt getMemBarrierOpt() const {
618     assert(Kind == k_MemBarrierOpt && "Invalid access!");
619     return MBOpt.Val;
620   }
621 
622   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
623     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
624     return ISBOpt.Val;
625   }
626 
627   ARM_PROC::IFlags getProcIFlags() const {
628     assert(Kind == k_ProcIFlags && "Invalid access!");
629     return IFlags.Val;
630   }
631 
632   unsigned getMSRMask() const {
633     assert(Kind == k_MSRMask && "Invalid access!");
634     return MMask.Val;
635   }
636 
637   unsigned getBankedReg() const {
638     assert(Kind == k_BankedReg && "Invalid access!");
639     return BankedReg.Val;
640   }
641 
642   bool isCoprocNum() const { return Kind == k_CoprocNum; }
643   bool isCoprocReg() const { return Kind == k_CoprocReg; }
644   bool isCoprocOption() const { return Kind == k_CoprocOption; }
645   bool isCondCode() const { return Kind == k_CondCode; }
646   bool isCCOut() const { return Kind == k_CCOut; }
647   bool isITMask() const { return Kind == k_ITCondMask; }
648   bool isITCondCode() const { return Kind == k_CondCode; }
649   bool isImm() const override { return Kind == k_Immediate; }
650   // checks whether this operand is an unsigned offset which fits is a field
651   // of specified width and scaled by a specific number of bits
652   template<unsigned width, unsigned scale>
653   bool isUnsignedOffset() const {
654     if (!isImm()) return false;
655     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
656     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
657       int64_t Val = CE->getValue();
658       int64_t Align = 1LL << scale;
659       int64_t Max = Align * ((1LL << width) - 1);
660       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
661     }
662     return false;
663   }
664   // checks whether this operand is an signed offset which fits is a field
665   // of specified width and scaled by a specific number of bits
666   template<unsigned width, unsigned scale>
667   bool isSignedOffset() const {
668     if (!isImm()) return false;
669     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
670     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
671       int64_t Val = CE->getValue();
672       int64_t Align = 1LL << scale;
673       int64_t Max = Align * ((1LL << (width-1)) - 1);
674       int64_t Min = -Align * (1LL << (width-1));
675       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
676     }
677     return false;
678   }
679 
680   // checks whether this operand is a memory operand computed as an offset
681   // applied to PC. the offset may have 8 bits of magnitude and is represented
682   // with two bits of shift. textually it may be either [pc, #imm], #imm or
683   // relocable expression...
684   bool isThumbMemPC() const {
685     int64_t Val = 0;
686     if (isImm()) {
687       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
688       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
689       if (!CE) return false;
690       Val = CE->getValue();
691     }
692     else if (isMem()) {
693       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
694       if(Memory.BaseRegNum != ARM::PC) return false;
695       Val = Memory.OffsetImm->getValue();
696     }
697     else return false;
698     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
699   }
700   bool isFPImm() const {
701     if (!isImm()) return false;
702     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
703     if (!CE) return false;
704     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
705     return Val != -1;
706   }
707   bool isFBits16() const {
708     if (!isImm()) return false;
709     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
710     if (!CE) return false;
711     int64_t Value = CE->getValue();
712     return Value >= 0 && Value <= 16;
713   }
714   bool isFBits32() const {
715     if (!isImm()) return false;
716     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
717     if (!CE) return false;
718     int64_t Value = CE->getValue();
719     return Value >= 1 && Value <= 32;
720   }
721   bool isImm8s4() const {
722     if (!isImm()) return false;
723     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
724     if (!CE) return false;
725     int64_t Value = CE->getValue();
726     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
727   }
728   bool isImm0_1020s4() const {
729     if (!isImm()) return false;
730     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
731     if (!CE) return false;
732     int64_t Value = CE->getValue();
733     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
734   }
735   bool isImm0_508s4() const {
736     if (!isImm()) return false;
737     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
738     if (!CE) return false;
739     int64_t Value = CE->getValue();
740     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
741   }
742   bool isImm0_508s4Neg() const {
743     if (!isImm()) return false;
744     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
745     if (!CE) return false;
746     int64_t Value = -CE->getValue();
747     // explicitly exclude zero. we want that to use the normal 0_508 version.
748     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
749   }
750   bool isImm0_239() const {
751     if (!isImm()) return false;
752     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
753     if (!CE) return false;
754     int64_t Value = CE->getValue();
755     return Value >= 0 && Value < 240;
756   }
757   bool isImm0_255() const {
758     if (!isImm()) return false;
759     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
760     if (!CE) return false;
761     int64_t Value = CE->getValue();
762     return Value >= 0 && Value < 256;
763   }
764   bool isImm0_4095() const {
765     if (!isImm()) return false;
766     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
767     if (!CE) return false;
768     int64_t Value = CE->getValue();
769     return Value >= 0 && Value < 4096;
770   }
771   bool isImm0_4095Neg() const {
772     if (!isImm()) return false;
773     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
774     if (!CE) return false;
775     int64_t Value = -CE->getValue();
776     return Value > 0 && Value < 4096;
777   }
778   bool isImm0_1() const {
779     if (!isImm()) return false;
780     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
781     if (!CE) return false;
782     int64_t Value = CE->getValue();
783     return Value >= 0 && Value < 2;
784   }
785   bool isImm0_3() const {
786     if (!isImm()) return false;
787     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
788     if (!CE) return false;
789     int64_t Value = CE->getValue();
790     return Value >= 0 && Value < 4;
791   }
792   bool isImm0_7() const {
793     if (!isImm()) return false;
794     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
795     if (!CE) return false;
796     int64_t Value = CE->getValue();
797     return Value >= 0 && Value < 8;
798   }
799   bool isImm0_15() const {
800     if (!isImm()) return false;
801     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
802     if (!CE) return false;
803     int64_t Value = CE->getValue();
804     return Value >= 0 && Value < 16;
805   }
806   bool isImm0_31() const {
807     if (!isImm()) return false;
808     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
809     if (!CE) return false;
810     int64_t Value = CE->getValue();
811     return Value >= 0 && Value < 32;
812   }
813   bool isImm0_63() const {
814     if (!isImm()) return false;
815     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
816     if (!CE) return false;
817     int64_t Value = CE->getValue();
818     return Value >= 0 && Value < 64;
819   }
820   bool isImm8() const {
821     if (!isImm()) return false;
822     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
823     if (!CE) return false;
824     int64_t Value = CE->getValue();
825     return Value == 8;
826   }
827   bool isImm16() const {
828     if (!isImm()) return false;
829     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
830     if (!CE) return false;
831     int64_t Value = CE->getValue();
832     return Value == 16;
833   }
834   bool isImm32() const {
835     if (!isImm()) return false;
836     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
837     if (!CE) return false;
838     int64_t Value = CE->getValue();
839     return Value == 32;
840   }
841   bool isShrImm8() const {
842     if (!isImm()) return false;
843     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
844     if (!CE) return false;
845     int64_t Value = CE->getValue();
846     return Value > 0 && Value <= 8;
847   }
848   bool isShrImm16() const {
849     if (!isImm()) return false;
850     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
851     if (!CE) return false;
852     int64_t Value = CE->getValue();
853     return Value > 0 && Value <= 16;
854   }
855   bool isShrImm32() const {
856     if (!isImm()) return false;
857     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
858     if (!CE) return false;
859     int64_t Value = CE->getValue();
860     return Value > 0 && Value <= 32;
861   }
862   bool isShrImm64() const {
863     if (!isImm()) return false;
864     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
865     if (!CE) return false;
866     int64_t Value = CE->getValue();
867     return Value > 0 && Value <= 64;
868   }
869   bool isImm1_7() const {
870     if (!isImm()) return false;
871     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
872     if (!CE) return false;
873     int64_t Value = CE->getValue();
874     return Value > 0 && Value < 8;
875   }
876   bool isImm1_15() const {
877     if (!isImm()) return false;
878     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
879     if (!CE) return false;
880     int64_t Value = CE->getValue();
881     return Value > 0 && Value < 16;
882   }
883   bool isImm1_31() const {
884     if (!isImm()) return false;
885     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
886     if (!CE) return false;
887     int64_t Value = CE->getValue();
888     return Value > 0 && Value < 32;
889   }
890   bool isImm1_16() const {
891     if (!isImm()) return false;
892     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
893     if (!CE) return false;
894     int64_t Value = CE->getValue();
895     return Value > 0 && Value < 17;
896   }
897   bool isImm1_32() const {
898     if (!isImm()) return false;
899     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
900     if (!CE) return false;
901     int64_t Value = CE->getValue();
902     return Value > 0 && Value < 33;
903   }
904   bool isImm0_32() const {
905     if (!isImm()) return false;
906     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
907     if (!CE) return false;
908     int64_t Value = CE->getValue();
909     return Value >= 0 && Value < 33;
910   }
911   bool isImm0_65535() const {
912     if (!isImm()) return false;
913     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
914     if (!CE) return false;
915     int64_t Value = CE->getValue();
916     return Value >= 0 && Value < 65536;
917   }
918   bool isImm256_65535Expr() const {
919     if (!isImm()) return false;
920     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
921     // If it's not a constant expression, it'll generate a fixup and be
922     // handled later.
923     if (!CE) return true;
924     int64_t Value = CE->getValue();
925     return Value >= 256 && Value < 65536;
926   }
927   bool isImm0_65535Expr() const {
928     if (!isImm()) return false;
929     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
930     // If it's not a constant expression, it'll generate a fixup and be
931     // handled later.
932     if (!CE) return true;
933     int64_t Value = CE->getValue();
934     return Value >= 0 && Value < 65536;
935   }
936   bool isImm24bit() const {
937     if (!isImm()) return false;
938     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
939     if (!CE) return false;
940     int64_t Value = CE->getValue();
941     return Value >= 0 && Value <= 0xffffff;
942   }
943   bool isImmThumbSR() const {
944     if (!isImm()) return false;
945     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
946     if (!CE) return false;
947     int64_t Value = CE->getValue();
948     return Value > 0 && Value < 33;
949   }
950   bool isPKHLSLImm() const {
951     if (!isImm()) return false;
952     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
953     if (!CE) return false;
954     int64_t Value = CE->getValue();
955     return Value >= 0 && Value < 32;
956   }
957   bool isPKHASRImm() 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     return Value > 0 && Value <= 32;
963   }
964   bool isAdrLabel() const {
965     // If we have an immediate that's not a constant, treat it as a label
966     // reference needing a fixup.
967     if (isImm() && !isa<MCConstantExpr>(getImm()))
968       return true;
969 
970     // If it is a constant, it must fit into a modified immediate encoding.
971     if (!isImm()) return false;
972     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
973     if (!CE) return false;
974     int64_t Value = CE->getValue();
975     return (ARM_AM::getSOImmVal(Value) != -1 ||
976             ARM_AM::getSOImmVal(-Value) != -1);
977   }
978   bool isT2SOImm() const {
979     if (!isImm()) return false;
980     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
981     if (!CE) return false;
982     int64_t Value = CE->getValue();
983     return ARM_AM::getT2SOImmVal(Value) != -1;
984   }
985   bool isT2SOImmNot() const {
986     if (!isImm()) return false;
987     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
988     if (!CE) return false;
989     int64_t Value = CE->getValue();
990     return ARM_AM::getT2SOImmVal(Value) == -1 &&
991       ARM_AM::getT2SOImmVal(~Value) != -1;
992   }
993   bool isT2SOImmNeg() const {
994     if (!isImm()) return false;
995     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
996     if (!CE) return false;
997     int64_t Value = CE->getValue();
998     // Only use this when not representable as a plain so_imm.
999     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1000       ARM_AM::getT2SOImmVal(-Value) != -1;
1001   }
1002   bool isSetEndImm() const {
1003     if (!isImm()) return false;
1004     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1005     if (!CE) return false;
1006     int64_t Value = CE->getValue();
1007     return Value == 1 || Value == 0;
1008   }
1009   bool isReg() const override { return Kind == k_Register; }
1010   bool isRegList() const { return Kind == k_RegisterList; }
1011   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1012   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1013   bool isToken() const override { return Kind == k_Token; }
1014   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1015   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1016   bool isMem() const override { return Kind == k_Memory; }
1017   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1018   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1019   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1020   bool isRotImm() const { return Kind == k_RotateImmediate; }
1021   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1022   bool isModImmNot() const {
1023     if (!isImm()) return false;
1024     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1025     if (!CE) return false;
1026     int64_t Value = CE->getValue();
1027     return ARM_AM::getSOImmVal(~Value) != -1;
1028   }
1029   bool isModImmNeg() const {
1030     if (!isImm()) return false;
1031     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1032     if (!CE) return false;
1033     int64_t Value = CE->getValue();
1034     return ARM_AM::getSOImmVal(Value) == -1 &&
1035       ARM_AM::getSOImmVal(-Value) != -1;
1036   }
1037   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1038   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1039   bool isPostIdxReg() const {
1040     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1041   }
1042   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1043     if (!isMem())
1044       return false;
1045     // No offset of any kind.
1046     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1047      (alignOK || Memory.Alignment == Alignment);
1048   }
1049   bool isMemPCRelImm12() const {
1050     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1051       return false;
1052     // Base register must be PC.
1053     if (Memory.BaseRegNum != ARM::PC)
1054       return false;
1055     // Immediate offset in range [-4095, 4095].
1056     if (!Memory.OffsetImm) return true;
1057     int64_t Val = Memory.OffsetImm->getValue();
1058     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1059   }
1060   bool isAlignedMemory() const {
1061     return isMemNoOffset(true);
1062   }
1063   bool isAlignedMemoryNone() const {
1064     return isMemNoOffset(false, 0);
1065   }
1066   bool isDupAlignedMemoryNone() const {
1067     return isMemNoOffset(false, 0);
1068   }
1069   bool isAlignedMemory16() const {
1070     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1071       return true;
1072     return isMemNoOffset(false, 0);
1073   }
1074   bool isDupAlignedMemory16() const {
1075     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1076       return true;
1077     return isMemNoOffset(false, 0);
1078   }
1079   bool isAlignedMemory32() const {
1080     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1081       return true;
1082     return isMemNoOffset(false, 0);
1083   }
1084   bool isDupAlignedMemory32() const {
1085     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1086       return true;
1087     return isMemNoOffset(false, 0);
1088   }
1089   bool isAlignedMemory64() const {
1090     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1091       return true;
1092     return isMemNoOffset(false, 0);
1093   }
1094   bool isDupAlignedMemory64() const {
1095     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1096       return true;
1097     return isMemNoOffset(false, 0);
1098   }
1099   bool isAlignedMemory64or128() const {
1100     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1101       return true;
1102     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1103       return true;
1104     return isMemNoOffset(false, 0);
1105   }
1106   bool isDupAlignedMemory64or128() const {
1107     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1108       return true;
1109     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1110       return true;
1111     return isMemNoOffset(false, 0);
1112   }
1113   bool isAlignedMemory64or128or256() const {
1114     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1115       return true;
1116     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1117       return true;
1118     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1119       return true;
1120     return isMemNoOffset(false, 0);
1121   }
1122   bool isAddrMode2() const {
1123     if (!isMem() || Memory.Alignment != 0) return false;
1124     // Check for register offset.
1125     if (Memory.OffsetRegNum) return true;
1126     // Immediate offset in range [-4095, 4095].
1127     if (!Memory.OffsetImm) return true;
1128     int64_t Val = Memory.OffsetImm->getValue();
1129     return Val > -4096 && Val < 4096;
1130   }
1131   bool isAM2OffsetImm() const {
1132     if (!isImm()) return false;
1133     // Immediate offset in range [-4095, 4095].
1134     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1135     if (!CE) return false;
1136     int64_t Val = CE->getValue();
1137     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1138   }
1139   bool isAddrMode3() const {
1140     // If we have an immediate that's not a constant, treat it as a label
1141     // reference needing a fixup. If it is a constant, it's something else
1142     // and we reject it.
1143     if (isImm() && !isa<MCConstantExpr>(getImm()))
1144       return true;
1145     if (!isMem() || Memory.Alignment != 0) return false;
1146     // No shifts are legal for AM3.
1147     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1148     // Check for register offset.
1149     if (Memory.OffsetRegNum) return true;
1150     // Immediate offset in range [-255, 255].
1151     if (!Memory.OffsetImm) return true;
1152     int64_t Val = Memory.OffsetImm->getValue();
1153     // The #-0 offset is encoded as INT32_MIN, and we have to check
1154     // for this too.
1155     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1156   }
1157   bool isAM3Offset() const {
1158     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1159       return false;
1160     if (Kind == k_PostIndexRegister)
1161       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1162     // Immediate offset in range [-255, 255].
1163     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1164     if (!CE) return false;
1165     int64_t Val = CE->getValue();
1166     // Special case, #-0 is INT32_MIN.
1167     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1168   }
1169   bool isAddrMode5() const {
1170     // If we have an immediate that's not a constant, treat it as a label
1171     // reference needing a fixup. If it is a constant, it's something else
1172     // and we reject it.
1173     if (isImm() && !isa<MCConstantExpr>(getImm()))
1174       return true;
1175     if (!isMem() || Memory.Alignment != 0) return false;
1176     // Check for register offset.
1177     if (Memory.OffsetRegNum) return false;
1178     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1179     if (!Memory.OffsetImm) return true;
1180     int64_t Val = Memory.OffsetImm->getValue();
1181     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1182       Val == INT32_MIN;
1183   }
1184   bool isMemTBB() const {
1185     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1186         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1187       return false;
1188     return true;
1189   }
1190   bool isMemTBH() const {
1191     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1192         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1193         Memory.Alignment != 0 )
1194       return false;
1195     return true;
1196   }
1197   bool isMemRegOffset() const {
1198     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1199       return false;
1200     return true;
1201   }
1202   bool isT2MemRegOffset() const {
1203     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1204         Memory.Alignment != 0)
1205       return false;
1206     // Only lsl #{0, 1, 2, 3} allowed.
1207     if (Memory.ShiftType == ARM_AM::no_shift)
1208       return true;
1209     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1210       return false;
1211     return true;
1212   }
1213   bool isMemThumbRR() const {
1214     // Thumb reg+reg addressing is simple. Just two registers, a base and
1215     // an offset. No shifts, negations or any other complicating factors.
1216     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1217         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1218       return false;
1219     return isARMLowRegister(Memory.BaseRegNum) &&
1220       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1221   }
1222   bool isMemThumbRIs4() const {
1223     if (!isMem() || Memory.OffsetRegNum != 0 ||
1224         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1225       return false;
1226     // Immediate offset, multiple of 4 in range [0, 124].
1227     if (!Memory.OffsetImm) return true;
1228     int64_t Val = Memory.OffsetImm->getValue();
1229     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1230   }
1231   bool isMemThumbRIs2() const {
1232     if (!isMem() || Memory.OffsetRegNum != 0 ||
1233         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1234       return false;
1235     // Immediate offset, multiple of 4 in range [0, 62].
1236     if (!Memory.OffsetImm) return true;
1237     int64_t Val = Memory.OffsetImm->getValue();
1238     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1239   }
1240   bool isMemThumbRIs1() const {
1241     if (!isMem() || Memory.OffsetRegNum != 0 ||
1242         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1243       return false;
1244     // Immediate offset in range [0, 31].
1245     if (!Memory.OffsetImm) return true;
1246     int64_t Val = Memory.OffsetImm->getValue();
1247     return Val >= 0 && Val <= 31;
1248   }
1249   bool isMemThumbSPI() const {
1250     if (!isMem() || Memory.OffsetRegNum != 0 ||
1251         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1252       return false;
1253     // Immediate offset, multiple of 4 in range [0, 1020].
1254     if (!Memory.OffsetImm) return true;
1255     int64_t Val = Memory.OffsetImm->getValue();
1256     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1257   }
1258   bool isMemImm8s4Offset() 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.OffsetRegNum != 0 || Memory.Alignment != 0)
1265       return false;
1266     // Immediate offset a multiple of 4 in range [-1020, 1020].
1267     if (!Memory.OffsetImm) return true;
1268     int64_t Val = Memory.OffsetImm->getValue();
1269     // Special case, #-0 is INT32_MIN.
1270     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1271   }
1272   bool isMemImm0_1020s4Offset() const {
1273     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1274       return false;
1275     // Immediate offset a multiple of 4 in range [0, 1020].
1276     if (!Memory.OffsetImm) return true;
1277     int64_t Val = Memory.OffsetImm->getValue();
1278     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1279   }
1280   bool isMemImm8Offset() const {
1281     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1282       return false;
1283     // Base reg of PC isn't allowed for these encodings.
1284     if (Memory.BaseRegNum == ARM::PC) return false;
1285     // Immediate offset in range [-255, 255].
1286     if (!Memory.OffsetImm) return true;
1287     int64_t Val = Memory.OffsetImm->getValue();
1288     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1289   }
1290   bool isMemPosImm8Offset() const {
1291     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1292       return false;
1293     // Immediate offset in range [0, 255].
1294     if (!Memory.OffsetImm) return true;
1295     int64_t Val = Memory.OffsetImm->getValue();
1296     return Val >= 0 && Val < 256;
1297   }
1298   bool isMemNegImm8Offset() const {
1299     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1300       return false;
1301     // Base reg of PC isn't allowed for these encodings.
1302     if (Memory.BaseRegNum == ARM::PC) return false;
1303     // Immediate offset in range [-255, -1].
1304     if (!Memory.OffsetImm) return false;
1305     int64_t Val = Memory.OffsetImm->getValue();
1306     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1307   }
1308   bool isMemUImm12Offset() const {
1309     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1310       return false;
1311     // Immediate offset in range [0, 4095].
1312     if (!Memory.OffsetImm) return true;
1313     int64_t Val = Memory.OffsetImm->getValue();
1314     return (Val >= 0 && Val < 4096);
1315   }
1316   bool isMemImm12Offset() const {
1317     // If we have an immediate that's not a constant, treat it as a label
1318     // reference needing a fixup. If it is a constant, it's something else
1319     // and we reject it.
1320     if (isImm() && !isa<MCConstantExpr>(getImm()))
1321       return true;
1322 
1323     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1324       return false;
1325     // Immediate offset in range [-4095, 4095].
1326     if (!Memory.OffsetImm) return true;
1327     int64_t Val = Memory.OffsetImm->getValue();
1328     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1329   }
1330   bool isPostIdxImm8() const {
1331     if (!isImm()) return false;
1332     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1333     if (!CE) return false;
1334     int64_t Val = CE->getValue();
1335     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1336   }
1337   bool isPostIdxImm8s4() const {
1338     if (!isImm()) return false;
1339     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1340     if (!CE) return false;
1341     int64_t Val = CE->getValue();
1342     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1343       (Val == INT32_MIN);
1344   }
1345 
1346   bool isMSRMask() const { return Kind == k_MSRMask; }
1347   bool isBankedReg() const { return Kind == k_BankedReg; }
1348   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1349 
1350   // NEON operands.
1351   bool isSingleSpacedVectorList() const {
1352     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1353   }
1354   bool isDoubleSpacedVectorList() const {
1355     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1356   }
1357   bool isVecListOneD() const {
1358     if (!isSingleSpacedVectorList()) return false;
1359     return VectorList.Count == 1;
1360   }
1361 
1362   bool isVecListDPair() const {
1363     if (!isSingleSpacedVectorList()) return false;
1364     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1365               .contains(VectorList.RegNum));
1366   }
1367 
1368   bool isVecListThreeD() const {
1369     if (!isSingleSpacedVectorList()) return false;
1370     return VectorList.Count == 3;
1371   }
1372 
1373   bool isVecListFourD() const {
1374     if (!isSingleSpacedVectorList()) return false;
1375     return VectorList.Count == 4;
1376   }
1377 
1378   bool isVecListDPairSpaced() const {
1379     if (Kind != k_VectorList) return false;
1380     if (isSingleSpacedVectorList()) return false;
1381     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1382               .contains(VectorList.RegNum));
1383   }
1384 
1385   bool isVecListThreeQ() const {
1386     if (!isDoubleSpacedVectorList()) return false;
1387     return VectorList.Count == 3;
1388   }
1389 
1390   bool isVecListFourQ() const {
1391     if (!isDoubleSpacedVectorList()) return false;
1392     return VectorList.Count == 4;
1393   }
1394 
1395   bool isSingleSpacedVectorAllLanes() const {
1396     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1397   }
1398   bool isDoubleSpacedVectorAllLanes() const {
1399     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1400   }
1401   bool isVecListOneDAllLanes() const {
1402     if (!isSingleSpacedVectorAllLanes()) return false;
1403     return VectorList.Count == 1;
1404   }
1405 
1406   bool isVecListDPairAllLanes() const {
1407     if (!isSingleSpacedVectorAllLanes()) return false;
1408     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1409               .contains(VectorList.RegNum));
1410   }
1411 
1412   bool isVecListDPairSpacedAllLanes() const {
1413     if (!isDoubleSpacedVectorAllLanes()) return false;
1414     return VectorList.Count == 2;
1415   }
1416 
1417   bool isVecListThreeDAllLanes() const {
1418     if (!isSingleSpacedVectorAllLanes()) return false;
1419     return VectorList.Count == 3;
1420   }
1421 
1422   bool isVecListThreeQAllLanes() const {
1423     if (!isDoubleSpacedVectorAllLanes()) return false;
1424     return VectorList.Count == 3;
1425   }
1426 
1427   bool isVecListFourDAllLanes() const {
1428     if (!isSingleSpacedVectorAllLanes()) return false;
1429     return VectorList.Count == 4;
1430   }
1431 
1432   bool isVecListFourQAllLanes() const {
1433     if (!isDoubleSpacedVectorAllLanes()) return false;
1434     return VectorList.Count == 4;
1435   }
1436 
1437   bool isSingleSpacedVectorIndexed() const {
1438     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1439   }
1440   bool isDoubleSpacedVectorIndexed() const {
1441     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1442   }
1443   bool isVecListOneDByteIndexed() const {
1444     if (!isSingleSpacedVectorIndexed()) return false;
1445     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1446   }
1447 
1448   bool isVecListOneDHWordIndexed() const {
1449     if (!isSingleSpacedVectorIndexed()) return false;
1450     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1451   }
1452 
1453   bool isVecListOneDWordIndexed() const {
1454     if (!isSingleSpacedVectorIndexed()) return false;
1455     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1456   }
1457 
1458   bool isVecListTwoDByteIndexed() const {
1459     if (!isSingleSpacedVectorIndexed()) return false;
1460     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1461   }
1462 
1463   bool isVecListTwoDHWordIndexed() const {
1464     if (!isSingleSpacedVectorIndexed()) return false;
1465     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1466   }
1467 
1468   bool isVecListTwoQWordIndexed() const {
1469     if (!isDoubleSpacedVectorIndexed()) return false;
1470     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1471   }
1472 
1473   bool isVecListTwoQHWordIndexed() const {
1474     if (!isDoubleSpacedVectorIndexed()) return false;
1475     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1476   }
1477 
1478   bool isVecListTwoDWordIndexed() const {
1479     if (!isSingleSpacedVectorIndexed()) return false;
1480     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1481   }
1482 
1483   bool isVecListThreeDByteIndexed() const {
1484     if (!isSingleSpacedVectorIndexed()) return false;
1485     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1486   }
1487 
1488   bool isVecListThreeDHWordIndexed() const {
1489     if (!isSingleSpacedVectorIndexed()) return false;
1490     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1491   }
1492 
1493   bool isVecListThreeQWordIndexed() const {
1494     if (!isDoubleSpacedVectorIndexed()) return false;
1495     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1496   }
1497 
1498   bool isVecListThreeQHWordIndexed() const {
1499     if (!isDoubleSpacedVectorIndexed()) return false;
1500     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1501   }
1502 
1503   bool isVecListThreeDWordIndexed() const {
1504     if (!isSingleSpacedVectorIndexed()) return false;
1505     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1506   }
1507 
1508   bool isVecListFourDByteIndexed() const {
1509     if (!isSingleSpacedVectorIndexed()) return false;
1510     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1511   }
1512 
1513   bool isVecListFourDHWordIndexed() const {
1514     if (!isSingleSpacedVectorIndexed()) return false;
1515     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1516   }
1517 
1518   bool isVecListFourQWordIndexed() const {
1519     if (!isDoubleSpacedVectorIndexed()) return false;
1520     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1521   }
1522 
1523   bool isVecListFourQHWordIndexed() const {
1524     if (!isDoubleSpacedVectorIndexed()) return false;
1525     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1526   }
1527 
1528   bool isVecListFourDWordIndexed() const {
1529     if (!isSingleSpacedVectorIndexed()) return false;
1530     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1531   }
1532 
1533   bool isVectorIndex8() const {
1534     if (Kind != k_VectorIndex) return false;
1535     return VectorIndex.Val < 8;
1536   }
1537   bool isVectorIndex16() const {
1538     if (Kind != k_VectorIndex) return false;
1539     return VectorIndex.Val < 4;
1540   }
1541   bool isVectorIndex32() const {
1542     if (Kind != k_VectorIndex) return false;
1543     return VectorIndex.Val < 2;
1544   }
1545 
1546   bool isNEONi8splat() const {
1547     if (!isImm()) return false;
1548     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1549     // Must be a constant.
1550     if (!CE) return false;
1551     int64_t Value = CE->getValue();
1552     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1553     // value.
1554     return Value >= 0 && Value < 256;
1555   }
1556 
1557   bool isNEONi16splat() const {
1558     if (isNEONByteReplicate(2))
1559       return false; // Leave that for bytes replication and forbid by default.
1560     if (!isImm())
1561       return false;
1562     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1563     // Must be a constant.
1564     if (!CE) return false;
1565     unsigned Value = CE->getValue();
1566     return ARM_AM::isNEONi16splat(Value);
1567   }
1568 
1569   bool isNEONi16splatNot() const {
1570     if (!isImm())
1571       return false;
1572     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1573     // Must be a constant.
1574     if (!CE) return false;
1575     unsigned Value = CE->getValue();
1576     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1577   }
1578 
1579   bool isNEONi32splat() const {
1580     if (isNEONByteReplicate(4))
1581       return false; // Leave that for bytes replication and forbid by default.
1582     if (!isImm())
1583       return false;
1584     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1585     // Must be a constant.
1586     if (!CE) return false;
1587     unsigned Value = CE->getValue();
1588     return ARM_AM::isNEONi32splat(Value);
1589   }
1590 
1591   bool isNEONi32splatNot() const {
1592     if (!isImm())
1593       return false;
1594     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1595     // Must be a constant.
1596     if (!CE) return false;
1597     unsigned Value = CE->getValue();
1598     return ARM_AM::isNEONi32splat(~Value);
1599   }
1600 
1601   bool isNEONByteReplicate(unsigned NumBytes) const {
1602     if (!isImm())
1603       return false;
1604     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1605     // Must be a constant.
1606     if (!CE)
1607       return false;
1608     int64_t Value = CE->getValue();
1609     if (!Value)
1610       return false; // Don't bother with zero.
1611 
1612     unsigned char B = Value & 0xff;
1613     for (unsigned i = 1; i < NumBytes; ++i) {
1614       Value >>= 8;
1615       if ((Value & 0xff) != B)
1616         return false;
1617     }
1618     return true;
1619   }
1620   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1621   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1622   bool isNEONi32vmov() const {
1623     if (isNEONByteReplicate(4))
1624       return false; // Let it to be classified as byte-replicate case.
1625     if (!isImm())
1626       return false;
1627     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1628     // Must be a constant.
1629     if (!CE)
1630       return false;
1631     int64_t Value = CE->getValue();
1632     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1633     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1634     // FIXME: This is probably wrong and a copy and paste from previous example
1635     return (Value >= 0 && Value < 256) ||
1636       (Value >= 0x0100 && Value <= 0xff00) ||
1637       (Value >= 0x010000 && Value <= 0xff0000) ||
1638       (Value >= 0x01000000 && Value <= 0xff000000) ||
1639       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1640       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1641   }
1642   bool isNEONi32vmovNeg() const {
1643     if (!isImm()) return false;
1644     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1645     // Must be a constant.
1646     if (!CE) return false;
1647     int64_t Value = ~CE->getValue();
1648     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1649     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1650     // FIXME: This is probably wrong and a copy and paste from previous example
1651     return (Value >= 0 && Value < 256) ||
1652       (Value >= 0x0100 && Value <= 0xff00) ||
1653       (Value >= 0x010000 && Value <= 0xff0000) ||
1654       (Value >= 0x01000000 && Value <= 0xff000000) ||
1655       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1656       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1657   }
1658 
1659   bool isNEONi64splat() const {
1660     if (!isImm()) return false;
1661     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1662     // Must be a constant.
1663     if (!CE) return false;
1664     uint64_t Value = CE->getValue();
1665     // i64 value with each byte being either 0 or 0xff.
1666     for (unsigned i = 0; i < 8; ++i)
1667       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1668     return true;
1669   }
1670 
1671   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1672     // Add as immediates when possible.  Null MCExpr = 0.
1673     if (!Expr)
1674       Inst.addOperand(MCOperand::createImm(0));
1675     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1676       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1677     else
1678       Inst.addOperand(MCOperand::createExpr(Expr));
1679   }
1680 
1681   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1682     assert(N == 2 && "Invalid number of operands!");
1683     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1684     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1685     Inst.addOperand(MCOperand::createReg(RegNum));
1686   }
1687 
1688   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1689     assert(N == 1 && "Invalid number of operands!");
1690     Inst.addOperand(MCOperand::createImm(getCoproc()));
1691   }
1692 
1693   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1694     assert(N == 1 && "Invalid number of operands!");
1695     Inst.addOperand(MCOperand::createImm(getCoproc()));
1696   }
1697 
1698   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1699     assert(N == 1 && "Invalid number of operands!");
1700     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1701   }
1702 
1703   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1704     assert(N == 1 && "Invalid number of operands!");
1705     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1706   }
1707 
1708   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1709     assert(N == 1 && "Invalid number of operands!");
1710     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1711   }
1712 
1713   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1714     assert(N == 1 && "Invalid number of operands!");
1715     Inst.addOperand(MCOperand::createReg(getReg()));
1716   }
1717 
1718   void addRegOperands(MCInst &Inst, unsigned N) const {
1719     assert(N == 1 && "Invalid number of operands!");
1720     Inst.addOperand(MCOperand::createReg(getReg()));
1721   }
1722 
1723   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1724     assert(N == 3 && "Invalid number of operands!");
1725     assert(isRegShiftedReg() &&
1726            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1727     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1728     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1729     Inst.addOperand(MCOperand::createImm(
1730       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1731   }
1732 
1733   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1734     assert(N == 2 && "Invalid number of operands!");
1735     assert(isRegShiftedImm() &&
1736            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1737     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1738     // Shift of #32 is encoded as 0 where permitted
1739     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1740     Inst.addOperand(MCOperand::createImm(
1741       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1742   }
1743 
1744   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1745     assert(N == 1 && "Invalid number of operands!");
1746     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1747                                          ShifterImm.Imm));
1748   }
1749 
1750   void addRegListOperands(MCInst &Inst, unsigned N) const {
1751     assert(N == 1 && "Invalid number of operands!");
1752     const SmallVectorImpl<unsigned> &RegList = getRegList();
1753     for (SmallVectorImpl<unsigned>::const_iterator
1754            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1755       Inst.addOperand(MCOperand::createReg(*I));
1756   }
1757 
1758   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1759     addRegListOperands(Inst, N);
1760   }
1761 
1762   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1763     addRegListOperands(Inst, N);
1764   }
1765 
1766   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1767     assert(N == 1 && "Invalid number of operands!");
1768     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1769     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1770   }
1771 
1772   void addModImmOperands(MCInst &Inst, unsigned N) const {
1773     assert(N == 1 && "Invalid number of operands!");
1774 
1775     // Support for fixups (MCFixup)
1776     if (isImm())
1777       return addImmOperands(Inst, N);
1778 
1779     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
1780   }
1781 
1782   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1783     assert(N == 1 && "Invalid number of operands!");
1784     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1785     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1786     Inst.addOperand(MCOperand::createImm(Enc));
1787   }
1788 
1789   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1790     assert(N == 1 && "Invalid number of operands!");
1791     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1792     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1793     Inst.addOperand(MCOperand::createImm(Enc));
1794   }
1795 
1796   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1797     assert(N == 1 && "Invalid number of operands!");
1798     // Munge the lsb/width into a bitfield mask.
1799     unsigned lsb = Bitfield.LSB;
1800     unsigned width = Bitfield.Width;
1801     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1802     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1803                       (32 - (lsb + width)));
1804     Inst.addOperand(MCOperand::createImm(Mask));
1805   }
1806 
1807   void addImmOperands(MCInst &Inst, unsigned N) const {
1808     assert(N == 1 && "Invalid number of operands!");
1809     addExpr(Inst, getImm());
1810   }
1811 
1812   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1813     assert(N == 1 && "Invalid number of operands!");
1814     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1815     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
1816   }
1817 
1818   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1819     assert(N == 1 && "Invalid number of operands!");
1820     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1821     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
1822   }
1823 
1824   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1825     assert(N == 1 && "Invalid number of operands!");
1826     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1827     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1828     Inst.addOperand(MCOperand::createImm(Val));
1829   }
1830 
1831   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1832     assert(N == 1 && "Invalid number of operands!");
1833     // FIXME: We really want to scale the value here, but the LDRD/STRD
1834     // instruction don't encode operands that way yet.
1835     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1836     Inst.addOperand(MCOperand::createImm(CE->getValue()));
1837   }
1838 
1839   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1840     assert(N == 1 && "Invalid number of operands!");
1841     // The immediate is scaled by four in the encoding and is stored
1842     // in the MCInst as such. Lop off the low two bits here.
1843     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1844     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1845   }
1846 
1847   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1848     assert(N == 1 && "Invalid number of operands!");
1849     // The immediate is scaled by four in the encoding and is stored
1850     // in the MCInst as such. Lop off the low two bits here.
1851     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1852     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
1853   }
1854 
1855   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1856     assert(N == 1 && "Invalid number of operands!");
1857     // The immediate is scaled by four in the encoding and is stored
1858     // in the MCInst as such. Lop off the low two bits here.
1859     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1860     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1861   }
1862 
1863   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1864     assert(N == 1 && "Invalid number of operands!");
1865     // The constant encodes as the immediate-1, and we store in the instruction
1866     // the bits as encoded, so subtract off one here.
1867     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1868     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1869   }
1870 
1871   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1872     assert(N == 1 && "Invalid number of operands!");
1873     // The constant encodes as the immediate-1, and we store in the instruction
1874     // the bits as encoded, so subtract off one here.
1875     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1876     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1877   }
1878 
1879   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1880     assert(N == 1 && "Invalid number of operands!");
1881     // The constant encodes as the immediate, except for 32, which encodes as
1882     // zero.
1883     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1884     unsigned Imm = CE->getValue();
1885     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
1886   }
1887 
1888   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1889     assert(N == 1 && "Invalid number of operands!");
1890     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1891     // the instruction as well.
1892     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1893     int Val = CE->getValue();
1894     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
1895   }
1896 
1897   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
1898     assert(N == 1 && "Invalid number of operands!");
1899     // The operand is actually a t2_so_imm, but we have its bitwise
1900     // negation in the assembly source, so twiddle it here.
1901     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1902     Inst.addOperand(MCOperand::createImm(~CE->getValue()));
1903   }
1904 
1905   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
1906     assert(N == 1 && "Invalid number of operands!");
1907     // The operand is actually a t2_so_imm, but we have its
1908     // negation in the assembly source, so twiddle it here.
1909     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1910     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1911   }
1912 
1913   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
1914     assert(N == 1 && "Invalid number of operands!");
1915     // The operand is actually an imm0_4095, but we have its
1916     // negation in the assembly source, so twiddle it here.
1917     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1918     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1919   }
1920 
1921   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
1922     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
1923       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
1924       return;
1925     }
1926 
1927     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1928     assert(SR && "Unknown value type!");
1929     Inst.addOperand(MCOperand::createExpr(SR));
1930   }
1931 
1932   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
1933     assert(N == 1 && "Invalid number of operands!");
1934     if (isImm()) {
1935       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1936       if (CE) {
1937         Inst.addOperand(MCOperand::createImm(CE->getValue()));
1938         return;
1939       }
1940 
1941       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1942       assert(SR && "Unknown value type!");
1943       Inst.addOperand(MCOperand::createExpr(SR));
1944       return;
1945     }
1946 
1947     assert(isMem()  && "Unknown value type!");
1948     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
1949     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
1950   }
1951 
1952   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
1953     assert(N == 1 && "Invalid number of operands!");
1954     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
1955   }
1956 
1957   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
1958     assert(N == 1 && "Invalid number of operands!");
1959     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
1960   }
1961 
1962   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
1963     assert(N == 1 && "Invalid number of operands!");
1964     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
1965   }
1966 
1967   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
1968     assert(N == 1 && "Invalid number of operands!");
1969     int32_t Imm = Memory.OffsetImm->getValue();
1970     Inst.addOperand(MCOperand::createImm(Imm));
1971   }
1972 
1973   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
1974     assert(N == 1 && "Invalid number of operands!");
1975     assert(isImm() && "Not an immediate!");
1976 
1977     // If we have an immediate that's not a constant, treat it as a label
1978     // reference needing a fixup.
1979     if (!isa<MCConstantExpr>(getImm())) {
1980       Inst.addOperand(MCOperand::createExpr(getImm()));
1981       return;
1982     }
1983 
1984     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1985     int Val = CE->getValue();
1986     Inst.addOperand(MCOperand::createImm(Val));
1987   }
1988 
1989   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
1990     assert(N == 2 && "Invalid number of operands!");
1991     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
1992     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
1993   }
1994 
1995   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
1996     addAlignedMemoryOperands(Inst, N);
1997   }
1998 
1999   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2000     addAlignedMemoryOperands(Inst, N);
2001   }
2002 
2003   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2004     addAlignedMemoryOperands(Inst, N);
2005   }
2006 
2007   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2008     addAlignedMemoryOperands(Inst, N);
2009   }
2010 
2011   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2012     addAlignedMemoryOperands(Inst, N);
2013   }
2014 
2015   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2016     addAlignedMemoryOperands(Inst, N);
2017   }
2018 
2019   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2020     addAlignedMemoryOperands(Inst, N);
2021   }
2022 
2023   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2024     addAlignedMemoryOperands(Inst, N);
2025   }
2026 
2027   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2028     addAlignedMemoryOperands(Inst, N);
2029   }
2030 
2031   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2032     addAlignedMemoryOperands(Inst, N);
2033   }
2034 
2035   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2036     addAlignedMemoryOperands(Inst, N);
2037   }
2038 
2039   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2040     assert(N == 3 && "Invalid number of operands!");
2041     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2042     if (!Memory.OffsetRegNum) {
2043       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2044       // Special case for #-0
2045       if (Val == INT32_MIN) Val = 0;
2046       if (Val < 0) Val = -Val;
2047       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2048     } else {
2049       // For register offset, we encode the shift type and negation flag
2050       // here.
2051       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2052                               Memory.ShiftImm, Memory.ShiftType);
2053     }
2054     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2055     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2056     Inst.addOperand(MCOperand::createImm(Val));
2057   }
2058 
2059   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2060     assert(N == 2 && "Invalid number of operands!");
2061     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2062     assert(CE && "non-constant AM2OffsetImm operand!");
2063     int32_t Val = CE->getValue();
2064     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2065     // Special case for #-0
2066     if (Val == INT32_MIN) Val = 0;
2067     if (Val < 0) Val = -Val;
2068     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2069     Inst.addOperand(MCOperand::createReg(0));
2070     Inst.addOperand(MCOperand::createImm(Val));
2071   }
2072 
2073   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2074     assert(N == 3 && "Invalid number of operands!");
2075     // If we have an immediate that's not a constant, treat it as a label
2076     // reference needing a fixup. If it is a constant, it's something else
2077     // and we reject it.
2078     if (isImm()) {
2079       Inst.addOperand(MCOperand::createExpr(getImm()));
2080       Inst.addOperand(MCOperand::createReg(0));
2081       Inst.addOperand(MCOperand::createImm(0));
2082       return;
2083     }
2084 
2085     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2086     if (!Memory.OffsetRegNum) {
2087       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2088       // Special case for #-0
2089       if (Val == INT32_MIN) Val = 0;
2090       if (Val < 0) Val = -Val;
2091       Val = ARM_AM::getAM3Opc(AddSub, Val);
2092     } else {
2093       // For register offset, we encode the shift type and negation flag
2094       // here.
2095       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2096     }
2097     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2098     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2099     Inst.addOperand(MCOperand::createImm(Val));
2100   }
2101 
2102   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2103     assert(N == 2 && "Invalid number of operands!");
2104     if (Kind == k_PostIndexRegister) {
2105       int32_t Val =
2106         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2107       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2108       Inst.addOperand(MCOperand::createImm(Val));
2109       return;
2110     }
2111 
2112     // Constant offset.
2113     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2114     int32_t Val = CE->getValue();
2115     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2116     // Special case for #-0
2117     if (Val == INT32_MIN) Val = 0;
2118     if (Val < 0) Val = -Val;
2119     Val = ARM_AM::getAM3Opc(AddSub, Val);
2120     Inst.addOperand(MCOperand::createReg(0));
2121     Inst.addOperand(MCOperand::createImm(Val));
2122   }
2123 
2124   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2125     assert(N == 2 && "Invalid number of operands!");
2126     // If we have an immediate that's not a constant, treat it as a label
2127     // reference needing a fixup. If it is a constant, it's something else
2128     // and we reject it.
2129     if (isImm()) {
2130       Inst.addOperand(MCOperand::createExpr(getImm()));
2131       Inst.addOperand(MCOperand::createImm(0));
2132       return;
2133     }
2134 
2135     // The lower two bits are always zero and as such are not encoded.
2136     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2137     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2138     // Special case for #-0
2139     if (Val == INT32_MIN) Val = 0;
2140     if (Val < 0) Val = -Val;
2141     Val = ARM_AM::getAM5Opc(AddSub, Val);
2142     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2143     Inst.addOperand(MCOperand::createImm(Val));
2144   }
2145 
2146   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2147     assert(N == 2 && "Invalid number of operands!");
2148     // If we have an immediate that's not a constant, treat it as a label
2149     // reference needing a fixup. If it is a constant, it's something else
2150     // and we reject it.
2151     if (isImm()) {
2152       Inst.addOperand(MCOperand::createExpr(getImm()));
2153       Inst.addOperand(MCOperand::createImm(0));
2154       return;
2155     }
2156 
2157     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2158     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2159     Inst.addOperand(MCOperand::createImm(Val));
2160   }
2161 
2162   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2163     assert(N == 2 && "Invalid number of operands!");
2164     // The lower two bits are always zero and as such are not encoded.
2165     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2166     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2167     Inst.addOperand(MCOperand::createImm(Val));
2168   }
2169 
2170   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2171     assert(N == 2 && "Invalid number of operands!");
2172     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2173     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2174     Inst.addOperand(MCOperand::createImm(Val));
2175   }
2176 
2177   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2178     addMemImm8OffsetOperands(Inst, N);
2179   }
2180 
2181   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2182     addMemImm8OffsetOperands(Inst, N);
2183   }
2184 
2185   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2186     assert(N == 2 && "Invalid number of operands!");
2187     // If this is an immediate, it's a label reference.
2188     if (isImm()) {
2189       addExpr(Inst, getImm());
2190       Inst.addOperand(MCOperand::createImm(0));
2191       return;
2192     }
2193 
2194     // Otherwise, it's a normal memory reg+offset.
2195     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2196     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2197     Inst.addOperand(MCOperand::createImm(Val));
2198   }
2199 
2200   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2201     assert(N == 2 && "Invalid number of operands!");
2202     // If this is an immediate, it's a label reference.
2203     if (isImm()) {
2204       addExpr(Inst, getImm());
2205       Inst.addOperand(MCOperand::createImm(0));
2206       return;
2207     }
2208 
2209     // Otherwise, it's a normal memory reg+offset.
2210     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2211     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2212     Inst.addOperand(MCOperand::createImm(Val));
2213   }
2214 
2215   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2216     assert(N == 2 && "Invalid number of operands!");
2217     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2218     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2219   }
2220 
2221   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2222     assert(N == 2 && "Invalid number of operands!");
2223     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2224     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2225   }
2226 
2227   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2228     assert(N == 3 && "Invalid number of operands!");
2229     unsigned Val =
2230       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2231                         Memory.ShiftImm, Memory.ShiftType);
2232     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2233     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2234     Inst.addOperand(MCOperand::createImm(Val));
2235   }
2236 
2237   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2238     assert(N == 3 && "Invalid number of operands!");
2239     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2240     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2241     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2242   }
2243 
2244   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2245     assert(N == 2 && "Invalid number of operands!");
2246     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2247     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2248   }
2249 
2250   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2251     assert(N == 2 && "Invalid number of operands!");
2252     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2253     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2254     Inst.addOperand(MCOperand::createImm(Val));
2255   }
2256 
2257   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2258     assert(N == 2 && "Invalid number of operands!");
2259     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2260     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2261     Inst.addOperand(MCOperand::createImm(Val));
2262   }
2263 
2264   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2265     assert(N == 2 && "Invalid number of operands!");
2266     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2267     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2268     Inst.addOperand(MCOperand::createImm(Val));
2269   }
2270 
2271   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2272     assert(N == 2 && "Invalid number of operands!");
2273     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2274     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2275     Inst.addOperand(MCOperand::createImm(Val));
2276   }
2277 
2278   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2279     assert(N == 1 && "Invalid number of operands!");
2280     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2281     assert(CE && "non-constant post-idx-imm8 operand!");
2282     int Imm = CE->getValue();
2283     bool isAdd = Imm >= 0;
2284     if (Imm == INT32_MIN) Imm = 0;
2285     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2286     Inst.addOperand(MCOperand::createImm(Imm));
2287   }
2288 
2289   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2290     assert(N == 1 && "Invalid number of operands!");
2291     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2292     assert(CE && "non-constant post-idx-imm8s4 operand!");
2293     int Imm = CE->getValue();
2294     bool isAdd = Imm >= 0;
2295     if (Imm == INT32_MIN) Imm = 0;
2296     // Immediate is scaled by 4.
2297     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2298     Inst.addOperand(MCOperand::createImm(Imm));
2299   }
2300 
2301   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2302     assert(N == 2 && "Invalid number of operands!");
2303     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2304     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2305   }
2306 
2307   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2308     assert(N == 2 && "Invalid number of operands!");
2309     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2310     // The sign, shift type, and shift amount are encoded in a single operand
2311     // using the AM2 encoding helpers.
2312     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2313     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2314                                      PostIdxReg.ShiftTy);
2315     Inst.addOperand(MCOperand::createImm(Imm));
2316   }
2317 
2318   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2319     assert(N == 1 && "Invalid number of operands!");
2320     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2321   }
2322 
2323   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2324     assert(N == 1 && "Invalid number of operands!");
2325     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2326   }
2327 
2328   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2329     assert(N == 1 && "Invalid number of operands!");
2330     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2331   }
2332 
2333   void addVecListOperands(MCInst &Inst, unsigned N) const {
2334     assert(N == 1 && "Invalid number of operands!");
2335     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2336   }
2337 
2338   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2339     assert(N == 2 && "Invalid number of operands!");
2340     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2341     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2342   }
2343 
2344   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2345     assert(N == 1 && "Invalid number of operands!");
2346     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2347   }
2348 
2349   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2350     assert(N == 1 && "Invalid number of operands!");
2351     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2352   }
2353 
2354   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2355     assert(N == 1 && "Invalid number of operands!");
2356     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2357   }
2358 
2359   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2360     assert(N == 1 && "Invalid number of operands!");
2361     // The immediate encodes the type of constant as well as the value.
2362     // Mask in that this is an i8 splat.
2363     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2364     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2365   }
2366 
2367   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2368     assert(N == 1 && "Invalid number of operands!");
2369     // The immediate encodes the type of constant as well as the value.
2370     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2371     unsigned Value = CE->getValue();
2372     Value = ARM_AM::encodeNEONi16splat(Value);
2373     Inst.addOperand(MCOperand::createImm(Value));
2374   }
2375 
2376   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2377     assert(N == 1 && "Invalid number of operands!");
2378     // The immediate encodes the type of constant as well as the value.
2379     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2380     unsigned Value = CE->getValue();
2381     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2382     Inst.addOperand(MCOperand::createImm(Value));
2383   }
2384 
2385   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2386     assert(N == 1 && "Invalid number of operands!");
2387     // The immediate encodes the type of constant as well as the value.
2388     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2389     unsigned Value = CE->getValue();
2390     Value = ARM_AM::encodeNEONi32splat(Value);
2391     Inst.addOperand(MCOperand::createImm(Value));
2392   }
2393 
2394   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2395     assert(N == 1 && "Invalid number of operands!");
2396     // The immediate encodes the type of constant as well as the value.
2397     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2398     unsigned Value = CE->getValue();
2399     Value = ARM_AM::encodeNEONi32splat(~Value);
2400     Inst.addOperand(MCOperand::createImm(Value));
2401   }
2402 
2403   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2404     assert(N == 1 && "Invalid number of operands!");
2405     // The immediate encodes the type of constant as well as the value.
2406     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2407     unsigned Value = CE->getValue();
2408     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2409             Inst.getOpcode() == ARM::VMOVv16i8) &&
2410            "All vmvn instructions that wants to replicate non-zero byte "
2411            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2412     unsigned B = ((~Value) & 0xff);
2413     B |= 0xe00; // cmode = 0b1110
2414     Inst.addOperand(MCOperand::createImm(B));
2415   }
2416   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2417     assert(N == 1 && "Invalid number of operands!");
2418     // The immediate encodes the type of constant as well as the value.
2419     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2420     unsigned Value = CE->getValue();
2421     if (Value >= 256 && Value <= 0xffff)
2422       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2423     else if (Value > 0xffff && Value <= 0xffffff)
2424       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2425     else if (Value > 0xffffff)
2426       Value = (Value >> 24) | 0x600;
2427     Inst.addOperand(MCOperand::createImm(Value));
2428   }
2429 
2430   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2431     assert(N == 1 && "Invalid number of operands!");
2432     // The immediate encodes the type of constant as well as the value.
2433     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2434     unsigned Value = CE->getValue();
2435     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2436             Inst.getOpcode() == ARM::VMOVv16i8) &&
2437            "All instructions that wants to replicate non-zero byte "
2438            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2439     unsigned B = Value & 0xff;
2440     B |= 0xe00; // cmode = 0b1110
2441     Inst.addOperand(MCOperand::createImm(B));
2442   }
2443   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2444     assert(N == 1 && "Invalid number of operands!");
2445     // The immediate encodes the type of constant as well as the value.
2446     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2447     unsigned Value = ~CE->getValue();
2448     if (Value >= 256 && Value <= 0xffff)
2449       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2450     else if (Value > 0xffff && Value <= 0xffffff)
2451       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2452     else if (Value > 0xffffff)
2453       Value = (Value >> 24) | 0x600;
2454     Inst.addOperand(MCOperand::createImm(Value));
2455   }
2456 
2457   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2458     assert(N == 1 && "Invalid number of operands!");
2459     // The immediate encodes the type of constant as well as the value.
2460     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2461     uint64_t Value = CE->getValue();
2462     unsigned Imm = 0;
2463     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2464       Imm |= (Value & 1) << i;
2465     }
2466     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2467   }
2468 
2469   void print(raw_ostream &OS) const override;
2470 
2471   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2472     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2473     Op->ITMask.Mask = Mask;
2474     Op->StartLoc = S;
2475     Op->EndLoc = S;
2476     return Op;
2477   }
2478 
2479   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2480                                                     SMLoc S) {
2481     auto Op = make_unique<ARMOperand>(k_CondCode);
2482     Op->CC.Val = CC;
2483     Op->StartLoc = S;
2484     Op->EndLoc = S;
2485     return Op;
2486   }
2487 
2488   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2489     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2490     Op->Cop.Val = CopVal;
2491     Op->StartLoc = S;
2492     Op->EndLoc = S;
2493     return Op;
2494   }
2495 
2496   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2497     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2498     Op->Cop.Val = CopVal;
2499     Op->StartLoc = S;
2500     Op->EndLoc = S;
2501     return Op;
2502   }
2503 
2504   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2505                                                         SMLoc E) {
2506     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2507     Op->Cop.Val = Val;
2508     Op->StartLoc = S;
2509     Op->EndLoc = E;
2510     return Op;
2511   }
2512 
2513   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2514     auto Op = make_unique<ARMOperand>(k_CCOut);
2515     Op->Reg.RegNum = RegNum;
2516     Op->StartLoc = S;
2517     Op->EndLoc = S;
2518     return Op;
2519   }
2520 
2521   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2522     auto Op = make_unique<ARMOperand>(k_Token);
2523     Op->Tok.Data = Str.data();
2524     Op->Tok.Length = Str.size();
2525     Op->StartLoc = S;
2526     Op->EndLoc = S;
2527     return Op;
2528   }
2529 
2530   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2531                                                SMLoc E) {
2532     auto Op = make_unique<ARMOperand>(k_Register);
2533     Op->Reg.RegNum = RegNum;
2534     Op->StartLoc = S;
2535     Op->EndLoc = E;
2536     return Op;
2537   }
2538 
2539   static std::unique_ptr<ARMOperand>
2540   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2541                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2542                         SMLoc E) {
2543     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2544     Op->RegShiftedReg.ShiftTy = ShTy;
2545     Op->RegShiftedReg.SrcReg = SrcReg;
2546     Op->RegShiftedReg.ShiftReg = ShiftReg;
2547     Op->RegShiftedReg.ShiftImm = ShiftImm;
2548     Op->StartLoc = S;
2549     Op->EndLoc = E;
2550     return Op;
2551   }
2552 
2553   static std::unique_ptr<ARMOperand>
2554   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2555                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2556     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2557     Op->RegShiftedImm.ShiftTy = ShTy;
2558     Op->RegShiftedImm.SrcReg = SrcReg;
2559     Op->RegShiftedImm.ShiftImm = ShiftImm;
2560     Op->StartLoc = S;
2561     Op->EndLoc = E;
2562     return Op;
2563   }
2564 
2565   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2566                                                       SMLoc S, SMLoc E) {
2567     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2568     Op->ShifterImm.isASR = isASR;
2569     Op->ShifterImm.Imm = Imm;
2570     Op->StartLoc = S;
2571     Op->EndLoc = E;
2572     return Op;
2573   }
2574 
2575   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2576                                                   SMLoc E) {
2577     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2578     Op->RotImm.Imm = Imm;
2579     Op->StartLoc = S;
2580     Op->EndLoc = E;
2581     return Op;
2582   }
2583 
2584   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2585                                                   SMLoc S, SMLoc E) {
2586     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2587     Op->ModImm.Bits = Bits;
2588     Op->ModImm.Rot = Rot;
2589     Op->StartLoc = S;
2590     Op->EndLoc = E;
2591     return Op;
2592   }
2593 
2594   static std::unique_ptr<ARMOperand>
2595   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2596     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2597     Op->Bitfield.LSB = LSB;
2598     Op->Bitfield.Width = Width;
2599     Op->StartLoc = S;
2600     Op->EndLoc = E;
2601     return Op;
2602   }
2603 
2604   static std::unique_ptr<ARMOperand>
2605   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2606                 SMLoc StartLoc, SMLoc EndLoc) {
2607     assert (Regs.size() > 0 && "RegList contains no registers?");
2608     KindTy Kind = k_RegisterList;
2609 
2610     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2611       Kind = k_DPRRegisterList;
2612     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2613              contains(Regs.front().second))
2614       Kind = k_SPRRegisterList;
2615 
2616     // Sort based on the register encoding values.
2617     array_pod_sort(Regs.begin(), Regs.end());
2618 
2619     auto Op = make_unique<ARMOperand>(Kind);
2620     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2621            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2622       Op->Registers.push_back(I->second);
2623     Op->StartLoc = StartLoc;
2624     Op->EndLoc = EndLoc;
2625     return Op;
2626   }
2627 
2628   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2629                                                       unsigned Count,
2630                                                       bool isDoubleSpaced,
2631                                                       SMLoc S, SMLoc E) {
2632     auto Op = make_unique<ARMOperand>(k_VectorList);
2633     Op->VectorList.RegNum = RegNum;
2634     Op->VectorList.Count = Count;
2635     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2636     Op->StartLoc = S;
2637     Op->EndLoc = E;
2638     return Op;
2639   }
2640 
2641   static std::unique_ptr<ARMOperand>
2642   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2643                            SMLoc S, SMLoc E) {
2644     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2645     Op->VectorList.RegNum = RegNum;
2646     Op->VectorList.Count = Count;
2647     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2648     Op->StartLoc = S;
2649     Op->EndLoc = E;
2650     return Op;
2651   }
2652 
2653   static std::unique_ptr<ARMOperand>
2654   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2655                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2656     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2657     Op->VectorList.RegNum = RegNum;
2658     Op->VectorList.Count = Count;
2659     Op->VectorList.LaneIndex = Index;
2660     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2661     Op->StartLoc = S;
2662     Op->EndLoc = E;
2663     return Op;
2664   }
2665 
2666   static std::unique_ptr<ARMOperand>
2667   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2668     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2669     Op->VectorIndex.Val = Idx;
2670     Op->StartLoc = S;
2671     Op->EndLoc = E;
2672     return Op;
2673   }
2674 
2675   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2676                                                SMLoc E) {
2677     auto Op = make_unique<ARMOperand>(k_Immediate);
2678     Op->Imm.Val = Val;
2679     Op->StartLoc = S;
2680     Op->EndLoc = E;
2681     return Op;
2682   }
2683 
2684   static std::unique_ptr<ARMOperand>
2685   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2686             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2687             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2688             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2689     auto Op = make_unique<ARMOperand>(k_Memory);
2690     Op->Memory.BaseRegNum = BaseRegNum;
2691     Op->Memory.OffsetImm = OffsetImm;
2692     Op->Memory.OffsetRegNum = OffsetRegNum;
2693     Op->Memory.ShiftType = ShiftType;
2694     Op->Memory.ShiftImm = ShiftImm;
2695     Op->Memory.Alignment = Alignment;
2696     Op->Memory.isNegative = isNegative;
2697     Op->StartLoc = S;
2698     Op->EndLoc = E;
2699     Op->AlignmentLoc = AlignmentLoc;
2700     return Op;
2701   }
2702 
2703   static std::unique_ptr<ARMOperand>
2704   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2705                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2706     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2707     Op->PostIdxReg.RegNum = RegNum;
2708     Op->PostIdxReg.isAdd = isAdd;
2709     Op->PostIdxReg.ShiftTy = ShiftTy;
2710     Op->PostIdxReg.ShiftImm = ShiftImm;
2711     Op->StartLoc = S;
2712     Op->EndLoc = E;
2713     return Op;
2714   }
2715 
2716   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2717                                                          SMLoc S) {
2718     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2719     Op->MBOpt.Val = Opt;
2720     Op->StartLoc = S;
2721     Op->EndLoc = S;
2722     return Op;
2723   }
2724 
2725   static std::unique_ptr<ARMOperand>
2726   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2727     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2728     Op->ISBOpt.Val = Opt;
2729     Op->StartLoc = S;
2730     Op->EndLoc = S;
2731     return Op;
2732   }
2733 
2734   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2735                                                       SMLoc S) {
2736     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2737     Op->IFlags.Val = IFlags;
2738     Op->StartLoc = S;
2739     Op->EndLoc = S;
2740     return Op;
2741   }
2742 
2743   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2744     auto Op = make_unique<ARMOperand>(k_MSRMask);
2745     Op->MMask.Val = MMask;
2746     Op->StartLoc = S;
2747     Op->EndLoc = S;
2748     return Op;
2749   }
2750 
2751   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2752     auto Op = make_unique<ARMOperand>(k_BankedReg);
2753     Op->BankedReg.Val = Reg;
2754     Op->StartLoc = S;
2755     Op->EndLoc = S;
2756     return Op;
2757   }
2758 };
2759 
2760 } // end anonymous namespace.
2761 
2762 void ARMOperand::print(raw_ostream &OS) const {
2763   switch (Kind) {
2764   case k_CondCode:
2765     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2766     break;
2767   case k_CCOut:
2768     OS << "<ccout " << getReg() << ">";
2769     break;
2770   case k_ITCondMask: {
2771     static const char *const MaskStr[] = {
2772       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2773       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2774     };
2775     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2776     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2777     break;
2778   }
2779   case k_CoprocNum:
2780     OS << "<coprocessor number: " << getCoproc() << ">";
2781     break;
2782   case k_CoprocReg:
2783     OS << "<coprocessor register: " << getCoproc() << ">";
2784     break;
2785   case k_CoprocOption:
2786     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2787     break;
2788   case k_MSRMask:
2789     OS << "<mask: " << getMSRMask() << ">";
2790     break;
2791   case k_BankedReg:
2792     OS << "<banked reg: " << getBankedReg() << ">";
2793     break;
2794   case k_Immediate:
2795     OS << *getImm();
2796     break;
2797   case k_MemBarrierOpt:
2798     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2799     break;
2800   case k_InstSyncBarrierOpt:
2801     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2802     break;
2803   case k_Memory:
2804     OS << "<memory "
2805        << " base:" << Memory.BaseRegNum;
2806     OS << ">";
2807     break;
2808   case k_PostIndexRegister:
2809     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2810        << PostIdxReg.RegNum;
2811     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2812       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2813          << PostIdxReg.ShiftImm;
2814     OS << ">";
2815     break;
2816   case k_ProcIFlags: {
2817     OS << "<ARM_PROC::";
2818     unsigned IFlags = getProcIFlags();
2819     for (int i=2; i >= 0; --i)
2820       if (IFlags & (1 << i))
2821         OS << ARM_PROC::IFlagsToString(1 << i);
2822     OS << ">";
2823     break;
2824   }
2825   case k_Register:
2826     OS << "<register " << getReg() << ">";
2827     break;
2828   case k_ShifterImmediate:
2829     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2830        << " #" << ShifterImm.Imm << ">";
2831     break;
2832   case k_ShiftedRegister:
2833     OS << "<so_reg_reg "
2834        << RegShiftedReg.SrcReg << " "
2835        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2836        << " " << RegShiftedReg.ShiftReg << ">";
2837     break;
2838   case k_ShiftedImmediate:
2839     OS << "<so_reg_imm "
2840        << RegShiftedImm.SrcReg << " "
2841        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2842        << " #" << RegShiftedImm.ShiftImm << ">";
2843     break;
2844   case k_RotateImmediate:
2845     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2846     break;
2847   case k_ModifiedImmediate:
2848     OS << "<mod_imm #" << ModImm.Bits << ", #"
2849        <<  ModImm.Rot << ")>";
2850     break;
2851   case k_BitfieldDescriptor:
2852     OS << "<bitfield " << "lsb: " << Bitfield.LSB
2853        << ", width: " << Bitfield.Width << ">";
2854     break;
2855   case k_RegisterList:
2856   case k_DPRRegisterList:
2857   case k_SPRRegisterList: {
2858     OS << "<register_list ";
2859 
2860     const SmallVectorImpl<unsigned> &RegList = getRegList();
2861     for (SmallVectorImpl<unsigned>::const_iterator
2862            I = RegList.begin(), E = RegList.end(); I != E; ) {
2863       OS << *I;
2864       if (++I < E) OS << ", ";
2865     }
2866 
2867     OS << ">";
2868     break;
2869   }
2870   case k_VectorList:
2871     OS << "<vector_list " << VectorList.Count << " * "
2872        << VectorList.RegNum << ">";
2873     break;
2874   case k_VectorListAllLanes:
2875     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
2876        << VectorList.RegNum << ">";
2877     break;
2878   case k_VectorListIndexed:
2879     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
2880        << VectorList.Count << " * " << VectorList.RegNum << ">";
2881     break;
2882   case k_Token:
2883     OS << "'" << getToken() << "'";
2884     break;
2885   case k_VectorIndex:
2886     OS << "<vectorindex " << getVectorIndex() << ">";
2887     break;
2888   }
2889 }
2890 
2891 /// @name Auto-generated Match Functions
2892 /// {
2893 
2894 static unsigned MatchRegisterName(StringRef Name);
2895 
2896 /// }
2897 
2898 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
2899                                  SMLoc &StartLoc, SMLoc &EndLoc) {
2900   const AsmToken &Tok = getParser().getTok();
2901   StartLoc = Tok.getLoc();
2902   EndLoc = Tok.getEndLoc();
2903   RegNo = tryParseRegister();
2904 
2905   return (RegNo == (unsigned)-1);
2906 }
2907 
2908 /// Try to parse a register name.  The token must be an Identifier when called,
2909 /// and if it is a register name the token is eaten and the register number is
2910 /// returned.  Otherwise return -1.
2911 ///
2912 int ARMAsmParser::tryParseRegister() {
2913   MCAsmParser &Parser = getParser();
2914   const AsmToken &Tok = Parser.getTok();
2915   if (Tok.isNot(AsmToken::Identifier)) return -1;
2916 
2917   std::string lowerCase = Tok.getString().lower();
2918   unsigned RegNum = MatchRegisterName(lowerCase);
2919   if (!RegNum) {
2920     RegNum = StringSwitch<unsigned>(lowerCase)
2921       .Case("r13", ARM::SP)
2922       .Case("r14", ARM::LR)
2923       .Case("r15", ARM::PC)
2924       .Case("ip", ARM::R12)
2925       // Additional register name aliases for 'gas' compatibility.
2926       .Case("a1", ARM::R0)
2927       .Case("a2", ARM::R1)
2928       .Case("a3", ARM::R2)
2929       .Case("a4", ARM::R3)
2930       .Case("v1", ARM::R4)
2931       .Case("v2", ARM::R5)
2932       .Case("v3", ARM::R6)
2933       .Case("v4", ARM::R7)
2934       .Case("v5", ARM::R8)
2935       .Case("v6", ARM::R9)
2936       .Case("v7", ARM::R10)
2937       .Case("v8", ARM::R11)
2938       .Case("sb", ARM::R9)
2939       .Case("sl", ARM::R10)
2940       .Case("fp", ARM::R11)
2941       .Default(0);
2942   }
2943   if (!RegNum) {
2944     // Check for aliases registered via .req. Canonicalize to lower case.
2945     // That's more consistent since register names are case insensitive, and
2946     // it's how the original entry was passed in from MC/MCParser/AsmParser.
2947     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
2948     // If no match, return failure.
2949     if (Entry == RegisterReqs.end())
2950       return -1;
2951     Parser.Lex(); // Eat identifier token.
2952     return Entry->getValue();
2953   }
2954 
2955   // Some FPUs only have 16 D registers, so D16-D31 are invalid
2956   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
2957     return -1;
2958 
2959   Parser.Lex(); // Eat identifier token.
2960 
2961   return RegNum;
2962 }
2963 
2964 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
2965 // If a recoverable error occurs, return 1. If an irrecoverable error
2966 // occurs, return -1. An irrecoverable error is one where tokens have been
2967 // consumed in the process of trying to parse the shifter (i.e., when it is
2968 // indeed a shifter operand, but malformed).
2969 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
2970   MCAsmParser &Parser = getParser();
2971   SMLoc S = Parser.getTok().getLoc();
2972   const AsmToken &Tok = Parser.getTok();
2973   if (Tok.isNot(AsmToken::Identifier))
2974     return -1;
2975 
2976   std::string lowerCase = Tok.getString().lower();
2977   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
2978       .Case("asl", ARM_AM::lsl)
2979       .Case("lsl", ARM_AM::lsl)
2980       .Case("lsr", ARM_AM::lsr)
2981       .Case("asr", ARM_AM::asr)
2982       .Case("ror", ARM_AM::ror)
2983       .Case("rrx", ARM_AM::rrx)
2984       .Default(ARM_AM::no_shift);
2985 
2986   if (ShiftTy == ARM_AM::no_shift)
2987     return 1;
2988 
2989   Parser.Lex(); // Eat the operator.
2990 
2991   // The source register for the shift has already been added to the
2992   // operand list, so we need to pop it off and combine it into the shifted
2993   // register operand instead.
2994   std::unique_ptr<ARMOperand> PrevOp(
2995       (ARMOperand *)Operands.pop_back_val().release());
2996   if (!PrevOp->isReg())
2997     return Error(PrevOp->getStartLoc(), "shift must be of a register");
2998   int SrcReg = PrevOp->getReg();
2999 
3000   SMLoc EndLoc;
3001   int64_t Imm = 0;
3002   int ShiftReg = 0;
3003   if (ShiftTy == ARM_AM::rrx) {
3004     // RRX Doesn't have an explicit shift amount. The encoder expects
3005     // the shift register to be the same as the source register. Seems odd,
3006     // but OK.
3007     ShiftReg = SrcReg;
3008   } else {
3009     // Figure out if this is shifted by a constant or a register (for non-RRX).
3010     if (Parser.getTok().is(AsmToken::Hash) ||
3011         Parser.getTok().is(AsmToken::Dollar)) {
3012       Parser.Lex(); // Eat hash.
3013       SMLoc ImmLoc = Parser.getTok().getLoc();
3014       const MCExpr *ShiftExpr = nullptr;
3015       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3016         Error(ImmLoc, "invalid immediate shift value");
3017         return -1;
3018       }
3019       // The expression must be evaluatable as an immediate.
3020       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3021       if (!CE) {
3022         Error(ImmLoc, "invalid immediate shift value");
3023         return -1;
3024       }
3025       // Range check the immediate.
3026       // lsl, ror: 0 <= imm <= 31
3027       // lsr, asr: 0 <= imm <= 32
3028       Imm = CE->getValue();
3029       if (Imm < 0 ||
3030           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3031           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3032         Error(ImmLoc, "immediate shift value out of range");
3033         return -1;
3034       }
3035       // shift by zero is a nop. Always send it through as lsl.
3036       // ('as' compatibility)
3037       if (Imm == 0)
3038         ShiftTy = ARM_AM::lsl;
3039     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3040       SMLoc L = Parser.getTok().getLoc();
3041       EndLoc = Parser.getTok().getEndLoc();
3042       ShiftReg = tryParseRegister();
3043       if (ShiftReg == -1) {
3044         Error(L, "expected immediate or register in shift operand");
3045         return -1;
3046       }
3047     } else {
3048       Error(Parser.getTok().getLoc(),
3049             "expected immediate or register in shift operand");
3050       return -1;
3051     }
3052   }
3053 
3054   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3055     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3056                                                          ShiftReg, Imm,
3057                                                          S, EndLoc));
3058   else
3059     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3060                                                           S, EndLoc));
3061 
3062   return 0;
3063 }
3064 
3065 
3066 /// Try to parse a register name.  The token must be an Identifier when called.
3067 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3068 /// if there is a "writeback". 'true' if it's not a register.
3069 ///
3070 /// TODO this is likely to change to allow different register types and or to
3071 /// parse for a specific register type.
3072 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3073   MCAsmParser &Parser = getParser();
3074   const AsmToken &RegTok = Parser.getTok();
3075   int RegNo = tryParseRegister();
3076   if (RegNo == -1)
3077     return true;
3078 
3079   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3080                                            RegTok.getEndLoc()));
3081 
3082   const AsmToken &ExclaimTok = Parser.getTok();
3083   if (ExclaimTok.is(AsmToken::Exclaim)) {
3084     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3085                                                ExclaimTok.getLoc()));
3086     Parser.Lex(); // Eat exclaim token
3087     return false;
3088   }
3089 
3090   // Also check for an index operand. This is only legal for vector registers,
3091   // but that'll get caught OK in operand matching, so we don't need to
3092   // explicitly filter everything else out here.
3093   if (Parser.getTok().is(AsmToken::LBrac)) {
3094     SMLoc SIdx = Parser.getTok().getLoc();
3095     Parser.Lex(); // Eat left bracket token.
3096 
3097     const MCExpr *ImmVal;
3098     if (getParser().parseExpression(ImmVal))
3099       return true;
3100     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3101     if (!MCE)
3102       return TokError("immediate value expected for vector index");
3103 
3104     if (Parser.getTok().isNot(AsmToken::RBrac))
3105       return Error(Parser.getTok().getLoc(), "']' expected");
3106 
3107     SMLoc E = Parser.getTok().getEndLoc();
3108     Parser.Lex(); // Eat right bracket token.
3109 
3110     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3111                                                      SIdx, E,
3112                                                      getContext()));
3113   }
3114 
3115   return false;
3116 }
3117 
3118 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3119 /// instruction with a symbolic operand name.
3120 /// We accept "crN" syntax for GAS compatibility.
3121 /// <operand-name> ::= <prefix><number>
3122 /// If CoprocOp is 'c', then:
3123 ///   <prefix> ::= c | cr
3124 /// If CoprocOp is 'p', then :
3125 ///   <prefix> ::= p
3126 /// <number> ::= integer in range [0, 15]
3127 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3128   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3129   // but efficient.
3130   if (Name.size() < 2 || Name[0] != CoprocOp)
3131     return -1;
3132   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3133 
3134   switch (Name.size()) {
3135   default: return -1;
3136   case 1:
3137     switch (Name[0]) {
3138     default:  return -1;
3139     case '0': return 0;
3140     case '1': return 1;
3141     case '2': return 2;
3142     case '3': return 3;
3143     case '4': return 4;
3144     case '5': return 5;
3145     case '6': return 6;
3146     case '7': return 7;
3147     case '8': return 8;
3148     case '9': return 9;
3149     }
3150   case 2:
3151     if (Name[0] != '1')
3152       return -1;
3153     switch (Name[1]) {
3154     default:  return -1;
3155     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3156     // However, old cores (v5/v6) did use them in that way.
3157     case '0': return 10;
3158     case '1': return 11;
3159     case '2': return 12;
3160     case '3': return 13;
3161     case '4': return 14;
3162     case '5': return 15;
3163     }
3164   }
3165 }
3166 
3167 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3168 ARMAsmParser::OperandMatchResultTy
3169 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3170   MCAsmParser &Parser = getParser();
3171   SMLoc S = Parser.getTok().getLoc();
3172   const AsmToken &Tok = Parser.getTok();
3173   if (!Tok.is(AsmToken::Identifier))
3174     return MatchOperand_NoMatch;
3175   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3176     .Case("eq", ARMCC::EQ)
3177     .Case("ne", ARMCC::NE)
3178     .Case("hs", ARMCC::HS)
3179     .Case("cs", ARMCC::HS)
3180     .Case("lo", ARMCC::LO)
3181     .Case("cc", ARMCC::LO)
3182     .Case("mi", ARMCC::MI)
3183     .Case("pl", ARMCC::PL)
3184     .Case("vs", ARMCC::VS)
3185     .Case("vc", ARMCC::VC)
3186     .Case("hi", ARMCC::HI)
3187     .Case("ls", ARMCC::LS)
3188     .Case("ge", ARMCC::GE)
3189     .Case("lt", ARMCC::LT)
3190     .Case("gt", ARMCC::GT)
3191     .Case("le", ARMCC::LE)
3192     .Case("al", ARMCC::AL)
3193     .Default(~0U);
3194   if (CC == ~0U)
3195     return MatchOperand_NoMatch;
3196   Parser.Lex(); // Eat the token.
3197 
3198   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3199 
3200   return MatchOperand_Success;
3201 }
3202 
3203 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3204 /// token must be an Identifier when called, and if it is a coprocessor
3205 /// number, the token is eaten and the operand is added to the operand list.
3206 ARMAsmParser::OperandMatchResultTy
3207 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3208   MCAsmParser &Parser = getParser();
3209   SMLoc S = Parser.getTok().getLoc();
3210   const AsmToken &Tok = Parser.getTok();
3211   if (Tok.isNot(AsmToken::Identifier))
3212     return MatchOperand_NoMatch;
3213 
3214   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3215   if (Num == -1)
3216     return MatchOperand_NoMatch;
3217   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3218   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3219     return MatchOperand_NoMatch;
3220 
3221   Parser.Lex(); // Eat identifier token.
3222   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3223   return MatchOperand_Success;
3224 }
3225 
3226 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3227 /// token must be an Identifier when called, and if it is a coprocessor
3228 /// number, the token is eaten and the operand is added to the operand list.
3229 ARMAsmParser::OperandMatchResultTy
3230 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3231   MCAsmParser &Parser = getParser();
3232   SMLoc S = Parser.getTok().getLoc();
3233   const AsmToken &Tok = Parser.getTok();
3234   if (Tok.isNot(AsmToken::Identifier))
3235     return MatchOperand_NoMatch;
3236 
3237   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3238   if (Reg == -1)
3239     return MatchOperand_NoMatch;
3240 
3241   Parser.Lex(); // Eat identifier token.
3242   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3243   return MatchOperand_Success;
3244 }
3245 
3246 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3247 /// coproc_option : '{' imm0_255 '}'
3248 ARMAsmParser::OperandMatchResultTy
3249 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3250   MCAsmParser &Parser = getParser();
3251   SMLoc S = Parser.getTok().getLoc();
3252 
3253   // If this isn't a '{', this isn't a coprocessor immediate operand.
3254   if (Parser.getTok().isNot(AsmToken::LCurly))
3255     return MatchOperand_NoMatch;
3256   Parser.Lex(); // Eat the '{'
3257 
3258   const MCExpr *Expr;
3259   SMLoc Loc = Parser.getTok().getLoc();
3260   if (getParser().parseExpression(Expr)) {
3261     Error(Loc, "illegal expression");
3262     return MatchOperand_ParseFail;
3263   }
3264   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3265   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3266     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3267     return MatchOperand_ParseFail;
3268   }
3269   int Val = CE->getValue();
3270 
3271   // Check for and consume the closing '}'
3272   if (Parser.getTok().isNot(AsmToken::RCurly))
3273     return MatchOperand_ParseFail;
3274   SMLoc E = Parser.getTok().getEndLoc();
3275   Parser.Lex(); // Eat the '}'
3276 
3277   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3278   return MatchOperand_Success;
3279 }
3280 
3281 // For register list parsing, we need to map from raw GPR register numbering
3282 // to the enumeration values. The enumeration values aren't sorted by
3283 // register number due to our using "sp", "lr" and "pc" as canonical names.
3284 static unsigned getNextRegister(unsigned Reg) {
3285   // If this is a GPR, we need to do it manually, otherwise we can rely
3286   // on the sort ordering of the enumeration since the other reg-classes
3287   // are sane.
3288   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3289     return Reg + 1;
3290   switch(Reg) {
3291   default: llvm_unreachable("Invalid GPR number!");
3292   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3293   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3294   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3295   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3296   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3297   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3298   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3299   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3300   }
3301 }
3302 
3303 // Return the low-subreg of a given Q register.
3304 static unsigned getDRegFromQReg(unsigned QReg) {
3305   switch (QReg) {
3306   default: llvm_unreachable("expected a Q register!");
3307   case ARM::Q0:  return ARM::D0;
3308   case ARM::Q1:  return ARM::D2;
3309   case ARM::Q2:  return ARM::D4;
3310   case ARM::Q3:  return ARM::D6;
3311   case ARM::Q4:  return ARM::D8;
3312   case ARM::Q5:  return ARM::D10;
3313   case ARM::Q6:  return ARM::D12;
3314   case ARM::Q7:  return ARM::D14;
3315   case ARM::Q8:  return ARM::D16;
3316   case ARM::Q9:  return ARM::D18;
3317   case ARM::Q10: return ARM::D20;
3318   case ARM::Q11: return ARM::D22;
3319   case ARM::Q12: return ARM::D24;
3320   case ARM::Q13: return ARM::D26;
3321   case ARM::Q14: return ARM::D28;
3322   case ARM::Q15: return ARM::D30;
3323   }
3324 }
3325 
3326 /// Parse a register list.
3327 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3328   MCAsmParser &Parser = getParser();
3329   assert(Parser.getTok().is(AsmToken::LCurly) &&
3330          "Token is not a Left Curly Brace");
3331   SMLoc S = Parser.getTok().getLoc();
3332   Parser.Lex(); // Eat '{' token.
3333   SMLoc RegLoc = Parser.getTok().getLoc();
3334 
3335   // Check the first register in the list to see what register class
3336   // this is a list of.
3337   int Reg = tryParseRegister();
3338   if (Reg == -1)
3339     return Error(RegLoc, "register expected");
3340 
3341   // The reglist instructions have at most 16 registers, so reserve
3342   // space for that many.
3343   int EReg = 0;
3344   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3345 
3346   // Allow Q regs and just interpret them as the two D sub-registers.
3347   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3348     Reg = getDRegFromQReg(Reg);
3349     EReg = MRI->getEncodingValue(Reg);
3350     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3351     ++Reg;
3352   }
3353   const MCRegisterClass *RC;
3354   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3355     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3356   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3357     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3358   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3359     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3360   else
3361     return Error(RegLoc, "invalid register in register list");
3362 
3363   // Store the register.
3364   EReg = MRI->getEncodingValue(Reg);
3365   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3366 
3367   // This starts immediately after the first register token in the list,
3368   // so we can see either a comma or a minus (range separator) as a legal
3369   // next token.
3370   while (Parser.getTok().is(AsmToken::Comma) ||
3371          Parser.getTok().is(AsmToken::Minus)) {
3372     if (Parser.getTok().is(AsmToken::Minus)) {
3373       Parser.Lex(); // Eat the minus.
3374       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3375       int EndReg = tryParseRegister();
3376       if (EndReg == -1)
3377         return Error(AfterMinusLoc, "register expected");
3378       // Allow Q regs and just interpret them as the two D sub-registers.
3379       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3380         EndReg = getDRegFromQReg(EndReg) + 1;
3381       // If the register is the same as the start reg, there's nothing
3382       // more to do.
3383       if (Reg == EndReg)
3384         continue;
3385       // The register must be in the same register class as the first.
3386       if (!RC->contains(EndReg))
3387         return Error(AfterMinusLoc, "invalid register in register list");
3388       // Ranges must go from low to high.
3389       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3390         return Error(AfterMinusLoc, "bad range in register list");
3391 
3392       // Add all the registers in the range to the register list.
3393       while (Reg != EndReg) {
3394         Reg = getNextRegister(Reg);
3395         EReg = MRI->getEncodingValue(Reg);
3396         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3397       }
3398       continue;
3399     }
3400     Parser.Lex(); // Eat the comma.
3401     RegLoc = Parser.getTok().getLoc();
3402     int OldReg = Reg;
3403     const AsmToken RegTok = Parser.getTok();
3404     Reg = tryParseRegister();
3405     if (Reg == -1)
3406       return Error(RegLoc, "register expected");
3407     // Allow Q regs and just interpret them as the two D sub-registers.
3408     bool isQReg = false;
3409     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3410       Reg = getDRegFromQReg(Reg);
3411       isQReg = true;
3412     }
3413     // The register must be in the same register class as the first.
3414     if (!RC->contains(Reg))
3415       return Error(RegLoc, "invalid register in register list");
3416     // List must be monotonically increasing.
3417     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3418       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3419         Warning(RegLoc, "register list not in ascending order");
3420       else
3421         return Error(RegLoc, "register list not in ascending order");
3422     }
3423     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3424       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3425               ") in register list");
3426       continue;
3427     }
3428     // VFP register lists must also be contiguous.
3429     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3430         Reg != OldReg + 1)
3431       return Error(RegLoc, "non-contiguous register range");
3432     EReg = MRI->getEncodingValue(Reg);
3433     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3434     if (isQReg) {
3435       EReg = MRI->getEncodingValue(++Reg);
3436       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3437     }
3438   }
3439 
3440   if (Parser.getTok().isNot(AsmToken::RCurly))
3441     return Error(Parser.getTok().getLoc(), "'}' expected");
3442   SMLoc E = Parser.getTok().getEndLoc();
3443   Parser.Lex(); // Eat '}' token.
3444 
3445   // Push the register list operand.
3446   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3447 
3448   // The ARM system instruction variants for LDM/STM have a '^' token here.
3449   if (Parser.getTok().is(AsmToken::Caret)) {
3450     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3451     Parser.Lex(); // Eat '^' token.
3452   }
3453 
3454   return false;
3455 }
3456 
3457 // Helper function to parse the lane index for vector lists.
3458 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3459 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3460   MCAsmParser &Parser = getParser();
3461   Index = 0; // Always return a defined index value.
3462   if (Parser.getTok().is(AsmToken::LBrac)) {
3463     Parser.Lex(); // Eat the '['.
3464     if (Parser.getTok().is(AsmToken::RBrac)) {
3465       // "Dn[]" is the 'all lanes' syntax.
3466       LaneKind = AllLanes;
3467       EndLoc = Parser.getTok().getEndLoc();
3468       Parser.Lex(); // Eat the ']'.
3469       return MatchOperand_Success;
3470     }
3471 
3472     // There's an optional '#' token here. Normally there wouldn't be, but
3473     // inline assemble puts one in, and it's friendly to accept that.
3474     if (Parser.getTok().is(AsmToken::Hash))
3475       Parser.Lex(); // Eat '#' or '$'.
3476 
3477     const MCExpr *LaneIndex;
3478     SMLoc Loc = Parser.getTok().getLoc();
3479     if (getParser().parseExpression(LaneIndex)) {
3480       Error(Loc, "illegal expression");
3481       return MatchOperand_ParseFail;
3482     }
3483     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3484     if (!CE) {
3485       Error(Loc, "lane index must be empty or an integer");
3486       return MatchOperand_ParseFail;
3487     }
3488     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3489       Error(Parser.getTok().getLoc(), "']' expected");
3490       return MatchOperand_ParseFail;
3491     }
3492     EndLoc = Parser.getTok().getEndLoc();
3493     Parser.Lex(); // Eat the ']'.
3494     int64_t Val = CE->getValue();
3495 
3496     // FIXME: Make this range check context sensitive for .8, .16, .32.
3497     if (Val < 0 || Val > 7) {
3498       Error(Parser.getTok().getLoc(), "lane index out of range");
3499       return MatchOperand_ParseFail;
3500     }
3501     Index = Val;
3502     LaneKind = IndexedLane;
3503     return MatchOperand_Success;
3504   }
3505   LaneKind = NoLanes;
3506   return MatchOperand_Success;
3507 }
3508 
3509 // parse a vector register list
3510 ARMAsmParser::OperandMatchResultTy
3511 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3512   MCAsmParser &Parser = getParser();
3513   VectorLaneTy LaneKind;
3514   unsigned LaneIndex;
3515   SMLoc S = Parser.getTok().getLoc();
3516   // As an extension (to match gas), support a plain D register or Q register
3517   // (without encosing curly braces) as a single or double entry list,
3518   // respectively.
3519   if (Parser.getTok().is(AsmToken::Identifier)) {
3520     SMLoc E = Parser.getTok().getEndLoc();
3521     int Reg = tryParseRegister();
3522     if (Reg == -1)
3523       return MatchOperand_NoMatch;
3524     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3525       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3526       if (Res != MatchOperand_Success)
3527         return Res;
3528       switch (LaneKind) {
3529       case NoLanes:
3530         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3531         break;
3532       case AllLanes:
3533         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3534                                                                 S, E));
3535         break;
3536       case IndexedLane:
3537         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3538                                                                LaneIndex,
3539                                                                false, S, E));
3540         break;
3541       }
3542       return MatchOperand_Success;
3543     }
3544     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3545       Reg = getDRegFromQReg(Reg);
3546       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3547       if (Res != MatchOperand_Success)
3548         return Res;
3549       switch (LaneKind) {
3550       case NoLanes:
3551         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3552                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3553         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3554         break;
3555       case AllLanes:
3556         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3557                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3558         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3559                                                                 S, E));
3560         break;
3561       case IndexedLane:
3562         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3563                                                                LaneIndex,
3564                                                                false, S, E));
3565         break;
3566       }
3567       return MatchOperand_Success;
3568     }
3569     Error(S, "vector register expected");
3570     return MatchOperand_ParseFail;
3571   }
3572 
3573   if (Parser.getTok().isNot(AsmToken::LCurly))
3574     return MatchOperand_NoMatch;
3575 
3576   Parser.Lex(); // Eat '{' token.
3577   SMLoc RegLoc = Parser.getTok().getLoc();
3578 
3579   int Reg = tryParseRegister();
3580   if (Reg == -1) {
3581     Error(RegLoc, "register expected");
3582     return MatchOperand_ParseFail;
3583   }
3584   unsigned Count = 1;
3585   int Spacing = 0;
3586   unsigned FirstReg = Reg;
3587   // The list is of D registers, but we also allow Q regs and just interpret
3588   // them as the two D sub-registers.
3589   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3590     FirstReg = Reg = getDRegFromQReg(Reg);
3591     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3592                  // it's ambiguous with four-register single spaced.
3593     ++Reg;
3594     ++Count;
3595   }
3596 
3597   SMLoc E;
3598   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3599     return MatchOperand_ParseFail;
3600 
3601   while (Parser.getTok().is(AsmToken::Comma) ||
3602          Parser.getTok().is(AsmToken::Minus)) {
3603     if (Parser.getTok().is(AsmToken::Minus)) {
3604       if (!Spacing)
3605         Spacing = 1; // Register range implies a single spaced list.
3606       else if (Spacing == 2) {
3607         Error(Parser.getTok().getLoc(),
3608               "sequential registers in double spaced list");
3609         return MatchOperand_ParseFail;
3610       }
3611       Parser.Lex(); // Eat the minus.
3612       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3613       int EndReg = tryParseRegister();
3614       if (EndReg == -1) {
3615         Error(AfterMinusLoc, "register expected");
3616         return MatchOperand_ParseFail;
3617       }
3618       // Allow Q regs and just interpret them as the two D sub-registers.
3619       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3620         EndReg = getDRegFromQReg(EndReg) + 1;
3621       // If the register is the same as the start reg, there's nothing
3622       // more to do.
3623       if (Reg == EndReg)
3624         continue;
3625       // The register must be in the same register class as the first.
3626       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3627         Error(AfterMinusLoc, "invalid register in register list");
3628         return MatchOperand_ParseFail;
3629       }
3630       // Ranges must go from low to high.
3631       if (Reg > EndReg) {
3632         Error(AfterMinusLoc, "bad range in register list");
3633         return MatchOperand_ParseFail;
3634       }
3635       // Parse the lane specifier if present.
3636       VectorLaneTy NextLaneKind;
3637       unsigned NextLaneIndex;
3638       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3639           MatchOperand_Success)
3640         return MatchOperand_ParseFail;
3641       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3642         Error(AfterMinusLoc, "mismatched lane index in register list");
3643         return MatchOperand_ParseFail;
3644       }
3645 
3646       // Add all the registers in the range to the register list.
3647       Count += EndReg - Reg;
3648       Reg = EndReg;
3649       continue;
3650     }
3651     Parser.Lex(); // Eat the comma.
3652     RegLoc = Parser.getTok().getLoc();
3653     int OldReg = Reg;
3654     Reg = tryParseRegister();
3655     if (Reg == -1) {
3656       Error(RegLoc, "register expected");
3657       return MatchOperand_ParseFail;
3658     }
3659     // vector register lists must be contiguous.
3660     // It's OK to use the enumeration values directly here rather, as the
3661     // VFP register classes have the enum sorted properly.
3662     //
3663     // The list is of D registers, but we also allow Q regs and just interpret
3664     // them as the two D sub-registers.
3665     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3666       if (!Spacing)
3667         Spacing = 1; // Register range implies a single spaced list.
3668       else if (Spacing == 2) {
3669         Error(RegLoc,
3670               "invalid register in double-spaced list (must be 'D' register')");
3671         return MatchOperand_ParseFail;
3672       }
3673       Reg = getDRegFromQReg(Reg);
3674       if (Reg != OldReg + 1) {
3675         Error(RegLoc, "non-contiguous register range");
3676         return MatchOperand_ParseFail;
3677       }
3678       ++Reg;
3679       Count += 2;
3680       // Parse the lane specifier if present.
3681       VectorLaneTy NextLaneKind;
3682       unsigned NextLaneIndex;
3683       SMLoc LaneLoc = Parser.getTok().getLoc();
3684       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3685           MatchOperand_Success)
3686         return MatchOperand_ParseFail;
3687       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3688         Error(LaneLoc, "mismatched lane index in register list");
3689         return MatchOperand_ParseFail;
3690       }
3691       continue;
3692     }
3693     // Normal D register.
3694     // Figure out the register spacing (single or double) of the list if
3695     // we don't know it already.
3696     if (!Spacing)
3697       Spacing = 1 + (Reg == OldReg + 2);
3698 
3699     // Just check that it's contiguous and keep going.
3700     if (Reg != OldReg + Spacing) {
3701       Error(RegLoc, "non-contiguous register range");
3702       return MatchOperand_ParseFail;
3703     }
3704     ++Count;
3705     // Parse the lane specifier if present.
3706     VectorLaneTy NextLaneKind;
3707     unsigned NextLaneIndex;
3708     SMLoc EndLoc = Parser.getTok().getLoc();
3709     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3710       return MatchOperand_ParseFail;
3711     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3712       Error(EndLoc, "mismatched lane index in register list");
3713       return MatchOperand_ParseFail;
3714     }
3715   }
3716 
3717   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3718     Error(Parser.getTok().getLoc(), "'}' expected");
3719     return MatchOperand_ParseFail;
3720   }
3721   E = Parser.getTok().getEndLoc();
3722   Parser.Lex(); // Eat '}' token.
3723 
3724   switch (LaneKind) {
3725   case NoLanes:
3726     // Two-register operands have been converted to the
3727     // composite register classes.
3728     if (Count == 2) {
3729       const MCRegisterClass *RC = (Spacing == 1) ?
3730         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3731         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3732       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3733     }
3734 
3735     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3736                                                     (Spacing == 2), S, E));
3737     break;
3738   case AllLanes:
3739     // Two-register operands have been converted to the
3740     // composite register classes.
3741     if (Count == 2) {
3742       const MCRegisterClass *RC = (Spacing == 1) ?
3743         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3744         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3745       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3746     }
3747     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3748                                                             (Spacing == 2),
3749                                                             S, E));
3750     break;
3751   case IndexedLane:
3752     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3753                                                            LaneIndex,
3754                                                            (Spacing == 2),
3755                                                            S, E));
3756     break;
3757   }
3758   return MatchOperand_Success;
3759 }
3760 
3761 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3762 ARMAsmParser::OperandMatchResultTy
3763 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3764   MCAsmParser &Parser = getParser();
3765   SMLoc S = Parser.getTok().getLoc();
3766   const AsmToken &Tok = Parser.getTok();
3767   unsigned Opt;
3768 
3769   if (Tok.is(AsmToken::Identifier)) {
3770     StringRef OptStr = Tok.getString();
3771 
3772     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3773       .Case("sy",    ARM_MB::SY)
3774       .Case("st",    ARM_MB::ST)
3775       .Case("ld",    ARM_MB::LD)
3776       .Case("sh",    ARM_MB::ISH)
3777       .Case("ish",   ARM_MB::ISH)
3778       .Case("shst",  ARM_MB::ISHST)
3779       .Case("ishst", ARM_MB::ISHST)
3780       .Case("ishld", ARM_MB::ISHLD)
3781       .Case("nsh",   ARM_MB::NSH)
3782       .Case("un",    ARM_MB::NSH)
3783       .Case("nshst", ARM_MB::NSHST)
3784       .Case("nshld", ARM_MB::NSHLD)
3785       .Case("unst",  ARM_MB::NSHST)
3786       .Case("osh",   ARM_MB::OSH)
3787       .Case("oshst", ARM_MB::OSHST)
3788       .Case("oshld", ARM_MB::OSHLD)
3789       .Default(~0U);
3790 
3791     // ishld, oshld, nshld and ld are only available from ARMv8.
3792     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3793                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3794       Opt = ~0U;
3795 
3796     if (Opt == ~0U)
3797       return MatchOperand_NoMatch;
3798 
3799     Parser.Lex(); // Eat identifier token.
3800   } else if (Tok.is(AsmToken::Hash) ||
3801              Tok.is(AsmToken::Dollar) ||
3802              Tok.is(AsmToken::Integer)) {
3803     if (Parser.getTok().isNot(AsmToken::Integer))
3804       Parser.Lex(); // Eat '#' or '$'.
3805     SMLoc Loc = Parser.getTok().getLoc();
3806 
3807     const MCExpr *MemBarrierID;
3808     if (getParser().parseExpression(MemBarrierID)) {
3809       Error(Loc, "illegal expression");
3810       return MatchOperand_ParseFail;
3811     }
3812 
3813     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3814     if (!CE) {
3815       Error(Loc, "constant expression expected");
3816       return MatchOperand_ParseFail;
3817     }
3818 
3819     int Val = CE->getValue();
3820     if (Val & ~0xf) {
3821       Error(Loc, "immediate value out of range");
3822       return MatchOperand_ParseFail;
3823     }
3824 
3825     Opt = ARM_MB::RESERVED_0 + Val;
3826   } else
3827     return MatchOperand_ParseFail;
3828 
3829   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3830   return MatchOperand_Success;
3831 }
3832 
3833 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3834 ARMAsmParser::OperandMatchResultTy
3835 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3836   MCAsmParser &Parser = getParser();
3837   SMLoc S = Parser.getTok().getLoc();
3838   const AsmToken &Tok = Parser.getTok();
3839   unsigned Opt;
3840 
3841   if (Tok.is(AsmToken::Identifier)) {
3842     StringRef OptStr = Tok.getString();
3843 
3844     if (OptStr.equals_lower("sy"))
3845       Opt = ARM_ISB::SY;
3846     else
3847       return MatchOperand_NoMatch;
3848 
3849     Parser.Lex(); // Eat identifier token.
3850   } else if (Tok.is(AsmToken::Hash) ||
3851              Tok.is(AsmToken::Dollar) ||
3852              Tok.is(AsmToken::Integer)) {
3853     if (Parser.getTok().isNot(AsmToken::Integer))
3854       Parser.Lex(); // Eat '#' or '$'.
3855     SMLoc Loc = Parser.getTok().getLoc();
3856 
3857     const MCExpr *ISBarrierID;
3858     if (getParser().parseExpression(ISBarrierID)) {
3859       Error(Loc, "illegal expression");
3860       return MatchOperand_ParseFail;
3861     }
3862 
3863     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
3864     if (!CE) {
3865       Error(Loc, "constant expression expected");
3866       return MatchOperand_ParseFail;
3867     }
3868 
3869     int Val = CE->getValue();
3870     if (Val & ~0xf) {
3871       Error(Loc, "immediate value out of range");
3872       return MatchOperand_ParseFail;
3873     }
3874 
3875     Opt = ARM_ISB::RESERVED_0 + Val;
3876   } else
3877     return MatchOperand_ParseFail;
3878 
3879   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
3880           (ARM_ISB::InstSyncBOpt)Opt, S));
3881   return MatchOperand_Success;
3882 }
3883 
3884 
3885 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
3886 ARMAsmParser::OperandMatchResultTy
3887 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
3888   MCAsmParser &Parser = getParser();
3889   SMLoc S = Parser.getTok().getLoc();
3890   const AsmToken &Tok = Parser.getTok();
3891   if (!Tok.is(AsmToken::Identifier))
3892     return MatchOperand_NoMatch;
3893   StringRef IFlagsStr = Tok.getString();
3894 
3895   // An iflags string of "none" is interpreted to mean that none of the AIF
3896   // bits are set.  Not a terribly useful instruction, but a valid encoding.
3897   unsigned IFlags = 0;
3898   if (IFlagsStr != "none") {
3899         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
3900       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
3901         .Case("a", ARM_PROC::A)
3902         .Case("i", ARM_PROC::I)
3903         .Case("f", ARM_PROC::F)
3904         .Default(~0U);
3905 
3906       // If some specific iflag is already set, it means that some letter is
3907       // present more than once, this is not acceptable.
3908       if (Flag == ~0U || (IFlags & Flag))
3909         return MatchOperand_NoMatch;
3910 
3911       IFlags |= Flag;
3912     }
3913   }
3914 
3915   Parser.Lex(); // Eat identifier token.
3916   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
3917   return MatchOperand_Success;
3918 }
3919 
3920 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
3921 ARMAsmParser::OperandMatchResultTy
3922 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
3923   MCAsmParser &Parser = getParser();
3924   SMLoc S = Parser.getTok().getLoc();
3925   const AsmToken &Tok = Parser.getTok();
3926   if (!Tok.is(AsmToken::Identifier))
3927     return MatchOperand_NoMatch;
3928   StringRef Mask = Tok.getString();
3929 
3930   if (isMClass()) {
3931     // See ARMv6-M 10.1.1
3932     std::string Name = Mask.lower();
3933     unsigned FlagsVal = StringSwitch<unsigned>(Name)
3934       // Note: in the documentation:
3935       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
3936       //  for MSR APSR_nzcvq.
3937       // but we do make it an alias here.  This is so to get the "mask encoding"
3938       // bits correct on MSR APSR writes.
3939       //
3940       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
3941       // should really only be allowed when writing a special register.  Note
3942       // they get dropped in the MRS instruction reading a special register as
3943       // the SYSm field is only 8 bits.
3944       .Case("apsr", 0x800)
3945       .Case("apsr_nzcvq", 0x800)
3946       .Case("apsr_g", 0x400)
3947       .Case("apsr_nzcvqg", 0xc00)
3948       .Case("iapsr", 0x801)
3949       .Case("iapsr_nzcvq", 0x801)
3950       .Case("iapsr_g", 0x401)
3951       .Case("iapsr_nzcvqg", 0xc01)
3952       .Case("eapsr", 0x802)
3953       .Case("eapsr_nzcvq", 0x802)
3954       .Case("eapsr_g", 0x402)
3955       .Case("eapsr_nzcvqg", 0xc02)
3956       .Case("xpsr", 0x803)
3957       .Case("xpsr_nzcvq", 0x803)
3958       .Case("xpsr_g", 0x403)
3959       .Case("xpsr_nzcvqg", 0xc03)
3960       .Case("ipsr", 0x805)
3961       .Case("epsr", 0x806)
3962       .Case("iepsr", 0x807)
3963       .Case("msp", 0x808)
3964       .Case("psp", 0x809)
3965       .Case("primask", 0x810)
3966       .Case("basepri", 0x811)
3967       .Case("basepri_max", 0x812)
3968       .Case("faultmask", 0x813)
3969       .Case("control", 0x814)
3970       .Default(~0U);
3971 
3972     if (FlagsVal == ~0U)
3973       return MatchOperand_NoMatch;
3974 
3975     if (!hasThumb2DSP() && (FlagsVal & 0x400))
3976       // The _g and _nzcvqg versions are only valid if the DSP extension is
3977       // available.
3978       return MatchOperand_NoMatch;
3979 
3980     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
3981       // basepri, basepri_max and faultmask only valid for V7m.
3982       return MatchOperand_NoMatch;
3983 
3984     Parser.Lex(); // Eat identifier token.
3985     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
3986     return MatchOperand_Success;
3987   }
3988 
3989   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
3990   size_t Start = 0, Next = Mask.find('_');
3991   StringRef Flags = "";
3992   std::string SpecReg = Mask.slice(Start, Next).lower();
3993   if (Next != StringRef::npos)
3994     Flags = Mask.slice(Next+1, Mask.size());
3995 
3996   // FlagsVal contains the complete mask:
3997   // 3-0: Mask
3998   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
3999   unsigned FlagsVal = 0;
4000 
4001   if (SpecReg == "apsr") {
4002     FlagsVal = StringSwitch<unsigned>(Flags)
4003     .Case("nzcvq",  0x8) // same as CPSR_f
4004     .Case("g",      0x4) // same as CPSR_s
4005     .Case("nzcvqg", 0xc) // same as CPSR_fs
4006     .Default(~0U);
4007 
4008     if (FlagsVal == ~0U) {
4009       if (!Flags.empty())
4010         return MatchOperand_NoMatch;
4011       else
4012         FlagsVal = 8; // No flag
4013     }
4014   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4015     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4016     if (Flags == "all" || Flags == "")
4017       Flags = "fc";
4018     for (int i = 0, e = Flags.size(); i != e; ++i) {
4019       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4020       .Case("c", 1)
4021       .Case("x", 2)
4022       .Case("s", 4)
4023       .Case("f", 8)
4024       .Default(~0U);
4025 
4026       // If some specific flag is already set, it means that some letter is
4027       // present more than once, this is not acceptable.
4028       if (FlagsVal == ~0U || (FlagsVal & Flag))
4029         return MatchOperand_NoMatch;
4030       FlagsVal |= Flag;
4031     }
4032   } else // No match for special register.
4033     return MatchOperand_NoMatch;
4034 
4035   // Special register without flags is NOT equivalent to "fc" flags.
4036   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4037   // two lines would enable gas compatibility at the expense of breaking
4038   // round-tripping.
4039   //
4040   // if (!FlagsVal)
4041   //  FlagsVal = 0x9;
4042 
4043   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4044   if (SpecReg == "spsr")
4045     FlagsVal |= 16;
4046 
4047   Parser.Lex(); // Eat identifier token.
4048   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4049   return MatchOperand_Success;
4050 }
4051 
4052 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4053 /// use in the MRS/MSR instructions added to support virtualization.
4054 ARMAsmParser::OperandMatchResultTy
4055 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4056   MCAsmParser &Parser = getParser();
4057   SMLoc S = Parser.getTok().getLoc();
4058   const AsmToken &Tok = Parser.getTok();
4059   if (!Tok.is(AsmToken::Identifier))
4060     return MatchOperand_NoMatch;
4061   StringRef RegName = Tok.getString();
4062 
4063   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4064   // and bit 5 is R.
4065   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4066                           .Case("r8_usr", 0x00)
4067                           .Case("r9_usr", 0x01)
4068                           .Case("r10_usr", 0x02)
4069                           .Case("r11_usr", 0x03)
4070                           .Case("r12_usr", 0x04)
4071                           .Case("sp_usr", 0x05)
4072                           .Case("lr_usr", 0x06)
4073                           .Case("r8_fiq", 0x08)
4074                           .Case("r9_fiq", 0x09)
4075                           .Case("r10_fiq", 0x0a)
4076                           .Case("r11_fiq", 0x0b)
4077                           .Case("r12_fiq", 0x0c)
4078                           .Case("sp_fiq", 0x0d)
4079                           .Case("lr_fiq", 0x0e)
4080                           .Case("lr_irq", 0x10)
4081                           .Case("sp_irq", 0x11)
4082                           .Case("lr_svc", 0x12)
4083                           .Case("sp_svc", 0x13)
4084                           .Case("lr_abt", 0x14)
4085                           .Case("sp_abt", 0x15)
4086                           .Case("lr_und", 0x16)
4087                           .Case("sp_und", 0x17)
4088                           .Case("lr_mon", 0x1c)
4089                           .Case("sp_mon", 0x1d)
4090                           .Case("elr_hyp", 0x1e)
4091                           .Case("sp_hyp", 0x1f)
4092                           .Case("spsr_fiq", 0x2e)
4093                           .Case("spsr_irq", 0x30)
4094                           .Case("spsr_svc", 0x32)
4095                           .Case("spsr_abt", 0x34)
4096                           .Case("spsr_und", 0x36)
4097                           .Case("spsr_mon", 0x3c)
4098                           .Case("spsr_hyp", 0x3e)
4099                           .Default(~0U);
4100 
4101   if (Encoding == ~0U)
4102     return MatchOperand_NoMatch;
4103 
4104   Parser.Lex(); // Eat identifier token.
4105   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4106   return MatchOperand_Success;
4107 }
4108 
4109 ARMAsmParser::OperandMatchResultTy
4110 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4111                           int High) {
4112   MCAsmParser &Parser = getParser();
4113   const AsmToken &Tok = Parser.getTok();
4114   if (Tok.isNot(AsmToken::Identifier)) {
4115     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4116     return MatchOperand_ParseFail;
4117   }
4118   StringRef ShiftName = Tok.getString();
4119   std::string LowerOp = Op.lower();
4120   std::string UpperOp = Op.upper();
4121   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4122     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4123     return MatchOperand_ParseFail;
4124   }
4125   Parser.Lex(); // Eat shift type token.
4126 
4127   // There must be a '#' and a shift amount.
4128   if (Parser.getTok().isNot(AsmToken::Hash) &&
4129       Parser.getTok().isNot(AsmToken::Dollar)) {
4130     Error(Parser.getTok().getLoc(), "'#' expected");
4131     return MatchOperand_ParseFail;
4132   }
4133   Parser.Lex(); // Eat hash token.
4134 
4135   const MCExpr *ShiftAmount;
4136   SMLoc Loc = Parser.getTok().getLoc();
4137   SMLoc EndLoc;
4138   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4139     Error(Loc, "illegal expression");
4140     return MatchOperand_ParseFail;
4141   }
4142   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4143   if (!CE) {
4144     Error(Loc, "constant expression expected");
4145     return MatchOperand_ParseFail;
4146   }
4147   int Val = CE->getValue();
4148   if (Val < Low || Val > High) {
4149     Error(Loc, "immediate value out of range");
4150     return MatchOperand_ParseFail;
4151   }
4152 
4153   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4154 
4155   return MatchOperand_Success;
4156 }
4157 
4158 ARMAsmParser::OperandMatchResultTy
4159 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4160   MCAsmParser &Parser = getParser();
4161   const AsmToken &Tok = Parser.getTok();
4162   SMLoc S = Tok.getLoc();
4163   if (Tok.isNot(AsmToken::Identifier)) {
4164     Error(S, "'be' or 'le' operand expected");
4165     return MatchOperand_ParseFail;
4166   }
4167   int Val = StringSwitch<int>(Tok.getString().lower())
4168     .Case("be", 1)
4169     .Case("le", 0)
4170     .Default(-1);
4171   Parser.Lex(); // Eat the token.
4172 
4173   if (Val == -1) {
4174     Error(S, "'be' or 'le' operand expected");
4175     return MatchOperand_ParseFail;
4176   }
4177   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4178                                                                   getContext()),
4179                                            S, Tok.getEndLoc()));
4180   return MatchOperand_Success;
4181 }
4182 
4183 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4184 /// instructions. Legal values are:
4185 ///     lsl #n  'n' in [0,31]
4186 ///     asr #n  'n' in [1,32]
4187 ///             n == 32 encoded as n == 0.
4188 ARMAsmParser::OperandMatchResultTy
4189 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4190   MCAsmParser &Parser = getParser();
4191   const AsmToken &Tok = Parser.getTok();
4192   SMLoc S = Tok.getLoc();
4193   if (Tok.isNot(AsmToken::Identifier)) {
4194     Error(S, "shift operator 'asr' or 'lsl' expected");
4195     return MatchOperand_ParseFail;
4196   }
4197   StringRef ShiftName = Tok.getString();
4198   bool isASR;
4199   if (ShiftName == "lsl" || ShiftName == "LSL")
4200     isASR = false;
4201   else if (ShiftName == "asr" || ShiftName == "ASR")
4202     isASR = true;
4203   else {
4204     Error(S, "shift operator 'asr' or 'lsl' expected");
4205     return MatchOperand_ParseFail;
4206   }
4207   Parser.Lex(); // Eat the operator.
4208 
4209   // A '#' and a shift amount.
4210   if (Parser.getTok().isNot(AsmToken::Hash) &&
4211       Parser.getTok().isNot(AsmToken::Dollar)) {
4212     Error(Parser.getTok().getLoc(), "'#' expected");
4213     return MatchOperand_ParseFail;
4214   }
4215   Parser.Lex(); // Eat hash token.
4216   SMLoc ExLoc = Parser.getTok().getLoc();
4217 
4218   const MCExpr *ShiftAmount;
4219   SMLoc EndLoc;
4220   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4221     Error(ExLoc, "malformed shift expression");
4222     return MatchOperand_ParseFail;
4223   }
4224   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4225   if (!CE) {
4226     Error(ExLoc, "shift amount must be an immediate");
4227     return MatchOperand_ParseFail;
4228   }
4229 
4230   int64_t Val = CE->getValue();
4231   if (isASR) {
4232     // Shift amount must be in [1,32]
4233     if (Val < 1 || Val > 32) {
4234       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4235       return MatchOperand_ParseFail;
4236     }
4237     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4238     if (isThumb() && Val == 32) {
4239       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4240       return MatchOperand_ParseFail;
4241     }
4242     if (Val == 32) Val = 0;
4243   } else {
4244     // Shift amount must be in [1,32]
4245     if (Val < 0 || Val > 31) {
4246       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4247       return MatchOperand_ParseFail;
4248     }
4249   }
4250 
4251   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4252 
4253   return MatchOperand_Success;
4254 }
4255 
4256 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4257 /// of instructions. Legal values are:
4258 ///     ror #n  'n' in {0, 8, 16, 24}
4259 ARMAsmParser::OperandMatchResultTy
4260 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4261   MCAsmParser &Parser = getParser();
4262   const AsmToken &Tok = Parser.getTok();
4263   SMLoc S = Tok.getLoc();
4264   if (Tok.isNot(AsmToken::Identifier))
4265     return MatchOperand_NoMatch;
4266   StringRef ShiftName = Tok.getString();
4267   if (ShiftName != "ror" && ShiftName != "ROR")
4268     return MatchOperand_NoMatch;
4269   Parser.Lex(); // Eat the operator.
4270 
4271   // A '#' and a rotate amount.
4272   if (Parser.getTok().isNot(AsmToken::Hash) &&
4273       Parser.getTok().isNot(AsmToken::Dollar)) {
4274     Error(Parser.getTok().getLoc(), "'#' expected");
4275     return MatchOperand_ParseFail;
4276   }
4277   Parser.Lex(); // Eat hash token.
4278   SMLoc ExLoc = Parser.getTok().getLoc();
4279 
4280   const MCExpr *ShiftAmount;
4281   SMLoc EndLoc;
4282   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4283     Error(ExLoc, "malformed rotate expression");
4284     return MatchOperand_ParseFail;
4285   }
4286   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4287   if (!CE) {
4288     Error(ExLoc, "rotate amount must be an immediate");
4289     return MatchOperand_ParseFail;
4290   }
4291 
4292   int64_t Val = CE->getValue();
4293   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4294   // normally, zero is represented in asm by omitting the rotate operand
4295   // entirely.
4296   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4297     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4298     return MatchOperand_ParseFail;
4299   }
4300 
4301   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4302 
4303   return MatchOperand_Success;
4304 }
4305 
4306 ARMAsmParser::OperandMatchResultTy
4307 ARMAsmParser::parseModImm(OperandVector &Operands) {
4308   MCAsmParser &Parser = getParser();
4309   MCAsmLexer &Lexer = getLexer();
4310   int64_t Imm1, Imm2;
4311 
4312   SMLoc S = Parser.getTok().getLoc();
4313 
4314   // 1) A mod_imm operand can appear in the place of a register name:
4315   //   add r0, #mod_imm
4316   //   add r0, r0, #mod_imm
4317   // to correctly handle the latter, we bail out as soon as we see an
4318   // identifier.
4319   //
4320   // 2) Similarly, we do not want to parse into complex operands:
4321   //   mov r0, #mod_imm
4322   //   mov r0, :lower16:(_foo)
4323   if (Parser.getTok().is(AsmToken::Identifier) ||
4324       Parser.getTok().is(AsmToken::Colon))
4325     return MatchOperand_NoMatch;
4326 
4327   // Hash (dollar) is optional as per the ARMARM
4328   if (Parser.getTok().is(AsmToken::Hash) ||
4329       Parser.getTok().is(AsmToken::Dollar)) {
4330     // Avoid parsing into complex operands (#:)
4331     if (Lexer.peekTok().is(AsmToken::Colon))
4332       return MatchOperand_NoMatch;
4333 
4334     // Eat the hash (dollar)
4335     Parser.Lex();
4336   }
4337 
4338   SMLoc Sx1, Ex1;
4339   Sx1 = Parser.getTok().getLoc();
4340   const MCExpr *Imm1Exp;
4341   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4342     Error(Sx1, "malformed expression");
4343     return MatchOperand_ParseFail;
4344   }
4345 
4346   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4347 
4348   if (CE) {
4349     // Immediate must fit within 32-bits
4350     Imm1 = CE->getValue();
4351     int Enc = ARM_AM::getSOImmVal(Imm1);
4352     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4353       // We have a match!
4354       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4355                                                   (Enc & 0xF00) >> 7,
4356                                                   Sx1, Ex1));
4357       return MatchOperand_Success;
4358     }
4359 
4360     // We have parsed an immediate which is not for us, fallback to a plain
4361     // immediate. This can happen for instruction aliases. For an example,
4362     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4363     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4364     // instruction with a mod_imm operand. The alias is defined such that the
4365     // parser method is shared, that's why we have to do this here.
4366     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4367       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4368       return MatchOperand_Success;
4369     }
4370   } else {
4371     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4372     // MCFixup). Fallback to a plain immediate.
4373     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4374     return MatchOperand_Success;
4375   }
4376 
4377   // From this point onward, we expect the input to be a (#bits, #rot) pair
4378   if (Parser.getTok().isNot(AsmToken::Comma)) {
4379     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4380     return MatchOperand_ParseFail;
4381   }
4382 
4383   if (Imm1 & ~0xFF) {
4384     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4385     return MatchOperand_ParseFail;
4386   }
4387 
4388   // Eat the comma
4389   Parser.Lex();
4390 
4391   // Repeat for #rot
4392   SMLoc Sx2, Ex2;
4393   Sx2 = Parser.getTok().getLoc();
4394 
4395   // Eat the optional hash (dollar)
4396   if (Parser.getTok().is(AsmToken::Hash) ||
4397       Parser.getTok().is(AsmToken::Dollar))
4398     Parser.Lex();
4399 
4400   const MCExpr *Imm2Exp;
4401   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4402     Error(Sx2, "malformed expression");
4403     return MatchOperand_ParseFail;
4404   }
4405 
4406   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4407 
4408   if (CE) {
4409     Imm2 = CE->getValue();
4410     if (!(Imm2 & ~0x1E)) {
4411       // We have a match!
4412       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4413       return MatchOperand_Success;
4414     }
4415     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4416     return MatchOperand_ParseFail;
4417   } else {
4418     Error(Sx2, "constant expression expected");
4419     return MatchOperand_ParseFail;
4420   }
4421 }
4422 
4423 ARMAsmParser::OperandMatchResultTy
4424 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4425   MCAsmParser &Parser = getParser();
4426   SMLoc S = Parser.getTok().getLoc();
4427   // The bitfield descriptor is really two operands, the LSB and the width.
4428   if (Parser.getTok().isNot(AsmToken::Hash) &&
4429       Parser.getTok().isNot(AsmToken::Dollar)) {
4430     Error(Parser.getTok().getLoc(), "'#' expected");
4431     return MatchOperand_ParseFail;
4432   }
4433   Parser.Lex(); // Eat hash token.
4434 
4435   const MCExpr *LSBExpr;
4436   SMLoc E = Parser.getTok().getLoc();
4437   if (getParser().parseExpression(LSBExpr)) {
4438     Error(E, "malformed immediate expression");
4439     return MatchOperand_ParseFail;
4440   }
4441   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4442   if (!CE) {
4443     Error(E, "'lsb' operand must be an immediate");
4444     return MatchOperand_ParseFail;
4445   }
4446 
4447   int64_t LSB = CE->getValue();
4448   // The LSB must be in the range [0,31]
4449   if (LSB < 0 || LSB > 31) {
4450     Error(E, "'lsb' operand must be in the range [0,31]");
4451     return MatchOperand_ParseFail;
4452   }
4453   E = Parser.getTok().getLoc();
4454 
4455   // Expect another immediate operand.
4456   if (Parser.getTok().isNot(AsmToken::Comma)) {
4457     Error(Parser.getTok().getLoc(), "too few operands");
4458     return MatchOperand_ParseFail;
4459   }
4460   Parser.Lex(); // Eat hash token.
4461   if (Parser.getTok().isNot(AsmToken::Hash) &&
4462       Parser.getTok().isNot(AsmToken::Dollar)) {
4463     Error(Parser.getTok().getLoc(), "'#' expected");
4464     return MatchOperand_ParseFail;
4465   }
4466   Parser.Lex(); // Eat hash token.
4467 
4468   const MCExpr *WidthExpr;
4469   SMLoc EndLoc;
4470   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4471     Error(E, "malformed immediate expression");
4472     return MatchOperand_ParseFail;
4473   }
4474   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4475   if (!CE) {
4476     Error(E, "'width' operand must be an immediate");
4477     return MatchOperand_ParseFail;
4478   }
4479 
4480   int64_t Width = CE->getValue();
4481   // The LSB must be in the range [1,32-lsb]
4482   if (Width < 1 || Width > 32 - LSB) {
4483     Error(E, "'width' operand must be in the range [1,32-lsb]");
4484     return MatchOperand_ParseFail;
4485   }
4486 
4487   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4488 
4489   return MatchOperand_Success;
4490 }
4491 
4492 ARMAsmParser::OperandMatchResultTy
4493 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4494   // Check for a post-index addressing register operand. Specifically:
4495   // postidx_reg := '+' register {, shift}
4496   //              | '-' register {, shift}
4497   //              | register {, shift}
4498 
4499   // This method must return MatchOperand_NoMatch without consuming any tokens
4500   // in the case where there is no match, as other alternatives take other
4501   // parse methods.
4502   MCAsmParser &Parser = getParser();
4503   AsmToken Tok = Parser.getTok();
4504   SMLoc S = Tok.getLoc();
4505   bool haveEaten = false;
4506   bool isAdd = true;
4507   if (Tok.is(AsmToken::Plus)) {
4508     Parser.Lex(); // Eat the '+' token.
4509     haveEaten = true;
4510   } else if (Tok.is(AsmToken::Minus)) {
4511     Parser.Lex(); // Eat the '-' token.
4512     isAdd = false;
4513     haveEaten = true;
4514   }
4515 
4516   SMLoc E = Parser.getTok().getEndLoc();
4517   int Reg = tryParseRegister();
4518   if (Reg == -1) {
4519     if (!haveEaten)
4520       return MatchOperand_NoMatch;
4521     Error(Parser.getTok().getLoc(), "register expected");
4522     return MatchOperand_ParseFail;
4523   }
4524 
4525   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4526   unsigned ShiftImm = 0;
4527   if (Parser.getTok().is(AsmToken::Comma)) {
4528     Parser.Lex(); // Eat the ','.
4529     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4530       return MatchOperand_ParseFail;
4531 
4532     // FIXME: Only approximates end...may include intervening whitespace.
4533     E = Parser.getTok().getLoc();
4534   }
4535 
4536   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4537                                                   ShiftImm, S, E));
4538 
4539   return MatchOperand_Success;
4540 }
4541 
4542 ARMAsmParser::OperandMatchResultTy
4543 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4544   // Check for a post-index addressing register operand. Specifically:
4545   // am3offset := '+' register
4546   //              | '-' register
4547   //              | register
4548   //              | # imm
4549   //              | # + imm
4550   //              | # - imm
4551 
4552   // This method must return MatchOperand_NoMatch without consuming any tokens
4553   // in the case where there is no match, as other alternatives take other
4554   // parse methods.
4555   MCAsmParser &Parser = getParser();
4556   AsmToken Tok = Parser.getTok();
4557   SMLoc S = Tok.getLoc();
4558 
4559   // Do immediates first, as we always parse those if we have a '#'.
4560   if (Parser.getTok().is(AsmToken::Hash) ||
4561       Parser.getTok().is(AsmToken::Dollar)) {
4562     Parser.Lex(); // Eat '#' or '$'.
4563     // Explicitly look for a '-', as we need to encode negative zero
4564     // differently.
4565     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4566     const MCExpr *Offset;
4567     SMLoc E;
4568     if (getParser().parseExpression(Offset, E))
4569       return MatchOperand_ParseFail;
4570     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4571     if (!CE) {
4572       Error(S, "constant expression expected");
4573       return MatchOperand_ParseFail;
4574     }
4575     // Negative zero is encoded as the flag value INT32_MIN.
4576     int32_t Val = CE->getValue();
4577     if (isNegative && Val == 0)
4578       Val = INT32_MIN;
4579 
4580     Operands.push_back(
4581       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4582 
4583     return MatchOperand_Success;
4584   }
4585 
4586 
4587   bool haveEaten = false;
4588   bool isAdd = true;
4589   if (Tok.is(AsmToken::Plus)) {
4590     Parser.Lex(); // Eat the '+' token.
4591     haveEaten = true;
4592   } else if (Tok.is(AsmToken::Minus)) {
4593     Parser.Lex(); // Eat the '-' token.
4594     isAdd = false;
4595     haveEaten = true;
4596   }
4597 
4598   Tok = Parser.getTok();
4599   int Reg = tryParseRegister();
4600   if (Reg == -1) {
4601     if (!haveEaten)
4602       return MatchOperand_NoMatch;
4603     Error(Tok.getLoc(), "register expected");
4604     return MatchOperand_ParseFail;
4605   }
4606 
4607   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4608                                                   0, S, Tok.getEndLoc()));
4609 
4610   return MatchOperand_Success;
4611 }
4612 
4613 /// Convert parsed operands to MCInst.  Needed here because this instruction
4614 /// only has two register operands, but multiplication is commutative so
4615 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4616 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4617                                     const OperandVector &Operands) {
4618   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4619   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4620   // If we have a three-operand form, make sure to set Rn to be the operand
4621   // that isn't the same as Rd.
4622   unsigned RegOp = 4;
4623   if (Operands.size() == 6 &&
4624       ((ARMOperand &)*Operands[4]).getReg() ==
4625           ((ARMOperand &)*Operands[3]).getReg())
4626     RegOp = 5;
4627   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4628   Inst.addOperand(Inst.getOperand(0));
4629   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4630 }
4631 
4632 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4633                                     const OperandVector &Operands) {
4634   int CondOp = -1, ImmOp = -1;
4635   switch(Inst.getOpcode()) {
4636     case ARM::tB:
4637     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4638 
4639     case ARM::t2B:
4640     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4641 
4642     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4643   }
4644   // first decide whether or not the branch should be conditional
4645   // by looking at it's location relative to an IT block
4646   if(inITBlock()) {
4647     // inside an IT block we cannot have any conditional branches. any
4648     // such instructions needs to be converted to unconditional form
4649     switch(Inst.getOpcode()) {
4650       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4651       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4652     }
4653   } else {
4654     // outside IT blocks we can only have unconditional branches with AL
4655     // condition code or conditional branches with non-AL condition code
4656     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4657     switch(Inst.getOpcode()) {
4658       case ARM::tB:
4659       case ARM::tBcc:
4660         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4661         break;
4662       case ARM::t2B:
4663       case ARM::t2Bcc:
4664         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4665         break;
4666     }
4667   }
4668 
4669   // now decide on encoding size based on branch target range
4670   switch(Inst.getOpcode()) {
4671     // classify tB as either t2B or t1B based on range of immediate operand
4672     case ARM::tB: {
4673       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4674       if (!op.isSignedOffset<11, 1>() && isThumbTwo())
4675         Inst.setOpcode(ARM::t2B);
4676       break;
4677     }
4678     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4679     case ARM::tBcc: {
4680       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4681       if (!op.isSignedOffset<8, 1>() && isThumbTwo())
4682         Inst.setOpcode(ARM::t2Bcc);
4683       break;
4684     }
4685   }
4686   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4687   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4688 }
4689 
4690 /// Parse an ARM memory expression, return false if successful else return true
4691 /// or an error.  The first token must be a '[' when called.
4692 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4693   MCAsmParser &Parser = getParser();
4694   SMLoc S, E;
4695   assert(Parser.getTok().is(AsmToken::LBrac) &&
4696          "Token is not a Left Bracket");
4697   S = Parser.getTok().getLoc();
4698   Parser.Lex(); // Eat left bracket token.
4699 
4700   const AsmToken &BaseRegTok = Parser.getTok();
4701   int BaseRegNum = tryParseRegister();
4702   if (BaseRegNum == -1)
4703     return Error(BaseRegTok.getLoc(), "register expected");
4704 
4705   // The next token must either be a comma, a colon or a closing bracket.
4706   const AsmToken &Tok = Parser.getTok();
4707   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4708       !Tok.is(AsmToken::RBrac))
4709     return Error(Tok.getLoc(), "malformed memory operand");
4710 
4711   if (Tok.is(AsmToken::RBrac)) {
4712     E = Tok.getEndLoc();
4713     Parser.Lex(); // Eat right bracket token.
4714 
4715     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4716                                              ARM_AM::no_shift, 0, 0, false,
4717                                              S, E));
4718 
4719     // If there's a pre-indexing writeback marker, '!', just add it as a token
4720     // operand. It's rather odd, but syntactically valid.
4721     if (Parser.getTok().is(AsmToken::Exclaim)) {
4722       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4723       Parser.Lex(); // Eat the '!'.
4724     }
4725 
4726     return false;
4727   }
4728 
4729   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4730          "Lost colon or comma in memory operand?!");
4731   if (Tok.is(AsmToken::Comma)) {
4732     Parser.Lex(); // Eat the comma.
4733   }
4734 
4735   // If we have a ':', it's an alignment specifier.
4736   if (Parser.getTok().is(AsmToken::Colon)) {
4737     Parser.Lex(); // Eat the ':'.
4738     E = Parser.getTok().getLoc();
4739     SMLoc AlignmentLoc = Tok.getLoc();
4740 
4741     const MCExpr *Expr;
4742     if (getParser().parseExpression(Expr))
4743      return true;
4744 
4745     // The expression has to be a constant. Memory references with relocations
4746     // don't come through here, as they use the <label> forms of the relevant
4747     // instructions.
4748     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4749     if (!CE)
4750       return Error (E, "constant expression expected");
4751 
4752     unsigned Align = 0;
4753     switch (CE->getValue()) {
4754     default:
4755       return Error(E,
4756                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4757     case 16:  Align = 2; break;
4758     case 32:  Align = 4; break;
4759     case 64:  Align = 8; break;
4760     case 128: Align = 16; break;
4761     case 256: Align = 32; break;
4762     }
4763 
4764     // Now we should have the closing ']'
4765     if (Parser.getTok().isNot(AsmToken::RBrac))
4766       return Error(Parser.getTok().getLoc(), "']' expected");
4767     E = Parser.getTok().getEndLoc();
4768     Parser.Lex(); // Eat right bracket token.
4769 
4770     // Don't worry about range checking the value here. That's handled by
4771     // the is*() predicates.
4772     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4773                                              ARM_AM::no_shift, 0, Align,
4774                                              false, S, E, AlignmentLoc));
4775 
4776     // If there's a pre-indexing writeback marker, '!', just add it as a token
4777     // operand.
4778     if (Parser.getTok().is(AsmToken::Exclaim)) {
4779       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4780       Parser.Lex(); // Eat the '!'.
4781     }
4782 
4783     return false;
4784   }
4785 
4786   // If we have a '#', it's an immediate offset, else assume it's a register
4787   // offset. Be friendly and also accept a plain integer (without a leading
4788   // hash) for gas compatibility.
4789   if (Parser.getTok().is(AsmToken::Hash) ||
4790       Parser.getTok().is(AsmToken::Dollar) ||
4791       Parser.getTok().is(AsmToken::Integer)) {
4792     if (Parser.getTok().isNot(AsmToken::Integer))
4793       Parser.Lex(); // Eat '#' or '$'.
4794     E = Parser.getTok().getLoc();
4795 
4796     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4797     const MCExpr *Offset;
4798     if (getParser().parseExpression(Offset))
4799      return true;
4800 
4801     // The expression has to be a constant. Memory references with relocations
4802     // don't come through here, as they use the <label> forms of the relevant
4803     // instructions.
4804     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4805     if (!CE)
4806       return Error (E, "constant expression expected");
4807 
4808     // If the constant was #-0, represent it as INT32_MIN.
4809     int32_t Val = CE->getValue();
4810     if (isNegative && Val == 0)
4811       CE = MCConstantExpr::create(INT32_MIN, getContext());
4812 
4813     // Now we should have the closing ']'
4814     if (Parser.getTok().isNot(AsmToken::RBrac))
4815       return Error(Parser.getTok().getLoc(), "']' expected");
4816     E = Parser.getTok().getEndLoc();
4817     Parser.Lex(); // Eat right bracket token.
4818 
4819     // Don't worry about range checking the value here. That's handled by
4820     // the is*() predicates.
4821     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4822                                              ARM_AM::no_shift, 0, 0,
4823                                              false, S, E));
4824 
4825     // If there's a pre-indexing writeback marker, '!', just add it as a token
4826     // operand.
4827     if (Parser.getTok().is(AsmToken::Exclaim)) {
4828       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4829       Parser.Lex(); // Eat the '!'.
4830     }
4831 
4832     return false;
4833   }
4834 
4835   // The register offset is optionally preceded by a '+' or '-'
4836   bool isNegative = false;
4837   if (Parser.getTok().is(AsmToken::Minus)) {
4838     isNegative = true;
4839     Parser.Lex(); // Eat the '-'.
4840   } else if (Parser.getTok().is(AsmToken::Plus)) {
4841     // Nothing to do.
4842     Parser.Lex(); // Eat the '+'.
4843   }
4844 
4845   E = Parser.getTok().getLoc();
4846   int OffsetRegNum = tryParseRegister();
4847   if (OffsetRegNum == -1)
4848     return Error(E, "register expected");
4849 
4850   // If there's a shift operator, handle it.
4851   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4852   unsigned ShiftImm = 0;
4853   if (Parser.getTok().is(AsmToken::Comma)) {
4854     Parser.Lex(); // Eat the ','.
4855     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4856       return true;
4857   }
4858 
4859   // Now we should have the closing ']'
4860   if (Parser.getTok().isNot(AsmToken::RBrac))
4861     return Error(Parser.getTok().getLoc(), "']' expected");
4862   E = Parser.getTok().getEndLoc();
4863   Parser.Lex(); // Eat right bracket token.
4864 
4865   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
4866                                            ShiftType, ShiftImm, 0, isNegative,
4867                                            S, E));
4868 
4869   // If there's a pre-indexing writeback marker, '!', just add it as a token
4870   // operand.
4871   if (Parser.getTok().is(AsmToken::Exclaim)) {
4872     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4873     Parser.Lex(); // Eat the '!'.
4874   }
4875 
4876   return false;
4877 }
4878 
4879 /// parseMemRegOffsetShift - one of these two:
4880 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4881 ///   rrx
4882 /// return true if it parses a shift otherwise it returns false.
4883 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4884                                           unsigned &Amount) {
4885   MCAsmParser &Parser = getParser();
4886   SMLoc Loc = Parser.getTok().getLoc();
4887   const AsmToken &Tok = Parser.getTok();
4888   if (Tok.isNot(AsmToken::Identifier))
4889     return true;
4890   StringRef ShiftName = Tok.getString();
4891   if (ShiftName == "lsl" || ShiftName == "LSL" ||
4892       ShiftName == "asl" || ShiftName == "ASL")
4893     St = ARM_AM::lsl;
4894   else if (ShiftName == "lsr" || ShiftName == "LSR")
4895     St = ARM_AM::lsr;
4896   else if (ShiftName == "asr" || ShiftName == "ASR")
4897     St = ARM_AM::asr;
4898   else if (ShiftName == "ror" || ShiftName == "ROR")
4899     St = ARM_AM::ror;
4900   else if (ShiftName == "rrx" || ShiftName == "RRX")
4901     St = ARM_AM::rrx;
4902   else
4903     return Error(Loc, "illegal shift operator");
4904   Parser.Lex(); // Eat shift type token.
4905 
4906   // rrx stands alone.
4907   Amount = 0;
4908   if (St != ARM_AM::rrx) {
4909     Loc = Parser.getTok().getLoc();
4910     // A '#' and a shift amount.
4911     const AsmToken &HashTok = Parser.getTok();
4912     if (HashTok.isNot(AsmToken::Hash) &&
4913         HashTok.isNot(AsmToken::Dollar))
4914       return Error(HashTok.getLoc(), "'#' expected");
4915     Parser.Lex(); // Eat hash token.
4916 
4917     const MCExpr *Expr;
4918     if (getParser().parseExpression(Expr))
4919       return true;
4920     // Range check the immediate.
4921     // lsl, ror: 0 <= imm <= 31
4922     // lsr, asr: 0 <= imm <= 32
4923     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4924     if (!CE)
4925       return Error(Loc, "shift amount must be an immediate");
4926     int64_t Imm = CE->getValue();
4927     if (Imm < 0 ||
4928         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
4929         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
4930       return Error(Loc, "immediate shift value out of range");
4931     // If <ShiftTy> #0, turn it into a no_shift.
4932     if (Imm == 0)
4933       St = ARM_AM::lsl;
4934     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
4935     if (Imm == 32)
4936       Imm = 0;
4937     Amount = Imm;
4938   }
4939 
4940   return false;
4941 }
4942 
4943 /// parseFPImm - A floating point immediate expression operand.
4944 ARMAsmParser::OperandMatchResultTy
4945 ARMAsmParser::parseFPImm(OperandVector &Operands) {
4946   MCAsmParser &Parser = getParser();
4947   // Anything that can accept a floating point constant as an operand
4948   // needs to go through here, as the regular parseExpression is
4949   // integer only.
4950   //
4951   // This routine still creates a generic Immediate operand, containing
4952   // a bitcast of the 64-bit floating point value. The various operands
4953   // that accept floats can check whether the value is valid for them
4954   // via the standard is*() predicates.
4955 
4956   SMLoc S = Parser.getTok().getLoc();
4957 
4958   if (Parser.getTok().isNot(AsmToken::Hash) &&
4959       Parser.getTok().isNot(AsmToken::Dollar))
4960     return MatchOperand_NoMatch;
4961 
4962   // Disambiguate the VMOV forms that can accept an FP immediate.
4963   // vmov.f32 <sreg>, #imm
4964   // vmov.f64 <dreg>, #imm
4965   // vmov.f32 <dreg>, #imm  @ vector f32x2
4966   // vmov.f32 <qreg>, #imm  @ vector f32x4
4967   //
4968   // There are also the NEON VMOV instructions which expect an
4969   // integer constant. Make sure we don't try to parse an FPImm
4970   // for these:
4971   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
4972   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
4973   bool isVmovf = TyOp.isToken() &&
4974                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64");
4975   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
4976   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
4977                                          Mnemonic.getToken() == "fconsts");
4978   if (!(isVmovf || isFconst))
4979     return MatchOperand_NoMatch;
4980 
4981   Parser.Lex(); // Eat '#' or '$'.
4982 
4983   // Handle negation, as that still comes through as a separate token.
4984   bool isNegative = false;
4985   if (Parser.getTok().is(AsmToken::Minus)) {
4986     isNegative = true;
4987     Parser.Lex();
4988   }
4989   const AsmToken &Tok = Parser.getTok();
4990   SMLoc Loc = Tok.getLoc();
4991   if (Tok.is(AsmToken::Real) && isVmovf) {
4992     APFloat RealVal(APFloat::IEEEsingle, Tok.getString());
4993     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
4994     // If we had a '-' in front, toggle the sign bit.
4995     IntVal ^= (uint64_t)isNegative << 31;
4996     Parser.Lex(); // Eat the token.
4997     Operands.push_back(ARMOperand::CreateImm(
4998           MCConstantExpr::create(IntVal, getContext()),
4999           S, Parser.getTok().getLoc()));
5000     return MatchOperand_Success;
5001   }
5002   // Also handle plain integers. Instructions which allow floating point
5003   // immediates also allow a raw encoded 8-bit value.
5004   if (Tok.is(AsmToken::Integer) && isFconst) {
5005     int64_t Val = Tok.getIntVal();
5006     Parser.Lex(); // Eat the token.
5007     if (Val > 255 || Val < 0) {
5008       Error(Loc, "encoded floating point value out of range");
5009       return MatchOperand_ParseFail;
5010     }
5011     float RealVal = ARM_AM::getFPImmFloat(Val);
5012     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5013 
5014     Operands.push_back(ARMOperand::CreateImm(
5015         MCConstantExpr::create(Val, getContext()), S,
5016         Parser.getTok().getLoc()));
5017     return MatchOperand_Success;
5018   }
5019 
5020   Error(Loc, "invalid floating point immediate");
5021   return MatchOperand_ParseFail;
5022 }
5023 
5024 /// Parse a arm instruction operand.  For now this parses the operand regardless
5025 /// of the mnemonic.
5026 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5027   MCAsmParser &Parser = getParser();
5028   SMLoc S, E;
5029 
5030   // Check if the current operand has a custom associated parser, if so, try to
5031   // custom parse the operand, or fallback to the general approach.
5032   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5033   if (ResTy == MatchOperand_Success)
5034     return false;
5035   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5036   // there was a match, but an error occurred, in which case, just return that
5037   // the operand parsing failed.
5038   if (ResTy == MatchOperand_ParseFail)
5039     return true;
5040 
5041   switch (getLexer().getKind()) {
5042   default:
5043     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5044     return true;
5045   case AsmToken::Identifier: {
5046     // If we've seen a branch mnemonic, the next operand must be a label.  This
5047     // is true even if the label is a register name.  So "br r1" means branch to
5048     // label "r1".
5049     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5050     if (!ExpectLabel) {
5051       if (!tryParseRegisterWithWriteBack(Operands))
5052         return false;
5053       int Res = tryParseShiftRegister(Operands);
5054       if (Res == 0) // success
5055         return false;
5056       else if (Res == -1) // irrecoverable error
5057         return true;
5058       // If this is VMRS, check for the apsr_nzcv operand.
5059       if (Mnemonic == "vmrs" &&
5060           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5061         S = Parser.getTok().getLoc();
5062         Parser.Lex();
5063         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5064         return false;
5065       }
5066     }
5067 
5068     // Fall though for the Identifier case that is not a register or a
5069     // special name.
5070   }
5071   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5072   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5073   case AsmToken::String:  // quoted label names.
5074   case AsmToken::Dot: {   // . as a branch target
5075     // This was not a register so parse other operands that start with an
5076     // identifier (like labels) as expressions and create them as immediates.
5077     const MCExpr *IdVal;
5078     S = Parser.getTok().getLoc();
5079     if (getParser().parseExpression(IdVal))
5080       return true;
5081     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5082     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5083     return false;
5084   }
5085   case AsmToken::LBrac:
5086     return parseMemory(Operands);
5087   case AsmToken::LCurly:
5088     return parseRegisterList(Operands);
5089   case AsmToken::Dollar:
5090   case AsmToken::Hash: {
5091     // #42 -> immediate.
5092     S = Parser.getTok().getLoc();
5093     Parser.Lex();
5094 
5095     if (Parser.getTok().isNot(AsmToken::Colon)) {
5096       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5097       const MCExpr *ImmVal;
5098       if (getParser().parseExpression(ImmVal))
5099         return true;
5100       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5101       if (CE) {
5102         int32_t Val = CE->getValue();
5103         if (isNegative && Val == 0)
5104           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5105       }
5106       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5107       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5108 
5109       // There can be a trailing '!' on operands that we want as a separate
5110       // '!' Token operand. Handle that here. For example, the compatibility
5111       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5112       if (Parser.getTok().is(AsmToken::Exclaim)) {
5113         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5114                                                    Parser.getTok().getLoc()));
5115         Parser.Lex(); // Eat exclaim token
5116       }
5117       return false;
5118     }
5119     // w/ a ':' after the '#', it's just like a plain ':'.
5120     // FALLTHROUGH
5121   }
5122   case AsmToken::Colon: {
5123     // ":lower16:" and ":upper16:" expression prefixes
5124     // FIXME: Check it's an expression prefix,
5125     // e.g. (FOO - :lower16:BAR) isn't legal.
5126     ARMMCExpr::VariantKind RefKind;
5127     if (parsePrefix(RefKind))
5128       return true;
5129 
5130     const MCExpr *SubExprVal;
5131     if (getParser().parseExpression(SubExprVal))
5132       return true;
5133 
5134     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5135                                               getContext());
5136     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5137     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5138     return false;
5139   }
5140   case AsmToken::Equal: {
5141     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5142       return Error(Parser.getTok().getLoc(), "unexpected token in operand");
5143 
5144     Parser.Lex(); // Eat '='
5145     const MCExpr *SubExprVal;
5146     if (getParser().parseExpression(SubExprVal))
5147       return true;
5148     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5149 
5150     const MCExpr *CPLoc = getTargetStreamer().addConstantPoolEntry(SubExprVal);
5151     Operands.push_back(ARMOperand::CreateImm(CPLoc, S, E));
5152     return false;
5153   }
5154   }
5155 }
5156 
5157 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5158 //  :lower16: and :upper16:.
5159 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5160   MCAsmParser &Parser = getParser();
5161   RefKind = ARMMCExpr::VK_ARM_None;
5162 
5163   // consume an optional '#' (GNU compatibility)
5164   if (getLexer().is(AsmToken::Hash))
5165     Parser.Lex();
5166 
5167   // :lower16: and :upper16: modifiers
5168   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5169   Parser.Lex(); // Eat ':'
5170 
5171   if (getLexer().isNot(AsmToken::Identifier)) {
5172     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5173     return true;
5174   }
5175 
5176   static const struct PrefixEntry {
5177     const char *Spelling;
5178     ARMMCExpr::VariantKind VariantKind;
5179   } PrefixEntries[] = {
5180       {"lower16", ARMMCExpr::VK_ARM_LO16}, {"upper16", ARMMCExpr::VK_ARM_HI16},
5181   };
5182 
5183   StringRef IDVal = Parser.getTok().getIdentifier();
5184 
5185   const auto &Prefix =
5186       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5187                    [&IDVal](const PrefixEntry &PE) {
5188                       return PE.Spelling == IDVal;
5189                    });
5190   if (Prefix == std::end(PrefixEntries)) {
5191     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5192     return true;
5193   }
5194 
5195   RefKind = Prefix->VariantKind;
5196   Parser.Lex();
5197 
5198   if (getLexer().isNot(AsmToken::Colon)) {
5199     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5200     return true;
5201   }
5202   Parser.Lex(); // Eat the last ':'
5203 
5204   return false;
5205 }
5206 
5207 /// \brief Given a mnemonic, split out possible predication code and carry
5208 /// setting letters to form a canonical mnemonic and flags.
5209 //
5210 // FIXME: Would be nice to autogen this.
5211 // FIXME: This is a bit of a maze of special cases.
5212 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5213                                       unsigned &PredicationCode,
5214                                       bool &CarrySetting,
5215                                       unsigned &ProcessorIMod,
5216                                       StringRef &ITMask) {
5217   PredicationCode = ARMCC::AL;
5218   CarrySetting = false;
5219   ProcessorIMod = 0;
5220 
5221   // Ignore some mnemonics we know aren't predicated forms.
5222   //
5223   // FIXME: Would be nice to autogen this.
5224   if ((Mnemonic == "movs" && isThumb()) ||
5225       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5226       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5227       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5228       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5229       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5230       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5231       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5232       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5233       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5234       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5235       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5236       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5237       Mnemonic.startswith("vsel"))
5238     return Mnemonic;
5239 
5240   // First, split out any predication code. Ignore mnemonics we know aren't
5241   // predicated but do have a carry-set and so weren't caught above.
5242   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5243       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5244       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5245       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5246     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5247       .Case("eq", ARMCC::EQ)
5248       .Case("ne", ARMCC::NE)
5249       .Case("hs", ARMCC::HS)
5250       .Case("cs", ARMCC::HS)
5251       .Case("lo", ARMCC::LO)
5252       .Case("cc", ARMCC::LO)
5253       .Case("mi", ARMCC::MI)
5254       .Case("pl", ARMCC::PL)
5255       .Case("vs", ARMCC::VS)
5256       .Case("vc", ARMCC::VC)
5257       .Case("hi", ARMCC::HI)
5258       .Case("ls", ARMCC::LS)
5259       .Case("ge", ARMCC::GE)
5260       .Case("lt", ARMCC::LT)
5261       .Case("gt", ARMCC::GT)
5262       .Case("le", ARMCC::LE)
5263       .Case("al", ARMCC::AL)
5264       .Default(~0U);
5265     if (CC != ~0U) {
5266       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5267       PredicationCode = CC;
5268     }
5269   }
5270 
5271   // Next, determine if we have a carry setting bit. We explicitly ignore all
5272   // the instructions we know end in 's'.
5273   if (Mnemonic.endswith("s") &&
5274       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5275         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5276         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5277         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5278         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5279         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5280         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5281         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5282         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5283         (Mnemonic == "movs" && isThumb()))) {
5284     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5285     CarrySetting = true;
5286   }
5287 
5288   // The "cps" instruction can have a interrupt mode operand which is glued into
5289   // the mnemonic. Check if this is the case, split it and parse the imod op
5290   if (Mnemonic.startswith("cps")) {
5291     // Split out any imod code.
5292     unsigned IMod =
5293       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5294       .Case("ie", ARM_PROC::IE)
5295       .Case("id", ARM_PROC::ID)
5296       .Default(~0U);
5297     if (IMod != ~0U) {
5298       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5299       ProcessorIMod = IMod;
5300     }
5301   }
5302 
5303   // The "it" instruction has the condition mask on the end of the mnemonic.
5304   if (Mnemonic.startswith("it")) {
5305     ITMask = Mnemonic.slice(2, Mnemonic.size());
5306     Mnemonic = Mnemonic.slice(0, 2);
5307   }
5308 
5309   return Mnemonic;
5310 }
5311 
5312 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5313 /// inclusion of carry set or predication code operands.
5314 //
5315 // FIXME: It would be nice to autogen this.
5316 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5317                                          bool &CanAcceptCarrySet,
5318                                          bool &CanAcceptPredicationCode) {
5319   CanAcceptCarrySet =
5320       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5321       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5322       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5323       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5324       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5325       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5326       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5327       (!isThumb() &&
5328        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5329         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5330 
5331   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5332       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5333       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5334       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5335       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5336       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5337       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5338       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5339       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5340       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5341       (FullInst.startswith("vmull") && FullInst.endswith(".p64"))) {
5342     // These mnemonics are never predicable
5343     CanAcceptPredicationCode = false;
5344   } else if (!isThumb()) {
5345     // Some instructions are only predicable in Thumb mode
5346     CanAcceptPredicationCode =
5347         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5348         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5349         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5350         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5351         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5352         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5353         !Mnemonic.startswith("srs");
5354   } else if (isThumbOne()) {
5355     if (hasV6MOps())
5356       CanAcceptPredicationCode = Mnemonic != "movs";
5357     else
5358       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5359   } else
5360     CanAcceptPredicationCode = true;
5361 }
5362 
5363 // \brief Some Thumb instructions have two operand forms that are not
5364 // available as three operand, convert to two operand form if possible.
5365 //
5366 // FIXME: We would really like to be able to tablegen'erate this.
5367 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5368                                                  bool CarrySetting,
5369                                                  OperandVector &Operands) {
5370   if (Operands.size() != 6)
5371     return;
5372 
5373   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5374         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5375   if (!Op3.isReg() || !Op4.isReg())
5376     return;
5377 
5378   auto Op3Reg = Op3.getReg();
5379   auto Op4Reg = Op4.getReg();
5380 
5381   // For most Thumb2 cases we just generate the 3 operand form and reduce
5382   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5383   // won't accept SP or PC so we do the transformation here taking care
5384   // with immediate range in the 'add sp, sp #imm' case.
5385   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5386   if (isThumbTwo()) {
5387     if (Mnemonic != "add")
5388       return;
5389     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5390                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5391     if (!TryTransform) {
5392       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5393                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5394                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5395                        Op5.isImm() && !Op5.isImm0_508s4());
5396     }
5397     if (!TryTransform)
5398       return;
5399   } else if (!isThumbOne())
5400     return;
5401 
5402   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5403         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5404         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5405         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5406     return;
5407 
5408   // If first 2 operands of a 3 operand instruction are the same
5409   // then transform to 2 operand version of the same instruction
5410   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5411   bool Transform = Op3Reg == Op4Reg;
5412 
5413   // For communtative operations, we might be able to transform if we swap
5414   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5415   // as tADDrsp.
5416   const ARMOperand *LastOp = &Op5;
5417   bool Swap = false;
5418   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5419       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5420        Mnemonic == "and" || Mnemonic == "eor" ||
5421        Mnemonic == "adc" || Mnemonic == "orr")) {
5422     Swap = true;
5423     LastOp = &Op4;
5424     Transform = true;
5425   }
5426 
5427   // If both registers are the same then remove one of them from
5428   // the operand list, with certain exceptions.
5429   if (Transform) {
5430     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5431     // 2 operand forms don't exist.
5432     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5433         LastOp->isReg())
5434       Transform = false;
5435 
5436     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5437     // 3-bits because the ARMARM says not to.
5438     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5439       Transform = false;
5440   }
5441 
5442   if (Transform) {
5443     if (Swap)
5444       std::swap(Op4, Op5);
5445     Operands.erase(Operands.begin() + 3);
5446   }
5447 }
5448 
5449 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5450                                           OperandVector &Operands) {
5451   // FIXME: This is all horribly hacky. We really need a better way to deal
5452   // with optional operands like this in the matcher table.
5453 
5454   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5455   // another does not. Specifically, the MOVW instruction does not. So we
5456   // special case it here and remove the defaulted (non-setting) cc_out
5457   // operand if that's the instruction we're trying to match.
5458   //
5459   // We do this as post-processing of the explicit operands rather than just
5460   // conditionally adding the cc_out in the first place because we need
5461   // to check the type of the parsed immediate operand.
5462   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5463       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5464       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5465       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5466     return true;
5467 
5468   // Register-register 'add' for thumb does not have a cc_out operand
5469   // when there are only two register operands.
5470   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5471       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5472       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5473       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5474     return true;
5475   // Register-register 'add' for thumb does not have a cc_out operand
5476   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5477   // have to check the immediate range here since Thumb2 has a variant
5478   // that can handle a different range and has a cc_out operand.
5479   if (((isThumb() && Mnemonic == "add") ||
5480        (isThumbTwo() && Mnemonic == "sub")) &&
5481       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5482       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5483       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5484       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5485       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5486        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5487     return true;
5488   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5489   // imm0_4095 variant. That's the least-preferred variant when
5490   // selecting via the generic "add" mnemonic, so to know that we
5491   // should remove the cc_out operand, we have to explicitly check that
5492   // it's not one of the other variants. Ugh.
5493   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5494       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5495       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5496       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5497     // Nest conditions rather than one big 'if' statement for readability.
5498     //
5499     // If both registers are low, we're in an IT block, and the immediate is
5500     // in range, we should use encoding T1 instead, which has a cc_out.
5501     if (inITBlock() &&
5502         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5503         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5504         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5505       return false;
5506     // Check against T3. If the second register is the PC, this is an
5507     // alternate form of ADR, which uses encoding T4, so check for that too.
5508     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5509         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5510       return false;
5511 
5512     // Otherwise, we use encoding T4, which does not have a cc_out
5513     // operand.
5514     return true;
5515   }
5516 
5517   // The thumb2 multiply instruction doesn't have a CCOut register, so
5518   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5519   // use the 16-bit encoding or not.
5520   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5521       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5522       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5523       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5524       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5525       // If the registers aren't low regs, the destination reg isn't the
5526       // same as one of the source regs, or the cc_out operand is zero
5527       // outside of an IT block, we have to use the 32-bit encoding, so
5528       // remove the cc_out operand.
5529       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5530        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5531        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5532        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5533                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5534                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5535                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5536     return true;
5537 
5538   // Also check the 'mul' syntax variant that doesn't specify an explicit
5539   // destination register.
5540   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5541       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5542       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5543       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5544       // If the registers aren't low regs  or the cc_out operand is zero
5545       // outside of an IT block, we have to use the 32-bit encoding, so
5546       // remove the cc_out operand.
5547       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5548        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5549        !inITBlock()))
5550     return true;
5551 
5552 
5553 
5554   // Register-register 'add/sub' for thumb does not have a cc_out operand
5555   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5556   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5557   // right, this will result in better diagnostics (which operand is off)
5558   // anyway.
5559   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5560       (Operands.size() == 5 || Operands.size() == 6) &&
5561       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5562       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5563       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5564       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5565        (Operands.size() == 6 &&
5566         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5567     return true;
5568 
5569   return false;
5570 }
5571 
5572 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5573                                               OperandVector &Operands) {
5574   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5575   unsigned RegIdx = 3;
5576   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5577       static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32") {
5578     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5579         static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32")
5580       RegIdx = 4;
5581 
5582     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5583         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5584              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5585          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5586              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5587       return true;
5588   }
5589   return false;
5590 }
5591 
5592 static bool isDataTypeToken(StringRef Tok) {
5593   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5594     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5595     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5596     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5597     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5598     Tok == ".f" || Tok == ".d";
5599 }
5600 
5601 // FIXME: This bit should probably be handled via an explicit match class
5602 // in the .td files that matches the suffix instead of having it be
5603 // a literal string token the way it is now.
5604 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5605   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5606 }
5607 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5608                                  unsigned VariantID);
5609 
5610 static bool RequiresVFPRegListValidation(StringRef Inst,
5611                                          bool &AcceptSinglePrecisionOnly,
5612                                          bool &AcceptDoublePrecisionOnly) {
5613   if (Inst.size() < 7)
5614     return false;
5615 
5616   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5617     StringRef AddressingMode = Inst.substr(4, 2);
5618     if (AddressingMode == "ia" || AddressingMode == "db" ||
5619         AddressingMode == "ea" || AddressingMode == "fd") {
5620       AcceptSinglePrecisionOnly = Inst[6] == 's';
5621       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5622       return true;
5623     }
5624   }
5625 
5626   return false;
5627 }
5628 
5629 /// Parse an arm instruction mnemonic followed by its operands.
5630 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5631                                     SMLoc NameLoc, OperandVector &Operands) {
5632   MCAsmParser &Parser = getParser();
5633   // FIXME: Can this be done via tablegen in some fashion?
5634   bool RequireVFPRegisterListCheck;
5635   bool AcceptSinglePrecisionOnly;
5636   bool AcceptDoublePrecisionOnly;
5637   RequireVFPRegisterListCheck =
5638     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5639                                  AcceptDoublePrecisionOnly);
5640 
5641   // Apply mnemonic aliases before doing anything else, as the destination
5642   // mnemonic may include suffices and we want to handle them normally.
5643   // The generic tblgen'erated code does this later, at the start of
5644   // MatchInstructionImpl(), but that's too late for aliases that include
5645   // any sort of suffix.
5646   uint64_t AvailableFeatures = getAvailableFeatures();
5647   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5648   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5649 
5650   // First check for the ARM-specific .req directive.
5651   if (Parser.getTok().is(AsmToken::Identifier) &&
5652       Parser.getTok().getIdentifier() == ".req") {
5653     parseDirectiveReq(Name, NameLoc);
5654     // We always return 'error' for this, as we're done with this
5655     // statement and don't need to match the 'instruction."
5656     return true;
5657   }
5658 
5659   // Create the leading tokens for the mnemonic, split by '.' characters.
5660   size_t Start = 0, Next = Name.find('.');
5661   StringRef Mnemonic = Name.slice(Start, Next);
5662 
5663   // Split out the predication code and carry setting flag from the mnemonic.
5664   unsigned PredicationCode;
5665   unsigned ProcessorIMod;
5666   bool CarrySetting;
5667   StringRef ITMask;
5668   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5669                            ProcessorIMod, ITMask);
5670 
5671   // In Thumb1, only the branch (B) instruction can be predicated.
5672   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5673     Parser.eatToEndOfStatement();
5674     return Error(NameLoc, "conditional execution not supported in Thumb1");
5675   }
5676 
5677   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5678 
5679   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5680   // is the mask as it will be for the IT encoding if the conditional
5681   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5682   // where the conditional bit0 is zero, the instruction post-processing
5683   // will adjust the mask accordingly.
5684   if (Mnemonic == "it") {
5685     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5686     if (ITMask.size() > 3) {
5687       Parser.eatToEndOfStatement();
5688       return Error(Loc, "too many conditions on IT instruction");
5689     }
5690     unsigned Mask = 8;
5691     for (unsigned i = ITMask.size(); i != 0; --i) {
5692       char pos = ITMask[i - 1];
5693       if (pos != 't' && pos != 'e') {
5694         Parser.eatToEndOfStatement();
5695         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5696       }
5697       Mask >>= 1;
5698       if (ITMask[i - 1] == 't')
5699         Mask |= 8;
5700     }
5701     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5702   }
5703 
5704   // FIXME: This is all a pretty gross hack. We should automatically handle
5705   // optional operands like this via tblgen.
5706 
5707   // Next, add the CCOut and ConditionCode operands, if needed.
5708   //
5709   // For mnemonics which can ever incorporate a carry setting bit or predication
5710   // code, our matching model involves us always generating CCOut and
5711   // ConditionCode operands to match the mnemonic "as written" and then we let
5712   // the matcher deal with finding the right instruction or generating an
5713   // appropriate error.
5714   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5715   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5716 
5717   // If we had a carry-set on an instruction that can't do that, issue an
5718   // error.
5719   if (!CanAcceptCarrySet && CarrySetting) {
5720     Parser.eatToEndOfStatement();
5721     return Error(NameLoc, "instruction '" + Mnemonic +
5722                  "' can not set flags, but 's' suffix specified");
5723   }
5724   // If we had a predication code on an instruction that can't do that, issue an
5725   // error.
5726   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5727     Parser.eatToEndOfStatement();
5728     return Error(NameLoc, "instruction '" + Mnemonic +
5729                  "' is not predicable, but condition code specified");
5730   }
5731 
5732   // Add the carry setting operand, if necessary.
5733   if (CanAcceptCarrySet) {
5734     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5735     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5736                                                Loc));
5737   }
5738 
5739   // Add the predication code operand, if necessary.
5740   if (CanAcceptPredicationCode) {
5741     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5742                                       CarrySetting);
5743     Operands.push_back(ARMOperand::CreateCondCode(
5744                          ARMCC::CondCodes(PredicationCode), Loc));
5745   }
5746 
5747   // Add the processor imod operand, if necessary.
5748   if (ProcessorIMod) {
5749     Operands.push_back(ARMOperand::CreateImm(
5750           MCConstantExpr::create(ProcessorIMod, getContext()),
5751                                  NameLoc, NameLoc));
5752   } else if (Mnemonic == "cps" && isMClass()) {
5753     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5754   }
5755 
5756   // Add the remaining tokens in the mnemonic.
5757   while (Next != StringRef::npos) {
5758     Start = Next;
5759     Next = Name.find('.', Start + 1);
5760     StringRef ExtraToken = Name.slice(Start, Next);
5761 
5762     // Some NEON instructions have an optional datatype suffix that is
5763     // completely ignored. Check for that.
5764     if (isDataTypeToken(ExtraToken) &&
5765         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5766       continue;
5767 
5768     // For for ARM mode generate an error if the .n qualifier is used.
5769     if (ExtraToken == ".n" && !isThumb()) {
5770       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5771       Parser.eatToEndOfStatement();
5772       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5773                    "arm mode");
5774     }
5775 
5776     // The .n qualifier is always discarded as that is what the tables
5777     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5778     // so discard it to avoid errors that can be caused by the matcher.
5779     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5780       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5781       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5782     }
5783   }
5784 
5785   // Read the remaining operands.
5786   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5787     // Read the first operand.
5788     if (parseOperand(Operands, Mnemonic)) {
5789       Parser.eatToEndOfStatement();
5790       return true;
5791     }
5792 
5793     while (getLexer().is(AsmToken::Comma)) {
5794       Parser.Lex();  // Eat the comma.
5795 
5796       // Parse and remember the operand.
5797       if (parseOperand(Operands, Mnemonic)) {
5798         Parser.eatToEndOfStatement();
5799         return true;
5800       }
5801     }
5802   }
5803 
5804   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5805     SMLoc Loc = getLexer().getLoc();
5806     Parser.eatToEndOfStatement();
5807     return Error(Loc, "unexpected token in argument list");
5808   }
5809 
5810   Parser.Lex(); // Consume the EndOfStatement
5811 
5812   if (RequireVFPRegisterListCheck) {
5813     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5814     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5815       return Error(Op.getStartLoc(),
5816                    "VFP/Neon single precision register expected");
5817     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5818       return Error(Op.getStartLoc(),
5819                    "VFP/Neon double precision register expected");
5820   }
5821 
5822   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
5823 
5824   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5825   // do and don't have a cc_out optional-def operand. With some spot-checks
5826   // of the operand list, we can figure out which variant we're trying to
5827   // parse and adjust accordingly before actually matching. We shouldn't ever
5828   // try to remove a cc_out operand that was explicitly set on the
5829   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5830   // table driven matcher doesn't fit well with the ARM instruction set.
5831   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
5832     Operands.erase(Operands.begin() + 1);
5833 
5834   // Some instructions have the same mnemonic, but don't always
5835   // have a predicate. Distinguish them here and delete the
5836   // predicate if needed.
5837   if (shouldOmitPredicateOperand(Mnemonic, Operands))
5838     Operands.erase(Operands.begin() + 1);
5839 
5840   // ARM mode 'blx' need special handling, as the register operand version
5841   // is predicable, but the label operand version is not. So, we can't rely
5842   // on the Mnemonic based checking to correctly figure out when to put
5843   // a k_CondCode operand in the list. If we're trying to match the label
5844   // version, remove the k_CondCode operand here.
5845   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
5846       static_cast<ARMOperand &>(*Operands[2]).isImm())
5847     Operands.erase(Operands.begin() + 1);
5848 
5849   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
5850   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
5851   // a single GPRPair reg operand is used in the .td file to replace the two
5852   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
5853   // expressed as a GPRPair, so we have to manually merge them.
5854   // FIXME: We would really like to be able to tablegen'erate this.
5855   if (!isThumb() && Operands.size() > 4 &&
5856       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
5857        Mnemonic == "stlexd")) {
5858     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
5859     unsigned Idx = isLoad ? 2 : 3;
5860     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
5861     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
5862 
5863     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
5864     // Adjust only if Op1 and Op2 are GPRs.
5865     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
5866         MRC.contains(Op2.getReg())) {
5867       unsigned Reg1 = Op1.getReg();
5868       unsigned Reg2 = Op2.getReg();
5869       unsigned Rt = MRI->getEncodingValue(Reg1);
5870       unsigned Rt2 = MRI->getEncodingValue(Reg2);
5871 
5872       // Rt2 must be Rt + 1 and Rt must be even.
5873       if (Rt + 1 != Rt2 || (Rt & 1)) {
5874         Error(Op2.getStartLoc(), isLoad
5875                                      ? "destination operands must be sequential"
5876                                      : "source operands must be sequential");
5877         return true;
5878       }
5879       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
5880           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
5881       Operands[Idx] =
5882           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
5883       Operands.erase(Operands.begin() + Idx + 1);
5884     }
5885   }
5886 
5887   // GNU Assembler extension (compatibility)
5888   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
5889     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5890     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5891     if (Op3.isMem()) {
5892       assert(Op2.isReg() && "expected register argument");
5893 
5894       unsigned SuperReg = MRI->getMatchingSuperReg(
5895           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
5896 
5897       assert(SuperReg && "expected register pair");
5898 
5899       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
5900 
5901       Operands.insert(
5902           Operands.begin() + 3,
5903           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
5904     }
5905   }
5906 
5907   // FIXME: As said above, this is all a pretty gross hack.  This instruction
5908   // does not fit with other "subs" and tblgen.
5909   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
5910   // so the Mnemonic is the original name "subs" and delete the predicate
5911   // operand so it will match the table entry.
5912   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
5913       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5914       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
5915       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5916       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
5917       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5918     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
5919     Operands.erase(Operands.begin() + 1);
5920   }
5921   return false;
5922 }
5923 
5924 // Validate context-sensitive operand constraints.
5925 
5926 // return 'true' if register list contains non-low GPR registers,
5927 // 'false' otherwise. If Reg is in the register list or is HiReg, set
5928 // 'containsReg' to true.
5929 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
5930                                  unsigned Reg, unsigned HiReg,
5931                                  bool &containsReg) {
5932   containsReg = false;
5933   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
5934     unsigned OpReg = Inst.getOperand(i).getReg();
5935     if (OpReg == Reg)
5936       containsReg = true;
5937     // Anything other than a low register isn't legal here.
5938     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
5939       return true;
5940   }
5941   return false;
5942 }
5943 
5944 // Check if the specified regisgter is in the register list of the inst,
5945 // starting at the indicated operand number.
5946 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
5947   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
5948     unsigned OpReg = Inst.getOperand(i).getReg();
5949     if (OpReg == Reg)
5950       return true;
5951   }
5952   return false;
5953 }
5954 
5955 // Return true if instruction has the interesting property of being
5956 // allowed in IT blocks, but not being predicable.
5957 static bool instIsBreakpoint(const MCInst &Inst) {
5958     return Inst.getOpcode() == ARM::tBKPT ||
5959            Inst.getOpcode() == ARM::BKPT ||
5960            Inst.getOpcode() == ARM::tHLT ||
5961            Inst.getOpcode() == ARM::HLT;
5962 
5963 }
5964 
5965 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
5966                                        const OperandVector &Operands,
5967                                        unsigned ListNo, bool IsARPop) {
5968   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
5969   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
5970 
5971   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
5972   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
5973   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
5974 
5975   if (!IsARPop && ListContainsSP)
5976     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
5977                  "SP may not be in the register list");
5978   else if (ListContainsPC && ListContainsLR)
5979     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
5980                  "PC and LR may not be in the register list simultaneously");
5981   else if (inITBlock() && !lastInITBlock() && ListContainsPC)
5982     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
5983                  "instruction must be outside of IT block or the last "
5984                  "instruction in an IT block");
5985   return false;
5986 }
5987 
5988 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
5989                                        const OperandVector &Operands,
5990                                        unsigned ListNo) {
5991   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
5992   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
5993 
5994   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
5995   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
5996 
5997   if (ListContainsSP && ListContainsPC)
5998     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
5999                  "SP and PC may not be in the register list");
6000   else if (ListContainsSP)
6001     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6002                  "SP may not be in the register list");
6003   else if (ListContainsPC)
6004     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6005                  "PC may not be in the register list");
6006   return false;
6007 }
6008 
6009 // FIXME: We would really like to be able to tablegen'erate this.
6010 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6011                                        const OperandVector &Operands) {
6012   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6013   SMLoc Loc = Operands[0]->getStartLoc();
6014 
6015   // Check the IT block state first.
6016   // NOTE: BKPT and HLT instructions have the interesting property of being
6017   // allowed in IT blocks, but not being predicable. They just always execute.
6018   if (inITBlock() && !instIsBreakpoint(Inst)) {
6019     unsigned Bit = 1;
6020     if (ITState.FirstCond)
6021       ITState.FirstCond = false;
6022     else
6023       Bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
6024     // The instruction must be predicable.
6025     if (!MCID.isPredicable())
6026       return Error(Loc, "instructions in IT block must be predicable");
6027     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6028     unsigned ITCond = Bit ? ITState.Cond :
6029       ARMCC::getOppositeCondition(ITState.Cond);
6030     if (Cond != ITCond) {
6031       // Find the condition code Operand to get its SMLoc information.
6032       SMLoc CondLoc;
6033       for (unsigned I = 1; I < Operands.size(); ++I)
6034         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6035           CondLoc = Operands[I]->getStartLoc();
6036       return Error(CondLoc, "incorrect condition in IT block; got '" +
6037                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6038                    "', but expected '" +
6039                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
6040     }
6041   // Check for non-'al' condition codes outside of the IT block.
6042   } else if (isThumbTwo() && MCID.isPredicable() &&
6043              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6044              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6045              Inst.getOpcode() != ARM::t2Bcc)
6046     return Error(Loc, "predicated instructions must be in IT block");
6047 
6048   const unsigned Opcode = Inst.getOpcode();
6049   switch (Opcode) {
6050   case ARM::LDRD:
6051   case ARM::LDRD_PRE:
6052   case ARM::LDRD_POST: {
6053     const unsigned RtReg = Inst.getOperand(0).getReg();
6054 
6055     // Rt can't be R14.
6056     if (RtReg == ARM::LR)
6057       return Error(Operands[3]->getStartLoc(),
6058                    "Rt can't be R14");
6059 
6060     const unsigned Rt = MRI->getEncodingValue(RtReg);
6061     // Rt must be even-numbered.
6062     if ((Rt & 1) == 1)
6063       return Error(Operands[3]->getStartLoc(),
6064                    "Rt must be even-numbered");
6065 
6066     // Rt2 must be Rt + 1.
6067     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6068     if (Rt2 != Rt + 1)
6069       return Error(Operands[3]->getStartLoc(),
6070                    "destination operands must be sequential");
6071 
6072     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6073       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6074       // For addressing modes with writeback, the base register needs to be
6075       // different from the destination registers.
6076       if (Rn == Rt || Rn == Rt2)
6077         return Error(Operands[3]->getStartLoc(),
6078                      "base register needs to be different from destination "
6079                      "registers");
6080     }
6081 
6082     return false;
6083   }
6084   case ARM::t2LDRDi8:
6085   case ARM::t2LDRD_PRE:
6086   case ARM::t2LDRD_POST: {
6087     // Rt2 must be different from Rt.
6088     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6089     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6090     if (Rt2 == Rt)
6091       return Error(Operands[3]->getStartLoc(),
6092                    "destination operands can't be identical");
6093     return false;
6094   }
6095   case ARM::t2BXJ: {
6096     const unsigned RmReg = Inst.getOperand(0).getReg();
6097     // Rm = SP is no longer unpredictable in v8-A
6098     if (RmReg == ARM::SP && !hasV8Ops())
6099       return Error(Operands[2]->getStartLoc(),
6100                    "r13 (SP) is an unpredictable operand to BXJ");
6101     return false;
6102   }
6103   case ARM::STRD: {
6104     // Rt2 must be Rt + 1.
6105     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6106     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6107     if (Rt2 != Rt + 1)
6108       return Error(Operands[3]->getStartLoc(),
6109                    "source operands must be sequential");
6110     return false;
6111   }
6112   case ARM::STRD_PRE:
6113   case ARM::STRD_POST: {
6114     // Rt2 must be Rt + 1.
6115     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6116     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6117     if (Rt2 != Rt + 1)
6118       return Error(Operands[3]->getStartLoc(),
6119                    "source operands must be sequential");
6120     return false;
6121   }
6122   case ARM::STR_PRE_IMM:
6123   case ARM::STR_PRE_REG:
6124   case ARM::STR_POST_IMM:
6125   case ARM::STR_POST_REG:
6126   case ARM::STRH_PRE:
6127   case ARM::STRH_POST:
6128   case ARM::STRB_PRE_IMM:
6129   case ARM::STRB_PRE_REG:
6130   case ARM::STRB_POST_IMM:
6131   case ARM::STRB_POST_REG: {
6132     // Rt must be different from Rn.
6133     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6134     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6135 
6136     if (Rt == Rn)
6137       return Error(Operands[3]->getStartLoc(),
6138                    "source register and base register can't be identical");
6139     return false;
6140   }
6141   case ARM::LDR_PRE_IMM:
6142   case ARM::LDR_PRE_REG:
6143   case ARM::LDR_POST_IMM:
6144   case ARM::LDR_POST_REG:
6145   case ARM::LDRH_PRE:
6146   case ARM::LDRH_POST:
6147   case ARM::LDRSH_PRE:
6148   case ARM::LDRSH_POST:
6149   case ARM::LDRB_PRE_IMM:
6150   case ARM::LDRB_PRE_REG:
6151   case ARM::LDRB_POST_IMM:
6152   case ARM::LDRB_POST_REG:
6153   case ARM::LDRSB_PRE:
6154   case ARM::LDRSB_POST: {
6155     // Rt must be different from Rn.
6156     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6157     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6158 
6159     if (Rt == Rn)
6160       return Error(Operands[3]->getStartLoc(),
6161                    "destination register and base register can't be identical");
6162     return false;
6163   }
6164   case ARM::SBFX:
6165   case ARM::UBFX: {
6166     // Width must be in range [1, 32-lsb].
6167     unsigned LSB = Inst.getOperand(2).getImm();
6168     unsigned Widthm1 = Inst.getOperand(3).getImm();
6169     if (Widthm1 >= 32 - LSB)
6170       return Error(Operands[5]->getStartLoc(),
6171                    "bitfield width must be in range [1,32-lsb]");
6172     return false;
6173   }
6174   // Notionally handles ARM::tLDMIA_UPD too.
6175   case ARM::tLDMIA: {
6176     // If we're parsing Thumb2, the .w variant is available and handles
6177     // most cases that are normally illegal for a Thumb1 LDM instruction.
6178     // We'll make the transformation in processInstruction() if necessary.
6179     //
6180     // Thumb LDM instructions are writeback iff the base register is not
6181     // in the register list.
6182     unsigned Rn = Inst.getOperand(0).getReg();
6183     bool HasWritebackToken =
6184         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6185          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6186     bool ListContainsBase;
6187     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6188       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6189                    "registers must be in range r0-r7");
6190     // If we should have writeback, then there should be a '!' token.
6191     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6192       return Error(Operands[2]->getStartLoc(),
6193                    "writeback operator '!' expected");
6194     // If we should not have writeback, there must not be a '!'. This is
6195     // true even for the 32-bit wide encodings.
6196     if (ListContainsBase && HasWritebackToken)
6197       return Error(Operands[3]->getStartLoc(),
6198                    "writeback operator '!' not allowed when base register "
6199                    "in register list");
6200 
6201     if (validatetLDMRegList(Inst, Operands, 3))
6202       return true;
6203     break;
6204   }
6205   case ARM::LDMIA_UPD:
6206   case ARM::LDMDB_UPD:
6207   case ARM::LDMIB_UPD:
6208   case ARM::LDMDA_UPD:
6209     // ARM variants loading and updating the same register are only officially
6210     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6211     if (!hasV7Ops())
6212       break;
6213     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6214       return Error(Operands.back()->getStartLoc(),
6215                    "writeback register not allowed in register list");
6216     break;
6217   case ARM::t2LDMIA:
6218   case ARM::t2LDMDB:
6219     if (validatetLDMRegList(Inst, Operands, 3))
6220       return true;
6221     break;
6222   case ARM::t2STMIA:
6223   case ARM::t2STMDB:
6224     if (validatetSTMRegList(Inst, Operands, 3))
6225       return true;
6226     break;
6227   case ARM::t2LDMIA_UPD:
6228   case ARM::t2LDMDB_UPD:
6229   case ARM::t2STMIA_UPD:
6230   case ARM::t2STMDB_UPD: {
6231     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6232       return Error(Operands.back()->getStartLoc(),
6233                    "writeback register not allowed in register list");
6234 
6235     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6236       if (validatetLDMRegList(Inst, Operands, 3))
6237         return true;
6238     } else {
6239       if (validatetSTMRegList(Inst, Operands, 3))
6240         return true;
6241     }
6242     break;
6243   }
6244   case ARM::sysLDMIA_UPD:
6245   case ARM::sysLDMDA_UPD:
6246   case ARM::sysLDMDB_UPD:
6247   case ARM::sysLDMIB_UPD:
6248     if (!listContainsReg(Inst, 3, ARM::PC))
6249       return Error(Operands[4]->getStartLoc(),
6250                    "writeback register only allowed on system LDM "
6251                    "if PC in register-list");
6252     break;
6253   case ARM::sysSTMIA_UPD:
6254   case ARM::sysSTMDA_UPD:
6255   case ARM::sysSTMDB_UPD:
6256   case ARM::sysSTMIB_UPD:
6257     return Error(Operands[2]->getStartLoc(),
6258                  "system STM cannot have writeback register");
6259   case ARM::tMUL: {
6260     // The second source operand must be the same register as the destination
6261     // operand.
6262     //
6263     // In this case, we must directly check the parsed operands because the
6264     // cvtThumbMultiply() function is written in such a way that it guarantees
6265     // this first statement is always true for the new Inst.  Essentially, the
6266     // destination is unconditionally copied into the second source operand
6267     // without checking to see if it matches what we actually parsed.
6268     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6269                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6270         (((ARMOperand &)*Operands[3]).getReg() !=
6271          ((ARMOperand &)*Operands[4]).getReg())) {
6272       return Error(Operands[3]->getStartLoc(),
6273                    "destination register must match source register");
6274     }
6275     break;
6276   }
6277   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6278   // so only issue a diagnostic for thumb1. The instructions will be
6279   // switched to the t2 encodings in processInstruction() if necessary.
6280   case ARM::tPOP: {
6281     bool ListContainsBase;
6282     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6283         !isThumbTwo())
6284       return Error(Operands[2]->getStartLoc(),
6285                    "registers must be in range r0-r7 or pc");
6286     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6287       return true;
6288     break;
6289   }
6290   case ARM::tPUSH: {
6291     bool ListContainsBase;
6292     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6293         !isThumbTwo())
6294       return Error(Operands[2]->getStartLoc(),
6295                    "registers must be in range r0-r7 or lr");
6296     if (validatetSTMRegList(Inst, Operands, 2))
6297       return true;
6298     break;
6299   }
6300   case ARM::tSTMIA_UPD: {
6301     bool ListContainsBase, InvalidLowList;
6302     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6303                                           0, ListContainsBase);
6304     if (InvalidLowList && !isThumbTwo())
6305       return Error(Operands[4]->getStartLoc(),
6306                    "registers must be in range r0-r7");
6307 
6308     // This would be converted to a 32-bit stm, but that's not valid if the
6309     // writeback register is in the list.
6310     if (InvalidLowList && ListContainsBase)
6311       return Error(Operands[4]->getStartLoc(),
6312                    "writeback operator '!' not allowed when base register "
6313                    "in register list");
6314 
6315     if (validatetSTMRegList(Inst, Operands, 4))
6316       return true;
6317     break;
6318   }
6319   case ARM::tADDrSP: {
6320     // If the non-SP source operand and the destination operand are not the
6321     // same, we need thumb2 (for the wide encoding), or we have an error.
6322     if (!isThumbTwo() &&
6323         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6324       return Error(Operands[4]->getStartLoc(),
6325                    "source register must be the same as destination");
6326     }
6327     break;
6328   }
6329   // Final range checking for Thumb unconditional branch instructions.
6330   case ARM::tB:
6331     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6332       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6333     break;
6334   case ARM::t2B: {
6335     int op = (Operands[2]->isImm()) ? 2 : 3;
6336     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6337       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6338     break;
6339   }
6340   // Final range checking for Thumb conditional branch instructions.
6341   case ARM::tBcc:
6342     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6343       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6344     break;
6345   case ARM::t2Bcc: {
6346     int Op = (Operands[2]->isImm()) ? 2 : 3;
6347     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6348       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6349     break;
6350   }
6351   case ARM::MOVi16:
6352   case ARM::t2MOVi16:
6353   case ARM::t2MOVTi16:
6354     {
6355     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6356     // especially when we turn it into a movw and the expression <symbol> does
6357     // not have a :lower16: or :upper16 as part of the expression.  We don't
6358     // want the behavior of silently truncating, which can be unexpected and
6359     // lead to bugs that are difficult to find since this is an easy mistake
6360     // to make.
6361     int i = (Operands[3]->isImm()) ? 3 : 4;
6362     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6363     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6364     if (CE) break;
6365     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6366     if (!E) break;
6367     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6368     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6369                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6370       return Error(
6371           Op.getStartLoc(),
6372           "immediate expression for mov requires :lower16: or :upper16");
6373     break;
6374   }
6375   }
6376 
6377   return false;
6378 }
6379 
6380 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6381   switch(Opc) {
6382   default: llvm_unreachable("unexpected opcode!");
6383   // VST1LN
6384   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6385   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6386   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6387   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6388   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6389   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6390   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6391   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6392   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6393 
6394   // VST2LN
6395   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6396   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6397   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6398   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6399   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6400 
6401   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6402   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6403   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6404   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6405   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6406 
6407   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6408   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6409   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6410   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6411   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6412 
6413   // VST3LN
6414   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6415   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6416   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6417   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6418   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6419   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6420   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6421   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6422   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6423   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6424   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6425   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6426   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6427   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6428   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6429 
6430   // VST3
6431   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6432   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6433   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6434   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6435   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6436   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6437   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6438   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6439   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6440   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6441   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6442   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6443   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6444   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6445   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6446   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6447   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6448   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6449 
6450   // VST4LN
6451   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6452   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6453   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6454   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6455   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6456   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6457   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6458   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6459   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6460   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6461   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6462   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6463   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6464   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6465   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6466 
6467   // VST4
6468   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6469   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6470   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6471   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6472   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6473   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6474   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6475   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6476   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6477   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6478   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6479   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6480   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6481   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6482   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6483   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6484   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6485   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6486   }
6487 }
6488 
6489 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6490   switch(Opc) {
6491   default: llvm_unreachable("unexpected opcode!");
6492   // VLD1LN
6493   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6494   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6495   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6496   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6497   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6498   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6499   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6500   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6501   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6502 
6503   // VLD2LN
6504   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6505   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6506   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6507   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6508   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6509   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6510   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6511   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6512   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6513   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6514   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6515   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6516   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6517   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6518   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6519 
6520   // VLD3DUP
6521   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6522   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6523   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6524   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6525   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6526   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6527   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6528   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6529   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6530   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6531   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6532   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6533   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6534   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6535   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6536   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6537   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6538   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6539 
6540   // VLD3LN
6541   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6542   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6543   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6544   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6545   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6546   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6547   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6548   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6549   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6550   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6551   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6552   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6553   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6554   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6555   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6556 
6557   // VLD3
6558   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6559   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6560   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6561   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6562   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6563   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6564   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6565   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6566   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6567   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6568   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6569   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6570   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6571   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6572   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6573   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6574   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6575   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6576 
6577   // VLD4LN
6578   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6579   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6580   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6581   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6582   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6583   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6584   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6585   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6586   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6587   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6588   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6589   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6590   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6591   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6592   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6593 
6594   // VLD4DUP
6595   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6596   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6597   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6598   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6599   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6600   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6601   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6602   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6603   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6604   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6605   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6606   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6607   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6608   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6609   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6610   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6611   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6612   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6613 
6614   // VLD4
6615   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6616   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6617   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6618   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6619   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6620   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6621   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6622   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6623   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6624   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6625   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6626   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6627   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6628   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6629   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6630   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6631   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6632   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6633   }
6634 }
6635 
6636 bool ARMAsmParser::processInstruction(MCInst &Inst,
6637                                       const OperandVector &Operands,
6638                                       MCStreamer &Out) {
6639   switch (Inst.getOpcode()) {
6640   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6641   case ARM::LDRT_POST:
6642   case ARM::LDRBT_POST: {
6643     const unsigned Opcode =
6644       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6645                                            : ARM::LDRBT_POST_IMM;
6646     MCInst TmpInst;
6647     TmpInst.setOpcode(Opcode);
6648     TmpInst.addOperand(Inst.getOperand(0));
6649     TmpInst.addOperand(Inst.getOperand(1));
6650     TmpInst.addOperand(Inst.getOperand(1));
6651     TmpInst.addOperand(MCOperand::createReg(0));
6652     TmpInst.addOperand(MCOperand::createImm(0));
6653     TmpInst.addOperand(Inst.getOperand(2));
6654     TmpInst.addOperand(Inst.getOperand(3));
6655     Inst = TmpInst;
6656     return true;
6657   }
6658   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6659   case ARM::STRT_POST:
6660   case ARM::STRBT_POST: {
6661     const unsigned Opcode =
6662       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6663                                            : ARM::STRBT_POST_IMM;
6664     MCInst TmpInst;
6665     TmpInst.setOpcode(Opcode);
6666     TmpInst.addOperand(Inst.getOperand(1));
6667     TmpInst.addOperand(Inst.getOperand(0));
6668     TmpInst.addOperand(Inst.getOperand(1));
6669     TmpInst.addOperand(MCOperand::createReg(0));
6670     TmpInst.addOperand(MCOperand::createImm(0));
6671     TmpInst.addOperand(Inst.getOperand(2));
6672     TmpInst.addOperand(Inst.getOperand(3));
6673     Inst = TmpInst;
6674     return true;
6675   }
6676   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6677   case ARM::ADDri: {
6678     if (Inst.getOperand(1).getReg() != ARM::PC ||
6679         Inst.getOperand(5).getReg() != 0 ||
6680         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6681       return false;
6682     MCInst TmpInst;
6683     TmpInst.setOpcode(ARM::ADR);
6684     TmpInst.addOperand(Inst.getOperand(0));
6685     if (Inst.getOperand(2).isImm()) {
6686       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6687       // before passing it to the ADR instruction.
6688       unsigned Enc = Inst.getOperand(2).getImm();
6689       TmpInst.addOperand(MCOperand::createImm(
6690         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6691     } else {
6692       // Turn PC-relative expression into absolute expression.
6693       // Reading PC provides the start of the current instruction + 8 and
6694       // the transform to adr is biased by that.
6695       MCSymbol *Dot = getContext().createTempSymbol();
6696       Out.EmitLabel(Dot);
6697       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6698       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6699                                                      MCSymbolRefExpr::VK_None,
6700                                                      getContext());
6701       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6702       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6703                                                      getContext());
6704       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6705                                                         getContext());
6706       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6707     }
6708     TmpInst.addOperand(Inst.getOperand(3));
6709     TmpInst.addOperand(Inst.getOperand(4));
6710     Inst = TmpInst;
6711     return true;
6712   }
6713   // Aliases for alternate PC+imm syntax of LDR instructions.
6714   case ARM::t2LDRpcrel:
6715     // Select the narrow version if the immediate will fit.
6716     if (Inst.getOperand(1).getImm() > 0 &&
6717         Inst.getOperand(1).getImm() <= 0xff &&
6718         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6719           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
6720       Inst.setOpcode(ARM::tLDRpci);
6721     else
6722       Inst.setOpcode(ARM::t2LDRpci);
6723     return true;
6724   case ARM::t2LDRBpcrel:
6725     Inst.setOpcode(ARM::t2LDRBpci);
6726     return true;
6727   case ARM::t2LDRHpcrel:
6728     Inst.setOpcode(ARM::t2LDRHpci);
6729     return true;
6730   case ARM::t2LDRSBpcrel:
6731     Inst.setOpcode(ARM::t2LDRSBpci);
6732     return true;
6733   case ARM::t2LDRSHpcrel:
6734     Inst.setOpcode(ARM::t2LDRSHpci);
6735     return true;
6736   // Handle NEON VST complex aliases.
6737   case ARM::VST1LNdWB_register_Asm_8:
6738   case ARM::VST1LNdWB_register_Asm_16:
6739   case ARM::VST1LNdWB_register_Asm_32: {
6740     MCInst TmpInst;
6741     // Shuffle the operands around so the lane index operand is in the
6742     // right place.
6743     unsigned Spacing;
6744     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6745     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6746     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6747     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6748     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6749     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6750     TmpInst.addOperand(Inst.getOperand(1)); // lane
6751     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6752     TmpInst.addOperand(Inst.getOperand(6));
6753     Inst = TmpInst;
6754     return true;
6755   }
6756 
6757   case ARM::VST2LNdWB_register_Asm_8:
6758   case ARM::VST2LNdWB_register_Asm_16:
6759   case ARM::VST2LNdWB_register_Asm_32:
6760   case ARM::VST2LNqWB_register_Asm_16:
6761   case ARM::VST2LNqWB_register_Asm_32: {
6762     MCInst TmpInst;
6763     // Shuffle the operands around so the lane index operand is in the
6764     // right place.
6765     unsigned Spacing;
6766     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6767     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6768     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6769     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6770     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6771     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6772     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6773                                             Spacing));
6774     TmpInst.addOperand(Inst.getOperand(1)); // lane
6775     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6776     TmpInst.addOperand(Inst.getOperand(6));
6777     Inst = TmpInst;
6778     return true;
6779   }
6780 
6781   case ARM::VST3LNdWB_register_Asm_8:
6782   case ARM::VST3LNdWB_register_Asm_16:
6783   case ARM::VST3LNdWB_register_Asm_32:
6784   case ARM::VST3LNqWB_register_Asm_16:
6785   case ARM::VST3LNqWB_register_Asm_32: {
6786     MCInst TmpInst;
6787     // Shuffle the operands around so the lane index operand is in the
6788     // right place.
6789     unsigned Spacing;
6790     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6791     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6792     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6793     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6794     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6795     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6796     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6797                                             Spacing));
6798     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6799                                             Spacing * 2));
6800     TmpInst.addOperand(Inst.getOperand(1)); // lane
6801     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6802     TmpInst.addOperand(Inst.getOperand(6));
6803     Inst = TmpInst;
6804     return true;
6805   }
6806 
6807   case ARM::VST4LNdWB_register_Asm_8:
6808   case ARM::VST4LNdWB_register_Asm_16:
6809   case ARM::VST4LNdWB_register_Asm_32:
6810   case ARM::VST4LNqWB_register_Asm_16:
6811   case ARM::VST4LNqWB_register_Asm_32: {
6812     MCInst TmpInst;
6813     // Shuffle the operands around so the lane index operand is in the
6814     // right place.
6815     unsigned Spacing;
6816     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6817     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6818     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6819     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6820     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6821     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6822     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6823                                             Spacing));
6824     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6825                                             Spacing * 2));
6826     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6827                                             Spacing * 3));
6828     TmpInst.addOperand(Inst.getOperand(1)); // lane
6829     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6830     TmpInst.addOperand(Inst.getOperand(6));
6831     Inst = TmpInst;
6832     return true;
6833   }
6834 
6835   case ARM::VST1LNdWB_fixed_Asm_8:
6836   case ARM::VST1LNdWB_fixed_Asm_16:
6837   case ARM::VST1LNdWB_fixed_Asm_32: {
6838     MCInst TmpInst;
6839     // Shuffle the operands around so the lane index operand is in the
6840     // right place.
6841     unsigned Spacing;
6842     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6843     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6844     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6845     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6846     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6847     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6848     TmpInst.addOperand(Inst.getOperand(1)); // lane
6849     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6850     TmpInst.addOperand(Inst.getOperand(5));
6851     Inst = TmpInst;
6852     return true;
6853   }
6854 
6855   case ARM::VST2LNdWB_fixed_Asm_8:
6856   case ARM::VST2LNdWB_fixed_Asm_16:
6857   case ARM::VST2LNdWB_fixed_Asm_32:
6858   case ARM::VST2LNqWB_fixed_Asm_16:
6859   case ARM::VST2LNqWB_fixed_Asm_32: {
6860     MCInst TmpInst;
6861     // Shuffle the operands around so the lane index operand is in the
6862     // right place.
6863     unsigned Spacing;
6864     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6865     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6866     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6867     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6868     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6869     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6870     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6871                                             Spacing));
6872     TmpInst.addOperand(Inst.getOperand(1)); // lane
6873     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6874     TmpInst.addOperand(Inst.getOperand(5));
6875     Inst = TmpInst;
6876     return true;
6877   }
6878 
6879   case ARM::VST3LNdWB_fixed_Asm_8:
6880   case ARM::VST3LNdWB_fixed_Asm_16:
6881   case ARM::VST3LNdWB_fixed_Asm_32:
6882   case ARM::VST3LNqWB_fixed_Asm_16:
6883   case ARM::VST3LNqWB_fixed_Asm_32: {
6884     MCInst TmpInst;
6885     // Shuffle the operands around so the lane index operand is in the
6886     // right place.
6887     unsigned Spacing;
6888     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6889     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6890     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6891     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6892     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6893     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6894     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6895                                             Spacing));
6896     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6897                                             Spacing * 2));
6898     TmpInst.addOperand(Inst.getOperand(1)); // lane
6899     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6900     TmpInst.addOperand(Inst.getOperand(5));
6901     Inst = TmpInst;
6902     return true;
6903   }
6904 
6905   case ARM::VST4LNdWB_fixed_Asm_8:
6906   case ARM::VST4LNdWB_fixed_Asm_16:
6907   case ARM::VST4LNdWB_fixed_Asm_32:
6908   case ARM::VST4LNqWB_fixed_Asm_16:
6909   case ARM::VST4LNqWB_fixed_Asm_32: {
6910     MCInst TmpInst;
6911     // Shuffle the operands around so the lane index operand is in the
6912     // right place.
6913     unsigned Spacing;
6914     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6915     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6916     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6917     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6918     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6919     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6920     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6921                                             Spacing));
6922     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6923                                             Spacing * 2));
6924     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6925                                             Spacing * 3));
6926     TmpInst.addOperand(Inst.getOperand(1)); // lane
6927     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6928     TmpInst.addOperand(Inst.getOperand(5));
6929     Inst = TmpInst;
6930     return true;
6931   }
6932 
6933   case ARM::VST1LNdAsm_8:
6934   case ARM::VST1LNdAsm_16:
6935   case ARM::VST1LNdAsm_32: {
6936     MCInst TmpInst;
6937     // Shuffle the operands around so the lane index operand is in the
6938     // right place.
6939     unsigned Spacing;
6940     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6941     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6942     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6943     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6944     TmpInst.addOperand(Inst.getOperand(1)); // lane
6945     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6946     TmpInst.addOperand(Inst.getOperand(5));
6947     Inst = TmpInst;
6948     return true;
6949   }
6950 
6951   case ARM::VST2LNdAsm_8:
6952   case ARM::VST2LNdAsm_16:
6953   case ARM::VST2LNdAsm_32:
6954   case ARM::VST2LNqAsm_16:
6955   case ARM::VST2LNqAsm_32: {
6956     MCInst TmpInst;
6957     // Shuffle the operands around so the lane index operand is in the
6958     // right place.
6959     unsigned Spacing;
6960     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6961     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6962     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6963     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6964     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6965                                             Spacing));
6966     TmpInst.addOperand(Inst.getOperand(1)); // lane
6967     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6968     TmpInst.addOperand(Inst.getOperand(5));
6969     Inst = TmpInst;
6970     return true;
6971   }
6972 
6973   case ARM::VST3LNdAsm_8:
6974   case ARM::VST3LNdAsm_16:
6975   case ARM::VST3LNdAsm_32:
6976   case ARM::VST3LNqAsm_16:
6977   case ARM::VST3LNqAsm_32: {
6978     MCInst TmpInst;
6979     // Shuffle the operands around so the lane index operand is in the
6980     // right place.
6981     unsigned Spacing;
6982     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6983     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6984     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6985     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6986     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6987                                             Spacing));
6988     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6989                                             Spacing * 2));
6990     TmpInst.addOperand(Inst.getOperand(1)); // lane
6991     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6992     TmpInst.addOperand(Inst.getOperand(5));
6993     Inst = TmpInst;
6994     return true;
6995   }
6996 
6997   case ARM::VST4LNdAsm_8:
6998   case ARM::VST4LNdAsm_16:
6999   case ARM::VST4LNdAsm_32:
7000   case ARM::VST4LNqAsm_16:
7001   case ARM::VST4LNqAsm_32: {
7002     MCInst TmpInst;
7003     // Shuffle the operands around so the lane index operand is in the
7004     // right place.
7005     unsigned Spacing;
7006     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7007     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7008     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7009     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7010     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7011                                             Spacing));
7012     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7013                                             Spacing * 2));
7014     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7015                                             Spacing * 3));
7016     TmpInst.addOperand(Inst.getOperand(1)); // lane
7017     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7018     TmpInst.addOperand(Inst.getOperand(5));
7019     Inst = TmpInst;
7020     return true;
7021   }
7022 
7023   // Handle NEON VLD complex aliases.
7024   case ARM::VLD1LNdWB_register_Asm_8:
7025   case ARM::VLD1LNdWB_register_Asm_16:
7026   case ARM::VLD1LNdWB_register_Asm_32: {
7027     MCInst TmpInst;
7028     // Shuffle the operands around so the lane index operand is in the
7029     // right place.
7030     unsigned Spacing;
7031     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7032     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7033     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7034     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7035     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7036     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7037     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7038     TmpInst.addOperand(Inst.getOperand(1)); // lane
7039     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7040     TmpInst.addOperand(Inst.getOperand(6));
7041     Inst = TmpInst;
7042     return true;
7043   }
7044 
7045   case ARM::VLD2LNdWB_register_Asm_8:
7046   case ARM::VLD2LNdWB_register_Asm_16:
7047   case ARM::VLD2LNdWB_register_Asm_32:
7048   case ARM::VLD2LNqWB_register_Asm_16:
7049   case ARM::VLD2LNqWB_register_Asm_32: {
7050     MCInst TmpInst;
7051     // Shuffle the operands around so the lane index operand is in the
7052     // right place.
7053     unsigned Spacing;
7054     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7055     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7056     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7057                                             Spacing));
7058     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7059     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7060     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7061     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7062     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7063     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7064                                             Spacing));
7065     TmpInst.addOperand(Inst.getOperand(1)); // lane
7066     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7067     TmpInst.addOperand(Inst.getOperand(6));
7068     Inst = TmpInst;
7069     return true;
7070   }
7071 
7072   case ARM::VLD3LNdWB_register_Asm_8:
7073   case ARM::VLD3LNdWB_register_Asm_16:
7074   case ARM::VLD3LNdWB_register_Asm_32:
7075   case ARM::VLD3LNqWB_register_Asm_16:
7076   case ARM::VLD3LNqWB_register_Asm_32: {
7077     MCInst TmpInst;
7078     // Shuffle the operands around so the lane index operand is in the
7079     // right place.
7080     unsigned Spacing;
7081     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7082     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7083     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7084                                             Spacing));
7085     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7086                                             Spacing * 2));
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)); // Tied operand src (== Vd)
7092     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7093                                             Spacing));
7094     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7095                                             Spacing * 2));
7096     TmpInst.addOperand(Inst.getOperand(1)); // lane
7097     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7098     TmpInst.addOperand(Inst.getOperand(6));
7099     Inst = TmpInst;
7100     return true;
7101   }
7102 
7103   case ARM::VLD4LNdWB_register_Asm_8:
7104   case ARM::VLD4LNdWB_register_Asm_16:
7105   case ARM::VLD4LNdWB_register_Asm_32:
7106   case ARM::VLD4LNqWB_register_Asm_16:
7107   case ARM::VLD4LNqWB_register_Asm_32: {
7108     MCInst TmpInst;
7109     // Shuffle the operands around so the lane index operand is in the
7110     // right place.
7111     unsigned Spacing;
7112     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7113     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7114     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7115                                             Spacing));
7116     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7117                                             Spacing * 2));
7118     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7119                                             Spacing * 3));
7120     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7121     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7122     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7123     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7124     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7125     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7126                                             Spacing));
7127     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7128                                             Spacing * 2));
7129     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7130                                             Spacing * 3));
7131     TmpInst.addOperand(Inst.getOperand(1)); // lane
7132     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7133     TmpInst.addOperand(Inst.getOperand(6));
7134     Inst = TmpInst;
7135     return true;
7136   }
7137 
7138   case ARM::VLD1LNdWB_fixed_Asm_8:
7139   case ARM::VLD1LNdWB_fixed_Asm_16:
7140   case ARM::VLD1LNdWB_fixed_Asm_32: {
7141     MCInst TmpInst;
7142     // Shuffle the operands around so the lane index operand is in the
7143     // right place.
7144     unsigned Spacing;
7145     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7146     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7147     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7148     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7149     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7150     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7151     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7152     TmpInst.addOperand(Inst.getOperand(1)); // lane
7153     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7154     TmpInst.addOperand(Inst.getOperand(5));
7155     Inst = TmpInst;
7156     return true;
7157   }
7158 
7159   case ARM::VLD2LNdWB_fixed_Asm_8:
7160   case ARM::VLD2LNdWB_fixed_Asm_16:
7161   case ARM::VLD2LNdWB_fixed_Asm_32:
7162   case ARM::VLD2LNqWB_fixed_Asm_16:
7163   case ARM::VLD2LNqWB_fixed_Asm_32: {
7164     MCInst TmpInst;
7165     // Shuffle the operands around so the lane index operand is in the
7166     // right place.
7167     unsigned Spacing;
7168     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7169     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7170     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7171                                             Spacing));
7172     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7173     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7174     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7175     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7176     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7177     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7178                                             Spacing));
7179     TmpInst.addOperand(Inst.getOperand(1)); // lane
7180     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7181     TmpInst.addOperand(Inst.getOperand(5));
7182     Inst = TmpInst;
7183     return true;
7184   }
7185 
7186   case ARM::VLD3LNdWB_fixed_Asm_8:
7187   case ARM::VLD3LNdWB_fixed_Asm_16:
7188   case ARM::VLD3LNdWB_fixed_Asm_32:
7189   case ARM::VLD3LNqWB_fixed_Asm_16:
7190   case ARM::VLD3LNqWB_fixed_Asm_32: {
7191     MCInst TmpInst;
7192     // Shuffle the operands around so the lane index operand is in the
7193     // right place.
7194     unsigned Spacing;
7195     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7196     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7197     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7198                                             Spacing));
7199     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7200                                             Spacing * 2));
7201     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7202     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7203     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7204     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7205     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7206     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7207                                             Spacing));
7208     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7209                                             Spacing * 2));
7210     TmpInst.addOperand(Inst.getOperand(1)); // lane
7211     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7212     TmpInst.addOperand(Inst.getOperand(5));
7213     Inst = TmpInst;
7214     return true;
7215   }
7216 
7217   case ARM::VLD4LNdWB_fixed_Asm_8:
7218   case ARM::VLD4LNdWB_fixed_Asm_16:
7219   case ARM::VLD4LNdWB_fixed_Asm_32:
7220   case ARM::VLD4LNqWB_fixed_Asm_16:
7221   case ARM::VLD4LNqWB_fixed_Asm_32: {
7222     MCInst TmpInst;
7223     // Shuffle the operands around so the lane index operand is in the
7224     // right place.
7225     unsigned Spacing;
7226     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7227     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7228     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7229                                             Spacing));
7230     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7231                                             Spacing * 2));
7232     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7233                                             Spacing * 3));
7234     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7235     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7236     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7237     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7238     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7239     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7240                                             Spacing));
7241     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7242                                             Spacing * 2));
7243     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7244                                             Spacing * 3));
7245     TmpInst.addOperand(Inst.getOperand(1)); // lane
7246     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7247     TmpInst.addOperand(Inst.getOperand(5));
7248     Inst = TmpInst;
7249     return true;
7250   }
7251 
7252   case ARM::VLD1LNdAsm_8:
7253   case ARM::VLD1LNdAsm_16:
7254   case ARM::VLD1LNdAsm_32: {
7255     MCInst TmpInst;
7256     // Shuffle the operands around so the lane index operand is in the
7257     // right place.
7258     unsigned Spacing;
7259     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7260     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7261     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7262     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7263     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== 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::VLD2LNdAsm_8:
7272   case ARM::VLD2LNdAsm_16:
7273   case ARM::VLD2LNdAsm_32:
7274   case ARM::VLD2LNqAsm_16:
7275   case ARM::VLD2LNqAsm_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(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7281     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7282     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7283                                             Spacing));
7284     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7285     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7286     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7287     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7288                                             Spacing));
7289     TmpInst.addOperand(Inst.getOperand(1)); // lane
7290     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7291     TmpInst.addOperand(Inst.getOperand(5));
7292     Inst = TmpInst;
7293     return true;
7294   }
7295 
7296   case ARM::VLD3LNdAsm_8:
7297   case ARM::VLD3LNdAsm_16:
7298   case ARM::VLD3LNdAsm_32:
7299   case ARM::VLD3LNqAsm_16:
7300   case ARM::VLD3LNqAsm_32: {
7301     MCInst TmpInst;
7302     // Shuffle the operands around so the lane index operand is in the
7303     // right place.
7304     unsigned Spacing;
7305     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7306     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7307     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7308                                             Spacing));
7309     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7310                                             Spacing * 2));
7311     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7312     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7313     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7314     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7315                                             Spacing));
7316     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7317                                             Spacing * 2));
7318     TmpInst.addOperand(Inst.getOperand(1)); // lane
7319     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7320     TmpInst.addOperand(Inst.getOperand(5));
7321     Inst = TmpInst;
7322     return true;
7323   }
7324 
7325   case ARM::VLD4LNdAsm_8:
7326   case ARM::VLD4LNdAsm_16:
7327   case ARM::VLD4LNdAsm_32:
7328   case ARM::VLD4LNqAsm_16:
7329   case ARM::VLD4LNqAsm_32: {
7330     MCInst TmpInst;
7331     // Shuffle the operands around so the lane index operand is in the
7332     // right place.
7333     unsigned Spacing;
7334     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7335     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7336     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7337                                             Spacing));
7338     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7339                                             Spacing * 2));
7340     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7341                                             Spacing * 3));
7342     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7343     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7344     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7345     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7346                                             Spacing));
7347     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7348                                             Spacing * 2));
7349     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7350                                             Spacing * 3));
7351     TmpInst.addOperand(Inst.getOperand(1)); // lane
7352     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7353     TmpInst.addOperand(Inst.getOperand(5));
7354     Inst = TmpInst;
7355     return true;
7356   }
7357 
7358   // VLD3DUP single 3-element structure to all lanes instructions.
7359   case ARM::VLD3DUPdAsm_8:
7360   case ARM::VLD3DUPdAsm_16:
7361   case ARM::VLD3DUPdAsm_32:
7362   case ARM::VLD3DUPqAsm_8:
7363   case ARM::VLD3DUPqAsm_16:
7364   case ARM::VLD3DUPqAsm_32: {
7365     MCInst TmpInst;
7366     unsigned Spacing;
7367     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7368     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7369     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7370                                             Spacing));
7371     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7372                                             Spacing * 2));
7373     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7374     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7375     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7376     TmpInst.addOperand(Inst.getOperand(4));
7377     Inst = TmpInst;
7378     return true;
7379   }
7380 
7381   case ARM::VLD3DUPdWB_fixed_Asm_8:
7382   case ARM::VLD3DUPdWB_fixed_Asm_16:
7383   case ARM::VLD3DUPdWB_fixed_Asm_32:
7384   case ARM::VLD3DUPqWB_fixed_Asm_8:
7385   case ARM::VLD3DUPqWB_fixed_Asm_16:
7386   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7387     MCInst TmpInst;
7388     unsigned Spacing;
7389     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7390     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7391     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7392                                             Spacing));
7393     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7394                                             Spacing * 2));
7395     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7396     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7397     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7398     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7399     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7400     TmpInst.addOperand(Inst.getOperand(4));
7401     Inst = TmpInst;
7402     return true;
7403   }
7404 
7405   case ARM::VLD3DUPdWB_register_Asm_8:
7406   case ARM::VLD3DUPdWB_register_Asm_16:
7407   case ARM::VLD3DUPdWB_register_Asm_32:
7408   case ARM::VLD3DUPqWB_register_Asm_8:
7409   case ARM::VLD3DUPqWB_register_Asm_16:
7410   case ARM::VLD3DUPqWB_register_Asm_32: {
7411     MCInst TmpInst;
7412     unsigned Spacing;
7413     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7414     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7415     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7416                                             Spacing));
7417     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7418                                             Spacing * 2));
7419     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7420     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7421     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7422     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7423     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7424     TmpInst.addOperand(Inst.getOperand(5));
7425     Inst = TmpInst;
7426     return true;
7427   }
7428 
7429   // VLD3 multiple 3-element structure instructions.
7430   case ARM::VLD3dAsm_8:
7431   case ARM::VLD3dAsm_16:
7432   case ARM::VLD3dAsm_32:
7433   case ARM::VLD3qAsm_8:
7434   case ARM::VLD3qAsm_16:
7435   case ARM::VLD3qAsm_32: {
7436     MCInst TmpInst;
7437     unsigned Spacing;
7438     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7439     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7440     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7441                                             Spacing));
7442     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7443                                             Spacing * 2));
7444     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7445     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7446     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7447     TmpInst.addOperand(Inst.getOperand(4));
7448     Inst = TmpInst;
7449     return true;
7450   }
7451 
7452   case ARM::VLD3dWB_fixed_Asm_8:
7453   case ARM::VLD3dWB_fixed_Asm_16:
7454   case ARM::VLD3dWB_fixed_Asm_32:
7455   case ARM::VLD3qWB_fixed_Asm_8:
7456   case ARM::VLD3qWB_fixed_Asm_16:
7457   case ARM::VLD3qWB_fixed_Asm_32: {
7458     MCInst TmpInst;
7459     unsigned Spacing;
7460     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7461     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7462     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7463                                             Spacing));
7464     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7465                                             Spacing * 2));
7466     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7467     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7468     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7469     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7470     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7471     TmpInst.addOperand(Inst.getOperand(4));
7472     Inst = TmpInst;
7473     return true;
7474   }
7475 
7476   case ARM::VLD3dWB_register_Asm_8:
7477   case ARM::VLD3dWB_register_Asm_16:
7478   case ARM::VLD3dWB_register_Asm_32:
7479   case ARM::VLD3qWB_register_Asm_8:
7480   case ARM::VLD3qWB_register_Asm_16:
7481   case ARM::VLD3qWB_register_Asm_32: {
7482     MCInst TmpInst;
7483     unsigned Spacing;
7484     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7485     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7486     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7487                                             Spacing));
7488     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7489                                             Spacing * 2));
7490     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7491     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7492     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7493     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7494     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7495     TmpInst.addOperand(Inst.getOperand(5));
7496     Inst = TmpInst;
7497     return true;
7498   }
7499 
7500   // VLD4DUP single 3-element structure to all lanes instructions.
7501   case ARM::VLD4DUPdAsm_8:
7502   case ARM::VLD4DUPdAsm_16:
7503   case ARM::VLD4DUPdAsm_32:
7504   case ARM::VLD4DUPqAsm_8:
7505   case ARM::VLD4DUPqAsm_16:
7506   case ARM::VLD4DUPqAsm_32: {
7507     MCInst TmpInst;
7508     unsigned Spacing;
7509     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7510     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7511     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7512                                             Spacing));
7513     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7514                                             Spacing * 2));
7515     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7516                                             Spacing * 3));
7517     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7518     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7519     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7520     TmpInst.addOperand(Inst.getOperand(4));
7521     Inst = TmpInst;
7522     return true;
7523   }
7524 
7525   case ARM::VLD4DUPdWB_fixed_Asm_8:
7526   case ARM::VLD4DUPdWB_fixed_Asm_16:
7527   case ARM::VLD4DUPdWB_fixed_Asm_32:
7528   case ARM::VLD4DUPqWB_fixed_Asm_8:
7529   case ARM::VLD4DUPqWB_fixed_Asm_16:
7530   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7531     MCInst TmpInst;
7532     unsigned Spacing;
7533     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7534     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7535     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7536                                             Spacing));
7537     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7538                                             Spacing * 2));
7539     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7540                                             Spacing * 3));
7541     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7542     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7543     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7544     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7545     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7546     TmpInst.addOperand(Inst.getOperand(4));
7547     Inst = TmpInst;
7548     return true;
7549   }
7550 
7551   case ARM::VLD4DUPdWB_register_Asm_8:
7552   case ARM::VLD4DUPdWB_register_Asm_16:
7553   case ARM::VLD4DUPdWB_register_Asm_32:
7554   case ARM::VLD4DUPqWB_register_Asm_8:
7555   case ARM::VLD4DUPqWB_register_Asm_16:
7556   case ARM::VLD4DUPqWB_register_Asm_32: {
7557     MCInst TmpInst;
7558     unsigned Spacing;
7559     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7560     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7561     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7562                                             Spacing));
7563     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7564                                             Spacing * 2));
7565     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7566                                             Spacing * 3));
7567     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7568     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7569     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7570     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7571     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7572     TmpInst.addOperand(Inst.getOperand(5));
7573     Inst = TmpInst;
7574     return true;
7575   }
7576 
7577   // VLD4 multiple 4-element structure instructions.
7578   case ARM::VLD4dAsm_8:
7579   case ARM::VLD4dAsm_16:
7580   case ARM::VLD4dAsm_32:
7581   case ARM::VLD4qAsm_8:
7582   case ARM::VLD4qAsm_16:
7583   case ARM::VLD4qAsm_32: {
7584     MCInst TmpInst;
7585     unsigned Spacing;
7586     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7587     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7588     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7589                                             Spacing));
7590     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7591                                             Spacing * 2));
7592     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7593                                             Spacing * 3));
7594     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7595     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7596     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7597     TmpInst.addOperand(Inst.getOperand(4));
7598     Inst = TmpInst;
7599     return true;
7600   }
7601 
7602   case ARM::VLD4dWB_fixed_Asm_8:
7603   case ARM::VLD4dWB_fixed_Asm_16:
7604   case ARM::VLD4dWB_fixed_Asm_32:
7605   case ARM::VLD4qWB_fixed_Asm_8:
7606   case ARM::VLD4qWB_fixed_Asm_16:
7607   case ARM::VLD4qWB_fixed_Asm_32: {
7608     MCInst TmpInst;
7609     unsigned Spacing;
7610     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7611     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7612     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7613                                             Spacing));
7614     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7615                                             Spacing * 2));
7616     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7617                                             Spacing * 3));
7618     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7619     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7620     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7621     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7622     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7623     TmpInst.addOperand(Inst.getOperand(4));
7624     Inst = TmpInst;
7625     return true;
7626   }
7627 
7628   case ARM::VLD4dWB_register_Asm_8:
7629   case ARM::VLD4dWB_register_Asm_16:
7630   case ARM::VLD4dWB_register_Asm_32:
7631   case ARM::VLD4qWB_register_Asm_8:
7632   case ARM::VLD4qWB_register_Asm_16:
7633   case ARM::VLD4qWB_register_Asm_32: {
7634     MCInst TmpInst;
7635     unsigned Spacing;
7636     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7637     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7638     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7639                                             Spacing));
7640     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7641                                             Spacing * 2));
7642     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7643                                             Spacing * 3));
7644     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7645     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7646     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7647     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7648     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7649     TmpInst.addOperand(Inst.getOperand(5));
7650     Inst = TmpInst;
7651     return true;
7652   }
7653 
7654   // VST3 multiple 3-element structure instructions.
7655   case ARM::VST3dAsm_8:
7656   case ARM::VST3dAsm_16:
7657   case ARM::VST3dAsm_32:
7658   case ARM::VST3qAsm_8:
7659   case ARM::VST3qAsm_16:
7660   case ARM::VST3qAsm_32: {
7661     MCInst TmpInst;
7662     unsigned Spacing;
7663     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7664     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7665     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7666     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7667     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7668                                             Spacing));
7669     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7670                                             Spacing * 2));
7671     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7672     TmpInst.addOperand(Inst.getOperand(4));
7673     Inst = TmpInst;
7674     return true;
7675   }
7676 
7677   case ARM::VST3dWB_fixed_Asm_8:
7678   case ARM::VST3dWB_fixed_Asm_16:
7679   case ARM::VST3dWB_fixed_Asm_32:
7680   case ARM::VST3qWB_fixed_Asm_8:
7681   case ARM::VST3qWB_fixed_Asm_16:
7682   case ARM::VST3qWB_fixed_Asm_32: {
7683     MCInst TmpInst;
7684     unsigned Spacing;
7685     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7686     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7687     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7688     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7689     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7690     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7691     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7692                                             Spacing));
7693     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7694                                             Spacing * 2));
7695     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7696     TmpInst.addOperand(Inst.getOperand(4));
7697     Inst = TmpInst;
7698     return true;
7699   }
7700 
7701   case ARM::VST3dWB_register_Asm_8:
7702   case ARM::VST3dWB_register_Asm_16:
7703   case ARM::VST3dWB_register_Asm_32:
7704   case ARM::VST3qWB_register_Asm_8:
7705   case ARM::VST3qWB_register_Asm_16:
7706   case ARM::VST3qWB_register_Asm_32: {
7707     MCInst TmpInst;
7708     unsigned Spacing;
7709     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7710     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7711     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7712     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7713     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7714     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7715     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7716                                             Spacing));
7717     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7718                                             Spacing * 2));
7719     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7720     TmpInst.addOperand(Inst.getOperand(5));
7721     Inst = TmpInst;
7722     return true;
7723   }
7724 
7725   // VST4 multiple 3-element structure instructions.
7726   case ARM::VST4dAsm_8:
7727   case ARM::VST4dAsm_16:
7728   case ARM::VST4dAsm_32:
7729   case ARM::VST4qAsm_8:
7730   case ARM::VST4qAsm_16:
7731   case ARM::VST4qAsm_32: {
7732     MCInst TmpInst;
7733     unsigned Spacing;
7734     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7735     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7736     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7737     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7738     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7739                                             Spacing));
7740     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7741                                             Spacing * 2));
7742     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7743                                             Spacing * 3));
7744     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7745     TmpInst.addOperand(Inst.getOperand(4));
7746     Inst = TmpInst;
7747     return true;
7748   }
7749 
7750   case ARM::VST4dWB_fixed_Asm_8:
7751   case ARM::VST4dWB_fixed_Asm_16:
7752   case ARM::VST4dWB_fixed_Asm_32:
7753   case ARM::VST4qWB_fixed_Asm_8:
7754   case ARM::VST4qWB_fixed_Asm_16:
7755   case ARM::VST4qWB_fixed_Asm_32: {
7756     MCInst TmpInst;
7757     unsigned Spacing;
7758     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7759     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7760     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7761     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7762     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7763     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7764     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7765                                             Spacing));
7766     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7767                                             Spacing * 2));
7768     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7769                                             Spacing * 3));
7770     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7771     TmpInst.addOperand(Inst.getOperand(4));
7772     Inst = TmpInst;
7773     return true;
7774   }
7775 
7776   case ARM::VST4dWB_register_Asm_8:
7777   case ARM::VST4dWB_register_Asm_16:
7778   case ARM::VST4dWB_register_Asm_32:
7779   case ARM::VST4qWB_register_Asm_8:
7780   case ARM::VST4qWB_register_Asm_16:
7781   case ARM::VST4qWB_register_Asm_32: {
7782     MCInst TmpInst;
7783     unsigned Spacing;
7784     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7785     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7786     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7787     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7788     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7789     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7790     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7791                                             Spacing));
7792     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7793                                             Spacing * 2));
7794     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7795                                             Spacing * 3));
7796     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7797     TmpInst.addOperand(Inst.getOperand(5));
7798     Inst = TmpInst;
7799     return true;
7800   }
7801 
7802   // Handle encoding choice for the shift-immediate instructions.
7803   case ARM::t2LSLri:
7804   case ARM::t2LSRri:
7805   case ARM::t2ASRri: {
7806     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7807         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7808         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
7809         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7810           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
7811       unsigned NewOpc;
7812       switch (Inst.getOpcode()) {
7813       default: llvm_unreachable("unexpected opcode");
7814       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
7815       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
7816       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
7817       }
7818       // The Thumb1 operands aren't in the same order. Awesome, eh?
7819       MCInst TmpInst;
7820       TmpInst.setOpcode(NewOpc);
7821       TmpInst.addOperand(Inst.getOperand(0));
7822       TmpInst.addOperand(Inst.getOperand(5));
7823       TmpInst.addOperand(Inst.getOperand(1));
7824       TmpInst.addOperand(Inst.getOperand(2));
7825       TmpInst.addOperand(Inst.getOperand(3));
7826       TmpInst.addOperand(Inst.getOperand(4));
7827       Inst = TmpInst;
7828       return true;
7829     }
7830     return false;
7831   }
7832 
7833   // Handle the Thumb2 mode MOV complex aliases.
7834   case ARM::t2MOVsr:
7835   case ARM::t2MOVSsr: {
7836     // Which instruction to expand to depends on the CCOut operand and
7837     // whether we're in an IT block if the register operands are low
7838     // registers.
7839     bool isNarrow = false;
7840     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7841         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7842         isARMLowRegister(Inst.getOperand(2).getReg()) &&
7843         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7844         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
7845       isNarrow = true;
7846     MCInst TmpInst;
7847     unsigned newOpc;
7848     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
7849     default: llvm_unreachable("unexpected opcode!");
7850     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
7851     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
7852     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
7853     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
7854     }
7855     TmpInst.setOpcode(newOpc);
7856     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7857     if (isNarrow)
7858       TmpInst.addOperand(MCOperand::createReg(
7859           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7860     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7861     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7862     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7863     TmpInst.addOperand(Inst.getOperand(5));
7864     if (!isNarrow)
7865       TmpInst.addOperand(MCOperand::createReg(
7866           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7867     Inst = TmpInst;
7868     return true;
7869   }
7870   case ARM::t2MOVsi:
7871   case ARM::t2MOVSsi: {
7872     // Which instruction to expand to depends on the CCOut operand and
7873     // whether we're in an IT block if the register operands are low
7874     // registers.
7875     bool isNarrow = false;
7876     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7877         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7878         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
7879       isNarrow = true;
7880     MCInst TmpInst;
7881     unsigned newOpc;
7882     switch(ARM_AM::getSORegShOp(Inst.getOperand(2).getImm())) {
7883     default: llvm_unreachable("unexpected opcode!");
7884     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
7885     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
7886     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
7887     case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
7888     case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
7889     }
7890     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
7891     if (Amount == 32) Amount = 0;
7892     TmpInst.setOpcode(newOpc);
7893     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7894     if (isNarrow)
7895       TmpInst.addOperand(MCOperand::createReg(
7896           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7897     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7898     if (newOpc != ARM::t2RRX)
7899       TmpInst.addOperand(MCOperand::createImm(Amount));
7900     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7901     TmpInst.addOperand(Inst.getOperand(4));
7902     if (!isNarrow)
7903       TmpInst.addOperand(MCOperand::createReg(
7904           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7905     Inst = TmpInst;
7906     return true;
7907   }
7908   // Handle the ARM mode MOV complex aliases.
7909   case ARM::ASRr:
7910   case ARM::LSRr:
7911   case ARM::LSLr:
7912   case ARM::RORr: {
7913     ARM_AM::ShiftOpc ShiftTy;
7914     switch(Inst.getOpcode()) {
7915     default: llvm_unreachable("unexpected opcode!");
7916     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
7917     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
7918     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
7919     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
7920     }
7921     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
7922     MCInst TmpInst;
7923     TmpInst.setOpcode(ARM::MOVsr);
7924     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7925     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7926     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7927     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7928     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7929     TmpInst.addOperand(Inst.getOperand(4));
7930     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7931     Inst = TmpInst;
7932     return true;
7933   }
7934   case ARM::ASRi:
7935   case ARM::LSRi:
7936   case ARM::LSLi:
7937   case ARM::RORi: {
7938     ARM_AM::ShiftOpc ShiftTy;
7939     switch(Inst.getOpcode()) {
7940     default: llvm_unreachable("unexpected opcode!");
7941     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
7942     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
7943     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
7944     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
7945     }
7946     // A shift by zero is a plain MOVr, not a MOVsi.
7947     unsigned Amt = Inst.getOperand(2).getImm();
7948     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
7949     // A shift by 32 should be encoded as 0 when permitted
7950     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
7951       Amt = 0;
7952     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
7953     MCInst TmpInst;
7954     TmpInst.setOpcode(Opc);
7955     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7956     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7957     if (Opc == ARM::MOVsi)
7958       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7959     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7960     TmpInst.addOperand(Inst.getOperand(4));
7961     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7962     Inst = TmpInst;
7963     return true;
7964   }
7965   case ARM::RRXi: {
7966     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
7967     MCInst TmpInst;
7968     TmpInst.setOpcode(ARM::MOVsi);
7969     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7970     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7971     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7972     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7973     TmpInst.addOperand(Inst.getOperand(3));
7974     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
7975     Inst = TmpInst;
7976     return true;
7977   }
7978   case ARM::t2LDMIA_UPD: {
7979     // If this is a load of a single register, then we should use
7980     // a post-indexed LDR instruction instead, per the ARM ARM.
7981     if (Inst.getNumOperands() != 5)
7982       return false;
7983     MCInst TmpInst;
7984     TmpInst.setOpcode(ARM::t2LDR_POST);
7985     TmpInst.addOperand(Inst.getOperand(4)); // Rt
7986     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
7987     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7988     TmpInst.addOperand(MCOperand::createImm(4));
7989     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7990     TmpInst.addOperand(Inst.getOperand(3));
7991     Inst = TmpInst;
7992     return true;
7993   }
7994   case ARM::t2STMDB_UPD: {
7995     // If this is a store of a single register, then we should use
7996     // a pre-indexed STR instruction instead, per the ARM ARM.
7997     if (Inst.getNumOperands() != 5)
7998       return false;
7999     MCInst TmpInst;
8000     TmpInst.setOpcode(ARM::t2STR_PRE);
8001     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8002     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8003     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8004     TmpInst.addOperand(MCOperand::createImm(-4));
8005     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8006     TmpInst.addOperand(Inst.getOperand(3));
8007     Inst = TmpInst;
8008     return true;
8009   }
8010   case ARM::LDMIA_UPD:
8011     // If this is a load of a single register via a 'pop', then we should use
8012     // a post-indexed LDR instruction instead, per the ARM ARM.
8013     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8014         Inst.getNumOperands() == 5) {
8015       MCInst TmpInst;
8016       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8017       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8018       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8019       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8020       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8021       TmpInst.addOperand(MCOperand::createImm(4));
8022       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8023       TmpInst.addOperand(Inst.getOperand(3));
8024       Inst = TmpInst;
8025       return true;
8026     }
8027     break;
8028   case ARM::STMDB_UPD:
8029     // If this is a store of a single register via a 'push', then we should use
8030     // a pre-indexed STR instruction instead, per the ARM ARM.
8031     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8032         Inst.getNumOperands() == 5) {
8033       MCInst TmpInst;
8034       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8035       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8036       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8037       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8038       TmpInst.addOperand(MCOperand::createImm(-4));
8039       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8040       TmpInst.addOperand(Inst.getOperand(3));
8041       Inst = TmpInst;
8042     }
8043     break;
8044   case ARM::t2ADDri12:
8045     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8046     // mnemonic was used (not "addw"), encoding T3 is preferred.
8047     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8048         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8049       break;
8050     Inst.setOpcode(ARM::t2ADDri);
8051     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8052     break;
8053   case ARM::t2SUBri12:
8054     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8055     // mnemonic was used (not "subw"), encoding T3 is preferred.
8056     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8057         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8058       break;
8059     Inst.setOpcode(ARM::t2SUBri);
8060     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8061     break;
8062   case ARM::tADDi8:
8063     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8064     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8065     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8066     // to encoding T1 if <Rd> is omitted."
8067     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8068       Inst.setOpcode(ARM::tADDi3);
8069       return true;
8070     }
8071     break;
8072   case ARM::tSUBi8:
8073     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8074     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8075     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8076     // to encoding T1 if <Rd> is omitted."
8077     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8078       Inst.setOpcode(ARM::tSUBi3);
8079       return true;
8080     }
8081     break;
8082   case ARM::t2ADDri:
8083   case ARM::t2SUBri: {
8084     // If the destination and first source operand are the same, and
8085     // the flags are compatible with the current IT status, use encoding T2
8086     // instead of T3. For compatibility with the system 'as'. Make sure the
8087     // wide encoding wasn't explicit.
8088     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8089         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8090         (unsigned)Inst.getOperand(2).getImm() > 255 ||
8091         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
8092          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
8093         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8094          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8095       break;
8096     MCInst TmpInst;
8097     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8098                       ARM::tADDi8 : ARM::tSUBi8);
8099     TmpInst.addOperand(Inst.getOperand(0));
8100     TmpInst.addOperand(Inst.getOperand(5));
8101     TmpInst.addOperand(Inst.getOperand(0));
8102     TmpInst.addOperand(Inst.getOperand(2));
8103     TmpInst.addOperand(Inst.getOperand(3));
8104     TmpInst.addOperand(Inst.getOperand(4));
8105     Inst = TmpInst;
8106     return true;
8107   }
8108   case ARM::t2ADDrr: {
8109     // If the destination and first source operand are the same, and
8110     // there's no setting of the flags, use encoding T2 instead of T3.
8111     // Note that this is only for ADD, not SUB. This mirrors the system
8112     // 'as' behaviour.  Also take advantage of ADD being commutative.
8113     // Make sure the wide encoding wasn't explicit.
8114     bool Swap = false;
8115     auto DestReg = Inst.getOperand(0).getReg();
8116     bool Transform = DestReg == Inst.getOperand(1).getReg();
8117     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8118       Transform = true;
8119       Swap = true;
8120     }
8121     if (!Transform ||
8122         Inst.getOperand(5).getReg() != 0 ||
8123         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8124          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8125       break;
8126     MCInst TmpInst;
8127     TmpInst.setOpcode(ARM::tADDhirr);
8128     TmpInst.addOperand(Inst.getOperand(0));
8129     TmpInst.addOperand(Inst.getOperand(0));
8130     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8131     TmpInst.addOperand(Inst.getOperand(3));
8132     TmpInst.addOperand(Inst.getOperand(4));
8133     Inst = TmpInst;
8134     return true;
8135   }
8136   case ARM::tADDrSP: {
8137     // If the non-SP source operand and the destination operand are not the
8138     // same, we need to use the 32-bit encoding if it's available.
8139     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8140       Inst.setOpcode(ARM::t2ADDrr);
8141       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8142       return true;
8143     }
8144     break;
8145   }
8146   case ARM::tB:
8147     // A Thumb conditional branch outside of an IT block is a tBcc.
8148     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8149       Inst.setOpcode(ARM::tBcc);
8150       return true;
8151     }
8152     break;
8153   case ARM::t2B:
8154     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8155     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8156       Inst.setOpcode(ARM::t2Bcc);
8157       return true;
8158     }
8159     break;
8160   case ARM::t2Bcc:
8161     // If the conditional is AL or we're in an IT block, we really want t2B.
8162     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8163       Inst.setOpcode(ARM::t2B);
8164       return true;
8165     }
8166     break;
8167   case ARM::tBcc:
8168     // If the conditional is AL, we really want tB.
8169     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8170       Inst.setOpcode(ARM::tB);
8171       return true;
8172     }
8173     break;
8174   case ARM::tLDMIA: {
8175     // If the register list contains any high registers, or if the writeback
8176     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8177     // instead if we're in Thumb2. Otherwise, this should have generated
8178     // an error in validateInstruction().
8179     unsigned Rn = Inst.getOperand(0).getReg();
8180     bool hasWritebackToken =
8181         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8182          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8183     bool listContainsBase;
8184     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8185         (!listContainsBase && !hasWritebackToken) ||
8186         (listContainsBase && hasWritebackToken)) {
8187       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8188       assert (isThumbTwo());
8189       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8190       // If we're switching to the updating version, we need to insert
8191       // the writeback tied operand.
8192       if (hasWritebackToken)
8193         Inst.insert(Inst.begin(),
8194                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8195       return true;
8196     }
8197     break;
8198   }
8199   case ARM::tSTMIA_UPD: {
8200     // If the register list contains any high registers, we need to use
8201     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8202     // should have generated an error in validateInstruction().
8203     unsigned Rn = Inst.getOperand(0).getReg();
8204     bool listContainsBase;
8205     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8206       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8207       assert (isThumbTwo());
8208       Inst.setOpcode(ARM::t2STMIA_UPD);
8209       return true;
8210     }
8211     break;
8212   }
8213   case ARM::tPOP: {
8214     bool listContainsBase;
8215     // If the register list contains any high registers, we need to use
8216     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8217     // should have generated an error in validateInstruction().
8218     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8219       return false;
8220     assert (isThumbTwo());
8221     Inst.setOpcode(ARM::t2LDMIA_UPD);
8222     // Add the base register and writeback operands.
8223     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8224     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8225     return true;
8226   }
8227   case ARM::tPUSH: {
8228     bool listContainsBase;
8229     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8230       return false;
8231     assert (isThumbTwo());
8232     Inst.setOpcode(ARM::t2STMDB_UPD);
8233     // Add the base register and writeback operands.
8234     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8235     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8236     return true;
8237   }
8238   case ARM::t2MOVi: {
8239     // If we can use the 16-bit encoding and the user didn't explicitly
8240     // request the 32-bit variant, transform it here.
8241     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8242         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8243         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8244           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8245          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8246         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8247          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8248       // The operands aren't in the same order for tMOVi8...
8249       MCInst TmpInst;
8250       TmpInst.setOpcode(ARM::tMOVi8);
8251       TmpInst.addOperand(Inst.getOperand(0));
8252       TmpInst.addOperand(Inst.getOperand(4));
8253       TmpInst.addOperand(Inst.getOperand(1));
8254       TmpInst.addOperand(Inst.getOperand(2));
8255       TmpInst.addOperand(Inst.getOperand(3));
8256       Inst = TmpInst;
8257       return true;
8258     }
8259     break;
8260   }
8261   case ARM::t2MOVr: {
8262     // If we can use the 16-bit encoding and the user didn't explicitly
8263     // request the 32-bit variant, transform it here.
8264     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8265         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8266         Inst.getOperand(2).getImm() == ARMCC::AL &&
8267         Inst.getOperand(4).getReg() == ARM::CPSR &&
8268         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8269          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8270       // The operands aren't the same for tMOV[S]r... (no cc_out)
8271       MCInst TmpInst;
8272       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8273       TmpInst.addOperand(Inst.getOperand(0));
8274       TmpInst.addOperand(Inst.getOperand(1));
8275       TmpInst.addOperand(Inst.getOperand(2));
8276       TmpInst.addOperand(Inst.getOperand(3));
8277       Inst = TmpInst;
8278       return true;
8279     }
8280     break;
8281   }
8282   case ARM::t2SXTH:
8283   case ARM::t2SXTB:
8284   case ARM::t2UXTH:
8285   case ARM::t2UXTB: {
8286     // If we can use the 16-bit encoding and the user didn't explicitly
8287     // request the 32-bit variant, transform it here.
8288     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8289         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8290         Inst.getOperand(2).getImm() == 0 &&
8291         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8292          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8293       unsigned NewOpc;
8294       switch (Inst.getOpcode()) {
8295       default: llvm_unreachable("Illegal opcode!");
8296       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8297       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8298       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8299       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8300       }
8301       // The operands aren't the same for thumb1 (no rotate operand).
8302       MCInst TmpInst;
8303       TmpInst.setOpcode(NewOpc);
8304       TmpInst.addOperand(Inst.getOperand(0));
8305       TmpInst.addOperand(Inst.getOperand(1));
8306       TmpInst.addOperand(Inst.getOperand(3));
8307       TmpInst.addOperand(Inst.getOperand(4));
8308       Inst = TmpInst;
8309       return true;
8310     }
8311     break;
8312   }
8313   case ARM::MOVsi: {
8314     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8315     // rrx shifts and asr/lsr of #32 is encoded as 0
8316     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8317       return false;
8318     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8319       // Shifting by zero is accepted as a vanilla 'MOVr'
8320       MCInst TmpInst;
8321       TmpInst.setOpcode(ARM::MOVr);
8322       TmpInst.addOperand(Inst.getOperand(0));
8323       TmpInst.addOperand(Inst.getOperand(1));
8324       TmpInst.addOperand(Inst.getOperand(3));
8325       TmpInst.addOperand(Inst.getOperand(4));
8326       TmpInst.addOperand(Inst.getOperand(5));
8327       Inst = TmpInst;
8328       return true;
8329     }
8330     return false;
8331   }
8332   case ARM::ANDrsi:
8333   case ARM::ORRrsi:
8334   case ARM::EORrsi:
8335   case ARM::BICrsi:
8336   case ARM::SUBrsi:
8337   case ARM::ADDrsi: {
8338     unsigned newOpc;
8339     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8340     if (SOpc == ARM_AM::rrx) return false;
8341     switch (Inst.getOpcode()) {
8342     default: llvm_unreachable("unexpected opcode!");
8343     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8344     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8345     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8346     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8347     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8348     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8349     }
8350     // If the shift is by zero, use the non-shifted instruction definition.
8351     // The exception is for right shifts, where 0 == 32
8352     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8353         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8354       MCInst TmpInst;
8355       TmpInst.setOpcode(newOpc);
8356       TmpInst.addOperand(Inst.getOperand(0));
8357       TmpInst.addOperand(Inst.getOperand(1));
8358       TmpInst.addOperand(Inst.getOperand(2));
8359       TmpInst.addOperand(Inst.getOperand(4));
8360       TmpInst.addOperand(Inst.getOperand(5));
8361       TmpInst.addOperand(Inst.getOperand(6));
8362       Inst = TmpInst;
8363       return true;
8364     }
8365     return false;
8366   }
8367   case ARM::ITasm:
8368   case ARM::t2IT: {
8369     // The mask bits for all but the first condition are represented as
8370     // the low bit of the condition code value implies 't'. We currently
8371     // always have 1 implies 't', so XOR toggle the bits if the low bit
8372     // of the condition code is zero.
8373     MCOperand &MO = Inst.getOperand(1);
8374     unsigned Mask = MO.getImm();
8375     unsigned OrigMask = Mask;
8376     unsigned TZ = countTrailingZeros(Mask);
8377     if ((Inst.getOperand(0).getImm() & 1) == 0) {
8378       assert(Mask && TZ <= 3 && "illegal IT mask value!");
8379       Mask ^= (0xE << TZ) & 0xF;
8380     }
8381     MO.setImm(Mask);
8382 
8383     // Set up the IT block state according to the IT instruction we just
8384     // matched.
8385     assert(!inITBlock() && "nested IT blocks?!");
8386     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8387     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
8388     ITState.CurPosition = 0;
8389     ITState.FirstCond = true;
8390     break;
8391   }
8392   case ARM::t2LSLrr:
8393   case ARM::t2LSRrr:
8394   case ARM::t2ASRrr:
8395   case ARM::t2SBCrr:
8396   case ARM::t2RORrr:
8397   case ARM::t2BICrr:
8398   {
8399     // Assemblers should use the narrow encodings of these instructions when permissible.
8400     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8401          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8402         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8403         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8404          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8405         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8406          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8407              ".w"))) {
8408       unsigned NewOpc;
8409       switch (Inst.getOpcode()) {
8410         default: llvm_unreachable("unexpected opcode");
8411         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8412         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8413         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8414         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8415         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8416         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8417       }
8418       MCInst TmpInst;
8419       TmpInst.setOpcode(NewOpc);
8420       TmpInst.addOperand(Inst.getOperand(0));
8421       TmpInst.addOperand(Inst.getOperand(5));
8422       TmpInst.addOperand(Inst.getOperand(1));
8423       TmpInst.addOperand(Inst.getOperand(2));
8424       TmpInst.addOperand(Inst.getOperand(3));
8425       TmpInst.addOperand(Inst.getOperand(4));
8426       Inst = TmpInst;
8427       return true;
8428     }
8429     return false;
8430   }
8431   case ARM::t2ANDrr:
8432   case ARM::t2EORrr:
8433   case ARM::t2ADCrr:
8434   case ARM::t2ORRrr:
8435   {
8436     // Assemblers should use the narrow encodings of these instructions when permissible.
8437     // These instructions are special in that they are commutable, so shorter encodings
8438     // are available more often.
8439     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8440          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8441         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8442          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8443         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8444          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8445         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8446          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8447              ".w"))) {
8448       unsigned NewOpc;
8449       switch (Inst.getOpcode()) {
8450         default: llvm_unreachable("unexpected opcode");
8451         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8452         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8453         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8454         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8455       }
8456       MCInst TmpInst;
8457       TmpInst.setOpcode(NewOpc);
8458       TmpInst.addOperand(Inst.getOperand(0));
8459       TmpInst.addOperand(Inst.getOperand(5));
8460       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8461         TmpInst.addOperand(Inst.getOperand(1));
8462         TmpInst.addOperand(Inst.getOperand(2));
8463       } else {
8464         TmpInst.addOperand(Inst.getOperand(2));
8465         TmpInst.addOperand(Inst.getOperand(1));
8466       }
8467       TmpInst.addOperand(Inst.getOperand(3));
8468       TmpInst.addOperand(Inst.getOperand(4));
8469       Inst = TmpInst;
8470       return true;
8471     }
8472     return false;
8473   }
8474   }
8475   return false;
8476 }
8477 
8478 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8479   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8480   // suffix depending on whether they're in an IT block or not.
8481   unsigned Opc = Inst.getOpcode();
8482   const MCInstrDesc &MCID = MII.get(Opc);
8483   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8484     assert(MCID.hasOptionalDef() &&
8485            "optionally flag setting instruction missing optional def operand");
8486     assert(MCID.NumOperands == Inst.getNumOperands() &&
8487            "operand count mismatch!");
8488     // Find the optional-def operand (cc_out).
8489     unsigned OpNo;
8490     for (OpNo = 0;
8491          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8492          ++OpNo)
8493       ;
8494     // If we're parsing Thumb1, reject it completely.
8495     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8496       return Match_MnemonicFail;
8497     // If we're parsing Thumb2, which form is legal depends on whether we're
8498     // in an IT block.
8499     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8500         !inITBlock())
8501       return Match_RequiresITBlock;
8502     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8503         inITBlock())
8504       return Match_RequiresNotITBlock;
8505   }
8506   // Some high-register supporting Thumb1 encodings only allow both registers
8507   // to be from r0-r7 when in Thumb2.
8508   else if (Opc == ARM::tADDhirr && isThumbOne() && !hasV6MOps() &&
8509            isARMLowRegister(Inst.getOperand(1).getReg()) &&
8510            isARMLowRegister(Inst.getOperand(2).getReg()))
8511     return Match_RequiresThumb2;
8512   // Others only require ARMv6 or later.
8513   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
8514            isARMLowRegister(Inst.getOperand(0).getReg()) &&
8515            isARMLowRegister(Inst.getOperand(1).getReg()))
8516     return Match_RequiresV6;
8517   return Match_Success;
8518 }
8519 
8520 namespace llvm {
8521 template <> inline bool IsCPSRDead<MCInst>(MCInst *Instr) {
8522   return true; // In an assembly source, no need to second-guess
8523 }
8524 }
8525 
8526 static const char *getSubtargetFeatureName(uint64_t Val);
8527 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8528                                            OperandVector &Operands,
8529                                            MCStreamer &Out, uint64_t &ErrorInfo,
8530                                            bool MatchingInlineAsm) {
8531   MCInst Inst;
8532   unsigned MatchResult;
8533 
8534   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
8535                                      MatchingInlineAsm);
8536   switch (MatchResult) {
8537   case Match_Success:
8538     // Context sensitive operand constraints aren't handled by the matcher,
8539     // so check them here.
8540     if (validateInstruction(Inst, Operands)) {
8541       // Still progress the IT block, otherwise one wrong condition causes
8542       // nasty cascading errors.
8543       forwardITPosition();
8544       return true;
8545     }
8546 
8547     { // processInstruction() updates inITBlock state, we need to save it away
8548       bool wasInITBlock = inITBlock();
8549 
8550       // Some instructions need post-processing to, for example, tweak which
8551       // encoding is selected. Loop on it while changes happen so the
8552       // individual transformations can chain off each other. E.g.,
8553       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
8554       while (processInstruction(Inst, Operands, Out))
8555         ;
8556 
8557       // Only after the instruction is fully processed, we can validate it
8558       if (wasInITBlock && hasV8Ops() && isThumb() &&
8559           !isV8EligibleForIT(&Inst)) {
8560         Warning(IDLoc, "deprecated instruction in IT block");
8561       }
8562     }
8563 
8564     // Only move forward at the very end so that everything in validate
8565     // and process gets a consistent answer about whether we're in an IT
8566     // block.
8567     forwardITPosition();
8568 
8569     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
8570     // doesn't actually encode.
8571     if (Inst.getOpcode() == ARM::ITasm)
8572       return false;
8573 
8574     Inst.setLoc(IDLoc);
8575     Out.EmitInstruction(Inst, STI);
8576     return false;
8577   case Match_MissingFeature: {
8578     assert(ErrorInfo && "Unknown missing feature!");
8579     // Special case the error message for the very common case where only
8580     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
8581     std::string Msg = "instruction requires:";
8582     uint64_t Mask = 1;
8583     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
8584       if (ErrorInfo & Mask) {
8585         Msg += " ";
8586         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
8587       }
8588       Mask <<= 1;
8589     }
8590     return Error(IDLoc, Msg);
8591   }
8592   case Match_InvalidOperand: {
8593     SMLoc ErrorLoc = IDLoc;
8594     if (ErrorInfo != ~0ULL) {
8595       if (ErrorInfo >= Operands.size())
8596         return Error(IDLoc, "too few operands for instruction");
8597 
8598       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8599       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8600     }
8601 
8602     return Error(ErrorLoc, "invalid operand for instruction");
8603   }
8604   case Match_MnemonicFail:
8605     return Error(IDLoc, "invalid instruction",
8606                  ((ARMOperand &)*Operands[0]).getLocRange());
8607   case Match_RequiresNotITBlock:
8608     return Error(IDLoc, "flag setting instruction only valid outside IT block");
8609   case Match_RequiresITBlock:
8610     return Error(IDLoc, "instruction only valid inside IT block");
8611   case Match_RequiresV6:
8612     return Error(IDLoc, "instruction variant requires ARMv6 or later");
8613   case Match_RequiresThumb2:
8614     return Error(IDLoc, "instruction variant requires Thumb2");
8615   case Match_ImmRange0_15: {
8616     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8617     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8618     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
8619   }
8620   case Match_ImmRange0_239: {
8621     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8622     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8623     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
8624   }
8625   case Match_AlignedMemoryRequiresNone:
8626   case Match_DupAlignedMemoryRequiresNone:
8627   case Match_AlignedMemoryRequires16:
8628   case Match_DupAlignedMemoryRequires16:
8629   case Match_AlignedMemoryRequires32:
8630   case Match_DupAlignedMemoryRequires32:
8631   case Match_AlignedMemoryRequires64:
8632   case Match_DupAlignedMemoryRequires64:
8633   case Match_AlignedMemoryRequires64or128:
8634   case Match_DupAlignedMemoryRequires64or128:
8635   case Match_AlignedMemoryRequires64or128or256:
8636   {
8637     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
8638     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8639     switch (MatchResult) {
8640       default:
8641         llvm_unreachable("Missing Match_Aligned type");
8642       case Match_AlignedMemoryRequiresNone:
8643       case Match_DupAlignedMemoryRequiresNone:
8644         return Error(ErrorLoc, "alignment must be omitted");
8645       case Match_AlignedMemoryRequires16:
8646       case Match_DupAlignedMemoryRequires16:
8647         return Error(ErrorLoc, "alignment must be 16 or omitted");
8648       case Match_AlignedMemoryRequires32:
8649       case Match_DupAlignedMemoryRequires32:
8650         return Error(ErrorLoc, "alignment must be 32 or omitted");
8651       case Match_AlignedMemoryRequires64:
8652       case Match_DupAlignedMemoryRequires64:
8653         return Error(ErrorLoc, "alignment must be 64 or omitted");
8654       case Match_AlignedMemoryRequires64or128:
8655       case Match_DupAlignedMemoryRequires64or128:
8656         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
8657       case Match_AlignedMemoryRequires64or128or256:
8658         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
8659     }
8660   }
8661   }
8662 
8663   llvm_unreachable("Implement any new match types added!");
8664 }
8665 
8666 /// parseDirective parses the arm specific directives
8667 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
8668   Triple::ObjectFormatType Format =
8669       getContext().getObjectFileInfo()->getTargetTriple().getObjectFormat();
8670   bool IsMachO = Format == Triple::MachO;
8671   bool IsCOFF = Format == Triple::COFF;
8672 
8673   StringRef IDVal = DirectiveID.getIdentifier();
8674   if (IDVal == ".word")
8675     return parseLiteralValues(4, DirectiveID.getLoc());
8676   else if (IDVal == ".short" || IDVal == ".hword")
8677     return parseLiteralValues(2, DirectiveID.getLoc());
8678   else if (IDVal == ".thumb")
8679     return parseDirectiveThumb(DirectiveID.getLoc());
8680   else if (IDVal == ".arm")
8681     return parseDirectiveARM(DirectiveID.getLoc());
8682   else if (IDVal == ".thumb_func")
8683     return parseDirectiveThumbFunc(DirectiveID.getLoc());
8684   else if (IDVal == ".code")
8685     return parseDirectiveCode(DirectiveID.getLoc());
8686   else if (IDVal == ".syntax")
8687     return parseDirectiveSyntax(DirectiveID.getLoc());
8688   else if (IDVal == ".unreq")
8689     return parseDirectiveUnreq(DirectiveID.getLoc());
8690   else if (IDVal == ".fnend")
8691     return parseDirectiveFnEnd(DirectiveID.getLoc());
8692   else if (IDVal == ".cantunwind")
8693     return parseDirectiveCantUnwind(DirectiveID.getLoc());
8694   else if (IDVal == ".personality")
8695     return parseDirectivePersonality(DirectiveID.getLoc());
8696   else if (IDVal == ".handlerdata")
8697     return parseDirectiveHandlerData(DirectiveID.getLoc());
8698   else if (IDVal == ".setfp")
8699     return parseDirectiveSetFP(DirectiveID.getLoc());
8700   else if (IDVal == ".pad")
8701     return parseDirectivePad(DirectiveID.getLoc());
8702   else if (IDVal == ".save")
8703     return parseDirectiveRegSave(DirectiveID.getLoc(), false);
8704   else if (IDVal == ".vsave")
8705     return parseDirectiveRegSave(DirectiveID.getLoc(), true);
8706   else if (IDVal == ".ltorg" || IDVal == ".pool")
8707     return parseDirectiveLtorg(DirectiveID.getLoc());
8708   else if (IDVal == ".even")
8709     return parseDirectiveEven(DirectiveID.getLoc());
8710   else if (IDVal == ".personalityindex")
8711     return parseDirectivePersonalityIndex(DirectiveID.getLoc());
8712   else if (IDVal == ".unwind_raw")
8713     return parseDirectiveUnwindRaw(DirectiveID.getLoc());
8714   else if (IDVal == ".movsp")
8715     return parseDirectiveMovSP(DirectiveID.getLoc());
8716   else if (IDVal == ".arch_extension")
8717     return parseDirectiveArchExtension(DirectiveID.getLoc());
8718   else if (IDVal == ".align")
8719     return parseDirectiveAlign(DirectiveID.getLoc());
8720   else if (IDVal == ".thumb_set")
8721     return parseDirectiveThumbSet(DirectiveID.getLoc());
8722 
8723   if (!IsMachO && !IsCOFF) {
8724     if (IDVal == ".arch")
8725       return parseDirectiveArch(DirectiveID.getLoc());
8726     else if (IDVal == ".cpu")
8727       return parseDirectiveCPU(DirectiveID.getLoc());
8728     else if (IDVal == ".eabi_attribute")
8729       return parseDirectiveEabiAttr(DirectiveID.getLoc());
8730     else if (IDVal == ".fpu")
8731       return parseDirectiveFPU(DirectiveID.getLoc());
8732     else if (IDVal == ".fnstart")
8733       return parseDirectiveFnStart(DirectiveID.getLoc());
8734     else if (IDVal == ".inst")
8735       return parseDirectiveInst(DirectiveID.getLoc());
8736     else if (IDVal == ".inst.n")
8737       return parseDirectiveInst(DirectiveID.getLoc(), 'n');
8738     else if (IDVal == ".inst.w")
8739       return parseDirectiveInst(DirectiveID.getLoc(), 'w');
8740     else if (IDVal == ".object_arch")
8741       return parseDirectiveObjectArch(DirectiveID.getLoc());
8742     else if (IDVal == ".tlsdescseq")
8743       return parseDirectiveTLSDescSeq(DirectiveID.getLoc());
8744   }
8745 
8746   return true;
8747 }
8748 
8749 /// parseLiteralValues
8750 ///  ::= .hword expression [, expression]*
8751 ///  ::= .short expression [, expression]*
8752 ///  ::= .word expression [, expression]*
8753 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
8754   MCAsmParser &Parser = getParser();
8755   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8756     for (;;) {
8757       const MCExpr *Value;
8758       if (getParser().parseExpression(Value)) {
8759         Parser.eatToEndOfStatement();
8760         return false;
8761       }
8762 
8763       getParser().getStreamer().EmitValue(Value, Size);
8764 
8765       if (getLexer().is(AsmToken::EndOfStatement))
8766         break;
8767 
8768       // FIXME: Improve diagnostic.
8769       if (getLexer().isNot(AsmToken::Comma)) {
8770         Error(L, "unexpected token in directive");
8771         return false;
8772       }
8773       Parser.Lex();
8774     }
8775   }
8776 
8777   Parser.Lex();
8778   return false;
8779 }
8780 
8781 /// parseDirectiveThumb
8782 ///  ::= .thumb
8783 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
8784   MCAsmParser &Parser = getParser();
8785   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8786     Error(L, "unexpected token in directive");
8787     return false;
8788   }
8789   Parser.Lex();
8790 
8791   if (!hasThumb()) {
8792     Error(L, "target does not support Thumb mode");
8793     return false;
8794   }
8795 
8796   if (!isThumb())
8797     SwitchMode();
8798 
8799   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8800   return false;
8801 }
8802 
8803 /// parseDirectiveARM
8804 ///  ::= .arm
8805 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
8806   MCAsmParser &Parser = getParser();
8807   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8808     Error(L, "unexpected token in directive");
8809     return false;
8810   }
8811   Parser.Lex();
8812 
8813   if (!hasARM()) {
8814     Error(L, "target does not support ARM mode");
8815     return false;
8816   }
8817 
8818   if (isThumb())
8819     SwitchMode();
8820 
8821   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8822   return false;
8823 }
8824 
8825 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
8826   if (NextSymbolIsThumb) {
8827     getParser().getStreamer().EmitThumbFunc(Symbol);
8828     NextSymbolIsThumb = false;
8829   }
8830 }
8831 
8832 /// parseDirectiveThumbFunc
8833 ///  ::= .thumbfunc symbol_name
8834 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
8835   MCAsmParser &Parser = getParser();
8836   Triple::ObjectFormatType Format =
8837       getContext().getObjectFileInfo()->getTargetTriple().getObjectFormat();
8838   bool IsMachO = Format == Triple::MachO;
8839 
8840   // Darwin asm has (optionally) function name after .thumb_func direction
8841   // ELF doesn't
8842   if (IsMachO) {
8843     const AsmToken &Tok = Parser.getTok();
8844     if (Tok.isNot(AsmToken::EndOfStatement)) {
8845       if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String)) {
8846         Error(L, "unexpected token in .thumb_func directive");
8847         return false;
8848       }
8849 
8850       MCSymbol *Func =
8851           getParser().getContext().getOrCreateSymbol(Tok.getIdentifier());
8852       getParser().getStreamer().EmitThumbFunc(Func);
8853       Parser.Lex(); // Consume the identifier token.
8854       return false;
8855     }
8856   }
8857 
8858   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8859     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8860     Parser.eatToEndOfStatement();
8861     return false;
8862   }
8863 
8864   NextSymbolIsThumb = true;
8865   return false;
8866 }
8867 
8868 /// parseDirectiveSyntax
8869 ///  ::= .syntax unified | divided
8870 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
8871   MCAsmParser &Parser = getParser();
8872   const AsmToken &Tok = Parser.getTok();
8873   if (Tok.isNot(AsmToken::Identifier)) {
8874     Error(L, "unexpected token in .syntax directive");
8875     return false;
8876   }
8877 
8878   StringRef Mode = Tok.getString();
8879   if (Mode == "unified" || Mode == "UNIFIED") {
8880     Parser.Lex();
8881   } else if (Mode == "divided" || Mode == "DIVIDED") {
8882     Error(L, "'.syntax divided' arm asssembly not supported");
8883     return false;
8884   } else {
8885     Error(L, "unrecognized syntax mode in .syntax directive");
8886     return false;
8887   }
8888 
8889   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8890     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8891     return false;
8892   }
8893   Parser.Lex();
8894 
8895   // TODO tell the MC streamer the mode
8896   // getParser().getStreamer().Emit???();
8897   return false;
8898 }
8899 
8900 /// parseDirectiveCode
8901 ///  ::= .code 16 | 32
8902 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
8903   MCAsmParser &Parser = getParser();
8904   const AsmToken &Tok = Parser.getTok();
8905   if (Tok.isNot(AsmToken::Integer)) {
8906     Error(L, "unexpected token in .code directive");
8907     return false;
8908   }
8909   int64_t Val = Parser.getTok().getIntVal();
8910   if (Val != 16 && Val != 32) {
8911     Error(L, "invalid operand to .code directive");
8912     return false;
8913   }
8914   Parser.Lex();
8915 
8916   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8917     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8918     return false;
8919   }
8920   Parser.Lex();
8921 
8922   if (Val == 16) {
8923     if (!hasThumb()) {
8924       Error(L, "target does not support Thumb mode");
8925       return false;
8926     }
8927 
8928     if (!isThumb())
8929       SwitchMode();
8930     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8931   } else {
8932     if (!hasARM()) {
8933       Error(L, "target does not support ARM mode");
8934       return false;
8935     }
8936 
8937     if (isThumb())
8938       SwitchMode();
8939     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8940   }
8941 
8942   return false;
8943 }
8944 
8945 /// parseDirectiveReq
8946 ///  ::= name .req registername
8947 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
8948   MCAsmParser &Parser = getParser();
8949   Parser.Lex(); // Eat the '.req' token.
8950   unsigned Reg;
8951   SMLoc SRegLoc, ERegLoc;
8952   if (ParseRegister(Reg, SRegLoc, ERegLoc)) {
8953     Parser.eatToEndOfStatement();
8954     Error(SRegLoc, "register name expected");
8955     return false;
8956   }
8957 
8958   // Shouldn't be anything else.
8959   if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
8960     Parser.eatToEndOfStatement();
8961     Error(Parser.getTok().getLoc(), "unexpected input in .req directive.");
8962     return false;
8963   }
8964 
8965   Parser.Lex(); // Consume the EndOfStatement
8966 
8967   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg) {
8968     Error(SRegLoc, "redefinition of '" + Name + "' does not match original.");
8969     return false;
8970   }
8971 
8972   return false;
8973 }
8974 
8975 /// parseDirectiveUneq
8976 ///  ::= .unreq registername
8977 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
8978   MCAsmParser &Parser = getParser();
8979   if (Parser.getTok().isNot(AsmToken::Identifier)) {
8980     Parser.eatToEndOfStatement();
8981     Error(L, "unexpected input in .unreq directive.");
8982     return false;
8983   }
8984   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
8985   Parser.Lex(); // Eat the identifier.
8986   return false;
8987 }
8988 
8989 /// parseDirectiveArch
8990 ///  ::= .arch token
8991 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
8992   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
8993 
8994   unsigned ID = ARMTargetParser::parseArch(Arch);
8995 
8996   if (ID == ARM::AK_INVALID) {
8997     Error(L, "Unknown arch name");
8998     return false;
8999   }
9000 
9001   getTargetStreamer().emitArch(ID);
9002   return false;
9003 }
9004 
9005 /// parseDirectiveEabiAttr
9006 ///  ::= .eabi_attribute int, int [, "str"]
9007 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9008 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9009   MCAsmParser &Parser = getParser();
9010   int64_t Tag;
9011   SMLoc TagLoc;
9012   TagLoc = Parser.getTok().getLoc();
9013   if (Parser.getTok().is(AsmToken::Identifier)) {
9014     StringRef Name = Parser.getTok().getIdentifier();
9015     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9016     if (Tag == -1) {
9017       Error(TagLoc, "attribute name not recognised: " + Name);
9018       Parser.eatToEndOfStatement();
9019       return false;
9020     }
9021     Parser.Lex();
9022   } else {
9023     const MCExpr *AttrExpr;
9024 
9025     TagLoc = Parser.getTok().getLoc();
9026     if (Parser.parseExpression(AttrExpr)) {
9027       Parser.eatToEndOfStatement();
9028       return false;
9029     }
9030 
9031     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9032     if (!CE) {
9033       Error(TagLoc, "expected numeric constant");
9034       Parser.eatToEndOfStatement();
9035       return false;
9036     }
9037 
9038     Tag = CE->getValue();
9039   }
9040 
9041   if (Parser.getTok().isNot(AsmToken::Comma)) {
9042     Error(Parser.getTok().getLoc(), "comma expected");
9043     Parser.eatToEndOfStatement();
9044     return false;
9045   }
9046   Parser.Lex(); // skip comma
9047 
9048   StringRef StringValue = "";
9049   bool IsStringValue = false;
9050 
9051   int64_t IntegerValue = 0;
9052   bool IsIntegerValue = false;
9053 
9054   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9055     IsStringValue = true;
9056   else if (Tag == ARMBuildAttrs::compatibility) {
9057     IsStringValue = true;
9058     IsIntegerValue = true;
9059   } else if (Tag < 32 || Tag % 2 == 0)
9060     IsIntegerValue = true;
9061   else if (Tag % 2 == 1)
9062     IsStringValue = true;
9063   else
9064     llvm_unreachable("invalid tag type");
9065 
9066   if (IsIntegerValue) {
9067     const MCExpr *ValueExpr;
9068     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9069     if (Parser.parseExpression(ValueExpr)) {
9070       Parser.eatToEndOfStatement();
9071       return false;
9072     }
9073 
9074     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9075     if (!CE) {
9076       Error(ValueExprLoc, "expected numeric constant");
9077       Parser.eatToEndOfStatement();
9078       return false;
9079     }
9080 
9081     IntegerValue = CE->getValue();
9082   }
9083 
9084   if (Tag == ARMBuildAttrs::compatibility) {
9085     if (Parser.getTok().isNot(AsmToken::Comma))
9086       IsStringValue = false;
9087     if (Parser.getTok().isNot(AsmToken::Comma)) {
9088       Error(Parser.getTok().getLoc(), "comma expected");
9089       Parser.eatToEndOfStatement();
9090       return false;
9091     } else {
9092        Parser.Lex();
9093     }
9094   }
9095 
9096   if (IsStringValue) {
9097     if (Parser.getTok().isNot(AsmToken::String)) {
9098       Error(Parser.getTok().getLoc(), "bad string constant");
9099       Parser.eatToEndOfStatement();
9100       return false;
9101     }
9102 
9103     StringValue = Parser.getTok().getStringContents();
9104     Parser.Lex();
9105   }
9106 
9107   if (IsIntegerValue && IsStringValue) {
9108     assert(Tag == ARMBuildAttrs::compatibility);
9109     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9110   } else if (IsIntegerValue)
9111     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9112   else if (IsStringValue)
9113     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9114   return false;
9115 }
9116 
9117 /// parseDirectiveCPU
9118 ///  ::= .cpu str
9119 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9120   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9121   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9122 
9123   // FIXME: This is using table-gen data, but should be moved to
9124   // ARMTargetParser once that is table-gen'd.
9125   if (!STI.isCPUStringValid(CPU)) {
9126     Error(L, "Unknown CPU name");
9127     return false;
9128   }
9129 
9130   STI.setDefaultFeatures(CPU);
9131   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9132 
9133   return false;
9134 }
9135 /// parseDirectiveFPU
9136 ///  ::= .fpu str
9137 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9138   SMLoc FPUNameLoc = getTok().getLoc();
9139   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9140 
9141   unsigned ID = ARMTargetParser::parseFPU(FPU);
9142   std::vector<const char *> Features;
9143   if (!ARMTargetParser::getFPUFeatures(ID, Features)) {
9144     Error(FPUNameLoc, "Unknown FPU name");
9145     return false;
9146   }
9147 
9148   for (auto Feature : Features)
9149     STI.ApplyFeatureFlag(Feature);
9150   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9151 
9152   getTargetStreamer().emitFPU(ID);
9153   return false;
9154 }
9155 
9156 /// parseDirectiveFnStart
9157 ///  ::= .fnstart
9158 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9159   if (UC.hasFnStart()) {
9160     Error(L, ".fnstart starts before the end of previous one");
9161     UC.emitFnStartLocNotes();
9162     return false;
9163   }
9164 
9165   // Reset the unwind directives parser state
9166   UC.reset();
9167 
9168   getTargetStreamer().emitFnStart();
9169 
9170   UC.recordFnStart(L);
9171   return false;
9172 }
9173 
9174 /// parseDirectiveFnEnd
9175 ///  ::= .fnend
9176 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9177   // Check the ordering of unwind directives
9178   if (!UC.hasFnStart()) {
9179     Error(L, ".fnstart must precede .fnend directive");
9180     return false;
9181   }
9182 
9183   // Reset the unwind directives parser state
9184   getTargetStreamer().emitFnEnd();
9185 
9186   UC.reset();
9187   return false;
9188 }
9189 
9190 /// parseDirectiveCantUnwind
9191 ///  ::= .cantunwind
9192 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9193   UC.recordCantUnwind(L);
9194 
9195   // Check the ordering of unwind directives
9196   if (!UC.hasFnStart()) {
9197     Error(L, ".fnstart must precede .cantunwind directive");
9198     return false;
9199   }
9200   if (UC.hasHandlerData()) {
9201     Error(L, ".cantunwind can't be used with .handlerdata directive");
9202     UC.emitHandlerDataLocNotes();
9203     return false;
9204   }
9205   if (UC.hasPersonality()) {
9206     Error(L, ".cantunwind can't be used with .personality directive");
9207     UC.emitPersonalityLocNotes();
9208     return false;
9209   }
9210 
9211   getTargetStreamer().emitCantUnwind();
9212   return false;
9213 }
9214 
9215 /// parseDirectivePersonality
9216 ///  ::= .personality name
9217 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9218   MCAsmParser &Parser = getParser();
9219   bool HasExistingPersonality = UC.hasPersonality();
9220 
9221   UC.recordPersonality(L);
9222 
9223   // Check the ordering of unwind directives
9224   if (!UC.hasFnStart()) {
9225     Error(L, ".fnstart must precede .personality directive");
9226     return false;
9227   }
9228   if (UC.cantUnwind()) {
9229     Error(L, ".personality can't be used with .cantunwind directive");
9230     UC.emitCantUnwindLocNotes();
9231     return false;
9232   }
9233   if (UC.hasHandlerData()) {
9234     Error(L, ".personality must precede .handlerdata directive");
9235     UC.emitHandlerDataLocNotes();
9236     return false;
9237   }
9238   if (HasExistingPersonality) {
9239     Parser.eatToEndOfStatement();
9240     Error(L, "multiple personality directives");
9241     UC.emitPersonalityLocNotes();
9242     return false;
9243   }
9244 
9245   // Parse the name of the personality routine
9246   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9247     Parser.eatToEndOfStatement();
9248     Error(L, "unexpected input in .personality directive.");
9249     return false;
9250   }
9251   StringRef Name(Parser.getTok().getIdentifier());
9252   Parser.Lex();
9253 
9254   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9255   getTargetStreamer().emitPersonality(PR);
9256   return false;
9257 }
9258 
9259 /// parseDirectiveHandlerData
9260 ///  ::= .handlerdata
9261 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9262   UC.recordHandlerData(L);
9263 
9264   // Check the ordering of unwind directives
9265   if (!UC.hasFnStart()) {
9266     Error(L, ".fnstart must precede .personality directive");
9267     return false;
9268   }
9269   if (UC.cantUnwind()) {
9270     Error(L, ".handlerdata can't be used with .cantunwind directive");
9271     UC.emitCantUnwindLocNotes();
9272     return false;
9273   }
9274 
9275   getTargetStreamer().emitHandlerData();
9276   return false;
9277 }
9278 
9279 /// parseDirectiveSetFP
9280 ///  ::= .setfp fpreg, spreg [, offset]
9281 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9282   MCAsmParser &Parser = getParser();
9283   // Check the ordering of unwind directives
9284   if (!UC.hasFnStart()) {
9285     Error(L, ".fnstart must precede .setfp directive");
9286     return false;
9287   }
9288   if (UC.hasHandlerData()) {
9289     Error(L, ".setfp must precede .handlerdata directive");
9290     return false;
9291   }
9292 
9293   // Parse fpreg
9294   SMLoc FPRegLoc = Parser.getTok().getLoc();
9295   int FPReg = tryParseRegister();
9296   if (FPReg == -1) {
9297     Error(FPRegLoc, "frame pointer register expected");
9298     return false;
9299   }
9300 
9301   // Consume comma
9302   if (Parser.getTok().isNot(AsmToken::Comma)) {
9303     Error(Parser.getTok().getLoc(), "comma expected");
9304     return false;
9305   }
9306   Parser.Lex(); // skip comma
9307 
9308   // Parse spreg
9309   SMLoc SPRegLoc = Parser.getTok().getLoc();
9310   int SPReg = tryParseRegister();
9311   if (SPReg == -1) {
9312     Error(SPRegLoc, "stack pointer register expected");
9313     return false;
9314   }
9315 
9316   if (SPReg != ARM::SP && SPReg != UC.getFPReg()) {
9317     Error(SPRegLoc, "register should be either $sp or the latest fp register");
9318     return false;
9319   }
9320 
9321   // Update the frame pointer register
9322   UC.saveFPReg(FPReg);
9323 
9324   // Parse offset
9325   int64_t Offset = 0;
9326   if (Parser.getTok().is(AsmToken::Comma)) {
9327     Parser.Lex(); // skip comma
9328 
9329     if (Parser.getTok().isNot(AsmToken::Hash) &&
9330         Parser.getTok().isNot(AsmToken::Dollar)) {
9331       Error(Parser.getTok().getLoc(), "'#' expected");
9332       return false;
9333     }
9334     Parser.Lex(); // skip hash token.
9335 
9336     const MCExpr *OffsetExpr;
9337     SMLoc ExLoc = Parser.getTok().getLoc();
9338     SMLoc EndLoc;
9339     if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9340       Error(ExLoc, "malformed setfp offset");
9341       return false;
9342     }
9343     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9344     if (!CE) {
9345       Error(ExLoc, "setfp offset must be an immediate");
9346       return false;
9347     }
9348 
9349     Offset = CE->getValue();
9350   }
9351 
9352   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9353                                 static_cast<unsigned>(SPReg), Offset);
9354   return false;
9355 }
9356 
9357 /// parseDirective
9358 ///  ::= .pad offset
9359 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9360   MCAsmParser &Parser = getParser();
9361   // Check the ordering of unwind directives
9362   if (!UC.hasFnStart()) {
9363     Error(L, ".fnstart must precede .pad directive");
9364     return false;
9365   }
9366   if (UC.hasHandlerData()) {
9367     Error(L, ".pad must precede .handlerdata directive");
9368     return false;
9369   }
9370 
9371   // Parse the offset
9372   if (Parser.getTok().isNot(AsmToken::Hash) &&
9373       Parser.getTok().isNot(AsmToken::Dollar)) {
9374     Error(Parser.getTok().getLoc(), "'#' expected");
9375     return false;
9376   }
9377   Parser.Lex(); // skip hash token.
9378 
9379   const MCExpr *OffsetExpr;
9380   SMLoc ExLoc = Parser.getTok().getLoc();
9381   SMLoc EndLoc;
9382   if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9383     Error(ExLoc, "malformed pad offset");
9384     return false;
9385   }
9386   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9387   if (!CE) {
9388     Error(ExLoc, "pad offset must be an immediate");
9389     return false;
9390   }
9391 
9392   getTargetStreamer().emitPad(CE->getValue());
9393   return false;
9394 }
9395 
9396 /// parseDirectiveRegSave
9397 ///  ::= .save  { registers }
9398 ///  ::= .vsave { registers }
9399 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9400   // Check the ordering of unwind directives
9401   if (!UC.hasFnStart()) {
9402     Error(L, ".fnstart must precede .save or .vsave directives");
9403     return false;
9404   }
9405   if (UC.hasHandlerData()) {
9406     Error(L, ".save or .vsave must precede .handlerdata directive");
9407     return false;
9408   }
9409 
9410   // RAII object to make sure parsed operands are deleted.
9411   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9412 
9413   // Parse the register list
9414   if (parseRegisterList(Operands))
9415     return false;
9416   ARMOperand &Op = (ARMOperand &)*Operands[0];
9417   if (!IsVector && !Op.isRegList()) {
9418     Error(L, ".save expects GPR registers");
9419     return false;
9420   }
9421   if (IsVector && !Op.isDPRRegList()) {
9422     Error(L, ".vsave expects DPR registers");
9423     return false;
9424   }
9425 
9426   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9427   return false;
9428 }
9429 
9430 /// parseDirectiveInst
9431 ///  ::= .inst opcode [, ...]
9432 ///  ::= .inst.n opcode [, ...]
9433 ///  ::= .inst.w opcode [, ...]
9434 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9435   MCAsmParser &Parser = getParser();
9436   int Width;
9437 
9438   if (isThumb()) {
9439     switch (Suffix) {
9440     case 'n':
9441       Width = 2;
9442       break;
9443     case 'w':
9444       Width = 4;
9445       break;
9446     default:
9447       Parser.eatToEndOfStatement();
9448       Error(Loc, "cannot determine Thumb instruction size, "
9449                  "use inst.n/inst.w instead");
9450       return false;
9451     }
9452   } else {
9453     if (Suffix) {
9454       Parser.eatToEndOfStatement();
9455       Error(Loc, "width suffixes are invalid in ARM mode");
9456       return false;
9457     }
9458     Width = 4;
9459   }
9460 
9461   if (getLexer().is(AsmToken::EndOfStatement)) {
9462     Parser.eatToEndOfStatement();
9463     Error(Loc, "expected expression following directive");
9464     return false;
9465   }
9466 
9467   for (;;) {
9468     const MCExpr *Expr;
9469 
9470     if (getParser().parseExpression(Expr)) {
9471       Error(Loc, "expected expression");
9472       return false;
9473     }
9474 
9475     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9476     if (!Value) {
9477       Error(Loc, "expected constant expression");
9478       return false;
9479     }
9480 
9481     switch (Width) {
9482     case 2:
9483       if (Value->getValue() > 0xffff) {
9484         Error(Loc, "inst.n operand is too big, use inst.w instead");
9485         return false;
9486       }
9487       break;
9488     case 4:
9489       if (Value->getValue() > 0xffffffff) {
9490         Error(Loc,
9491               StringRef(Suffix ? "inst.w" : "inst") + " operand is too big");
9492         return false;
9493       }
9494       break;
9495     default:
9496       llvm_unreachable("only supported widths are 2 and 4");
9497     }
9498 
9499     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9500 
9501     if (getLexer().is(AsmToken::EndOfStatement))
9502       break;
9503 
9504     if (getLexer().isNot(AsmToken::Comma)) {
9505       Error(Loc, "unexpected token in directive");
9506       return false;
9507     }
9508 
9509     Parser.Lex();
9510   }
9511 
9512   Parser.Lex();
9513   return false;
9514 }
9515 
9516 /// parseDirectiveLtorg
9517 ///  ::= .ltorg | .pool
9518 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9519   getTargetStreamer().emitCurrentConstantPool();
9520   return false;
9521 }
9522 
9523 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9524   const MCSection *Section = getStreamer().getCurrentSection().first;
9525 
9526   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9527     TokError("unexpected token in directive");
9528     return false;
9529   }
9530 
9531   if (!Section) {
9532     getStreamer().InitSections(false);
9533     Section = getStreamer().getCurrentSection().first;
9534   }
9535 
9536   assert(Section && "must have section to emit alignment");
9537   if (Section->UseCodeAlign())
9538     getStreamer().EmitCodeAlignment(2);
9539   else
9540     getStreamer().EmitValueToAlignment(2);
9541 
9542   return false;
9543 }
9544 
9545 /// parseDirectivePersonalityIndex
9546 ///   ::= .personalityindex index
9547 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9548   MCAsmParser &Parser = getParser();
9549   bool HasExistingPersonality = UC.hasPersonality();
9550 
9551   UC.recordPersonalityIndex(L);
9552 
9553   if (!UC.hasFnStart()) {
9554     Parser.eatToEndOfStatement();
9555     Error(L, ".fnstart must precede .personalityindex directive");
9556     return false;
9557   }
9558   if (UC.cantUnwind()) {
9559     Parser.eatToEndOfStatement();
9560     Error(L, ".personalityindex cannot be used with .cantunwind");
9561     UC.emitCantUnwindLocNotes();
9562     return false;
9563   }
9564   if (UC.hasHandlerData()) {
9565     Parser.eatToEndOfStatement();
9566     Error(L, ".personalityindex must precede .handlerdata directive");
9567     UC.emitHandlerDataLocNotes();
9568     return false;
9569   }
9570   if (HasExistingPersonality) {
9571     Parser.eatToEndOfStatement();
9572     Error(L, "multiple personality directives");
9573     UC.emitPersonalityLocNotes();
9574     return false;
9575   }
9576 
9577   const MCExpr *IndexExpression;
9578   SMLoc IndexLoc = Parser.getTok().getLoc();
9579   if (Parser.parseExpression(IndexExpression)) {
9580     Parser.eatToEndOfStatement();
9581     return false;
9582   }
9583 
9584   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9585   if (!CE) {
9586     Parser.eatToEndOfStatement();
9587     Error(IndexLoc, "index must be a constant number");
9588     return false;
9589   }
9590   if (CE->getValue() < 0 ||
9591       CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX) {
9592     Parser.eatToEndOfStatement();
9593     Error(IndexLoc, "personality routine index should be in range [0-3]");
9594     return false;
9595   }
9596 
9597   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9598   return false;
9599 }
9600 
9601 /// parseDirectiveUnwindRaw
9602 ///   ::= .unwind_raw offset, opcode [, opcode...]
9603 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9604   MCAsmParser &Parser = getParser();
9605   if (!UC.hasFnStart()) {
9606     Parser.eatToEndOfStatement();
9607     Error(L, ".fnstart must precede .unwind_raw directives");
9608     return false;
9609   }
9610 
9611   int64_t StackOffset;
9612 
9613   const MCExpr *OffsetExpr;
9614   SMLoc OffsetLoc = getLexer().getLoc();
9615   if (getLexer().is(AsmToken::EndOfStatement) ||
9616       getParser().parseExpression(OffsetExpr)) {
9617     Error(OffsetLoc, "expected expression");
9618     Parser.eatToEndOfStatement();
9619     return false;
9620   }
9621 
9622   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9623   if (!CE) {
9624     Error(OffsetLoc, "offset must be a constant");
9625     Parser.eatToEndOfStatement();
9626     return false;
9627   }
9628 
9629   StackOffset = CE->getValue();
9630 
9631   if (getLexer().isNot(AsmToken::Comma)) {
9632     Error(getLexer().getLoc(), "expected comma");
9633     Parser.eatToEndOfStatement();
9634     return false;
9635   }
9636   Parser.Lex();
9637 
9638   SmallVector<uint8_t, 16> Opcodes;
9639   for (;;) {
9640     const MCExpr *OE;
9641 
9642     SMLoc OpcodeLoc = getLexer().getLoc();
9643     if (getLexer().is(AsmToken::EndOfStatement) || Parser.parseExpression(OE)) {
9644       Error(OpcodeLoc, "expected opcode expression");
9645       Parser.eatToEndOfStatement();
9646       return false;
9647     }
9648 
9649     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9650     if (!OC) {
9651       Error(OpcodeLoc, "opcode value must be a constant");
9652       Parser.eatToEndOfStatement();
9653       return false;
9654     }
9655 
9656     const int64_t Opcode = OC->getValue();
9657     if (Opcode & ~0xff) {
9658       Error(OpcodeLoc, "invalid opcode");
9659       Parser.eatToEndOfStatement();
9660       return false;
9661     }
9662 
9663     Opcodes.push_back(uint8_t(Opcode));
9664 
9665     if (getLexer().is(AsmToken::EndOfStatement))
9666       break;
9667 
9668     if (getLexer().isNot(AsmToken::Comma)) {
9669       Error(getLexer().getLoc(), "unexpected token in directive");
9670       Parser.eatToEndOfStatement();
9671       return false;
9672     }
9673 
9674     Parser.Lex();
9675   }
9676 
9677   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9678 
9679   Parser.Lex();
9680   return false;
9681 }
9682 
9683 /// parseDirectiveTLSDescSeq
9684 ///   ::= .tlsdescseq tls-variable
9685 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9686   MCAsmParser &Parser = getParser();
9687 
9688   if (getLexer().isNot(AsmToken::Identifier)) {
9689     TokError("expected variable after '.tlsdescseq' directive");
9690     Parser.eatToEndOfStatement();
9691     return false;
9692   }
9693 
9694   const MCSymbolRefExpr *SRE =
9695     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
9696                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9697   Lex();
9698 
9699   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9700     Error(Parser.getTok().getLoc(), "unexpected token");
9701     Parser.eatToEndOfStatement();
9702     return false;
9703   }
9704 
9705   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9706   return false;
9707 }
9708 
9709 /// parseDirectiveMovSP
9710 ///  ::= .movsp reg [, #offset]
9711 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
9712   MCAsmParser &Parser = getParser();
9713   if (!UC.hasFnStart()) {
9714     Parser.eatToEndOfStatement();
9715     Error(L, ".fnstart must precede .movsp directives");
9716     return false;
9717   }
9718   if (UC.getFPReg() != ARM::SP) {
9719     Parser.eatToEndOfStatement();
9720     Error(L, "unexpected .movsp directive");
9721     return false;
9722   }
9723 
9724   SMLoc SPRegLoc = Parser.getTok().getLoc();
9725   int SPReg = tryParseRegister();
9726   if (SPReg == -1) {
9727     Parser.eatToEndOfStatement();
9728     Error(SPRegLoc, "register expected");
9729     return false;
9730   }
9731 
9732   if (SPReg == ARM::SP || SPReg == ARM::PC) {
9733     Parser.eatToEndOfStatement();
9734     Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
9735     return false;
9736   }
9737 
9738   int64_t Offset = 0;
9739   if (Parser.getTok().is(AsmToken::Comma)) {
9740     Parser.Lex();
9741 
9742     if (Parser.getTok().isNot(AsmToken::Hash)) {
9743       Error(Parser.getTok().getLoc(), "expected #constant");
9744       Parser.eatToEndOfStatement();
9745       return false;
9746     }
9747     Parser.Lex();
9748 
9749     const MCExpr *OffsetExpr;
9750     SMLoc OffsetLoc = Parser.getTok().getLoc();
9751     if (Parser.parseExpression(OffsetExpr)) {
9752       Parser.eatToEndOfStatement();
9753       Error(OffsetLoc, "malformed offset expression");
9754       return false;
9755     }
9756 
9757     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9758     if (!CE) {
9759       Parser.eatToEndOfStatement();
9760       Error(OffsetLoc, "offset must be an immediate constant");
9761       return false;
9762     }
9763 
9764     Offset = CE->getValue();
9765   }
9766 
9767   getTargetStreamer().emitMovSP(SPReg, Offset);
9768   UC.saveFPReg(SPReg);
9769 
9770   return false;
9771 }
9772 
9773 /// parseDirectiveObjectArch
9774 ///   ::= .object_arch name
9775 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
9776   MCAsmParser &Parser = getParser();
9777   if (getLexer().isNot(AsmToken::Identifier)) {
9778     Error(getLexer().getLoc(), "unexpected token");
9779     Parser.eatToEndOfStatement();
9780     return false;
9781   }
9782 
9783   StringRef Arch = Parser.getTok().getString();
9784   SMLoc ArchLoc = Parser.getTok().getLoc();
9785   getLexer().Lex();
9786 
9787   unsigned ID = ARMTargetParser::parseArch(Arch);
9788 
9789   if (ID == ARM::AK_INVALID) {
9790     Error(ArchLoc, "unknown architecture '" + Arch + "'");
9791     Parser.eatToEndOfStatement();
9792     return false;
9793   }
9794 
9795   getTargetStreamer().emitObjectArch(ID);
9796 
9797   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9798     Error(getLexer().getLoc(), "unexpected token");
9799     Parser.eatToEndOfStatement();
9800   }
9801 
9802   return false;
9803 }
9804 
9805 /// parseDirectiveAlign
9806 ///   ::= .align
9807 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
9808   // NOTE: if this is not the end of the statement, fall back to the target
9809   // agnostic handling for this directive which will correctly handle this.
9810   if (getLexer().isNot(AsmToken::EndOfStatement))
9811     return true;
9812 
9813   // '.align' is target specifically handled to mean 2**2 byte alignment.
9814   if (getStreamer().getCurrentSection().first->UseCodeAlign())
9815     getStreamer().EmitCodeAlignment(4, 0);
9816   else
9817     getStreamer().EmitValueToAlignment(4, 0, 1, 0);
9818 
9819   return false;
9820 }
9821 
9822 /// parseDirectiveThumbSet
9823 ///  ::= .thumb_set name, value
9824 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
9825   MCAsmParser &Parser = getParser();
9826 
9827   StringRef Name;
9828   if (Parser.parseIdentifier(Name)) {
9829     TokError("expected identifier after '.thumb_set'");
9830     Parser.eatToEndOfStatement();
9831     return false;
9832   }
9833 
9834   if (getLexer().isNot(AsmToken::Comma)) {
9835     TokError("expected comma after name '" + Name + "'");
9836     Parser.eatToEndOfStatement();
9837     return false;
9838   }
9839   Lex();
9840 
9841   MCSymbol *Sym;
9842   const MCExpr *Value;
9843   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
9844                                                Parser, Sym, Value))
9845     return true;
9846 
9847   getTargetStreamer().emitThumbSet(Sym, Value);
9848   return false;
9849 }
9850 
9851 /// Force static initialization.
9852 extern "C" void LLVMInitializeARMAsmParser() {
9853   RegisterMCAsmParser<ARMAsmParser> X(TheARMLETarget);
9854   RegisterMCAsmParser<ARMAsmParser> Y(TheARMBETarget);
9855   RegisterMCAsmParser<ARMAsmParser> A(TheThumbLETarget);
9856   RegisterMCAsmParser<ARMAsmParser> B(TheThumbBETarget);
9857 }
9858 
9859 #define GET_REGISTER_MATCHER
9860 #define GET_SUBTARGET_FEATURE_NAME
9861 #define GET_MATCHER_IMPLEMENTATION
9862 #include "ARMGenAsmMatcher.inc"
9863 
9864 // FIXME: This structure should be moved inside ARMTargetParser
9865 // when we start to table-generate them, and we can use the ARM
9866 // flags below, that were generated by table-gen.
9867 static const struct {
9868   const unsigned Kind;
9869   const unsigned ArchCheck;
9870   const FeatureBitset Features;
9871 } Extensions[] = {
9872   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
9873   { ARM::AEK_CRYPTO,  Feature_HasV8,
9874     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
9875   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
9876   { (ARM::AEK_HWDIV | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
9877     {ARM::FeatureHWDiv, ARM::FeatureHWDivARM} },
9878   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
9879   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
9880   // FIXME: Also available in ARMv6-K
9881   { ARM::AEK_SEC, Feature_HasV7, {ARM::FeatureTrustZone} },
9882   // FIXME: Only available in A-class, isel not predicated
9883   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
9884   // FIXME: Unsupported extensions.
9885   { ARM::AEK_OS, Feature_None, {} },
9886   { ARM::AEK_IWMMXT, Feature_None, {} },
9887   { ARM::AEK_IWMMXT2, Feature_None, {} },
9888   { ARM::AEK_MAVERICK, Feature_None, {} },
9889   { ARM::AEK_XSCALE, Feature_None, {} },
9890 };
9891 
9892 /// parseDirectiveArchExtension
9893 ///   ::= .arch_extension [no]feature
9894 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
9895   MCAsmParser &Parser = getParser();
9896 
9897   if (getLexer().isNot(AsmToken::Identifier)) {
9898     Error(getLexer().getLoc(), "unexpected token");
9899     Parser.eatToEndOfStatement();
9900     return false;
9901   }
9902 
9903   StringRef Name = Parser.getTok().getString();
9904   SMLoc ExtLoc = Parser.getTok().getLoc();
9905   getLexer().Lex();
9906 
9907   bool EnableFeature = true;
9908   if (Name.startswith_lower("no")) {
9909     EnableFeature = false;
9910     Name = Name.substr(2);
9911   }
9912   unsigned FeatureKind = ARMTargetParser::parseArchExt(Name);
9913   if (FeatureKind == ARM::AEK_INVALID)
9914     Error(ExtLoc, "unknown architectural extension: " + Name);
9915 
9916   for (const auto &Extension : Extensions) {
9917     if (Extension.Kind != FeatureKind)
9918       continue;
9919 
9920     if (Extension.Features.none())
9921       report_fatal_error("unsupported architectural extension: " + Name);
9922 
9923     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck) {
9924       Error(ExtLoc, "architectural extension '" + Name + "' is not "
9925             "allowed for the current base architecture");
9926       return false;
9927     }
9928 
9929     FeatureBitset ToggleFeatures = EnableFeature
9930       ? (~STI.getFeatureBits() & Extension.Features)
9931       : ( STI.getFeatureBits() & Extension.Features);
9932 
9933     uint64_t Features =
9934         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
9935     setAvailableFeatures(Features);
9936     return false;
9937   }
9938 
9939   Error(ExtLoc, "unknown architectural extension: " + Name);
9940   Parser.eatToEndOfStatement();
9941   return false;
9942 }
9943 
9944 // Define this matcher function after the auto-generated include so we
9945 // have the match class enum definitions.
9946 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
9947                                                   unsigned Kind) {
9948   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
9949   // If the kind is a token for a literal immediate, check if our asm
9950   // operand matches. This is for InstAliases which have a fixed-value
9951   // immediate in the syntax.
9952   switch (Kind) {
9953   default: break;
9954   case MCK__35_0:
9955     if (Op.isImm())
9956       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
9957         if (CE->getValue() == 0)
9958           return Match_Success;
9959     break;
9960   case MCK_ModImm:
9961     if (Op.isImm()) {
9962       const MCExpr *SOExpr = Op.getImm();
9963       int64_t Value;
9964       if (!SOExpr->evaluateAsAbsolute(Value))
9965         return Match_Success;
9966       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
9967              "expression value must be representable in 32 bits");
9968     }
9969     break;
9970   case MCK_GPRPair:
9971     if (Op.isReg() &&
9972         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
9973       return Match_Success;
9974     break;
9975   }
9976   return Match_InvalidOperand;
9977 }
9978