1 //===-- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "ARMFeatures.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMMCExpr.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
24 #include "llvm/MC/MCELFStreamer.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCObjectFileInfo.h"
30 #include "llvm/MC/MCParser/MCAsmLexer.h"
31 #include "llvm/MC/MCParser/MCAsmParser.h"
32 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
33 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
34 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
35 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/MC/MCSection.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSubtargetInfo.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/ARMBuildAttributes.h"
41 #include "llvm/Support/ARMEHABI.h"
42 #include "llvm/Support/COFF.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/TargetParser.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/raw_ostream.h"
50 
51 using namespace llvm;
52 
53 namespace {
54 
55 class ARMOperand;
56 
57 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
58 
59 class UnwindContext {
60   MCAsmParser &Parser;
61 
62   typedef SmallVector<SMLoc, 4> Locs;
63 
64   Locs FnStartLocs;
65   Locs CantUnwindLocs;
66   Locs PersonalityLocs;
67   Locs PersonalityIndexLocs;
68   Locs HandlerDataLocs;
69   int FPReg;
70 
71 public:
72   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
73 
74   bool hasFnStart() const { return !FnStartLocs.empty(); }
75   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
76   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
77   bool hasPersonality() const {
78     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
79   }
80 
81   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
82   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
83   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
84   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
85   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
86 
87   void saveFPReg(int Reg) { FPReg = Reg; }
88   int getFPReg() const { return FPReg; }
89 
90   void emitFnStartLocNotes() const {
91     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
92          FI != FE; ++FI)
93       Parser.Note(*FI, ".fnstart was specified here");
94   }
95   void emitCantUnwindLocNotes() const {
96     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
97                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
98       Parser.Note(*UI, ".cantunwind was specified here");
99   }
100   void emitHandlerDataLocNotes() const {
101     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
102                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
103       Parser.Note(*HI, ".handlerdata was specified here");
104   }
105   void emitPersonalityLocNotes() const {
106     for (Locs::const_iterator PI = PersonalityLocs.begin(),
107                               PE = PersonalityLocs.end(),
108                               PII = PersonalityIndexLocs.begin(),
109                               PIE = PersonalityIndexLocs.end();
110          PI != PE || PII != PIE;) {
111       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
112         Parser.Note(*PI++, ".personality was specified here");
113       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
114         Parser.Note(*PII++, ".personalityindex was specified here");
115       else
116         llvm_unreachable(".personality and .personalityindex cannot be "
117                          "at the same location");
118     }
119   }
120 
121   void reset() {
122     FnStartLocs = Locs();
123     CantUnwindLocs = Locs();
124     PersonalityLocs = Locs();
125     HandlerDataLocs = Locs();
126     PersonalityIndexLocs = Locs();
127     FPReg = ARM::SP;
128   }
129 };
130 
131 class ARMAsmParser : public MCTargetAsmParser {
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 getSTI().getFeatureBits()[ARM::ModeThumb];
250   }
251   bool isThumbOne() const {
252     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
253   }
254   bool isThumbTwo() const {
255     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
256   }
257   bool hasThumb() const {
258     return getSTI().getFeatureBits()[ARM::HasV4TOps];
259   }
260   bool hasThumb2() const {
261     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
262   }
263   bool hasV6Ops() const {
264     return getSTI().getFeatureBits()[ARM::HasV6Ops];
265   }
266   bool hasV6T2Ops() const {
267     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
268   }
269   bool hasV6MOps() const {
270     return getSTI().getFeatureBits()[ARM::HasV6MOps];
271   }
272   bool hasV7Ops() const {
273     return getSTI().getFeatureBits()[ARM::HasV7Ops];
274   }
275   bool hasV8Ops() const {
276     return getSTI().getFeatureBits()[ARM::HasV8Ops];
277   }
278   bool hasV8MBaseline() const {
279     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
280   }
281   bool hasV8MMainline() const {
282     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
283   }
284   bool has8MSecExt() const {
285     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
286   }
287   bool hasARM() const {
288     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
289   }
290   bool hasDSP() const {
291     return getSTI().getFeatureBits()[ARM::FeatureDSP];
292   }
293   bool hasD16() const {
294     return getSTI().getFeatureBits()[ARM::FeatureD16];
295   }
296   bool hasV8_1aOps() const {
297     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
298   }
299   bool hasRAS() const {
300     return getSTI().getFeatureBits()[ARM::FeatureRAS];
301   }
302 
303   void SwitchMode() {
304     MCSubtargetInfo &STI = copySTI();
305     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
306     setAvailableFeatures(FB);
307   }
308   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
309   bool isMClass() const {
310     return getSTI().getFeatureBits()[ARM::FeatureMClass];
311   }
312 
313   /// @name Auto-generated Match Functions
314   /// {
315 
316 #define GET_ASSEMBLER_HEADER
317 #include "ARMGenAsmMatcher.inc"
318 
319   /// }
320 
321   OperandMatchResultTy parseITCondCode(OperandVector &);
322   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
323   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
324   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
325   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
326   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
327   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
328   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
329   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
330   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
331                                    int High);
332   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
333     return parsePKHImm(O, "lsl", 0, 31);
334   }
335   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
336     return parsePKHImm(O, "asr", 1, 32);
337   }
338   OperandMatchResultTy parseSetEndImm(OperandVector &);
339   OperandMatchResultTy parseShifterImm(OperandVector &);
340   OperandMatchResultTy parseRotImm(OperandVector &);
341   OperandMatchResultTy parseModImm(OperandVector &);
342   OperandMatchResultTy parseBitfield(OperandVector &);
343   OperandMatchResultTy parsePostIdxReg(OperandVector &);
344   OperandMatchResultTy parseAM3Offset(OperandVector &);
345   OperandMatchResultTy parseFPImm(OperandVector &);
346   OperandMatchResultTy parseVectorList(OperandVector &);
347   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
348                                        SMLoc &EndLoc);
349 
350   // Asm Match Converter Methods
351   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
352   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
353 
354   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
355   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
356   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
357   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
358 
359 public:
360   enum ARMMatchResultTy {
361     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
362     Match_RequiresNotITBlock,
363     Match_RequiresV6,
364     Match_RequiresThumb2,
365     Match_RequiresV8,
366 #define GET_OPERAND_DIAGNOSTIC_TYPES
367 #include "ARMGenAsmMatcher.inc"
368 
369   };
370 
371   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
372                const MCInstrInfo &MII, const MCTargetOptions &Options)
373     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
374     MCAsmParserExtension::Initialize(Parser);
375 
376     // Cache the MCRegisterInfo.
377     MRI = getContext().getRegisterInfo();
378 
379     // Initialize the set of available features.
380     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
381 
382     // Not in an ITBlock to start with.
383     ITState.CurPosition = ~0U;
384 
385     NextSymbolIsThumb = false;
386   }
387 
388   // Implementation of the MCTargetAsmParser interface:
389   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
390   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
391                         SMLoc NameLoc, OperandVector &Operands) override;
392   bool ParseDirective(AsmToken DirectiveID) override;
393 
394   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
395                                       unsigned Kind) override;
396   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
397 
398   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
399                                OperandVector &Operands, MCStreamer &Out,
400                                uint64_t &ErrorInfo,
401                                bool MatchingInlineAsm) override;
402   void onLabelParsed(MCSymbol *Symbol) override;
403 };
404 } // end anonymous namespace
405 
406 namespace {
407 
408 /// ARMOperand - Instances of this class represent a parsed ARM machine
409 /// operand.
410 class ARMOperand : public MCParsedAsmOperand {
411   enum KindTy {
412     k_CondCode,
413     k_CCOut,
414     k_ITCondMask,
415     k_CoprocNum,
416     k_CoprocReg,
417     k_CoprocOption,
418     k_Immediate,
419     k_MemBarrierOpt,
420     k_InstSyncBarrierOpt,
421     k_Memory,
422     k_PostIndexRegister,
423     k_MSRMask,
424     k_BankedReg,
425     k_ProcIFlags,
426     k_VectorIndex,
427     k_Register,
428     k_RegisterList,
429     k_DPRRegisterList,
430     k_SPRRegisterList,
431     k_VectorList,
432     k_VectorListAllLanes,
433     k_VectorListIndexed,
434     k_ShiftedRegister,
435     k_ShiftedImmediate,
436     k_ShifterImmediate,
437     k_RotateImmediate,
438     k_ModifiedImmediate,
439     k_ConstantPoolImmediate,
440     k_BitfieldDescriptor,
441     k_Token,
442   } Kind;
443 
444   SMLoc StartLoc, EndLoc, AlignmentLoc;
445   SmallVector<unsigned, 8> Registers;
446 
447   struct CCOp {
448     ARMCC::CondCodes Val;
449   };
450 
451   struct CopOp {
452     unsigned Val;
453   };
454 
455   struct CoprocOptionOp {
456     unsigned Val;
457   };
458 
459   struct ITMaskOp {
460     unsigned Mask:4;
461   };
462 
463   struct MBOptOp {
464     ARM_MB::MemBOpt Val;
465   };
466 
467   struct ISBOptOp {
468     ARM_ISB::InstSyncBOpt Val;
469   };
470 
471   struct IFlagsOp {
472     ARM_PROC::IFlags Val;
473   };
474 
475   struct MMaskOp {
476     unsigned Val;
477   };
478 
479   struct BankedRegOp {
480     unsigned Val;
481   };
482 
483   struct TokOp {
484     const char *Data;
485     unsigned Length;
486   };
487 
488   struct RegOp {
489     unsigned RegNum;
490   };
491 
492   // A vector register list is a sequential list of 1 to 4 registers.
493   struct VectorListOp {
494     unsigned RegNum;
495     unsigned Count;
496     unsigned LaneIndex;
497     bool isDoubleSpaced;
498   };
499 
500   struct VectorIndexOp {
501     unsigned Val;
502   };
503 
504   struct ImmOp {
505     const MCExpr *Val;
506   };
507 
508   /// Combined record for all forms of ARM address expressions.
509   struct MemoryOp {
510     unsigned BaseRegNum;
511     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
512     // was specified.
513     const MCConstantExpr *OffsetImm;  // Offset immediate value
514     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
515     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
516     unsigned ShiftImm;        // shift for OffsetReg.
517     unsigned Alignment;       // 0 = no alignment specified
518     // n = alignment in bytes (2, 4, 8, 16, or 32)
519     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
520   };
521 
522   struct PostIdxRegOp {
523     unsigned RegNum;
524     bool isAdd;
525     ARM_AM::ShiftOpc ShiftTy;
526     unsigned ShiftImm;
527   };
528 
529   struct ShifterImmOp {
530     bool isASR;
531     unsigned Imm;
532   };
533 
534   struct RegShiftedRegOp {
535     ARM_AM::ShiftOpc ShiftTy;
536     unsigned SrcReg;
537     unsigned ShiftReg;
538     unsigned ShiftImm;
539   };
540 
541   struct RegShiftedImmOp {
542     ARM_AM::ShiftOpc ShiftTy;
543     unsigned SrcReg;
544     unsigned ShiftImm;
545   };
546 
547   struct RotImmOp {
548     unsigned Imm;
549   };
550 
551   struct ModImmOp {
552     unsigned Bits;
553     unsigned Rot;
554   };
555 
556   struct BitfieldOp {
557     unsigned LSB;
558     unsigned Width;
559   };
560 
561   union {
562     struct CCOp CC;
563     struct CopOp Cop;
564     struct CoprocOptionOp CoprocOption;
565     struct MBOptOp MBOpt;
566     struct ISBOptOp ISBOpt;
567     struct ITMaskOp ITMask;
568     struct IFlagsOp IFlags;
569     struct MMaskOp MMask;
570     struct BankedRegOp BankedReg;
571     struct TokOp Tok;
572     struct RegOp Reg;
573     struct VectorListOp VectorList;
574     struct VectorIndexOp VectorIndex;
575     struct ImmOp Imm;
576     struct MemoryOp Memory;
577     struct PostIdxRegOp PostIdxReg;
578     struct ShifterImmOp ShifterImm;
579     struct RegShiftedRegOp RegShiftedReg;
580     struct RegShiftedImmOp RegShiftedImm;
581     struct RotImmOp RotImm;
582     struct ModImmOp ModImm;
583     struct BitfieldOp Bitfield;
584   };
585 
586 public:
587   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
588 
589   /// getStartLoc - Get the location of the first token of this operand.
590   SMLoc getStartLoc() const override { return StartLoc; }
591   /// getEndLoc - Get the location of the last token of this operand.
592   SMLoc getEndLoc() const override { return EndLoc; }
593   /// getLocRange - Get the range between the first and last token of this
594   /// operand.
595   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
596 
597   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
598   SMLoc getAlignmentLoc() const {
599     assert(Kind == k_Memory && "Invalid access!");
600     return AlignmentLoc;
601   }
602 
603   ARMCC::CondCodes getCondCode() const {
604     assert(Kind == k_CondCode && "Invalid access!");
605     return CC.Val;
606   }
607 
608   unsigned getCoproc() const {
609     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
610     return Cop.Val;
611   }
612 
613   StringRef getToken() const {
614     assert(Kind == k_Token && "Invalid access!");
615     return StringRef(Tok.Data, Tok.Length);
616   }
617 
618   unsigned getReg() const override {
619     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
620     return Reg.RegNum;
621   }
622 
623   const SmallVectorImpl<unsigned> &getRegList() const {
624     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
625             Kind == k_SPRRegisterList) && "Invalid access!");
626     return Registers;
627   }
628 
629   const MCExpr *getImm() const {
630     assert(isImm() && "Invalid access!");
631     return Imm.Val;
632   }
633 
634   const MCExpr *getConstantPoolImm() const {
635     assert(isConstantPoolImm() && "Invalid access!");
636     return Imm.Val;
637   }
638 
639   unsigned getVectorIndex() const {
640     assert(Kind == k_VectorIndex && "Invalid access!");
641     return VectorIndex.Val;
642   }
643 
644   ARM_MB::MemBOpt getMemBarrierOpt() const {
645     assert(Kind == k_MemBarrierOpt && "Invalid access!");
646     return MBOpt.Val;
647   }
648 
649   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
650     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
651     return ISBOpt.Val;
652   }
653 
654   ARM_PROC::IFlags getProcIFlags() const {
655     assert(Kind == k_ProcIFlags && "Invalid access!");
656     return IFlags.Val;
657   }
658 
659   unsigned getMSRMask() const {
660     assert(Kind == k_MSRMask && "Invalid access!");
661     return MMask.Val;
662   }
663 
664   unsigned getBankedReg() const {
665     assert(Kind == k_BankedReg && "Invalid access!");
666     return BankedReg.Val;
667   }
668 
669   bool isCoprocNum() const { return Kind == k_CoprocNum; }
670   bool isCoprocReg() const { return Kind == k_CoprocReg; }
671   bool isCoprocOption() const { return Kind == k_CoprocOption; }
672   bool isCondCode() const { return Kind == k_CondCode; }
673   bool isCCOut() const { return Kind == k_CCOut; }
674   bool isITMask() const { return Kind == k_ITCondMask; }
675   bool isITCondCode() const { return Kind == k_CondCode; }
676   bool isImm() const override {
677     return Kind == k_Immediate;
678   }
679   // checks whether this operand is an unsigned offset which fits is a field
680   // of specified width and scaled by a specific number of bits
681   template<unsigned width, unsigned scale>
682   bool isUnsignedOffset() const {
683     if (!isImm()) return false;
684     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
685     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
686       int64_t Val = CE->getValue();
687       int64_t Align = 1LL << scale;
688       int64_t Max = Align * ((1LL << width) - 1);
689       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
690     }
691     return false;
692   }
693   // checks whether this operand is an signed offset which fits is a field
694   // of specified width and scaled by a specific number of bits
695   template<unsigned width, unsigned scale>
696   bool isSignedOffset() const {
697     if (!isImm()) return false;
698     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
699     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
700       int64_t Val = CE->getValue();
701       int64_t Align = 1LL << scale;
702       int64_t Max = Align * ((1LL << (width-1)) - 1);
703       int64_t Min = -Align * (1LL << (width-1));
704       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
705     }
706     return false;
707   }
708 
709   // checks whether this operand is a memory operand computed as an offset
710   // applied to PC. the offset may have 8 bits of magnitude and is represented
711   // with two bits of shift. textually it may be either [pc, #imm], #imm or
712   // relocable expression...
713   bool isThumbMemPC() const {
714     int64_t Val = 0;
715     if (isImm()) {
716       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
717       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
718       if (!CE) return false;
719       Val = CE->getValue();
720     }
721     else if (isMem()) {
722       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
723       if(Memory.BaseRegNum != ARM::PC) return false;
724       Val = Memory.OffsetImm->getValue();
725     }
726     else return false;
727     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
728   }
729   bool isFPImm() const {
730     if (!isImm()) return false;
731     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
732     if (!CE) return false;
733     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
734     return Val != -1;
735   }
736   bool isFBits16() const {
737     if (!isImm()) return false;
738     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
739     if (!CE) return false;
740     int64_t Value = CE->getValue();
741     return Value >= 0 && Value <= 16;
742   }
743   bool isFBits32() const {
744     if (!isImm()) return false;
745     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
746     if (!CE) return false;
747     int64_t Value = CE->getValue();
748     return Value >= 1 && Value <= 32;
749   }
750   bool isImm8s4() 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 & 3) == 0) && Value >= -1020 && Value <= 1020;
756   }
757   bool isImm0_1020s4() 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 & 3) == 0) && Value >= 0 && Value <= 1020;
763   }
764   bool isImm0_508s4() 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 & 3) == 0) && Value >= 0 && Value <= 508;
770   }
771   bool isImm0_508s4Neg() 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     // explicitly exclude zero. we want that to use the normal 0_508 version.
777     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
778   }
779   bool isImm0_239() const {
780     if (!isImm()) return false;
781     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
782     if (!CE) return false;
783     int64_t Value = CE->getValue();
784     return Value >= 0 && Value < 240;
785   }
786   bool isImm0_255() const {
787     if (!isImm()) return false;
788     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
789     if (!CE) return false;
790     int64_t Value = CE->getValue();
791     return Value >= 0 && Value < 256;
792   }
793   bool isImm0_4095() const {
794     if (!isImm()) return false;
795     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
796     if (!CE) return false;
797     int64_t Value = CE->getValue();
798     return Value >= 0 && Value < 4096;
799   }
800   bool isImm0_4095Neg() const {
801     if (!isImm()) return false;
802     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
803     if (!CE) return false;
804     int64_t Value = -CE->getValue();
805     return Value > 0 && Value < 4096;
806   }
807   bool isImm0_1() const {
808     if (!isImm()) return false;
809     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
810     if (!CE) return false;
811     int64_t Value = CE->getValue();
812     return Value >= 0 && Value < 2;
813   }
814   bool isImm0_3() const {
815     if (!isImm()) return false;
816     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
817     if (!CE) return false;
818     int64_t Value = CE->getValue();
819     return Value >= 0 && Value < 4;
820   }
821   bool isImm0_7() const {
822     if (!isImm()) return false;
823     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
824     if (!CE) return false;
825     int64_t Value = CE->getValue();
826     return Value >= 0 && Value < 8;
827   }
828   bool isImm0_15() const {
829     if (!isImm()) return false;
830     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
831     if (!CE) return false;
832     int64_t Value = CE->getValue();
833     return Value >= 0 && Value < 16;
834   }
835   bool isImm0_31() const {
836     if (!isImm()) return false;
837     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
838     if (!CE) return false;
839     int64_t Value = CE->getValue();
840     return Value >= 0 && Value < 32;
841   }
842   bool isImm0_63() const {
843     if (!isImm()) return false;
844     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
845     if (!CE) return false;
846     int64_t Value = CE->getValue();
847     return Value >= 0 && Value < 64;
848   }
849   bool isImm8() const {
850     if (!isImm()) return false;
851     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
852     if (!CE) return false;
853     int64_t Value = CE->getValue();
854     return Value == 8;
855   }
856   bool isImm16() const {
857     if (!isImm()) return false;
858     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
859     if (!CE) return false;
860     int64_t Value = CE->getValue();
861     return Value == 16;
862   }
863   bool isImm32() const {
864     if (!isImm()) return false;
865     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
866     if (!CE) return false;
867     int64_t Value = CE->getValue();
868     return Value == 32;
869   }
870   bool isShrImm8() const {
871     if (!isImm()) return false;
872     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
873     if (!CE) return false;
874     int64_t Value = CE->getValue();
875     return Value > 0 && Value <= 8;
876   }
877   bool isShrImm16() const {
878     if (!isImm()) return false;
879     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
880     if (!CE) return false;
881     int64_t Value = CE->getValue();
882     return Value > 0 && Value <= 16;
883   }
884   bool isShrImm32() const {
885     if (!isImm()) return false;
886     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
887     if (!CE) return false;
888     int64_t Value = CE->getValue();
889     return Value > 0 && Value <= 32;
890   }
891   bool isShrImm64() const {
892     if (!isImm()) return false;
893     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
894     if (!CE) return false;
895     int64_t Value = CE->getValue();
896     return Value > 0 && Value <= 64;
897   }
898   bool isImm1_7() const {
899     if (!isImm()) return false;
900     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
901     if (!CE) return false;
902     int64_t Value = CE->getValue();
903     return Value > 0 && Value < 8;
904   }
905   bool isImm1_15() const {
906     if (!isImm()) return false;
907     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
908     if (!CE) return false;
909     int64_t Value = CE->getValue();
910     return Value > 0 && Value < 16;
911   }
912   bool isImm1_31() const {
913     if (!isImm()) return false;
914     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
915     if (!CE) return false;
916     int64_t Value = CE->getValue();
917     return Value > 0 && Value < 32;
918   }
919   bool isImm1_16() const {
920     if (!isImm()) return false;
921     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
922     if (!CE) return false;
923     int64_t Value = CE->getValue();
924     return Value > 0 && Value < 17;
925   }
926   bool isImm1_32() const {
927     if (!isImm()) return false;
928     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
929     if (!CE) return false;
930     int64_t Value = CE->getValue();
931     return Value > 0 && Value < 33;
932   }
933   bool isImm0_32() const {
934     if (!isImm()) return false;
935     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
936     if (!CE) return false;
937     int64_t Value = CE->getValue();
938     return Value >= 0 && Value < 33;
939   }
940   bool isImm0_65535() const {
941     if (!isImm()) return false;
942     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
943     if (!CE) return false;
944     int64_t Value = CE->getValue();
945     return Value >= 0 && Value < 65536;
946   }
947   bool isImm256_65535Expr() const {
948     if (!isImm()) return false;
949     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
950     // If it's not a constant expression, it'll generate a fixup and be
951     // handled later.
952     if (!CE) return true;
953     int64_t Value = CE->getValue();
954     return Value >= 256 && Value < 65536;
955   }
956   bool isImm0_65535Expr() const {
957     if (!isImm()) return false;
958     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
959     // If it's not a constant expression, it'll generate a fixup and be
960     // handled later.
961     if (!CE) return true;
962     int64_t Value = CE->getValue();
963     return Value >= 0 && Value < 65536;
964   }
965   bool isImm24bit() const {
966     if (!isImm()) return false;
967     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
968     if (!CE) return false;
969     int64_t Value = CE->getValue();
970     return Value >= 0 && Value <= 0xffffff;
971   }
972   bool isImmThumbSR() const {
973     if (!isImm()) return false;
974     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
975     if (!CE) return false;
976     int64_t Value = CE->getValue();
977     return Value > 0 && Value < 33;
978   }
979   bool isPKHLSLImm() const {
980     if (!isImm()) return false;
981     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
982     if (!CE) return false;
983     int64_t Value = CE->getValue();
984     return Value >= 0 && Value < 32;
985   }
986   bool isPKHASRImm() const {
987     if (!isImm()) return false;
988     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
989     if (!CE) return false;
990     int64_t Value = CE->getValue();
991     return Value > 0 && Value <= 32;
992   }
993   bool isAdrLabel() const {
994     // If we have an immediate that's not a constant, treat it as a label
995     // reference needing a fixup.
996     if (isImm() && !isa<MCConstantExpr>(getImm()))
997       return true;
998 
999     // If it is a constant, it must fit into a modified immediate encoding.
1000     if (!isImm()) return false;
1001     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1002     if (!CE) return false;
1003     int64_t Value = CE->getValue();
1004     return (ARM_AM::getSOImmVal(Value) != -1 ||
1005             ARM_AM::getSOImmVal(-Value) != -1);
1006   }
1007   bool isT2SOImm() const {
1008     if (!isImm()) return false;
1009     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1010     if (!CE) return false;
1011     int64_t Value = CE->getValue();
1012     return ARM_AM::getT2SOImmVal(Value) != -1;
1013   }
1014   bool isT2SOImmNot() const {
1015     if (!isImm()) return false;
1016     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1017     if (!CE) return false;
1018     int64_t Value = CE->getValue();
1019     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1020       ARM_AM::getT2SOImmVal(~Value) != -1;
1021   }
1022   bool isT2SOImmNeg() 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     // Only use this when not representable as a plain so_imm.
1028     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1029       ARM_AM::getT2SOImmVal(-Value) != -1;
1030   }
1031   bool isSetEndImm() const {
1032     if (!isImm()) return false;
1033     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1034     if (!CE) return false;
1035     int64_t Value = CE->getValue();
1036     return Value == 1 || Value == 0;
1037   }
1038   bool isReg() const override { return Kind == k_Register; }
1039   bool isRegList() const { return Kind == k_RegisterList; }
1040   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1041   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1042   bool isToken() const override { return Kind == k_Token; }
1043   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1044   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1045   bool isMem() const override { return Kind == k_Memory; }
1046   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1047   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1048   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1049   bool isRotImm() const { return Kind == k_RotateImmediate; }
1050   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1051   bool isModImmNot() const {
1052     if (!isImm()) return false;
1053     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1054     if (!CE) return false;
1055     int64_t Value = CE->getValue();
1056     return ARM_AM::getSOImmVal(~Value) != -1;
1057   }
1058   bool isModImmNeg() const {
1059     if (!isImm()) return false;
1060     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1061     if (!CE) return false;
1062     int64_t Value = CE->getValue();
1063     return ARM_AM::getSOImmVal(Value) == -1 &&
1064       ARM_AM::getSOImmVal(-Value) != -1;
1065   }
1066   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1067   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1068   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1069   bool isPostIdxReg() const {
1070     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1071   }
1072   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1073     if (!isMem())
1074       return false;
1075     // No offset of any kind.
1076     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1077      (alignOK || Memory.Alignment == Alignment);
1078   }
1079   bool isMemPCRelImm12() const {
1080     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1081       return false;
1082     // Base register must be PC.
1083     if (Memory.BaseRegNum != ARM::PC)
1084       return false;
1085     // Immediate offset in range [-4095, 4095].
1086     if (!Memory.OffsetImm) return true;
1087     int64_t Val = Memory.OffsetImm->getValue();
1088     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1089   }
1090   bool isAlignedMemory() const {
1091     return isMemNoOffset(true);
1092   }
1093   bool isAlignedMemoryNone() const {
1094     return isMemNoOffset(false, 0);
1095   }
1096   bool isDupAlignedMemoryNone() const {
1097     return isMemNoOffset(false, 0);
1098   }
1099   bool isAlignedMemory16() const {
1100     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1101       return true;
1102     return isMemNoOffset(false, 0);
1103   }
1104   bool isDupAlignedMemory16() const {
1105     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1106       return true;
1107     return isMemNoOffset(false, 0);
1108   }
1109   bool isAlignedMemory32() const {
1110     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1111       return true;
1112     return isMemNoOffset(false, 0);
1113   }
1114   bool isDupAlignedMemory32() const {
1115     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1116       return true;
1117     return isMemNoOffset(false, 0);
1118   }
1119   bool isAlignedMemory64() const {
1120     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1121       return true;
1122     return isMemNoOffset(false, 0);
1123   }
1124   bool isDupAlignedMemory64() const {
1125     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1126       return true;
1127     return isMemNoOffset(false, 0);
1128   }
1129   bool isAlignedMemory64or128() const {
1130     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1131       return true;
1132     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1133       return true;
1134     return isMemNoOffset(false, 0);
1135   }
1136   bool isDupAlignedMemory64or128() const {
1137     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1138       return true;
1139     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1140       return true;
1141     return isMemNoOffset(false, 0);
1142   }
1143   bool isAlignedMemory64or128or256() const {
1144     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1145       return true;
1146     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1147       return true;
1148     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1149       return true;
1150     return isMemNoOffset(false, 0);
1151   }
1152   bool isAddrMode2() const {
1153     if (!isMem() || Memory.Alignment != 0) return false;
1154     // Check for register offset.
1155     if (Memory.OffsetRegNum) return true;
1156     // Immediate offset in range [-4095, 4095].
1157     if (!Memory.OffsetImm) return true;
1158     int64_t Val = Memory.OffsetImm->getValue();
1159     return Val > -4096 && Val < 4096;
1160   }
1161   bool isAM2OffsetImm() const {
1162     if (!isImm()) return false;
1163     // Immediate offset in range [-4095, 4095].
1164     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1165     if (!CE) return false;
1166     int64_t Val = CE->getValue();
1167     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1168   }
1169   bool isAddrMode3() 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     // No shifts are legal for AM3.
1177     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1178     // Check for register offset.
1179     if (Memory.OffsetRegNum) return true;
1180     // Immediate offset in range [-255, 255].
1181     if (!Memory.OffsetImm) return true;
1182     int64_t Val = Memory.OffsetImm->getValue();
1183     // The #-0 offset is encoded as INT32_MIN, and we have to check
1184     // for this too.
1185     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1186   }
1187   bool isAM3Offset() const {
1188     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1189       return false;
1190     if (Kind == k_PostIndexRegister)
1191       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1192     // Immediate offset in range [-255, 255].
1193     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1194     if (!CE) return false;
1195     int64_t Val = CE->getValue();
1196     // Special case, #-0 is INT32_MIN.
1197     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1198   }
1199   bool isAddrMode5() const {
1200     // If we have an immediate that's not a constant, treat it as a label
1201     // reference needing a fixup. If it is a constant, it's something else
1202     // and we reject it.
1203     if (isImm() && !isa<MCConstantExpr>(getImm()))
1204       return true;
1205     if (!isMem() || Memory.Alignment != 0) return false;
1206     // Check for register offset.
1207     if (Memory.OffsetRegNum) return false;
1208     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1209     if (!Memory.OffsetImm) return true;
1210     int64_t Val = Memory.OffsetImm->getValue();
1211     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1212       Val == INT32_MIN;
1213   }
1214   bool isAddrMode5FP16() const {
1215     // If we have an immediate that's not a constant, treat it as a label
1216     // reference needing a fixup. If it is a constant, it's something else
1217     // and we reject it.
1218     if (isImm() && !isa<MCConstantExpr>(getImm()))
1219       return true;
1220     if (!isMem() || Memory.Alignment != 0) return false;
1221     // Check for register offset.
1222     if (Memory.OffsetRegNum) return false;
1223     // Immediate offset in range [-510, 510] and a multiple of 2.
1224     if (!Memory.OffsetImm) return true;
1225     int64_t Val = Memory.OffsetImm->getValue();
1226     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) || Val == INT32_MIN;
1227   }
1228   bool isMemTBB() const {
1229     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1230         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1231       return false;
1232     return true;
1233   }
1234   bool isMemTBH() const {
1235     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1236         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1237         Memory.Alignment != 0 )
1238       return false;
1239     return true;
1240   }
1241   bool isMemRegOffset() const {
1242     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1243       return false;
1244     return true;
1245   }
1246   bool isT2MemRegOffset() const {
1247     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1248         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1249       return false;
1250     // Only lsl #{0, 1, 2, 3} allowed.
1251     if (Memory.ShiftType == ARM_AM::no_shift)
1252       return true;
1253     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1254       return false;
1255     return true;
1256   }
1257   bool isMemThumbRR() const {
1258     // Thumb reg+reg addressing is simple. Just two registers, a base and
1259     // an offset. No shifts, negations or any other complicating factors.
1260     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1261         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1262       return false;
1263     return isARMLowRegister(Memory.BaseRegNum) &&
1264       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1265   }
1266   bool isMemThumbRIs4() const {
1267     if (!isMem() || Memory.OffsetRegNum != 0 ||
1268         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1269       return false;
1270     // Immediate offset, multiple of 4 in range [0, 124].
1271     if (!Memory.OffsetImm) return true;
1272     int64_t Val = Memory.OffsetImm->getValue();
1273     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1274   }
1275   bool isMemThumbRIs2() const {
1276     if (!isMem() || Memory.OffsetRegNum != 0 ||
1277         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1278       return false;
1279     // Immediate offset, multiple of 4 in range [0, 62].
1280     if (!Memory.OffsetImm) return true;
1281     int64_t Val = Memory.OffsetImm->getValue();
1282     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1283   }
1284   bool isMemThumbRIs1() const {
1285     if (!isMem() || Memory.OffsetRegNum != 0 ||
1286         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1287       return false;
1288     // Immediate offset in range [0, 31].
1289     if (!Memory.OffsetImm) return true;
1290     int64_t Val = Memory.OffsetImm->getValue();
1291     return Val >= 0 && Val <= 31;
1292   }
1293   bool isMemThumbSPI() const {
1294     if (!isMem() || Memory.OffsetRegNum != 0 ||
1295         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1296       return false;
1297     // Immediate offset, multiple of 4 in range [0, 1020].
1298     if (!Memory.OffsetImm) return true;
1299     int64_t Val = Memory.OffsetImm->getValue();
1300     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1301   }
1302   bool isMemImm8s4Offset() const {
1303     // If we have an immediate that's not a constant, treat it as a label
1304     // reference needing a fixup. If it is a constant, it's something else
1305     // and we reject it.
1306     if (isImm() && !isa<MCConstantExpr>(getImm()))
1307       return true;
1308     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1309       return false;
1310     // Immediate offset a multiple of 4 in range [-1020, 1020].
1311     if (!Memory.OffsetImm) return true;
1312     int64_t Val = Memory.OffsetImm->getValue();
1313     // Special case, #-0 is INT32_MIN.
1314     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1315   }
1316   bool isMemImm0_1020s4Offset() const {
1317     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1318       return false;
1319     // Immediate offset a multiple of 4 in range [0, 1020].
1320     if (!Memory.OffsetImm) return true;
1321     int64_t Val = Memory.OffsetImm->getValue();
1322     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1323   }
1324   bool isMemImm8Offset() const {
1325     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1326       return false;
1327     // Base reg of PC isn't allowed for these encodings.
1328     if (Memory.BaseRegNum == ARM::PC) return false;
1329     // Immediate offset in range [-255, 255].
1330     if (!Memory.OffsetImm) return true;
1331     int64_t Val = Memory.OffsetImm->getValue();
1332     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1333   }
1334   bool isMemPosImm8Offset() const {
1335     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1336       return false;
1337     // Immediate offset in range [0, 255].
1338     if (!Memory.OffsetImm) return true;
1339     int64_t Val = Memory.OffsetImm->getValue();
1340     return Val >= 0 && Val < 256;
1341   }
1342   bool isMemNegImm8Offset() const {
1343     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1344       return false;
1345     // Base reg of PC isn't allowed for these encodings.
1346     if (Memory.BaseRegNum == ARM::PC) return false;
1347     // Immediate offset in range [-255, -1].
1348     if (!Memory.OffsetImm) return false;
1349     int64_t Val = Memory.OffsetImm->getValue();
1350     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1351   }
1352   bool isMemUImm12Offset() const {
1353     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1354       return false;
1355     // Immediate offset in range [0, 4095].
1356     if (!Memory.OffsetImm) return true;
1357     int64_t Val = Memory.OffsetImm->getValue();
1358     return (Val >= 0 && Val < 4096);
1359   }
1360   bool isMemImm12Offset() const {
1361     // If we have an immediate that's not a constant, treat it as a label
1362     // reference needing a fixup. If it is a constant, it's something else
1363     // and we reject it.
1364 
1365     if (isImm() && !isa<MCConstantExpr>(getImm()))
1366       return true;
1367 
1368     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1369       return false;
1370     // Immediate offset in range [-4095, 4095].
1371     if (!Memory.OffsetImm) return true;
1372     int64_t Val = Memory.OffsetImm->getValue();
1373     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1374   }
1375   bool isConstPoolAsmImm() const {
1376     // Delay processing of Constant Pool Immediate, this will turn into
1377     // a constant. Match no other operand
1378     return (isConstantPoolImm());
1379   }
1380   bool isPostIdxImm8() const {
1381     if (!isImm()) return false;
1382     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1383     if (!CE) return false;
1384     int64_t Val = CE->getValue();
1385     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1386   }
1387   bool isPostIdxImm8s4() const {
1388     if (!isImm()) return false;
1389     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1390     if (!CE) return false;
1391     int64_t Val = CE->getValue();
1392     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1393       (Val == INT32_MIN);
1394   }
1395 
1396   bool isMSRMask() const { return Kind == k_MSRMask; }
1397   bool isBankedReg() const { return Kind == k_BankedReg; }
1398   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1399 
1400   // NEON operands.
1401   bool isSingleSpacedVectorList() const {
1402     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1403   }
1404   bool isDoubleSpacedVectorList() const {
1405     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1406   }
1407   bool isVecListOneD() const {
1408     if (!isSingleSpacedVectorList()) return false;
1409     return VectorList.Count == 1;
1410   }
1411 
1412   bool isVecListDPair() const {
1413     if (!isSingleSpacedVectorList()) return false;
1414     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1415               .contains(VectorList.RegNum));
1416   }
1417 
1418   bool isVecListThreeD() const {
1419     if (!isSingleSpacedVectorList()) return false;
1420     return VectorList.Count == 3;
1421   }
1422 
1423   bool isVecListFourD() const {
1424     if (!isSingleSpacedVectorList()) return false;
1425     return VectorList.Count == 4;
1426   }
1427 
1428   bool isVecListDPairSpaced() const {
1429     if (Kind != k_VectorList) return false;
1430     if (isSingleSpacedVectorList()) return false;
1431     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1432               .contains(VectorList.RegNum));
1433   }
1434 
1435   bool isVecListThreeQ() const {
1436     if (!isDoubleSpacedVectorList()) return false;
1437     return VectorList.Count == 3;
1438   }
1439 
1440   bool isVecListFourQ() const {
1441     if (!isDoubleSpacedVectorList()) return false;
1442     return VectorList.Count == 4;
1443   }
1444 
1445   bool isSingleSpacedVectorAllLanes() const {
1446     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1447   }
1448   bool isDoubleSpacedVectorAllLanes() const {
1449     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1450   }
1451   bool isVecListOneDAllLanes() const {
1452     if (!isSingleSpacedVectorAllLanes()) return false;
1453     return VectorList.Count == 1;
1454   }
1455 
1456   bool isVecListDPairAllLanes() const {
1457     if (!isSingleSpacedVectorAllLanes()) return false;
1458     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1459               .contains(VectorList.RegNum));
1460   }
1461 
1462   bool isVecListDPairSpacedAllLanes() const {
1463     if (!isDoubleSpacedVectorAllLanes()) return false;
1464     return VectorList.Count == 2;
1465   }
1466 
1467   bool isVecListThreeDAllLanes() const {
1468     if (!isSingleSpacedVectorAllLanes()) return false;
1469     return VectorList.Count == 3;
1470   }
1471 
1472   bool isVecListThreeQAllLanes() const {
1473     if (!isDoubleSpacedVectorAllLanes()) return false;
1474     return VectorList.Count == 3;
1475   }
1476 
1477   bool isVecListFourDAllLanes() const {
1478     if (!isSingleSpacedVectorAllLanes()) return false;
1479     return VectorList.Count == 4;
1480   }
1481 
1482   bool isVecListFourQAllLanes() const {
1483     if (!isDoubleSpacedVectorAllLanes()) return false;
1484     return VectorList.Count == 4;
1485   }
1486 
1487   bool isSingleSpacedVectorIndexed() const {
1488     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1489   }
1490   bool isDoubleSpacedVectorIndexed() const {
1491     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1492   }
1493   bool isVecListOneDByteIndexed() const {
1494     if (!isSingleSpacedVectorIndexed()) return false;
1495     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1496   }
1497 
1498   bool isVecListOneDHWordIndexed() const {
1499     if (!isSingleSpacedVectorIndexed()) return false;
1500     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1501   }
1502 
1503   bool isVecListOneDWordIndexed() const {
1504     if (!isSingleSpacedVectorIndexed()) return false;
1505     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1506   }
1507 
1508   bool isVecListTwoDByteIndexed() const {
1509     if (!isSingleSpacedVectorIndexed()) return false;
1510     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1511   }
1512 
1513   bool isVecListTwoDHWordIndexed() const {
1514     if (!isSingleSpacedVectorIndexed()) return false;
1515     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1516   }
1517 
1518   bool isVecListTwoQWordIndexed() const {
1519     if (!isDoubleSpacedVectorIndexed()) return false;
1520     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1521   }
1522 
1523   bool isVecListTwoQHWordIndexed() const {
1524     if (!isDoubleSpacedVectorIndexed()) return false;
1525     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1526   }
1527 
1528   bool isVecListTwoDWordIndexed() const {
1529     if (!isSingleSpacedVectorIndexed()) return false;
1530     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1531   }
1532 
1533   bool isVecListThreeDByteIndexed() const {
1534     if (!isSingleSpacedVectorIndexed()) return false;
1535     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1536   }
1537 
1538   bool isVecListThreeDHWordIndexed() const {
1539     if (!isSingleSpacedVectorIndexed()) return false;
1540     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1541   }
1542 
1543   bool isVecListThreeQWordIndexed() const {
1544     if (!isDoubleSpacedVectorIndexed()) return false;
1545     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1546   }
1547 
1548   bool isVecListThreeQHWordIndexed() const {
1549     if (!isDoubleSpacedVectorIndexed()) return false;
1550     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1551   }
1552 
1553   bool isVecListThreeDWordIndexed() const {
1554     if (!isSingleSpacedVectorIndexed()) return false;
1555     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1556   }
1557 
1558   bool isVecListFourDByteIndexed() const {
1559     if (!isSingleSpacedVectorIndexed()) return false;
1560     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1561   }
1562 
1563   bool isVecListFourDHWordIndexed() const {
1564     if (!isSingleSpacedVectorIndexed()) return false;
1565     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1566   }
1567 
1568   bool isVecListFourQWordIndexed() const {
1569     if (!isDoubleSpacedVectorIndexed()) return false;
1570     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1571   }
1572 
1573   bool isVecListFourQHWordIndexed() const {
1574     if (!isDoubleSpacedVectorIndexed()) return false;
1575     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1576   }
1577 
1578   bool isVecListFourDWordIndexed() const {
1579     if (!isSingleSpacedVectorIndexed()) return false;
1580     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1581   }
1582 
1583   bool isVectorIndex8() const {
1584     if (Kind != k_VectorIndex) return false;
1585     return VectorIndex.Val < 8;
1586   }
1587   bool isVectorIndex16() const {
1588     if (Kind != k_VectorIndex) return false;
1589     return VectorIndex.Val < 4;
1590   }
1591   bool isVectorIndex32() const {
1592     if (Kind != k_VectorIndex) return false;
1593     return VectorIndex.Val < 2;
1594   }
1595 
1596   bool isNEONi8splat() const {
1597     if (!isImm()) return false;
1598     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1599     // Must be a constant.
1600     if (!CE) return false;
1601     int64_t Value = CE->getValue();
1602     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1603     // value.
1604     return Value >= 0 && Value < 256;
1605   }
1606 
1607   bool isNEONi16splat() const {
1608     if (isNEONByteReplicate(2))
1609       return false; // Leave that for bytes replication and forbid by default.
1610     if (!isImm())
1611       return false;
1612     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1613     // Must be a constant.
1614     if (!CE) return false;
1615     unsigned Value = CE->getValue();
1616     return ARM_AM::isNEONi16splat(Value);
1617   }
1618 
1619   bool isNEONi16splatNot() const {
1620     if (!isImm())
1621       return false;
1622     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1623     // Must be a constant.
1624     if (!CE) return false;
1625     unsigned Value = CE->getValue();
1626     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1627   }
1628 
1629   bool isNEONi32splat() const {
1630     if (isNEONByteReplicate(4))
1631       return false; // Leave that for bytes replication and forbid by default.
1632     if (!isImm())
1633       return false;
1634     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1635     // Must be a constant.
1636     if (!CE) return false;
1637     unsigned Value = CE->getValue();
1638     return ARM_AM::isNEONi32splat(Value);
1639   }
1640 
1641   bool isNEONi32splatNot() const {
1642     if (!isImm())
1643       return false;
1644     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1645     // Must be a constant.
1646     if (!CE) return false;
1647     unsigned Value = CE->getValue();
1648     return ARM_AM::isNEONi32splat(~Value);
1649   }
1650 
1651   bool isNEONByteReplicate(unsigned NumBytes) const {
1652     if (!isImm())
1653       return false;
1654     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1655     // Must be a constant.
1656     if (!CE)
1657       return false;
1658     int64_t Value = CE->getValue();
1659     if (!Value)
1660       return false; // Don't bother with zero.
1661 
1662     unsigned char B = Value & 0xff;
1663     for (unsigned i = 1; i < NumBytes; ++i) {
1664       Value >>= 8;
1665       if ((Value & 0xff) != B)
1666         return false;
1667     }
1668     return true;
1669   }
1670   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1671   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1672   bool isNEONi32vmov() const {
1673     if (isNEONByteReplicate(4))
1674       return false; // Let it to be classified as byte-replicate case.
1675     if (!isImm())
1676       return false;
1677     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1678     // Must be a constant.
1679     if (!CE)
1680       return false;
1681     int64_t Value = CE->getValue();
1682     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1683     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1684     // FIXME: This is probably wrong and a copy and paste from previous example
1685     return (Value >= 0 && Value < 256) ||
1686       (Value >= 0x0100 && Value <= 0xff00) ||
1687       (Value >= 0x010000 && Value <= 0xff0000) ||
1688       (Value >= 0x01000000 && Value <= 0xff000000) ||
1689       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1690       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1691   }
1692   bool isNEONi32vmovNeg() const {
1693     if (!isImm()) return false;
1694     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1695     // Must be a constant.
1696     if (!CE) return false;
1697     int64_t Value = ~CE->getValue();
1698     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1699     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1700     // FIXME: This is probably wrong and a copy and paste from previous example
1701     return (Value >= 0 && Value < 256) ||
1702       (Value >= 0x0100 && Value <= 0xff00) ||
1703       (Value >= 0x010000 && Value <= 0xff0000) ||
1704       (Value >= 0x01000000 && Value <= 0xff000000) ||
1705       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1706       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1707   }
1708 
1709   bool isNEONi64splat() const {
1710     if (!isImm()) return false;
1711     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1712     // Must be a constant.
1713     if (!CE) return false;
1714     uint64_t Value = CE->getValue();
1715     // i64 value with each byte being either 0 or 0xff.
1716     for (unsigned i = 0; i < 8; ++i)
1717       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1718     return true;
1719   }
1720 
1721   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1722     // Add as immediates when possible.  Null MCExpr = 0.
1723     if (!Expr)
1724       Inst.addOperand(MCOperand::createImm(0));
1725     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1726       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1727     else
1728       Inst.addOperand(MCOperand::createExpr(Expr));
1729   }
1730 
1731   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1732     assert(N == 2 && "Invalid number of operands!");
1733     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1734     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1735     Inst.addOperand(MCOperand::createReg(RegNum));
1736   }
1737 
1738   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1739     assert(N == 1 && "Invalid number of operands!");
1740     Inst.addOperand(MCOperand::createImm(getCoproc()));
1741   }
1742 
1743   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1744     assert(N == 1 && "Invalid number of operands!");
1745     Inst.addOperand(MCOperand::createImm(getCoproc()));
1746   }
1747 
1748   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1749     assert(N == 1 && "Invalid number of operands!");
1750     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1751   }
1752 
1753   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1754     assert(N == 1 && "Invalid number of operands!");
1755     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1756   }
1757 
1758   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1759     assert(N == 1 && "Invalid number of operands!");
1760     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1761   }
1762 
1763   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1764     assert(N == 1 && "Invalid number of operands!");
1765     Inst.addOperand(MCOperand::createReg(getReg()));
1766   }
1767 
1768   void addRegOperands(MCInst &Inst, unsigned N) const {
1769     assert(N == 1 && "Invalid number of operands!");
1770     Inst.addOperand(MCOperand::createReg(getReg()));
1771   }
1772 
1773   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1774     assert(N == 3 && "Invalid number of operands!");
1775     assert(isRegShiftedReg() &&
1776            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1777     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1778     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1779     Inst.addOperand(MCOperand::createImm(
1780       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1781   }
1782 
1783   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1784     assert(N == 2 && "Invalid number of operands!");
1785     assert(isRegShiftedImm() &&
1786            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1787     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1788     // Shift of #32 is encoded as 0 where permitted
1789     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1790     Inst.addOperand(MCOperand::createImm(
1791       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1792   }
1793 
1794   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1795     assert(N == 1 && "Invalid number of operands!");
1796     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1797                                          ShifterImm.Imm));
1798   }
1799 
1800   void addRegListOperands(MCInst &Inst, unsigned N) const {
1801     assert(N == 1 && "Invalid number of operands!");
1802     const SmallVectorImpl<unsigned> &RegList = getRegList();
1803     for (SmallVectorImpl<unsigned>::const_iterator
1804            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1805       Inst.addOperand(MCOperand::createReg(*I));
1806   }
1807 
1808   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1809     addRegListOperands(Inst, N);
1810   }
1811 
1812   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1813     addRegListOperands(Inst, N);
1814   }
1815 
1816   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1817     assert(N == 1 && "Invalid number of operands!");
1818     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1819     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1820   }
1821 
1822   void addModImmOperands(MCInst &Inst, unsigned N) const {
1823     assert(N == 1 && "Invalid number of operands!");
1824 
1825     // Support for fixups (MCFixup)
1826     if (isImm())
1827       return addImmOperands(Inst, N);
1828 
1829     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
1830   }
1831 
1832   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1833     assert(N == 1 && "Invalid number of operands!");
1834     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1835     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1836     Inst.addOperand(MCOperand::createImm(Enc));
1837   }
1838 
1839   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1840     assert(N == 1 && "Invalid number of operands!");
1841     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1842     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1843     Inst.addOperand(MCOperand::createImm(Enc));
1844   }
1845 
1846   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1847     assert(N == 1 && "Invalid number of operands!");
1848     // Munge the lsb/width into a bitfield mask.
1849     unsigned lsb = Bitfield.LSB;
1850     unsigned width = Bitfield.Width;
1851     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1852     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1853                       (32 - (lsb + width)));
1854     Inst.addOperand(MCOperand::createImm(Mask));
1855   }
1856 
1857   void addImmOperands(MCInst &Inst, unsigned N) const {
1858     assert(N == 1 && "Invalid number of operands!");
1859     addExpr(Inst, getImm());
1860   }
1861 
1862   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1863     assert(N == 1 && "Invalid number of operands!");
1864     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1865     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
1866   }
1867 
1868   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1869     assert(N == 1 && "Invalid number of operands!");
1870     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1871     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
1872   }
1873 
1874   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1875     assert(N == 1 && "Invalid number of operands!");
1876     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1877     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1878     Inst.addOperand(MCOperand::createImm(Val));
1879   }
1880 
1881   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1882     assert(N == 1 && "Invalid number of operands!");
1883     // FIXME: We really want to scale the value here, but the LDRD/STRD
1884     // instruction don't encode operands that way yet.
1885     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1886     Inst.addOperand(MCOperand::createImm(CE->getValue()));
1887   }
1888 
1889   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1890     assert(N == 1 && "Invalid number of operands!");
1891     // The immediate is scaled by four in the encoding and is stored
1892     // in the MCInst as such. Lop off the low two bits here.
1893     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1894     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1895   }
1896 
1897   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1898     assert(N == 1 && "Invalid number of operands!");
1899     // The immediate is scaled by four in the encoding and is stored
1900     // in the MCInst as such. Lop off the low two bits here.
1901     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1902     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
1903   }
1904 
1905   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1906     assert(N == 1 && "Invalid number of operands!");
1907     // The immediate is scaled by four in the encoding and is stored
1908     // in the MCInst as such. Lop off the low two bits here.
1909     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1910     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1911   }
1912 
1913   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1914     assert(N == 1 && "Invalid number of operands!");
1915     // The constant encodes as the immediate-1, and we store in the instruction
1916     // the bits as encoded, so subtract off one here.
1917     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1918     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1919   }
1920 
1921   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1922     assert(N == 1 && "Invalid number of operands!");
1923     // The constant encodes as the immediate-1, and we store in the instruction
1924     // the bits as encoded, so subtract off one here.
1925     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1926     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1927   }
1928 
1929   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1930     assert(N == 1 && "Invalid number of operands!");
1931     // The constant encodes as the immediate, except for 32, which encodes as
1932     // zero.
1933     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1934     unsigned Imm = CE->getValue();
1935     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
1936   }
1937 
1938   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1939     assert(N == 1 && "Invalid number of operands!");
1940     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1941     // the instruction as well.
1942     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1943     int Val = CE->getValue();
1944     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
1945   }
1946 
1947   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
1948     assert(N == 1 && "Invalid number of operands!");
1949     // The operand is actually a t2_so_imm, but we have its bitwise
1950     // negation in the assembly source, so twiddle it here.
1951     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1952     Inst.addOperand(MCOperand::createImm(~CE->getValue()));
1953   }
1954 
1955   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
1956     assert(N == 1 && "Invalid number of operands!");
1957     // The operand is actually a t2_so_imm, but we have its
1958     // negation in the assembly source, so twiddle it here.
1959     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1960     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1961   }
1962 
1963   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
1964     assert(N == 1 && "Invalid number of operands!");
1965     // The operand is actually an imm0_4095, but we have its
1966     // negation in the assembly source, so twiddle it here.
1967     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1968     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1969   }
1970 
1971   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
1972     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
1973       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
1974       return;
1975     }
1976 
1977     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1978     assert(SR && "Unknown value type!");
1979     Inst.addOperand(MCOperand::createExpr(SR));
1980   }
1981 
1982   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
1983     assert(N == 1 && "Invalid number of operands!");
1984     if (isImm()) {
1985       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1986       if (CE) {
1987         Inst.addOperand(MCOperand::createImm(CE->getValue()));
1988         return;
1989       }
1990 
1991       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1992 
1993       assert(SR && "Unknown value type!");
1994       Inst.addOperand(MCOperand::createExpr(SR));
1995       return;
1996     }
1997 
1998     assert(isMem()  && "Unknown value type!");
1999     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2000     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2001   }
2002 
2003   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2004     assert(N == 1 && "Invalid number of operands!");
2005     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2006   }
2007 
2008   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2009     assert(N == 1 && "Invalid number of operands!");
2010     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2011   }
2012 
2013   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2014     assert(N == 1 && "Invalid number of operands!");
2015     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2016   }
2017 
2018   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2019     assert(N == 1 && "Invalid number of operands!");
2020     int32_t Imm = Memory.OffsetImm->getValue();
2021     Inst.addOperand(MCOperand::createImm(Imm));
2022   }
2023 
2024   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2025     assert(N == 1 && "Invalid number of operands!");
2026     assert(isImm() && "Not an immediate!");
2027 
2028     // If we have an immediate that's not a constant, treat it as a label
2029     // reference needing a fixup.
2030     if (!isa<MCConstantExpr>(getImm())) {
2031       Inst.addOperand(MCOperand::createExpr(getImm()));
2032       return;
2033     }
2034 
2035     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2036     int Val = CE->getValue();
2037     Inst.addOperand(MCOperand::createImm(Val));
2038   }
2039 
2040   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2041     assert(N == 2 && "Invalid number of operands!");
2042     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2043     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2044   }
2045 
2046   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2047     addAlignedMemoryOperands(Inst, N);
2048   }
2049 
2050   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2051     addAlignedMemoryOperands(Inst, N);
2052   }
2053 
2054   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2055     addAlignedMemoryOperands(Inst, N);
2056   }
2057 
2058   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2059     addAlignedMemoryOperands(Inst, N);
2060   }
2061 
2062   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2063     addAlignedMemoryOperands(Inst, N);
2064   }
2065 
2066   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2067     addAlignedMemoryOperands(Inst, N);
2068   }
2069 
2070   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2071     addAlignedMemoryOperands(Inst, N);
2072   }
2073 
2074   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2075     addAlignedMemoryOperands(Inst, N);
2076   }
2077 
2078   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2079     addAlignedMemoryOperands(Inst, N);
2080   }
2081 
2082   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2083     addAlignedMemoryOperands(Inst, N);
2084   }
2085 
2086   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2087     addAlignedMemoryOperands(Inst, N);
2088   }
2089 
2090   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2091     assert(N == 3 && "Invalid number of operands!");
2092     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2093     if (!Memory.OffsetRegNum) {
2094       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2095       // Special case for #-0
2096       if (Val == INT32_MIN) Val = 0;
2097       if (Val < 0) Val = -Val;
2098       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2099     } else {
2100       // For register offset, we encode the shift type and negation flag
2101       // here.
2102       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2103                               Memory.ShiftImm, Memory.ShiftType);
2104     }
2105     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2106     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2107     Inst.addOperand(MCOperand::createImm(Val));
2108   }
2109 
2110   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2111     assert(N == 2 && "Invalid number of operands!");
2112     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2113     assert(CE && "non-constant AM2OffsetImm operand!");
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::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2120     Inst.addOperand(MCOperand::createReg(0));
2121     Inst.addOperand(MCOperand::createImm(Val));
2122   }
2123 
2124   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2125     assert(N == 3 && "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::createReg(0));
2132       Inst.addOperand(MCOperand::createImm(0));
2133       return;
2134     }
2135 
2136     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2137     if (!Memory.OffsetRegNum) {
2138       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2139       // Special case for #-0
2140       if (Val == INT32_MIN) Val = 0;
2141       if (Val < 0) Val = -Val;
2142       Val = ARM_AM::getAM3Opc(AddSub, Val);
2143     } else {
2144       // For register offset, we encode the shift type and negation flag
2145       // here.
2146       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2147     }
2148     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2149     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2150     Inst.addOperand(MCOperand::createImm(Val));
2151   }
2152 
2153   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2154     assert(N == 2 && "Invalid number of operands!");
2155     if (Kind == k_PostIndexRegister) {
2156       int32_t Val =
2157         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2158       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2159       Inst.addOperand(MCOperand::createImm(Val));
2160       return;
2161     }
2162 
2163     // Constant offset.
2164     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2165     int32_t Val = CE->getValue();
2166     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2167     // Special case for #-0
2168     if (Val == INT32_MIN) Val = 0;
2169     if (Val < 0) Val = -Val;
2170     Val = ARM_AM::getAM3Opc(AddSub, Val);
2171     Inst.addOperand(MCOperand::createReg(0));
2172     Inst.addOperand(MCOperand::createImm(Val));
2173   }
2174 
2175   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2176     assert(N == 2 && "Invalid number of operands!");
2177     // If we have an immediate that's not a constant, treat it as a label
2178     // reference needing a fixup. If it is a constant, it's something else
2179     // and we reject it.
2180     if (isImm()) {
2181       Inst.addOperand(MCOperand::createExpr(getImm()));
2182       Inst.addOperand(MCOperand::createImm(0));
2183       return;
2184     }
2185 
2186     // The lower two bits are always zero and as such are not encoded.
2187     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2188     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2189     // Special case for #-0
2190     if (Val == INT32_MIN) Val = 0;
2191     if (Val < 0) Val = -Val;
2192     Val = ARM_AM::getAM5Opc(AddSub, Val);
2193     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2194     Inst.addOperand(MCOperand::createImm(Val));
2195   }
2196 
2197   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2198     assert(N == 2 && "Invalid number of operands!");
2199     // If we have an immediate that's not a constant, treat it as a label
2200     // reference needing a fixup. If it is a constant, it's something else
2201     // and we reject it.
2202     if (isImm()) {
2203       Inst.addOperand(MCOperand::createExpr(getImm()));
2204       Inst.addOperand(MCOperand::createImm(0));
2205       return;
2206     }
2207 
2208     // The lower bit is always zero and as such is not encoded.
2209     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2210     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2211     // Special case for #-0
2212     if (Val == INT32_MIN) Val = 0;
2213     if (Val < 0) Val = -Val;
2214     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2215     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2216     Inst.addOperand(MCOperand::createImm(Val));
2217   }
2218 
2219   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2220     assert(N == 2 && "Invalid number of operands!");
2221     // If we have an immediate that's not a constant, treat it as a label
2222     // reference needing a fixup. If it is a constant, it's something else
2223     // and we reject it.
2224     if (isImm()) {
2225       Inst.addOperand(MCOperand::createExpr(getImm()));
2226       Inst.addOperand(MCOperand::createImm(0));
2227       return;
2228     }
2229 
2230     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2231     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2232     Inst.addOperand(MCOperand::createImm(Val));
2233   }
2234 
2235   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2236     assert(N == 2 && "Invalid number of operands!");
2237     // The lower two bits are always zero and as such are not encoded.
2238     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2239     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2240     Inst.addOperand(MCOperand::createImm(Val));
2241   }
2242 
2243   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2244     assert(N == 2 && "Invalid number of operands!");
2245     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2246     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2247     Inst.addOperand(MCOperand::createImm(Val));
2248   }
2249 
2250   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2251     addMemImm8OffsetOperands(Inst, N);
2252   }
2253 
2254   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2255     addMemImm8OffsetOperands(Inst, N);
2256   }
2257 
2258   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2259     assert(N == 2 && "Invalid number of operands!");
2260     // If this is an immediate, it's a label reference.
2261     if (isImm()) {
2262       addExpr(Inst, getImm());
2263       Inst.addOperand(MCOperand::createImm(0));
2264       return;
2265     }
2266 
2267     // Otherwise, it's a normal memory reg+offset.
2268     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2269     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2270     Inst.addOperand(MCOperand::createImm(Val));
2271   }
2272 
2273   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2274     assert(N == 2 && "Invalid number of operands!");
2275     // If this is an immediate, it's a label reference.
2276     if (isImm()) {
2277       addExpr(Inst, getImm());
2278       Inst.addOperand(MCOperand::createImm(0));
2279       return;
2280     }
2281 
2282     // Otherwise, it's a normal memory reg+offset.
2283     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2284     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2285     Inst.addOperand(MCOperand::createImm(Val));
2286   }
2287 
2288   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2289     assert(N == 1 && "Invalid number of operands!");
2290     // This is container for the immediate that we will create the constant
2291     // pool from
2292     addExpr(Inst, getConstantPoolImm());
2293     return;
2294   }
2295 
2296   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2297     assert(N == 2 && "Invalid number of operands!");
2298     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2299     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2300   }
2301 
2302   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2303     assert(N == 2 && "Invalid number of operands!");
2304     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2305     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2306   }
2307 
2308   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2309     assert(N == 3 && "Invalid number of operands!");
2310     unsigned Val =
2311       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2312                         Memory.ShiftImm, Memory.ShiftType);
2313     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2314     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2315     Inst.addOperand(MCOperand::createImm(Val));
2316   }
2317 
2318   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2319     assert(N == 3 && "Invalid number of operands!");
2320     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2321     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2322     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2323   }
2324 
2325   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2326     assert(N == 2 && "Invalid number of operands!");
2327     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2328     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2329   }
2330 
2331   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2332     assert(N == 2 && "Invalid number of operands!");
2333     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2334     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2335     Inst.addOperand(MCOperand::createImm(Val));
2336   }
2337 
2338   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2339     assert(N == 2 && "Invalid number of operands!");
2340     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2341     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2342     Inst.addOperand(MCOperand::createImm(Val));
2343   }
2344 
2345   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2346     assert(N == 2 && "Invalid number of operands!");
2347     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2348     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2349     Inst.addOperand(MCOperand::createImm(Val));
2350   }
2351 
2352   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2353     assert(N == 2 && "Invalid number of operands!");
2354     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2355     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2356     Inst.addOperand(MCOperand::createImm(Val));
2357   }
2358 
2359   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2360     assert(N == 1 && "Invalid number of operands!");
2361     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2362     assert(CE && "non-constant post-idx-imm8 operand!");
2363     int Imm = CE->getValue();
2364     bool isAdd = Imm >= 0;
2365     if (Imm == INT32_MIN) Imm = 0;
2366     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2367     Inst.addOperand(MCOperand::createImm(Imm));
2368   }
2369 
2370   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2371     assert(N == 1 && "Invalid number of operands!");
2372     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2373     assert(CE && "non-constant post-idx-imm8s4 operand!");
2374     int Imm = CE->getValue();
2375     bool isAdd = Imm >= 0;
2376     if (Imm == INT32_MIN) Imm = 0;
2377     // Immediate is scaled by 4.
2378     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2379     Inst.addOperand(MCOperand::createImm(Imm));
2380   }
2381 
2382   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2383     assert(N == 2 && "Invalid number of operands!");
2384     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2385     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2386   }
2387 
2388   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2389     assert(N == 2 && "Invalid number of operands!");
2390     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2391     // The sign, shift type, and shift amount are encoded in a single operand
2392     // using the AM2 encoding helpers.
2393     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2394     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2395                                      PostIdxReg.ShiftTy);
2396     Inst.addOperand(MCOperand::createImm(Imm));
2397   }
2398 
2399   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2400     assert(N == 1 && "Invalid number of operands!");
2401     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2402   }
2403 
2404   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2405     assert(N == 1 && "Invalid number of operands!");
2406     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2407   }
2408 
2409   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2410     assert(N == 1 && "Invalid number of operands!");
2411     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2412   }
2413 
2414   void addVecListOperands(MCInst &Inst, unsigned N) const {
2415     assert(N == 1 && "Invalid number of operands!");
2416     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2417   }
2418 
2419   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2420     assert(N == 2 && "Invalid number of operands!");
2421     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2422     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2423   }
2424 
2425   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2426     assert(N == 1 && "Invalid number of operands!");
2427     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2428   }
2429 
2430   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2431     assert(N == 1 && "Invalid number of operands!");
2432     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2433   }
2434 
2435   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2436     assert(N == 1 && "Invalid number of operands!");
2437     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2438   }
2439 
2440   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2441     assert(N == 1 && "Invalid number of operands!");
2442     // The immediate encodes the type of constant as well as the value.
2443     // Mask in that this is an i8 splat.
2444     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2445     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2446   }
2447 
2448   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2449     assert(N == 1 && "Invalid number of operands!");
2450     // The immediate encodes the type of constant as well as the value.
2451     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2452     unsigned Value = CE->getValue();
2453     Value = ARM_AM::encodeNEONi16splat(Value);
2454     Inst.addOperand(MCOperand::createImm(Value));
2455   }
2456 
2457   void addNEONi16splatNotOperands(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     unsigned Value = CE->getValue();
2462     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2463     Inst.addOperand(MCOperand::createImm(Value));
2464   }
2465 
2466   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2467     assert(N == 1 && "Invalid number of operands!");
2468     // The immediate encodes the type of constant as well as the value.
2469     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2470     unsigned Value = CE->getValue();
2471     Value = ARM_AM::encodeNEONi32splat(Value);
2472     Inst.addOperand(MCOperand::createImm(Value));
2473   }
2474 
2475   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2476     assert(N == 1 && "Invalid number of operands!");
2477     // The immediate encodes the type of constant as well as the value.
2478     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2479     unsigned Value = CE->getValue();
2480     Value = ARM_AM::encodeNEONi32splat(~Value);
2481     Inst.addOperand(MCOperand::createImm(Value));
2482   }
2483 
2484   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2485     assert(N == 1 && "Invalid number of operands!");
2486     // The immediate encodes the type of constant as well as the value.
2487     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2488     unsigned Value = CE->getValue();
2489     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2490             Inst.getOpcode() == ARM::VMOVv16i8) &&
2491            "All vmvn instructions that wants to replicate non-zero byte "
2492            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2493     unsigned B = ((~Value) & 0xff);
2494     B |= 0xe00; // cmode = 0b1110
2495     Inst.addOperand(MCOperand::createImm(B));
2496   }
2497   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2498     assert(N == 1 && "Invalid number of operands!");
2499     // The immediate encodes the type of constant as well as the value.
2500     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2501     unsigned Value = CE->getValue();
2502     if (Value >= 256 && Value <= 0xffff)
2503       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2504     else if (Value > 0xffff && Value <= 0xffffff)
2505       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2506     else if (Value > 0xffffff)
2507       Value = (Value >> 24) | 0x600;
2508     Inst.addOperand(MCOperand::createImm(Value));
2509   }
2510 
2511   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2512     assert(N == 1 && "Invalid number of operands!");
2513     // The immediate encodes the type of constant as well as the value.
2514     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2515     unsigned Value = CE->getValue();
2516     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2517             Inst.getOpcode() == ARM::VMOVv16i8) &&
2518            "All instructions that wants to replicate non-zero byte "
2519            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2520     unsigned B = Value & 0xff;
2521     B |= 0xe00; // cmode = 0b1110
2522     Inst.addOperand(MCOperand::createImm(B));
2523   }
2524   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2525     assert(N == 1 && "Invalid number of operands!");
2526     // The immediate encodes the type of constant as well as the value.
2527     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2528     unsigned Value = ~CE->getValue();
2529     if (Value >= 256 && Value <= 0xffff)
2530       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2531     else if (Value > 0xffff && Value <= 0xffffff)
2532       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2533     else if (Value > 0xffffff)
2534       Value = (Value >> 24) | 0x600;
2535     Inst.addOperand(MCOperand::createImm(Value));
2536   }
2537 
2538   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2539     assert(N == 1 && "Invalid number of operands!");
2540     // The immediate encodes the type of constant as well as the value.
2541     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2542     uint64_t Value = CE->getValue();
2543     unsigned Imm = 0;
2544     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2545       Imm |= (Value & 1) << i;
2546     }
2547     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2548   }
2549 
2550   void print(raw_ostream &OS) const override;
2551 
2552   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2553     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2554     Op->ITMask.Mask = Mask;
2555     Op->StartLoc = S;
2556     Op->EndLoc = S;
2557     return Op;
2558   }
2559 
2560   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2561                                                     SMLoc S) {
2562     auto Op = make_unique<ARMOperand>(k_CondCode);
2563     Op->CC.Val = CC;
2564     Op->StartLoc = S;
2565     Op->EndLoc = S;
2566     return Op;
2567   }
2568 
2569   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2570     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2571     Op->Cop.Val = CopVal;
2572     Op->StartLoc = S;
2573     Op->EndLoc = S;
2574     return Op;
2575   }
2576 
2577   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2578     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2579     Op->Cop.Val = CopVal;
2580     Op->StartLoc = S;
2581     Op->EndLoc = S;
2582     return Op;
2583   }
2584 
2585   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2586                                                         SMLoc E) {
2587     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2588     Op->Cop.Val = Val;
2589     Op->StartLoc = S;
2590     Op->EndLoc = E;
2591     return Op;
2592   }
2593 
2594   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2595     auto Op = make_unique<ARMOperand>(k_CCOut);
2596     Op->Reg.RegNum = RegNum;
2597     Op->StartLoc = S;
2598     Op->EndLoc = S;
2599     return Op;
2600   }
2601 
2602   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2603     auto Op = make_unique<ARMOperand>(k_Token);
2604     Op->Tok.Data = Str.data();
2605     Op->Tok.Length = Str.size();
2606     Op->StartLoc = S;
2607     Op->EndLoc = S;
2608     return Op;
2609   }
2610 
2611   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2612                                                SMLoc E) {
2613     auto Op = make_unique<ARMOperand>(k_Register);
2614     Op->Reg.RegNum = RegNum;
2615     Op->StartLoc = S;
2616     Op->EndLoc = E;
2617     return Op;
2618   }
2619 
2620   static std::unique_ptr<ARMOperand>
2621   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2622                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2623                         SMLoc E) {
2624     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2625     Op->RegShiftedReg.ShiftTy = ShTy;
2626     Op->RegShiftedReg.SrcReg = SrcReg;
2627     Op->RegShiftedReg.ShiftReg = ShiftReg;
2628     Op->RegShiftedReg.ShiftImm = ShiftImm;
2629     Op->StartLoc = S;
2630     Op->EndLoc = E;
2631     return Op;
2632   }
2633 
2634   static std::unique_ptr<ARMOperand>
2635   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2636                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2637     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2638     Op->RegShiftedImm.ShiftTy = ShTy;
2639     Op->RegShiftedImm.SrcReg = SrcReg;
2640     Op->RegShiftedImm.ShiftImm = ShiftImm;
2641     Op->StartLoc = S;
2642     Op->EndLoc = E;
2643     return Op;
2644   }
2645 
2646   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2647                                                       SMLoc S, SMLoc E) {
2648     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2649     Op->ShifterImm.isASR = isASR;
2650     Op->ShifterImm.Imm = Imm;
2651     Op->StartLoc = S;
2652     Op->EndLoc = E;
2653     return Op;
2654   }
2655 
2656   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2657                                                   SMLoc E) {
2658     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2659     Op->RotImm.Imm = Imm;
2660     Op->StartLoc = S;
2661     Op->EndLoc = E;
2662     return Op;
2663   }
2664 
2665   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2666                                                   SMLoc S, SMLoc E) {
2667     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2668     Op->ModImm.Bits = Bits;
2669     Op->ModImm.Rot = Rot;
2670     Op->StartLoc = S;
2671     Op->EndLoc = E;
2672     return Op;
2673   }
2674 
2675   static std::unique_ptr<ARMOperand>
2676   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2677     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
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   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2686     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2687     Op->Bitfield.LSB = LSB;
2688     Op->Bitfield.Width = Width;
2689     Op->StartLoc = S;
2690     Op->EndLoc = E;
2691     return Op;
2692   }
2693 
2694   static std::unique_ptr<ARMOperand>
2695   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2696                 SMLoc StartLoc, SMLoc EndLoc) {
2697     assert (Regs.size() > 0 && "RegList contains no registers?");
2698     KindTy Kind = k_RegisterList;
2699 
2700     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2701       Kind = k_DPRRegisterList;
2702     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2703              contains(Regs.front().second))
2704       Kind = k_SPRRegisterList;
2705 
2706     // Sort based on the register encoding values.
2707     array_pod_sort(Regs.begin(), Regs.end());
2708 
2709     auto Op = make_unique<ARMOperand>(Kind);
2710     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2711            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2712       Op->Registers.push_back(I->second);
2713     Op->StartLoc = StartLoc;
2714     Op->EndLoc = EndLoc;
2715     return Op;
2716   }
2717 
2718   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2719                                                       unsigned Count,
2720                                                       bool isDoubleSpaced,
2721                                                       SMLoc S, SMLoc E) {
2722     auto Op = make_unique<ARMOperand>(k_VectorList);
2723     Op->VectorList.RegNum = RegNum;
2724     Op->VectorList.Count = Count;
2725     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2726     Op->StartLoc = S;
2727     Op->EndLoc = E;
2728     return Op;
2729   }
2730 
2731   static std::unique_ptr<ARMOperand>
2732   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2733                            SMLoc S, SMLoc E) {
2734     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2735     Op->VectorList.RegNum = RegNum;
2736     Op->VectorList.Count = Count;
2737     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2738     Op->StartLoc = S;
2739     Op->EndLoc = E;
2740     return Op;
2741   }
2742 
2743   static std::unique_ptr<ARMOperand>
2744   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2745                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2746     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2747     Op->VectorList.RegNum = RegNum;
2748     Op->VectorList.Count = Count;
2749     Op->VectorList.LaneIndex = Index;
2750     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2751     Op->StartLoc = S;
2752     Op->EndLoc = E;
2753     return Op;
2754   }
2755 
2756   static std::unique_ptr<ARMOperand>
2757   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2758     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2759     Op->VectorIndex.Val = Idx;
2760     Op->StartLoc = S;
2761     Op->EndLoc = E;
2762     return Op;
2763   }
2764 
2765   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2766                                                SMLoc E) {
2767     auto Op = make_unique<ARMOperand>(k_Immediate);
2768     Op->Imm.Val = Val;
2769     Op->StartLoc = S;
2770     Op->EndLoc = E;
2771     return Op;
2772   }
2773 
2774   static std::unique_ptr<ARMOperand>
2775   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2776             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2777             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2778             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2779     auto Op = make_unique<ARMOperand>(k_Memory);
2780     Op->Memory.BaseRegNum = BaseRegNum;
2781     Op->Memory.OffsetImm = OffsetImm;
2782     Op->Memory.OffsetRegNum = OffsetRegNum;
2783     Op->Memory.ShiftType = ShiftType;
2784     Op->Memory.ShiftImm = ShiftImm;
2785     Op->Memory.Alignment = Alignment;
2786     Op->Memory.isNegative = isNegative;
2787     Op->StartLoc = S;
2788     Op->EndLoc = E;
2789     Op->AlignmentLoc = AlignmentLoc;
2790     return Op;
2791   }
2792 
2793   static std::unique_ptr<ARMOperand>
2794   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2795                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2796     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2797     Op->PostIdxReg.RegNum = RegNum;
2798     Op->PostIdxReg.isAdd = isAdd;
2799     Op->PostIdxReg.ShiftTy = ShiftTy;
2800     Op->PostIdxReg.ShiftImm = ShiftImm;
2801     Op->StartLoc = S;
2802     Op->EndLoc = E;
2803     return Op;
2804   }
2805 
2806   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2807                                                          SMLoc S) {
2808     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2809     Op->MBOpt.Val = Opt;
2810     Op->StartLoc = S;
2811     Op->EndLoc = S;
2812     return Op;
2813   }
2814 
2815   static std::unique_ptr<ARMOperand>
2816   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2817     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2818     Op->ISBOpt.Val = Opt;
2819     Op->StartLoc = S;
2820     Op->EndLoc = S;
2821     return Op;
2822   }
2823 
2824   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2825                                                       SMLoc S) {
2826     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2827     Op->IFlags.Val = IFlags;
2828     Op->StartLoc = S;
2829     Op->EndLoc = S;
2830     return Op;
2831   }
2832 
2833   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2834     auto Op = make_unique<ARMOperand>(k_MSRMask);
2835     Op->MMask.Val = MMask;
2836     Op->StartLoc = S;
2837     Op->EndLoc = S;
2838     return Op;
2839   }
2840 
2841   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2842     auto Op = make_unique<ARMOperand>(k_BankedReg);
2843     Op->BankedReg.Val = Reg;
2844     Op->StartLoc = S;
2845     Op->EndLoc = S;
2846     return Op;
2847   }
2848 };
2849 
2850 } // end anonymous namespace.
2851 
2852 void ARMOperand::print(raw_ostream &OS) const {
2853   switch (Kind) {
2854   case k_CondCode:
2855     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2856     break;
2857   case k_CCOut:
2858     OS << "<ccout " << getReg() << ">";
2859     break;
2860   case k_ITCondMask: {
2861     static const char *const MaskStr[] = {
2862       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2863       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2864     };
2865     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2866     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2867     break;
2868   }
2869   case k_CoprocNum:
2870     OS << "<coprocessor number: " << getCoproc() << ">";
2871     break;
2872   case k_CoprocReg:
2873     OS << "<coprocessor register: " << getCoproc() << ">";
2874     break;
2875   case k_CoprocOption:
2876     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2877     break;
2878   case k_MSRMask:
2879     OS << "<mask: " << getMSRMask() << ">";
2880     break;
2881   case k_BankedReg:
2882     OS << "<banked reg: " << getBankedReg() << ">";
2883     break;
2884   case k_Immediate:
2885     OS << *getImm();
2886     break;
2887   case k_MemBarrierOpt:
2888     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2889     break;
2890   case k_InstSyncBarrierOpt:
2891     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2892     break;
2893   case k_Memory:
2894     OS << "<memory "
2895        << " base:" << Memory.BaseRegNum;
2896     OS << ">";
2897     break;
2898   case k_PostIndexRegister:
2899     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2900        << PostIdxReg.RegNum;
2901     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2902       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2903          << PostIdxReg.ShiftImm;
2904     OS << ">";
2905     break;
2906   case k_ProcIFlags: {
2907     OS << "<ARM_PROC::";
2908     unsigned IFlags = getProcIFlags();
2909     for (int i=2; i >= 0; --i)
2910       if (IFlags & (1 << i))
2911         OS << ARM_PROC::IFlagsToString(1 << i);
2912     OS << ">";
2913     break;
2914   }
2915   case k_Register:
2916     OS << "<register " << getReg() << ">";
2917     break;
2918   case k_ShifterImmediate:
2919     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2920        << " #" << ShifterImm.Imm << ">";
2921     break;
2922   case k_ShiftedRegister:
2923     OS << "<so_reg_reg "
2924        << RegShiftedReg.SrcReg << " "
2925        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2926        << " " << RegShiftedReg.ShiftReg << ">";
2927     break;
2928   case k_ShiftedImmediate:
2929     OS << "<so_reg_imm "
2930        << RegShiftedImm.SrcReg << " "
2931        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2932        << " #" << RegShiftedImm.ShiftImm << ">";
2933     break;
2934   case k_RotateImmediate:
2935     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2936     break;
2937   case k_ModifiedImmediate:
2938     OS << "<mod_imm #" << ModImm.Bits << ", #"
2939        <<  ModImm.Rot << ")>";
2940     break;
2941   case k_ConstantPoolImmediate:
2942     OS << "<constant_pool_imm #" << *getConstantPoolImm();
2943     break;
2944   case k_BitfieldDescriptor:
2945     OS << "<bitfield " << "lsb: " << Bitfield.LSB
2946        << ", width: " << Bitfield.Width << ">";
2947     break;
2948   case k_RegisterList:
2949   case k_DPRRegisterList:
2950   case k_SPRRegisterList: {
2951     OS << "<register_list ";
2952 
2953     const SmallVectorImpl<unsigned> &RegList = getRegList();
2954     for (SmallVectorImpl<unsigned>::const_iterator
2955            I = RegList.begin(), E = RegList.end(); I != E; ) {
2956       OS << *I;
2957       if (++I < E) OS << ", ";
2958     }
2959 
2960     OS << ">";
2961     break;
2962   }
2963   case k_VectorList:
2964     OS << "<vector_list " << VectorList.Count << " * "
2965        << VectorList.RegNum << ">";
2966     break;
2967   case k_VectorListAllLanes:
2968     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
2969        << VectorList.RegNum << ">";
2970     break;
2971   case k_VectorListIndexed:
2972     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
2973        << VectorList.Count << " * " << VectorList.RegNum << ">";
2974     break;
2975   case k_Token:
2976     OS << "'" << getToken() << "'";
2977     break;
2978   case k_VectorIndex:
2979     OS << "<vectorindex " << getVectorIndex() << ">";
2980     break;
2981   }
2982 }
2983 
2984 /// @name Auto-generated Match Functions
2985 /// {
2986 
2987 static unsigned MatchRegisterName(StringRef Name);
2988 
2989 /// }
2990 
2991 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
2992                                  SMLoc &StartLoc, SMLoc &EndLoc) {
2993   const AsmToken &Tok = getParser().getTok();
2994   StartLoc = Tok.getLoc();
2995   EndLoc = Tok.getEndLoc();
2996   RegNo = tryParseRegister();
2997 
2998   return (RegNo == (unsigned)-1);
2999 }
3000 
3001 /// Try to parse a register name.  The token must be an Identifier when called,
3002 /// and if it is a register name the token is eaten and the register number is
3003 /// returned.  Otherwise return -1.
3004 ///
3005 int ARMAsmParser::tryParseRegister() {
3006   MCAsmParser &Parser = getParser();
3007   const AsmToken &Tok = Parser.getTok();
3008   if (Tok.isNot(AsmToken::Identifier)) return -1;
3009 
3010   std::string lowerCase = Tok.getString().lower();
3011   unsigned RegNum = MatchRegisterName(lowerCase);
3012   if (!RegNum) {
3013     RegNum = StringSwitch<unsigned>(lowerCase)
3014       .Case("r13", ARM::SP)
3015       .Case("r14", ARM::LR)
3016       .Case("r15", ARM::PC)
3017       .Case("ip", ARM::R12)
3018       // Additional register name aliases for 'gas' compatibility.
3019       .Case("a1", ARM::R0)
3020       .Case("a2", ARM::R1)
3021       .Case("a3", ARM::R2)
3022       .Case("a4", ARM::R3)
3023       .Case("v1", ARM::R4)
3024       .Case("v2", ARM::R5)
3025       .Case("v3", ARM::R6)
3026       .Case("v4", ARM::R7)
3027       .Case("v5", ARM::R8)
3028       .Case("v6", ARM::R9)
3029       .Case("v7", ARM::R10)
3030       .Case("v8", ARM::R11)
3031       .Case("sb", ARM::R9)
3032       .Case("sl", ARM::R10)
3033       .Case("fp", ARM::R11)
3034       .Default(0);
3035   }
3036   if (!RegNum) {
3037     // Check for aliases registered via .req. Canonicalize to lower case.
3038     // That's more consistent since register names are case insensitive, and
3039     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3040     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3041     // If no match, return failure.
3042     if (Entry == RegisterReqs.end())
3043       return -1;
3044     Parser.Lex(); // Eat identifier token.
3045     return Entry->getValue();
3046   }
3047 
3048   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3049   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3050     return -1;
3051 
3052   Parser.Lex(); // Eat identifier token.
3053 
3054   return RegNum;
3055 }
3056 
3057 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3058 // If a recoverable error occurs, return 1. If an irrecoverable error
3059 // occurs, return -1. An irrecoverable error is one where tokens have been
3060 // consumed in the process of trying to parse the shifter (i.e., when it is
3061 // indeed a shifter operand, but malformed).
3062 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3063   MCAsmParser &Parser = getParser();
3064   SMLoc S = Parser.getTok().getLoc();
3065   const AsmToken &Tok = Parser.getTok();
3066   if (Tok.isNot(AsmToken::Identifier))
3067     return -1;
3068 
3069   std::string lowerCase = Tok.getString().lower();
3070   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3071       .Case("asl", ARM_AM::lsl)
3072       .Case("lsl", ARM_AM::lsl)
3073       .Case("lsr", ARM_AM::lsr)
3074       .Case("asr", ARM_AM::asr)
3075       .Case("ror", ARM_AM::ror)
3076       .Case("rrx", ARM_AM::rrx)
3077       .Default(ARM_AM::no_shift);
3078 
3079   if (ShiftTy == ARM_AM::no_shift)
3080     return 1;
3081 
3082   Parser.Lex(); // Eat the operator.
3083 
3084   // The source register for the shift has already been added to the
3085   // operand list, so we need to pop it off and combine it into the shifted
3086   // register operand instead.
3087   std::unique_ptr<ARMOperand> PrevOp(
3088       (ARMOperand *)Operands.pop_back_val().release());
3089   if (!PrevOp->isReg())
3090     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3091   int SrcReg = PrevOp->getReg();
3092 
3093   SMLoc EndLoc;
3094   int64_t Imm = 0;
3095   int ShiftReg = 0;
3096   if (ShiftTy == ARM_AM::rrx) {
3097     // RRX Doesn't have an explicit shift amount. The encoder expects
3098     // the shift register to be the same as the source register. Seems odd,
3099     // but OK.
3100     ShiftReg = SrcReg;
3101   } else {
3102     // Figure out if this is shifted by a constant or a register (for non-RRX).
3103     if (Parser.getTok().is(AsmToken::Hash) ||
3104         Parser.getTok().is(AsmToken::Dollar)) {
3105       Parser.Lex(); // Eat hash.
3106       SMLoc ImmLoc = Parser.getTok().getLoc();
3107       const MCExpr *ShiftExpr = nullptr;
3108       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3109         Error(ImmLoc, "invalid immediate shift value");
3110         return -1;
3111       }
3112       // The expression must be evaluatable as an immediate.
3113       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3114       if (!CE) {
3115         Error(ImmLoc, "invalid immediate shift value");
3116         return -1;
3117       }
3118       // Range check the immediate.
3119       // lsl, ror: 0 <= imm <= 31
3120       // lsr, asr: 0 <= imm <= 32
3121       Imm = CE->getValue();
3122       if (Imm < 0 ||
3123           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3124           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3125         Error(ImmLoc, "immediate shift value out of range");
3126         return -1;
3127       }
3128       // shift by zero is a nop. Always send it through as lsl.
3129       // ('as' compatibility)
3130       if (Imm == 0)
3131         ShiftTy = ARM_AM::lsl;
3132     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3133       SMLoc L = Parser.getTok().getLoc();
3134       EndLoc = Parser.getTok().getEndLoc();
3135       ShiftReg = tryParseRegister();
3136       if (ShiftReg == -1) {
3137         Error(L, "expected immediate or register in shift operand");
3138         return -1;
3139       }
3140     } else {
3141       Error(Parser.getTok().getLoc(),
3142             "expected immediate or register in shift operand");
3143       return -1;
3144     }
3145   }
3146 
3147   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3148     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3149                                                          ShiftReg, Imm,
3150                                                          S, EndLoc));
3151   else
3152     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3153                                                           S, EndLoc));
3154 
3155   return 0;
3156 }
3157 
3158 
3159 /// Try to parse a register name.  The token must be an Identifier when called.
3160 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3161 /// if there is a "writeback". 'true' if it's not a register.
3162 ///
3163 /// TODO this is likely to change to allow different register types and or to
3164 /// parse for a specific register type.
3165 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3166   MCAsmParser &Parser = getParser();
3167   const AsmToken &RegTok = Parser.getTok();
3168   int RegNo = tryParseRegister();
3169   if (RegNo == -1)
3170     return true;
3171 
3172   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3173                                            RegTok.getEndLoc()));
3174 
3175   const AsmToken &ExclaimTok = Parser.getTok();
3176   if (ExclaimTok.is(AsmToken::Exclaim)) {
3177     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3178                                                ExclaimTok.getLoc()));
3179     Parser.Lex(); // Eat exclaim token
3180     return false;
3181   }
3182 
3183   // Also check for an index operand. This is only legal for vector registers,
3184   // but that'll get caught OK in operand matching, so we don't need to
3185   // explicitly filter everything else out here.
3186   if (Parser.getTok().is(AsmToken::LBrac)) {
3187     SMLoc SIdx = Parser.getTok().getLoc();
3188     Parser.Lex(); // Eat left bracket token.
3189 
3190     const MCExpr *ImmVal;
3191     if (getParser().parseExpression(ImmVal))
3192       return true;
3193     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3194     if (!MCE)
3195       return TokError("immediate value expected for vector index");
3196 
3197     if (Parser.getTok().isNot(AsmToken::RBrac))
3198       return Error(Parser.getTok().getLoc(), "']' expected");
3199 
3200     SMLoc E = Parser.getTok().getEndLoc();
3201     Parser.Lex(); // Eat right bracket token.
3202 
3203     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3204                                                      SIdx, E,
3205                                                      getContext()));
3206   }
3207 
3208   return false;
3209 }
3210 
3211 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3212 /// instruction with a symbolic operand name.
3213 /// We accept "crN" syntax for GAS compatibility.
3214 /// <operand-name> ::= <prefix><number>
3215 /// If CoprocOp is 'c', then:
3216 ///   <prefix> ::= c | cr
3217 /// If CoprocOp is 'p', then :
3218 ///   <prefix> ::= p
3219 /// <number> ::= integer in range [0, 15]
3220 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3221   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3222   // but efficient.
3223   if (Name.size() < 2 || Name[0] != CoprocOp)
3224     return -1;
3225   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3226 
3227   switch (Name.size()) {
3228   default: return -1;
3229   case 1:
3230     switch (Name[0]) {
3231     default:  return -1;
3232     case '0': return 0;
3233     case '1': return 1;
3234     case '2': return 2;
3235     case '3': return 3;
3236     case '4': return 4;
3237     case '5': return 5;
3238     case '6': return 6;
3239     case '7': return 7;
3240     case '8': return 8;
3241     case '9': return 9;
3242     }
3243   case 2:
3244     if (Name[0] != '1')
3245       return -1;
3246     switch (Name[1]) {
3247     default:  return -1;
3248     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3249     // However, old cores (v5/v6) did use them in that way.
3250     case '0': return 10;
3251     case '1': return 11;
3252     case '2': return 12;
3253     case '3': return 13;
3254     case '4': return 14;
3255     case '5': return 15;
3256     }
3257   }
3258 }
3259 
3260 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3261 ARMAsmParser::OperandMatchResultTy
3262 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3263   MCAsmParser &Parser = getParser();
3264   SMLoc S = Parser.getTok().getLoc();
3265   const AsmToken &Tok = Parser.getTok();
3266   if (!Tok.is(AsmToken::Identifier))
3267     return MatchOperand_NoMatch;
3268   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3269     .Case("eq", ARMCC::EQ)
3270     .Case("ne", ARMCC::NE)
3271     .Case("hs", ARMCC::HS)
3272     .Case("cs", ARMCC::HS)
3273     .Case("lo", ARMCC::LO)
3274     .Case("cc", ARMCC::LO)
3275     .Case("mi", ARMCC::MI)
3276     .Case("pl", ARMCC::PL)
3277     .Case("vs", ARMCC::VS)
3278     .Case("vc", ARMCC::VC)
3279     .Case("hi", ARMCC::HI)
3280     .Case("ls", ARMCC::LS)
3281     .Case("ge", ARMCC::GE)
3282     .Case("lt", ARMCC::LT)
3283     .Case("gt", ARMCC::GT)
3284     .Case("le", ARMCC::LE)
3285     .Case("al", ARMCC::AL)
3286     .Default(~0U);
3287   if (CC == ~0U)
3288     return MatchOperand_NoMatch;
3289   Parser.Lex(); // Eat the token.
3290 
3291   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3292 
3293   return MatchOperand_Success;
3294 }
3295 
3296 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3297 /// token must be an Identifier when called, and if it is a coprocessor
3298 /// number, the token is eaten and the operand is added to the operand list.
3299 ARMAsmParser::OperandMatchResultTy
3300 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3301   MCAsmParser &Parser = getParser();
3302   SMLoc S = Parser.getTok().getLoc();
3303   const AsmToken &Tok = Parser.getTok();
3304   if (Tok.isNot(AsmToken::Identifier))
3305     return MatchOperand_NoMatch;
3306 
3307   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3308   if (Num == -1)
3309     return MatchOperand_NoMatch;
3310   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3311   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3312     return MatchOperand_NoMatch;
3313 
3314   Parser.Lex(); // Eat identifier token.
3315   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3316   return MatchOperand_Success;
3317 }
3318 
3319 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3320 /// token must be an Identifier when called, and if it is a coprocessor
3321 /// number, the token is eaten and the operand is added to the operand list.
3322 ARMAsmParser::OperandMatchResultTy
3323 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3324   MCAsmParser &Parser = getParser();
3325   SMLoc S = Parser.getTok().getLoc();
3326   const AsmToken &Tok = Parser.getTok();
3327   if (Tok.isNot(AsmToken::Identifier))
3328     return MatchOperand_NoMatch;
3329 
3330   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3331   if (Reg == -1)
3332     return MatchOperand_NoMatch;
3333 
3334   Parser.Lex(); // Eat identifier token.
3335   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3336   return MatchOperand_Success;
3337 }
3338 
3339 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3340 /// coproc_option : '{' imm0_255 '}'
3341 ARMAsmParser::OperandMatchResultTy
3342 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3343   MCAsmParser &Parser = getParser();
3344   SMLoc S = Parser.getTok().getLoc();
3345 
3346   // If this isn't a '{', this isn't a coprocessor immediate operand.
3347   if (Parser.getTok().isNot(AsmToken::LCurly))
3348     return MatchOperand_NoMatch;
3349   Parser.Lex(); // Eat the '{'
3350 
3351   const MCExpr *Expr;
3352   SMLoc Loc = Parser.getTok().getLoc();
3353   if (getParser().parseExpression(Expr)) {
3354     Error(Loc, "illegal expression");
3355     return MatchOperand_ParseFail;
3356   }
3357   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3358   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3359     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3360     return MatchOperand_ParseFail;
3361   }
3362   int Val = CE->getValue();
3363 
3364   // Check for and consume the closing '}'
3365   if (Parser.getTok().isNot(AsmToken::RCurly))
3366     return MatchOperand_ParseFail;
3367   SMLoc E = Parser.getTok().getEndLoc();
3368   Parser.Lex(); // Eat the '}'
3369 
3370   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3371   return MatchOperand_Success;
3372 }
3373 
3374 // For register list parsing, we need to map from raw GPR register numbering
3375 // to the enumeration values. The enumeration values aren't sorted by
3376 // register number due to our using "sp", "lr" and "pc" as canonical names.
3377 static unsigned getNextRegister(unsigned Reg) {
3378   // If this is a GPR, we need to do it manually, otherwise we can rely
3379   // on the sort ordering of the enumeration since the other reg-classes
3380   // are sane.
3381   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3382     return Reg + 1;
3383   switch(Reg) {
3384   default: llvm_unreachable("Invalid GPR number!");
3385   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3386   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3387   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3388   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3389   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3390   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3391   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3392   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3393   }
3394 }
3395 
3396 // Return the low-subreg of a given Q register.
3397 static unsigned getDRegFromQReg(unsigned QReg) {
3398   switch (QReg) {
3399   default: llvm_unreachable("expected a Q register!");
3400   case ARM::Q0:  return ARM::D0;
3401   case ARM::Q1:  return ARM::D2;
3402   case ARM::Q2:  return ARM::D4;
3403   case ARM::Q3:  return ARM::D6;
3404   case ARM::Q4:  return ARM::D8;
3405   case ARM::Q5:  return ARM::D10;
3406   case ARM::Q6:  return ARM::D12;
3407   case ARM::Q7:  return ARM::D14;
3408   case ARM::Q8:  return ARM::D16;
3409   case ARM::Q9:  return ARM::D18;
3410   case ARM::Q10: return ARM::D20;
3411   case ARM::Q11: return ARM::D22;
3412   case ARM::Q12: return ARM::D24;
3413   case ARM::Q13: return ARM::D26;
3414   case ARM::Q14: return ARM::D28;
3415   case ARM::Q15: return ARM::D30;
3416   }
3417 }
3418 
3419 /// Parse a register list.
3420 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3421   MCAsmParser &Parser = getParser();
3422   assert(Parser.getTok().is(AsmToken::LCurly) &&
3423          "Token is not a Left Curly Brace");
3424   SMLoc S = Parser.getTok().getLoc();
3425   Parser.Lex(); // Eat '{' token.
3426   SMLoc RegLoc = Parser.getTok().getLoc();
3427 
3428   // Check the first register in the list to see what register class
3429   // this is a list of.
3430   int Reg = tryParseRegister();
3431   if (Reg == -1)
3432     return Error(RegLoc, "register expected");
3433 
3434   // The reglist instructions have at most 16 registers, so reserve
3435   // space for that many.
3436   int EReg = 0;
3437   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3438 
3439   // Allow Q regs and just interpret them as the two D sub-registers.
3440   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3441     Reg = getDRegFromQReg(Reg);
3442     EReg = MRI->getEncodingValue(Reg);
3443     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3444     ++Reg;
3445   }
3446   const MCRegisterClass *RC;
3447   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3448     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3449   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3450     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3451   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3452     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3453   else
3454     return Error(RegLoc, "invalid register in register list");
3455 
3456   // Store the register.
3457   EReg = MRI->getEncodingValue(Reg);
3458   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3459 
3460   // This starts immediately after the first register token in the list,
3461   // so we can see either a comma or a minus (range separator) as a legal
3462   // next token.
3463   while (Parser.getTok().is(AsmToken::Comma) ||
3464          Parser.getTok().is(AsmToken::Minus)) {
3465     if (Parser.getTok().is(AsmToken::Minus)) {
3466       Parser.Lex(); // Eat the minus.
3467       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3468       int EndReg = tryParseRegister();
3469       if (EndReg == -1)
3470         return Error(AfterMinusLoc, "register expected");
3471       // Allow Q regs and just interpret them as the two D sub-registers.
3472       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3473         EndReg = getDRegFromQReg(EndReg) + 1;
3474       // If the register is the same as the start reg, there's nothing
3475       // more to do.
3476       if (Reg == EndReg)
3477         continue;
3478       // The register must be in the same register class as the first.
3479       if (!RC->contains(EndReg))
3480         return Error(AfterMinusLoc, "invalid register in register list");
3481       // Ranges must go from low to high.
3482       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3483         return Error(AfterMinusLoc, "bad range in register list");
3484 
3485       // Add all the registers in the range to the register list.
3486       while (Reg != EndReg) {
3487         Reg = getNextRegister(Reg);
3488         EReg = MRI->getEncodingValue(Reg);
3489         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3490       }
3491       continue;
3492     }
3493     Parser.Lex(); // Eat the comma.
3494     RegLoc = Parser.getTok().getLoc();
3495     int OldReg = Reg;
3496     const AsmToken RegTok = Parser.getTok();
3497     Reg = tryParseRegister();
3498     if (Reg == -1)
3499       return Error(RegLoc, "register expected");
3500     // Allow Q regs and just interpret them as the two D sub-registers.
3501     bool isQReg = false;
3502     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3503       Reg = getDRegFromQReg(Reg);
3504       isQReg = true;
3505     }
3506     // The register must be in the same register class as the first.
3507     if (!RC->contains(Reg))
3508       return Error(RegLoc, "invalid register in register list");
3509     // List must be monotonically increasing.
3510     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3511       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3512         Warning(RegLoc, "register list not in ascending order");
3513       else
3514         return Error(RegLoc, "register list not in ascending order");
3515     }
3516     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3517       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3518               ") in register list");
3519       continue;
3520     }
3521     // VFP register lists must also be contiguous.
3522     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3523         Reg != OldReg + 1)
3524       return Error(RegLoc, "non-contiguous register range");
3525     EReg = MRI->getEncodingValue(Reg);
3526     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3527     if (isQReg) {
3528       EReg = MRI->getEncodingValue(++Reg);
3529       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3530     }
3531   }
3532 
3533   if (Parser.getTok().isNot(AsmToken::RCurly))
3534     return Error(Parser.getTok().getLoc(), "'}' expected");
3535   SMLoc E = Parser.getTok().getEndLoc();
3536   Parser.Lex(); // Eat '}' token.
3537 
3538   // Push the register list operand.
3539   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3540 
3541   // The ARM system instruction variants for LDM/STM have a '^' token here.
3542   if (Parser.getTok().is(AsmToken::Caret)) {
3543     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3544     Parser.Lex(); // Eat '^' token.
3545   }
3546 
3547   return false;
3548 }
3549 
3550 // Helper function to parse the lane index for vector lists.
3551 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3552 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3553   MCAsmParser &Parser = getParser();
3554   Index = 0; // Always return a defined index value.
3555   if (Parser.getTok().is(AsmToken::LBrac)) {
3556     Parser.Lex(); // Eat the '['.
3557     if (Parser.getTok().is(AsmToken::RBrac)) {
3558       // "Dn[]" is the 'all lanes' syntax.
3559       LaneKind = AllLanes;
3560       EndLoc = Parser.getTok().getEndLoc();
3561       Parser.Lex(); // Eat the ']'.
3562       return MatchOperand_Success;
3563     }
3564 
3565     // There's an optional '#' token here. Normally there wouldn't be, but
3566     // inline assemble puts one in, and it's friendly to accept that.
3567     if (Parser.getTok().is(AsmToken::Hash))
3568       Parser.Lex(); // Eat '#' or '$'.
3569 
3570     const MCExpr *LaneIndex;
3571     SMLoc Loc = Parser.getTok().getLoc();
3572     if (getParser().parseExpression(LaneIndex)) {
3573       Error(Loc, "illegal expression");
3574       return MatchOperand_ParseFail;
3575     }
3576     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3577     if (!CE) {
3578       Error(Loc, "lane index must be empty or an integer");
3579       return MatchOperand_ParseFail;
3580     }
3581     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3582       Error(Parser.getTok().getLoc(), "']' expected");
3583       return MatchOperand_ParseFail;
3584     }
3585     EndLoc = Parser.getTok().getEndLoc();
3586     Parser.Lex(); // Eat the ']'.
3587     int64_t Val = CE->getValue();
3588 
3589     // FIXME: Make this range check context sensitive for .8, .16, .32.
3590     if (Val < 0 || Val > 7) {
3591       Error(Parser.getTok().getLoc(), "lane index out of range");
3592       return MatchOperand_ParseFail;
3593     }
3594     Index = Val;
3595     LaneKind = IndexedLane;
3596     return MatchOperand_Success;
3597   }
3598   LaneKind = NoLanes;
3599   return MatchOperand_Success;
3600 }
3601 
3602 // parse a vector register list
3603 ARMAsmParser::OperandMatchResultTy
3604 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3605   MCAsmParser &Parser = getParser();
3606   VectorLaneTy LaneKind;
3607   unsigned LaneIndex;
3608   SMLoc S = Parser.getTok().getLoc();
3609   // As an extension (to match gas), support a plain D register or Q register
3610   // (without encosing curly braces) as a single or double entry list,
3611   // respectively.
3612   if (Parser.getTok().is(AsmToken::Identifier)) {
3613     SMLoc E = Parser.getTok().getEndLoc();
3614     int Reg = tryParseRegister();
3615     if (Reg == -1)
3616       return MatchOperand_NoMatch;
3617     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3618       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3619       if (Res != MatchOperand_Success)
3620         return Res;
3621       switch (LaneKind) {
3622       case NoLanes:
3623         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3624         break;
3625       case AllLanes:
3626         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3627                                                                 S, E));
3628         break;
3629       case IndexedLane:
3630         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3631                                                                LaneIndex,
3632                                                                false, S, E));
3633         break;
3634       }
3635       return MatchOperand_Success;
3636     }
3637     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3638       Reg = getDRegFromQReg(Reg);
3639       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3640       if (Res != MatchOperand_Success)
3641         return Res;
3642       switch (LaneKind) {
3643       case NoLanes:
3644         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3645                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3646         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3647         break;
3648       case AllLanes:
3649         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3650                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3651         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3652                                                                 S, E));
3653         break;
3654       case IndexedLane:
3655         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3656                                                                LaneIndex,
3657                                                                false, S, E));
3658         break;
3659       }
3660       return MatchOperand_Success;
3661     }
3662     Error(S, "vector register expected");
3663     return MatchOperand_ParseFail;
3664   }
3665 
3666   if (Parser.getTok().isNot(AsmToken::LCurly))
3667     return MatchOperand_NoMatch;
3668 
3669   Parser.Lex(); // Eat '{' token.
3670   SMLoc RegLoc = Parser.getTok().getLoc();
3671 
3672   int Reg = tryParseRegister();
3673   if (Reg == -1) {
3674     Error(RegLoc, "register expected");
3675     return MatchOperand_ParseFail;
3676   }
3677   unsigned Count = 1;
3678   int Spacing = 0;
3679   unsigned FirstReg = Reg;
3680   // The list is of D registers, but we also allow Q regs and just interpret
3681   // them as the two D sub-registers.
3682   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3683     FirstReg = Reg = getDRegFromQReg(Reg);
3684     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3685                  // it's ambiguous with four-register single spaced.
3686     ++Reg;
3687     ++Count;
3688   }
3689 
3690   SMLoc E;
3691   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3692     return MatchOperand_ParseFail;
3693 
3694   while (Parser.getTok().is(AsmToken::Comma) ||
3695          Parser.getTok().is(AsmToken::Minus)) {
3696     if (Parser.getTok().is(AsmToken::Minus)) {
3697       if (!Spacing)
3698         Spacing = 1; // Register range implies a single spaced list.
3699       else if (Spacing == 2) {
3700         Error(Parser.getTok().getLoc(),
3701               "sequential registers in double spaced list");
3702         return MatchOperand_ParseFail;
3703       }
3704       Parser.Lex(); // Eat the minus.
3705       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3706       int EndReg = tryParseRegister();
3707       if (EndReg == -1) {
3708         Error(AfterMinusLoc, "register expected");
3709         return MatchOperand_ParseFail;
3710       }
3711       // Allow Q regs and just interpret them as the two D sub-registers.
3712       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3713         EndReg = getDRegFromQReg(EndReg) + 1;
3714       // If the register is the same as the start reg, there's nothing
3715       // more to do.
3716       if (Reg == EndReg)
3717         continue;
3718       // The register must be in the same register class as the first.
3719       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3720         Error(AfterMinusLoc, "invalid register in register list");
3721         return MatchOperand_ParseFail;
3722       }
3723       // Ranges must go from low to high.
3724       if (Reg > EndReg) {
3725         Error(AfterMinusLoc, "bad range in register list");
3726         return MatchOperand_ParseFail;
3727       }
3728       // Parse the lane specifier if present.
3729       VectorLaneTy NextLaneKind;
3730       unsigned NextLaneIndex;
3731       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3732           MatchOperand_Success)
3733         return MatchOperand_ParseFail;
3734       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3735         Error(AfterMinusLoc, "mismatched lane index in register list");
3736         return MatchOperand_ParseFail;
3737       }
3738 
3739       // Add all the registers in the range to the register list.
3740       Count += EndReg - Reg;
3741       Reg = EndReg;
3742       continue;
3743     }
3744     Parser.Lex(); // Eat the comma.
3745     RegLoc = Parser.getTok().getLoc();
3746     int OldReg = Reg;
3747     Reg = tryParseRegister();
3748     if (Reg == -1) {
3749       Error(RegLoc, "register expected");
3750       return MatchOperand_ParseFail;
3751     }
3752     // vector register lists must be contiguous.
3753     // It's OK to use the enumeration values directly here rather, as the
3754     // VFP register classes have the enum sorted properly.
3755     //
3756     // The list is of D registers, but we also allow Q regs and just interpret
3757     // them as the two D sub-registers.
3758     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3759       if (!Spacing)
3760         Spacing = 1; // Register range implies a single spaced list.
3761       else if (Spacing == 2) {
3762         Error(RegLoc,
3763               "invalid register in double-spaced list (must be 'D' register')");
3764         return MatchOperand_ParseFail;
3765       }
3766       Reg = getDRegFromQReg(Reg);
3767       if (Reg != OldReg + 1) {
3768         Error(RegLoc, "non-contiguous register range");
3769         return MatchOperand_ParseFail;
3770       }
3771       ++Reg;
3772       Count += 2;
3773       // Parse the lane specifier if present.
3774       VectorLaneTy NextLaneKind;
3775       unsigned NextLaneIndex;
3776       SMLoc LaneLoc = Parser.getTok().getLoc();
3777       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3778           MatchOperand_Success)
3779         return MatchOperand_ParseFail;
3780       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3781         Error(LaneLoc, "mismatched lane index in register list");
3782         return MatchOperand_ParseFail;
3783       }
3784       continue;
3785     }
3786     // Normal D register.
3787     // Figure out the register spacing (single or double) of the list if
3788     // we don't know it already.
3789     if (!Spacing)
3790       Spacing = 1 + (Reg == OldReg + 2);
3791 
3792     // Just check that it's contiguous and keep going.
3793     if (Reg != OldReg + Spacing) {
3794       Error(RegLoc, "non-contiguous register range");
3795       return MatchOperand_ParseFail;
3796     }
3797     ++Count;
3798     // Parse the lane specifier if present.
3799     VectorLaneTy NextLaneKind;
3800     unsigned NextLaneIndex;
3801     SMLoc EndLoc = Parser.getTok().getLoc();
3802     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3803       return MatchOperand_ParseFail;
3804     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3805       Error(EndLoc, "mismatched lane index in register list");
3806       return MatchOperand_ParseFail;
3807     }
3808   }
3809 
3810   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3811     Error(Parser.getTok().getLoc(), "'}' expected");
3812     return MatchOperand_ParseFail;
3813   }
3814   E = Parser.getTok().getEndLoc();
3815   Parser.Lex(); // Eat '}' token.
3816 
3817   switch (LaneKind) {
3818   case NoLanes:
3819     // Two-register operands have been converted to the
3820     // composite register classes.
3821     if (Count == 2) {
3822       const MCRegisterClass *RC = (Spacing == 1) ?
3823         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3824         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3825       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3826     }
3827 
3828     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3829                                                     (Spacing == 2), S, E));
3830     break;
3831   case AllLanes:
3832     // Two-register operands have been converted to the
3833     // composite register classes.
3834     if (Count == 2) {
3835       const MCRegisterClass *RC = (Spacing == 1) ?
3836         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3837         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3838       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3839     }
3840     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3841                                                             (Spacing == 2),
3842                                                             S, E));
3843     break;
3844   case IndexedLane:
3845     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3846                                                            LaneIndex,
3847                                                            (Spacing == 2),
3848                                                            S, E));
3849     break;
3850   }
3851   return MatchOperand_Success;
3852 }
3853 
3854 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3855 ARMAsmParser::OperandMatchResultTy
3856 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3857   MCAsmParser &Parser = getParser();
3858   SMLoc S = Parser.getTok().getLoc();
3859   const AsmToken &Tok = Parser.getTok();
3860   unsigned Opt;
3861 
3862   if (Tok.is(AsmToken::Identifier)) {
3863     StringRef OptStr = Tok.getString();
3864 
3865     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3866       .Case("sy",    ARM_MB::SY)
3867       .Case("st",    ARM_MB::ST)
3868       .Case("ld",    ARM_MB::LD)
3869       .Case("sh",    ARM_MB::ISH)
3870       .Case("ish",   ARM_MB::ISH)
3871       .Case("shst",  ARM_MB::ISHST)
3872       .Case("ishst", ARM_MB::ISHST)
3873       .Case("ishld", ARM_MB::ISHLD)
3874       .Case("nsh",   ARM_MB::NSH)
3875       .Case("un",    ARM_MB::NSH)
3876       .Case("nshst", ARM_MB::NSHST)
3877       .Case("nshld", ARM_MB::NSHLD)
3878       .Case("unst",  ARM_MB::NSHST)
3879       .Case("osh",   ARM_MB::OSH)
3880       .Case("oshst", ARM_MB::OSHST)
3881       .Case("oshld", ARM_MB::OSHLD)
3882       .Default(~0U);
3883 
3884     // ishld, oshld, nshld and ld are only available from ARMv8.
3885     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3886                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3887       Opt = ~0U;
3888 
3889     if (Opt == ~0U)
3890       return MatchOperand_NoMatch;
3891 
3892     Parser.Lex(); // Eat identifier token.
3893   } else if (Tok.is(AsmToken::Hash) ||
3894              Tok.is(AsmToken::Dollar) ||
3895              Tok.is(AsmToken::Integer)) {
3896     if (Parser.getTok().isNot(AsmToken::Integer))
3897       Parser.Lex(); // Eat '#' or '$'.
3898     SMLoc Loc = Parser.getTok().getLoc();
3899 
3900     const MCExpr *MemBarrierID;
3901     if (getParser().parseExpression(MemBarrierID)) {
3902       Error(Loc, "illegal expression");
3903       return MatchOperand_ParseFail;
3904     }
3905 
3906     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3907     if (!CE) {
3908       Error(Loc, "constant expression expected");
3909       return MatchOperand_ParseFail;
3910     }
3911 
3912     int Val = CE->getValue();
3913     if (Val & ~0xf) {
3914       Error(Loc, "immediate value out of range");
3915       return MatchOperand_ParseFail;
3916     }
3917 
3918     Opt = ARM_MB::RESERVED_0 + Val;
3919   } else
3920     return MatchOperand_ParseFail;
3921 
3922   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3923   return MatchOperand_Success;
3924 }
3925 
3926 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3927 ARMAsmParser::OperandMatchResultTy
3928 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3929   MCAsmParser &Parser = getParser();
3930   SMLoc S = Parser.getTok().getLoc();
3931   const AsmToken &Tok = Parser.getTok();
3932   unsigned Opt;
3933 
3934   if (Tok.is(AsmToken::Identifier)) {
3935     StringRef OptStr = Tok.getString();
3936 
3937     if (OptStr.equals_lower("sy"))
3938       Opt = ARM_ISB::SY;
3939     else
3940       return MatchOperand_NoMatch;
3941 
3942     Parser.Lex(); // Eat identifier token.
3943   } else if (Tok.is(AsmToken::Hash) ||
3944              Tok.is(AsmToken::Dollar) ||
3945              Tok.is(AsmToken::Integer)) {
3946     if (Parser.getTok().isNot(AsmToken::Integer))
3947       Parser.Lex(); // Eat '#' or '$'.
3948     SMLoc Loc = Parser.getTok().getLoc();
3949 
3950     const MCExpr *ISBarrierID;
3951     if (getParser().parseExpression(ISBarrierID)) {
3952       Error(Loc, "illegal expression");
3953       return MatchOperand_ParseFail;
3954     }
3955 
3956     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
3957     if (!CE) {
3958       Error(Loc, "constant expression expected");
3959       return MatchOperand_ParseFail;
3960     }
3961 
3962     int Val = CE->getValue();
3963     if (Val & ~0xf) {
3964       Error(Loc, "immediate value out of range");
3965       return MatchOperand_ParseFail;
3966     }
3967 
3968     Opt = ARM_ISB::RESERVED_0 + Val;
3969   } else
3970     return MatchOperand_ParseFail;
3971 
3972   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
3973           (ARM_ISB::InstSyncBOpt)Opt, S));
3974   return MatchOperand_Success;
3975 }
3976 
3977 
3978 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
3979 ARMAsmParser::OperandMatchResultTy
3980 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
3981   MCAsmParser &Parser = getParser();
3982   SMLoc S = Parser.getTok().getLoc();
3983   const AsmToken &Tok = Parser.getTok();
3984   if (!Tok.is(AsmToken::Identifier))
3985     return MatchOperand_NoMatch;
3986   StringRef IFlagsStr = Tok.getString();
3987 
3988   // An iflags string of "none" is interpreted to mean that none of the AIF
3989   // bits are set.  Not a terribly useful instruction, but a valid encoding.
3990   unsigned IFlags = 0;
3991   if (IFlagsStr != "none") {
3992         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
3993       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
3994         .Case("a", ARM_PROC::A)
3995         .Case("i", ARM_PROC::I)
3996         .Case("f", ARM_PROC::F)
3997         .Default(~0U);
3998 
3999       // If some specific iflag is already set, it means that some letter is
4000       // present more than once, this is not acceptable.
4001       if (Flag == ~0U || (IFlags & Flag))
4002         return MatchOperand_NoMatch;
4003 
4004       IFlags |= Flag;
4005     }
4006   }
4007 
4008   Parser.Lex(); // Eat identifier token.
4009   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4010   return MatchOperand_Success;
4011 }
4012 
4013 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4014 ARMAsmParser::OperandMatchResultTy
4015 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4016   MCAsmParser &Parser = getParser();
4017   SMLoc S = Parser.getTok().getLoc();
4018   const AsmToken &Tok = Parser.getTok();
4019   if (!Tok.is(AsmToken::Identifier))
4020     return MatchOperand_NoMatch;
4021   StringRef Mask = Tok.getString();
4022 
4023   if (isMClass()) {
4024     // See ARMv6-M 10.1.1
4025     std::string Name = Mask.lower();
4026     unsigned FlagsVal = StringSwitch<unsigned>(Name)
4027       // Note: in the documentation:
4028       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
4029       //  for MSR APSR_nzcvq.
4030       // but we do make it an alias here.  This is so to get the "mask encoding"
4031       // bits correct on MSR APSR writes.
4032       //
4033       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
4034       // should really only be allowed when writing a special register.  Note
4035       // they get dropped in the MRS instruction reading a special register as
4036       // the SYSm field is only 8 bits.
4037       .Case("apsr", 0x800)
4038       .Case("apsr_nzcvq", 0x800)
4039       .Case("apsr_g", 0x400)
4040       .Case("apsr_nzcvqg", 0xc00)
4041       .Case("iapsr", 0x801)
4042       .Case("iapsr_nzcvq", 0x801)
4043       .Case("iapsr_g", 0x401)
4044       .Case("iapsr_nzcvqg", 0xc01)
4045       .Case("eapsr", 0x802)
4046       .Case("eapsr_nzcvq", 0x802)
4047       .Case("eapsr_g", 0x402)
4048       .Case("eapsr_nzcvqg", 0xc02)
4049       .Case("xpsr", 0x803)
4050       .Case("xpsr_nzcvq", 0x803)
4051       .Case("xpsr_g", 0x403)
4052       .Case("xpsr_nzcvqg", 0xc03)
4053       .Case("ipsr", 0x805)
4054       .Case("epsr", 0x806)
4055       .Case("iepsr", 0x807)
4056       .Case("msp", 0x808)
4057       .Case("psp", 0x809)
4058       .Case("primask", 0x810)
4059       .Case("basepri", 0x811)
4060       .Case("basepri_max", 0x812)
4061       .Case("faultmask", 0x813)
4062       .Case("control", 0x814)
4063       .Case("msplim", 0x80a)
4064       .Case("psplim", 0x80b)
4065       .Case("msp_ns", 0x888)
4066       .Case("psp_ns", 0x889)
4067       .Case("msplim_ns", 0x88a)
4068       .Case("psplim_ns", 0x88b)
4069       .Case("primask_ns", 0x890)
4070       .Case("basepri_ns", 0x891)
4071       .Case("basepri_max_ns", 0x892)
4072       .Case("faultmask_ns", 0x893)
4073       .Case("control_ns", 0x894)
4074       .Case("sp_ns", 0x898)
4075       .Default(~0U);
4076 
4077     if (FlagsVal == ~0U)
4078       return MatchOperand_NoMatch;
4079 
4080     if (!hasDSP() && (FlagsVal & 0x400))
4081       // The _g and _nzcvqg versions are only valid if the DSP extension is
4082       // available.
4083       return MatchOperand_NoMatch;
4084 
4085     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
4086       // basepri, basepri_max and faultmask only valid for V7m.
4087       return MatchOperand_NoMatch;
4088 
4089     if (!has8MSecExt() && (FlagsVal == 0x80a || FlagsVal == 0x80b ||
4090                              (FlagsVal > 0x814 && FlagsVal < 0xc00)))
4091       return MatchOperand_NoMatch;
4092 
4093     if (!hasV8MMainline() && (FlagsVal == 0x88a || FlagsVal == 0x88b ||
4094                               (FlagsVal > 0x890 && FlagsVal <= 0x893)))
4095       return MatchOperand_NoMatch;
4096 
4097     Parser.Lex(); // Eat identifier token.
4098     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4099     return MatchOperand_Success;
4100   }
4101 
4102   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4103   size_t Start = 0, Next = Mask.find('_');
4104   StringRef Flags = "";
4105   std::string SpecReg = Mask.slice(Start, Next).lower();
4106   if (Next != StringRef::npos)
4107     Flags = Mask.slice(Next+1, Mask.size());
4108 
4109   // FlagsVal contains the complete mask:
4110   // 3-0: Mask
4111   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4112   unsigned FlagsVal = 0;
4113 
4114   if (SpecReg == "apsr") {
4115     FlagsVal = StringSwitch<unsigned>(Flags)
4116     .Case("nzcvq",  0x8) // same as CPSR_f
4117     .Case("g",      0x4) // same as CPSR_s
4118     .Case("nzcvqg", 0xc) // same as CPSR_fs
4119     .Default(~0U);
4120 
4121     if (FlagsVal == ~0U) {
4122       if (!Flags.empty())
4123         return MatchOperand_NoMatch;
4124       else
4125         FlagsVal = 8; // No flag
4126     }
4127   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4128     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4129     if (Flags == "all" || Flags == "")
4130       Flags = "fc";
4131     for (int i = 0, e = Flags.size(); i != e; ++i) {
4132       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4133       .Case("c", 1)
4134       .Case("x", 2)
4135       .Case("s", 4)
4136       .Case("f", 8)
4137       .Default(~0U);
4138 
4139       // If some specific flag is already set, it means that some letter is
4140       // present more than once, this is not acceptable.
4141       if (FlagsVal == ~0U || (FlagsVal & Flag))
4142         return MatchOperand_NoMatch;
4143       FlagsVal |= Flag;
4144     }
4145   } else // No match for special register.
4146     return MatchOperand_NoMatch;
4147 
4148   // Special register without flags is NOT equivalent to "fc" flags.
4149   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4150   // two lines would enable gas compatibility at the expense of breaking
4151   // round-tripping.
4152   //
4153   // if (!FlagsVal)
4154   //  FlagsVal = 0x9;
4155 
4156   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4157   if (SpecReg == "spsr")
4158     FlagsVal |= 16;
4159 
4160   Parser.Lex(); // Eat identifier token.
4161   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4162   return MatchOperand_Success;
4163 }
4164 
4165 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4166 /// use in the MRS/MSR instructions added to support virtualization.
4167 ARMAsmParser::OperandMatchResultTy
4168 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4169   MCAsmParser &Parser = getParser();
4170   SMLoc S = Parser.getTok().getLoc();
4171   const AsmToken &Tok = Parser.getTok();
4172   if (!Tok.is(AsmToken::Identifier))
4173     return MatchOperand_NoMatch;
4174   StringRef RegName = Tok.getString();
4175 
4176   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4177   // and bit 5 is R.
4178   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4179                           .Case("r8_usr", 0x00)
4180                           .Case("r9_usr", 0x01)
4181                           .Case("r10_usr", 0x02)
4182                           .Case("r11_usr", 0x03)
4183                           .Case("r12_usr", 0x04)
4184                           .Case("sp_usr", 0x05)
4185                           .Case("lr_usr", 0x06)
4186                           .Case("r8_fiq", 0x08)
4187                           .Case("r9_fiq", 0x09)
4188                           .Case("r10_fiq", 0x0a)
4189                           .Case("r11_fiq", 0x0b)
4190                           .Case("r12_fiq", 0x0c)
4191                           .Case("sp_fiq", 0x0d)
4192                           .Case("lr_fiq", 0x0e)
4193                           .Case("lr_irq", 0x10)
4194                           .Case("sp_irq", 0x11)
4195                           .Case("lr_svc", 0x12)
4196                           .Case("sp_svc", 0x13)
4197                           .Case("lr_abt", 0x14)
4198                           .Case("sp_abt", 0x15)
4199                           .Case("lr_und", 0x16)
4200                           .Case("sp_und", 0x17)
4201                           .Case("lr_mon", 0x1c)
4202                           .Case("sp_mon", 0x1d)
4203                           .Case("elr_hyp", 0x1e)
4204                           .Case("sp_hyp", 0x1f)
4205                           .Case("spsr_fiq", 0x2e)
4206                           .Case("spsr_irq", 0x30)
4207                           .Case("spsr_svc", 0x32)
4208                           .Case("spsr_abt", 0x34)
4209                           .Case("spsr_und", 0x36)
4210                           .Case("spsr_mon", 0x3c)
4211                           .Case("spsr_hyp", 0x3e)
4212                           .Default(~0U);
4213 
4214   if (Encoding == ~0U)
4215     return MatchOperand_NoMatch;
4216 
4217   Parser.Lex(); // Eat identifier token.
4218   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4219   return MatchOperand_Success;
4220 }
4221 
4222 ARMAsmParser::OperandMatchResultTy
4223 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4224                           int High) {
4225   MCAsmParser &Parser = getParser();
4226   const AsmToken &Tok = Parser.getTok();
4227   if (Tok.isNot(AsmToken::Identifier)) {
4228     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4229     return MatchOperand_ParseFail;
4230   }
4231   StringRef ShiftName = Tok.getString();
4232   std::string LowerOp = Op.lower();
4233   std::string UpperOp = Op.upper();
4234   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4235     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4236     return MatchOperand_ParseFail;
4237   }
4238   Parser.Lex(); // Eat shift type token.
4239 
4240   // There must be a '#' and a shift amount.
4241   if (Parser.getTok().isNot(AsmToken::Hash) &&
4242       Parser.getTok().isNot(AsmToken::Dollar)) {
4243     Error(Parser.getTok().getLoc(), "'#' expected");
4244     return MatchOperand_ParseFail;
4245   }
4246   Parser.Lex(); // Eat hash token.
4247 
4248   const MCExpr *ShiftAmount;
4249   SMLoc Loc = Parser.getTok().getLoc();
4250   SMLoc EndLoc;
4251   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4252     Error(Loc, "illegal expression");
4253     return MatchOperand_ParseFail;
4254   }
4255   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4256   if (!CE) {
4257     Error(Loc, "constant expression expected");
4258     return MatchOperand_ParseFail;
4259   }
4260   int Val = CE->getValue();
4261   if (Val < Low || Val > High) {
4262     Error(Loc, "immediate value out of range");
4263     return MatchOperand_ParseFail;
4264   }
4265 
4266   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4267 
4268   return MatchOperand_Success;
4269 }
4270 
4271 ARMAsmParser::OperandMatchResultTy
4272 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4273   MCAsmParser &Parser = getParser();
4274   const AsmToken &Tok = Parser.getTok();
4275   SMLoc S = Tok.getLoc();
4276   if (Tok.isNot(AsmToken::Identifier)) {
4277     Error(S, "'be' or 'le' operand expected");
4278     return MatchOperand_ParseFail;
4279   }
4280   int Val = StringSwitch<int>(Tok.getString().lower())
4281     .Case("be", 1)
4282     .Case("le", 0)
4283     .Default(-1);
4284   Parser.Lex(); // Eat the token.
4285 
4286   if (Val == -1) {
4287     Error(S, "'be' or 'le' operand expected");
4288     return MatchOperand_ParseFail;
4289   }
4290   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4291                                                                   getContext()),
4292                                            S, Tok.getEndLoc()));
4293   return MatchOperand_Success;
4294 }
4295 
4296 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4297 /// instructions. Legal values are:
4298 ///     lsl #n  'n' in [0,31]
4299 ///     asr #n  'n' in [1,32]
4300 ///             n == 32 encoded as n == 0.
4301 ARMAsmParser::OperandMatchResultTy
4302 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4303   MCAsmParser &Parser = getParser();
4304   const AsmToken &Tok = Parser.getTok();
4305   SMLoc S = Tok.getLoc();
4306   if (Tok.isNot(AsmToken::Identifier)) {
4307     Error(S, "shift operator 'asr' or 'lsl' expected");
4308     return MatchOperand_ParseFail;
4309   }
4310   StringRef ShiftName = Tok.getString();
4311   bool isASR;
4312   if (ShiftName == "lsl" || ShiftName == "LSL")
4313     isASR = false;
4314   else if (ShiftName == "asr" || ShiftName == "ASR")
4315     isASR = true;
4316   else {
4317     Error(S, "shift operator 'asr' or 'lsl' expected");
4318     return MatchOperand_ParseFail;
4319   }
4320   Parser.Lex(); // Eat the operator.
4321 
4322   // A '#' and a shift amount.
4323   if (Parser.getTok().isNot(AsmToken::Hash) &&
4324       Parser.getTok().isNot(AsmToken::Dollar)) {
4325     Error(Parser.getTok().getLoc(), "'#' expected");
4326     return MatchOperand_ParseFail;
4327   }
4328   Parser.Lex(); // Eat hash token.
4329   SMLoc ExLoc = Parser.getTok().getLoc();
4330 
4331   const MCExpr *ShiftAmount;
4332   SMLoc EndLoc;
4333   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4334     Error(ExLoc, "malformed shift expression");
4335     return MatchOperand_ParseFail;
4336   }
4337   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4338   if (!CE) {
4339     Error(ExLoc, "shift amount must be an immediate");
4340     return MatchOperand_ParseFail;
4341   }
4342 
4343   int64_t Val = CE->getValue();
4344   if (isASR) {
4345     // Shift amount must be in [1,32]
4346     if (Val < 1 || Val > 32) {
4347       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4348       return MatchOperand_ParseFail;
4349     }
4350     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4351     if (isThumb() && Val == 32) {
4352       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4353       return MatchOperand_ParseFail;
4354     }
4355     if (Val == 32) Val = 0;
4356   } else {
4357     // Shift amount must be in [1,32]
4358     if (Val < 0 || Val > 31) {
4359       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4360       return MatchOperand_ParseFail;
4361     }
4362   }
4363 
4364   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4365 
4366   return MatchOperand_Success;
4367 }
4368 
4369 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4370 /// of instructions. Legal values are:
4371 ///     ror #n  'n' in {0, 8, 16, 24}
4372 ARMAsmParser::OperandMatchResultTy
4373 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4374   MCAsmParser &Parser = getParser();
4375   const AsmToken &Tok = Parser.getTok();
4376   SMLoc S = Tok.getLoc();
4377   if (Tok.isNot(AsmToken::Identifier))
4378     return MatchOperand_NoMatch;
4379   StringRef ShiftName = Tok.getString();
4380   if (ShiftName != "ror" && ShiftName != "ROR")
4381     return MatchOperand_NoMatch;
4382   Parser.Lex(); // Eat the operator.
4383 
4384   // A '#' and a rotate amount.
4385   if (Parser.getTok().isNot(AsmToken::Hash) &&
4386       Parser.getTok().isNot(AsmToken::Dollar)) {
4387     Error(Parser.getTok().getLoc(), "'#' expected");
4388     return MatchOperand_ParseFail;
4389   }
4390   Parser.Lex(); // Eat hash token.
4391   SMLoc ExLoc = Parser.getTok().getLoc();
4392 
4393   const MCExpr *ShiftAmount;
4394   SMLoc EndLoc;
4395   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4396     Error(ExLoc, "malformed rotate expression");
4397     return MatchOperand_ParseFail;
4398   }
4399   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4400   if (!CE) {
4401     Error(ExLoc, "rotate amount must be an immediate");
4402     return MatchOperand_ParseFail;
4403   }
4404 
4405   int64_t Val = CE->getValue();
4406   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4407   // normally, zero is represented in asm by omitting the rotate operand
4408   // entirely.
4409   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4410     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4411     return MatchOperand_ParseFail;
4412   }
4413 
4414   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4415 
4416   return MatchOperand_Success;
4417 }
4418 
4419 ARMAsmParser::OperandMatchResultTy
4420 ARMAsmParser::parseModImm(OperandVector &Operands) {
4421   MCAsmParser &Parser = getParser();
4422   MCAsmLexer &Lexer = getLexer();
4423   int64_t Imm1, Imm2;
4424 
4425   SMLoc S = Parser.getTok().getLoc();
4426 
4427   // 1) A mod_imm operand can appear in the place of a register name:
4428   //   add r0, #mod_imm
4429   //   add r0, r0, #mod_imm
4430   // to correctly handle the latter, we bail out as soon as we see an
4431   // identifier.
4432   //
4433   // 2) Similarly, we do not want to parse into complex operands:
4434   //   mov r0, #mod_imm
4435   //   mov r0, :lower16:(_foo)
4436   if (Parser.getTok().is(AsmToken::Identifier) ||
4437       Parser.getTok().is(AsmToken::Colon))
4438     return MatchOperand_NoMatch;
4439 
4440   // Hash (dollar) is optional as per the ARMARM
4441   if (Parser.getTok().is(AsmToken::Hash) ||
4442       Parser.getTok().is(AsmToken::Dollar)) {
4443     // Avoid parsing into complex operands (#:)
4444     if (Lexer.peekTok().is(AsmToken::Colon))
4445       return MatchOperand_NoMatch;
4446 
4447     // Eat the hash (dollar)
4448     Parser.Lex();
4449   }
4450 
4451   SMLoc Sx1, Ex1;
4452   Sx1 = Parser.getTok().getLoc();
4453   const MCExpr *Imm1Exp;
4454   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4455     Error(Sx1, "malformed expression");
4456     return MatchOperand_ParseFail;
4457   }
4458 
4459   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4460 
4461   if (CE) {
4462     // Immediate must fit within 32-bits
4463     Imm1 = CE->getValue();
4464     int Enc = ARM_AM::getSOImmVal(Imm1);
4465     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4466       // We have a match!
4467       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4468                                                   (Enc & 0xF00) >> 7,
4469                                                   Sx1, Ex1));
4470       return MatchOperand_Success;
4471     }
4472 
4473     // We have parsed an immediate which is not for us, fallback to a plain
4474     // immediate. This can happen for instruction aliases. For an example,
4475     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4476     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4477     // instruction with a mod_imm operand. The alias is defined such that the
4478     // parser method is shared, that's why we have to do this here.
4479     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4480       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4481       return MatchOperand_Success;
4482     }
4483   } else {
4484     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4485     // MCFixup). Fallback to a plain immediate.
4486     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4487     return MatchOperand_Success;
4488   }
4489 
4490   // From this point onward, we expect the input to be a (#bits, #rot) pair
4491   if (Parser.getTok().isNot(AsmToken::Comma)) {
4492     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4493     return MatchOperand_ParseFail;
4494   }
4495 
4496   if (Imm1 & ~0xFF) {
4497     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4498     return MatchOperand_ParseFail;
4499   }
4500 
4501   // Eat the comma
4502   Parser.Lex();
4503 
4504   // Repeat for #rot
4505   SMLoc Sx2, Ex2;
4506   Sx2 = Parser.getTok().getLoc();
4507 
4508   // Eat the optional hash (dollar)
4509   if (Parser.getTok().is(AsmToken::Hash) ||
4510       Parser.getTok().is(AsmToken::Dollar))
4511     Parser.Lex();
4512 
4513   const MCExpr *Imm2Exp;
4514   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4515     Error(Sx2, "malformed expression");
4516     return MatchOperand_ParseFail;
4517   }
4518 
4519   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4520 
4521   if (CE) {
4522     Imm2 = CE->getValue();
4523     if (!(Imm2 & ~0x1E)) {
4524       // We have a match!
4525       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4526       return MatchOperand_Success;
4527     }
4528     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4529     return MatchOperand_ParseFail;
4530   } else {
4531     Error(Sx2, "constant expression expected");
4532     return MatchOperand_ParseFail;
4533   }
4534 }
4535 
4536 ARMAsmParser::OperandMatchResultTy
4537 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4538   MCAsmParser &Parser = getParser();
4539   SMLoc S = Parser.getTok().getLoc();
4540   // The bitfield descriptor is really two operands, the LSB and the width.
4541   if (Parser.getTok().isNot(AsmToken::Hash) &&
4542       Parser.getTok().isNot(AsmToken::Dollar)) {
4543     Error(Parser.getTok().getLoc(), "'#' expected");
4544     return MatchOperand_ParseFail;
4545   }
4546   Parser.Lex(); // Eat hash token.
4547 
4548   const MCExpr *LSBExpr;
4549   SMLoc E = Parser.getTok().getLoc();
4550   if (getParser().parseExpression(LSBExpr)) {
4551     Error(E, "malformed immediate expression");
4552     return MatchOperand_ParseFail;
4553   }
4554   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4555   if (!CE) {
4556     Error(E, "'lsb' operand must be an immediate");
4557     return MatchOperand_ParseFail;
4558   }
4559 
4560   int64_t LSB = CE->getValue();
4561   // The LSB must be in the range [0,31]
4562   if (LSB < 0 || LSB > 31) {
4563     Error(E, "'lsb' operand must be in the range [0,31]");
4564     return MatchOperand_ParseFail;
4565   }
4566   E = Parser.getTok().getLoc();
4567 
4568   // Expect another immediate operand.
4569   if (Parser.getTok().isNot(AsmToken::Comma)) {
4570     Error(Parser.getTok().getLoc(), "too few operands");
4571     return MatchOperand_ParseFail;
4572   }
4573   Parser.Lex(); // Eat hash token.
4574   if (Parser.getTok().isNot(AsmToken::Hash) &&
4575       Parser.getTok().isNot(AsmToken::Dollar)) {
4576     Error(Parser.getTok().getLoc(), "'#' expected");
4577     return MatchOperand_ParseFail;
4578   }
4579   Parser.Lex(); // Eat hash token.
4580 
4581   const MCExpr *WidthExpr;
4582   SMLoc EndLoc;
4583   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4584     Error(E, "malformed immediate expression");
4585     return MatchOperand_ParseFail;
4586   }
4587   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4588   if (!CE) {
4589     Error(E, "'width' operand must be an immediate");
4590     return MatchOperand_ParseFail;
4591   }
4592 
4593   int64_t Width = CE->getValue();
4594   // The LSB must be in the range [1,32-lsb]
4595   if (Width < 1 || Width > 32 - LSB) {
4596     Error(E, "'width' operand must be in the range [1,32-lsb]");
4597     return MatchOperand_ParseFail;
4598   }
4599 
4600   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4601 
4602   return MatchOperand_Success;
4603 }
4604 
4605 ARMAsmParser::OperandMatchResultTy
4606 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4607   // Check for a post-index addressing register operand. Specifically:
4608   // postidx_reg := '+' register {, shift}
4609   //              | '-' register {, shift}
4610   //              | register {, shift}
4611 
4612   // This method must return MatchOperand_NoMatch without consuming any tokens
4613   // in the case where there is no match, as other alternatives take other
4614   // parse methods.
4615   MCAsmParser &Parser = getParser();
4616   AsmToken Tok = Parser.getTok();
4617   SMLoc S = Tok.getLoc();
4618   bool haveEaten = false;
4619   bool isAdd = true;
4620   if (Tok.is(AsmToken::Plus)) {
4621     Parser.Lex(); // Eat the '+' token.
4622     haveEaten = true;
4623   } else if (Tok.is(AsmToken::Minus)) {
4624     Parser.Lex(); // Eat the '-' token.
4625     isAdd = false;
4626     haveEaten = true;
4627   }
4628 
4629   SMLoc E = Parser.getTok().getEndLoc();
4630   int Reg = tryParseRegister();
4631   if (Reg == -1) {
4632     if (!haveEaten)
4633       return MatchOperand_NoMatch;
4634     Error(Parser.getTok().getLoc(), "register expected");
4635     return MatchOperand_ParseFail;
4636   }
4637 
4638   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4639   unsigned ShiftImm = 0;
4640   if (Parser.getTok().is(AsmToken::Comma)) {
4641     Parser.Lex(); // Eat the ','.
4642     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4643       return MatchOperand_ParseFail;
4644 
4645     // FIXME: Only approximates end...may include intervening whitespace.
4646     E = Parser.getTok().getLoc();
4647   }
4648 
4649   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4650                                                   ShiftImm, S, E));
4651 
4652   return MatchOperand_Success;
4653 }
4654 
4655 ARMAsmParser::OperandMatchResultTy
4656 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4657   // Check for a post-index addressing register operand. Specifically:
4658   // am3offset := '+' register
4659   //              | '-' register
4660   //              | register
4661   //              | # imm
4662   //              | # + imm
4663   //              | # - imm
4664 
4665   // This method must return MatchOperand_NoMatch without consuming any tokens
4666   // in the case where there is no match, as other alternatives take other
4667   // parse methods.
4668   MCAsmParser &Parser = getParser();
4669   AsmToken Tok = Parser.getTok();
4670   SMLoc S = Tok.getLoc();
4671 
4672   // Do immediates first, as we always parse those if we have a '#'.
4673   if (Parser.getTok().is(AsmToken::Hash) ||
4674       Parser.getTok().is(AsmToken::Dollar)) {
4675     Parser.Lex(); // Eat '#' or '$'.
4676     // Explicitly look for a '-', as we need to encode negative zero
4677     // differently.
4678     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4679     const MCExpr *Offset;
4680     SMLoc E;
4681     if (getParser().parseExpression(Offset, E))
4682       return MatchOperand_ParseFail;
4683     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4684     if (!CE) {
4685       Error(S, "constant expression expected");
4686       return MatchOperand_ParseFail;
4687     }
4688     // Negative zero is encoded as the flag value INT32_MIN.
4689     int32_t Val = CE->getValue();
4690     if (isNegative && Val == 0)
4691       Val = INT32_MIN;
4692 
4693     Operands.push_back(
4694       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4695 
4696     return MatchOperand_Success;
4697   }
4698 
4699 
4700   bool haveEaten = false;
4701   bool isAdd = true;
4702   if (Tok.is(AsmToken::Plus)) {
4703     Parser.Lex(); // Eat the '+' token.
4704     haveEaten = true;
4705   } else if (Tok.is(AsmToken::Minus)) {
4706     Parser.Lex(); // Eat the '-' token.
4707     isAdd = false;
4708     haveEaten = true;
4709   }
4710 
4711   Tok = Parser.getTok();
4712   int Reg = tryParseRegister();
4713   if (Reg == -1) {
4714     if (!haveEaten)
4715       return MatchOperand_NoMatch;
4716     Error(Tok.getLoc(), "register expected");
4717     return MatchOperand_ParseFail;
4718   }
4719 
4720   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4721                                                   0, S, Tok.getEndLoc()));
4722 
4723   return MatchOperand_Success;
4724 }
4725 
4726 /// Convert parsed operands to MCInst.  Needed here because this instruction
4727 /// only has two register operands, but multiplication is commutative so
4728 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4729 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4730                                     const OperandVector &Operands) {
4731   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4732   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4733   // If we have a three-operand form, make sure to set Rn to be the operand
4734   // that isn't the same as Rd.
4735   unsigned RegOp = 4;
4736   if (Operands.size() == 6 &&
4737       ((ARMOperand &)*Operands[4]).getReg() ==
4738           ((ARMOperand &)*Operands[3]).getReg())
4739     RegOp = 5;
4740   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4741   Inst.addOperand(Inst.getOperand(0));
4742   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4743 }
4744 
4745 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4746                                     const OperandVector &Operands) {
4747   int CondOp = -1, ImmOp = -1;
4748   switch(Inst.getOpcode()) {
4749     case ARM::tB:
4750     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4751 
4752     case ARM::t2B:
4753     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4754 
4755     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4756   }
4757   // first decide whether or not the branch should be conditional
4758   // by looking at it's location relative to an IT block
4759   if(inITBlock()) {
4760     // inside an IT block we cannot have any conditional branches. any
4761     // such instructions needs to be converted to unconditional form
4762     switch(Inst.getOpcode()) {
4763       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4764       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4765     }
4766   } else {
4767     // outside IT blocks we can only have unconditional branches with AL
4768     // condition code or conditional branches with non-AL condition code
4769     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4770     switch(Inst.getOpcode()) {
4771       case ARM::tB:
4772       case ARM::tBcc:
4773         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4774         break;
4775       case ARM::t2B:
4776       case ARM::t2Bcc:
4777         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4778         break;
4779     }
4780   }
4781 
4782   // now decide on encoding size based on branch target range
4783   switch(Inst.getOpcode()) {
4784     // classify tB as either t2B or t1B based on range of immediate operand
4785     case ARM::tB: {
4786       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4787       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4788         Inst.setOpcode(ARM::t2B);
4789       break;
4790     }
4791     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4792     case ARM::tBcc: {
4793       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4794       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4795         Inst.setOpcode(ARM::t2Bcc);
4796       break;
4797     }
4798   }
4799   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4800   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4801 }
4802 
4803 /// Parse an ARM memory expression, return false if successful else return true
4804 /// or an error.  The first token must be a '[' when called.
4805 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4806   MCAsmParser &Parser = getParser();
4807   SMLoc S, E;
4808   assert(Parser.getTok().is(AsmToken::LBrac) &&
4809          "Token is not a Left Bracket");
4810   S = Parser.getTok().getLoc();
4811   Parser.Lex(); // Eat left bracket token.
4812 
4813   const AsmToken &BaseRegTok = Parser.getTok();
4814   int BaseRegNum = tryParseRegister();
4815   if (BaseRegNum == -1)
4816     return Error(BaseRegTok.getLoc(), "register expected");
4817 
4818   // The next token must either be a comma, a colon or a closing bracket.
4819   const AsmToken &Tok = Parser.getTok();
4820   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4821       !Tok.is(AsmToken::RBrac))
4822     return Error(Tok.getLoc(), "malformed memory operand");
4823 
4824   if (Tok.is(AsmToken::RBrac)) {
4825     E = Tok.getEndLoc();
4826     Parser.Lex(); // Eat right bracket token.
4827 
4828     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4829                                              ARM_AM::no_shift, 0, 0, false,
4830                                              S, E));
4831 
4832     // If there's a pre-indexing writeback marker, '!', just add it as a token
4833     // operand. It's rather odd, but syntactically valid.
4834     if (Parser.getTok().is(AsmToken::Exclaim)) {
4835       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4836       Parser.Lex(); // Eat the '!'.
4837     }
4838 
4839     return false;
4840   }
4841 
4842   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4843          "Lost colon or comma in memory operand?!");
4844   if (Tok.is(AsmToken::Comma)) {
4845     Parser.Lex(); // Eat the comma.
4846   }
4847 
4848   // If we have a ':', it's an alignment specifier.
4849   if (Parser.getTok().is(AsmToken::Colon)) {
4850     Parser.Lex(); // Eat the ':'.
4851     E = Parser.getTok().getLoc();
4852     SMLoc AlignmentLoc = Tok.getLoc();
4853 
4854     const MCExpr *Expr;
4855     if (getParser().parseExpression(Expr))
4856      return true;
4857 
4858     // The expression has to be a constant. Memory references with relocations
4859     // don't come through here, as they use the <label> forms of the relevant
4860     // instructions.
4861     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4862     if (!CE)
4863       return Error (E, "constant expression expected");
4864 
4865     unsigned Align = 0;
4866     switch (CE->getValue()) {
4867     default:
4868       return Error(E,
4869                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4870     case 16:  Align = 2; break;
4871     case 32:  Align = 4; break;
4872     case 64:  Align = 8; break;
4873     case 128: Align = 16; break;
4874     case 256: Align = 32; break;
4875     }
4876 
4877     // Now we should have the closing ']'
4878     if (Parser.getTok().isNot(AsmToken::RBrac))
4879       return Error(Parser.getTok().getLoc(), "']' expected");
4880     E = Parser.getTok().getEndLoc();
4881     Parser.Lex(); // Eat right bracket token.
4882 
4883     // Don't worry about range checking the value here. That's handled by
4884     // the is*() predicates.
4885     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4886                                              ARM_AM::no_shift, 0, Align,
4887                                              false, S, E, AlignmentLoc));
4888 
4889     // If there's a pre-indexing writeback marker, '!', just add it as a token
4890     // operand.
4891     if (Parser.getTok().is(AsmToken::Exclaim)) {
4892       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4893       Parser.Lex(); // Eat the '!'.
4894     }
4895 
4896     return false;
4897   }
4898 
4899   // If we have a '#', it's an immediate offset, else assume it's a register
4900   // offset. Be friendly and also accept a plain integer (without a leading
4901   // hash) for gas compatibility.
4902   if (Parser.getTok().is(AsmToken::Hash) ||
4903       Parser.getTok().is(AsmToken::Dollar) ||
4904       Parser.getTok().is(AsmToken::Integer)) {
4905     if (Parser.getTok().isNot(AsmToken::Integer))
4906       Parser.Lex(); // Eat '#' or '$'.
4907     E = Parser.getTok().getLoc();
4908 
4909     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4910     const MCExpr *Offset;
4911     if (getParser().parseExpression(Offset))
4912      return true;
4913 
4914     // The expression has to be a constant. Memory references with relocations
4915     // don't come through here, as they use the <label> forms of the relevant
4916     // instructions.
4917     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4918     if (!CE)
4919       return Error (E, "constant expression expected");
4920 
4921     // If the constant was #-0, represent it as INT32_MIN.
4922     int32_t Val = CE->getValue();
4923     if (isNegative && Val == 0)
4924       CE = MCConstantExpr::create(INT32_MIN, getContext());
4925 
4926     // Now we should have the closing ']'
4927     if (Parser.getTok().isNot(AsmToken::RBrac))
4928       return Error(Parser.getTok().getLoc(), "']' expected");
4929     E = Parser.getTok().getEndLoc();
4930     Parser.Lex(); // Eat right bracket token.
4931 
4932     // Don't worry about range checking the value here. That's handled by
4933     // the is*() predicates.
4934     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4935                                              ARM_AM::no_shift, 0, 0,
4936                                              false, S, E));
4937 
4938     // If there's a pre-indexing writeback marker, '!', just add it as a token
4939     // operand.
4940     if (Parser.getTok().is(AsmToken::Exclaim)) {
4941       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4942       Parser.Lex(); // Eat the '!'.
4943     }
4944 
4945     return false;
4946   }
4947 
4948   // The register offset is optionally preceded by a '+' or '-'
4949   bool isNegative = false;
4950   if (Parser.getTok().is(AsmToken::Minus)) {
4951     isNegative = true;
4952     Parser.Lex(); // Eat the '-'.
4953   } else if (Parser.getTok().is(AsmToken::Plus)) {
4954     // Nothing to do.
4955     Parser.Lex(); // Eat the '+'.
4956   }
4957 
4958   E = Parser.getTok().getLoc();
4959   int OffsetRegNum = tryParseRegister();
4960   if (OffsetRegNum == -1)
4961     return Error(E, "register expected");
4962 
4963   // If there's a shift operator, handle it.
4964   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4965   unsigned ShiftImm = 0;
4966   if (Parser.getTok().is(AsmToken::Comma)) {
4967     Parser.Lex(); // Eat the ','.
4968     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4969       return true;
4970   }
4971 
4972   // Now we should have the closing ']'
4973   if (Parser.getTok().isNot(AsmToken::RBrac))
4974     return Error(Parser.getTok().getLoc(), "']' expected");
4975   E = Parser.getTok().getEndLoc();
4976   Parser.Lex(); // Eat right bracket token.
4977 
4978   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
4979                                            ShiftType, ShiftImm, 0, isNegative,
4980                                            S, E));
4981 
4982   // If there's a pre-indexing writeback marker, '!', just add it as a token
4983   // operand.
4984   if (Parser.getTok().is(AsmToken::Exclaim)) {
4985     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4986     Parser.Lex(); // Eat the '!'.
4987   }
4988 
4989   return false;
4990 }
4991 
4992 /// parseMemRegOffsetShift - one of these two:
4993 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4994 ///   rrx
4995 /// return true if it parses a shift otherwise it returns false.
4996 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4997                                           unsigned &Amount) {
4998   MCAsmParser &Parser = getParser();
4999   SMLoc Loc = Parser.getTok().getLoc();
5000   const AsmToken &Tok = Parser.getTok();
5001   if (Tok.isNot(AsmToken::Identifier))
5002     return true;
5003   StringRef ShiftName = Tok.getString();
5004   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5005       ShiftName == "asl" || ShiftName == "ASL")
5006     St = ARM_AM::lsl;
5007   else if (ShiftName == "lsr" || ShiftName == "LSR")
5008     St = ARM_AM::lsr;
5009   else if (ShiftName == "asr" || ShiftName == "ASR")
5010     St = ARM_AM::asr;
5011   else if (ShiftName == "ror" || ShiftName == "ROR")
5012     St = ARM_AM::ror;
5013   else if (ShiftName == "rrx" || ShiftName == "RRX")
5014     St = ARM_AM::rrx;
5015   else
5016     return Error(Loc, "illegal shift operator");
5017   Parser.Lex(); // Eat shift type token.
5018 
5019   // rrx stands alone.
5020   Amount = 0;
5021   if (St != ARM_AM::rrx) {
5022     Loc = Parser.getTok().getLoc();
5023     // A '#' and a shift amount.
5024     const AsmToken &HashTok = Parser.getTok();
5025     if (HashTok.isNot(AsmToken::Hash) &&
5026         HashTok.isNot(AsmToken::Dollar))
5027       return Error(HashTok.getLoc(), "'#' expected");
5028     Parser.Lex(); // Eat hash token.
5029 
5030     const MCExpr *Expr;
5031     if (getParser().parseExpression(Expr))
5032       return true;
5033     // Range check the immediate.
5034     // lsl, ror: 0 <= imm <= 31
5035     // lsr, asr: 0 <= imm <= 32
5036     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5037     if (!CE)
5038       return Error(Loc, "shift amount must be an immediate");
5039     int64_t Imm = CE->getValue();
5040     if (Imm < 0 ||
5041         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5042         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5043       return Error(Loc, "immediate shift value out of range");
5044     // If <ShiftTy> #0, turn it into a no_shift.
5045     if (Imm == 0)
5046       St = ARM_AM::lsl;
5047     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5048     if (Imm == 32)
5049       Imm = 0;
5050     Amount = Imm;
5051   }
5052 
5053   return false;
5054 }
5055 
5056 /// parseFPImm - A floating point immediate expression operand.
5057 ARMAsmParser::OperandMatchResultTy
5058 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5059   MCAsmParser &Parser = getParser();
5060   // Anything that can accept a floating point constant as an operand
5061   // needs to go through here, as the regular parseExpression is
5062   // integer only.
5063   //
5064   // This routine still creates a generic Immediate operand, containing
5065   // a bitcast of the 64-bit floating point value. The various operands
5066   // that accept floats can check whether the value is valid for them
5067   // via the standard is*() predicates.
5068 
5069   SMLoc S = Parser.getTok().getLoc();
5070 
5071   if (Parser.getTok().isNot(AsmToken::Hash) &&
5072       Parser.getTok().isNot(AsmToken::Dollar))
5073     return MatchOperand_NoMatch;
5074 
5075   // Disambiguate the VMOV forms that can accept an FP immediate.
5076   // vmov.f32 <sreg>, #imm
5077   // vmov.f64 <dreg>, #imm
5078   // vmov.f32 <dreg>, #imm  @ vector f32x2
5079   // vmov.f32 <qreg>, #imm  @ vector f32x4
5080   //
5081   // There are also the NEON VMOV instructions which expect an
5082   // integer constant. Make sure we don't try to parse an FPImm
5083   // for these:
5084   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5085   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5086   bool isVmovf = TyOp.isToken() &&
5087                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5088                   TyOp.getToken() == ".f16");
5089   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5090   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5091                                          Mnemonic.getToken() == "fconsts");
5092   if (!(isVmovf || isFconst))
5093     return MatchOperand_NoMatch;
5094 
5095   Parser.Lex(); // Eat '#' or '$'.
5096 
5097   // Handle negation, as that still comes through as a separate token.
5098   bool isNegative = false;
5099   if (Parser.getTok().is(AsmToken::Minus)) {
5100     isNegative = true;
5101     Parser.Lex();
5102   }
5103   const AsmToken &Tok = Parser.getTok();
5104   SMLoc Loc = Tok.getLoc();
5105   if (Tok.is(AsmToken::Real) && isVmovf) {
5106     APFloat RealVal(APFloat::IEEEsingle, Tok.getString());
5107     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5108     // If we had a '-' in front, toggle the sign bit.
5109     IntVal ^= (uint64_t)isNegative << 31;
5110     Parser.Lex(); // Eat the token.
5111     Operands.push_back(ARMOperand::CreateImm(
5112           MCConstantExpr::create(IntVal, getContext()),
5113           S, Parser.getTok().getLoc()));
5114     return MatchOperand_Success;
5115   }
5116   // Also handle plain integers. Instructions which allow floating point
5117   // immediates also allow a raw encoded 8-bit value.
5118   if (Tok.is(AsmToken::Integer) && isFconst) {
5119     int64_t Val = Tok.getIntVal();
5120     Parser.Lex(); // Eat the token.
5121     if (Val > 255 || Val < 0) {
5122       Error(Loc, "encoded floating point value out of range");
5123       return MatchOperand_ParseFail;
5124     }
5125     float RealVal = ARM_AM::getFPImmFloat(Val);
5126     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5127 
5128     Operands.push_back(ARMOperand::CreateImm(
5129         MCConstantExpr::create(Val, getContext()), S,
5130         Parser.getTok().getLoc()));
5131     return MatchOperand_Success;
5132   }
5133 
5134   Error(Loc, "invalid floating point immediate");
5135   return MatchOperand_ParseFail;
5136 }
5137 
5138 /// Parse a arm instruction operand.  For now this parses the operand regardless
5139 /// of the mnemonic.
5140 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5141   MCAsmParser &Parser = getParser();
5142   SMLoc S, E;
5143 
5144   // Check if the current operand has a custom associated parser, if so, try to
5145   // custom parse the operand, or fallback to the general approach.
5146   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5147   if (ResTy == MatchOperand_Success)
5148     return false;
5149   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5150   // there was a match, but an error occurred, in which case, just return that
5151   // the operand parsing failed.
5152   if (ResTy == MatchOperand_ParseFail)
5153     return true;
5154 
5155   switch (getLexer().getKind()) {
5156   default:
5157     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5158     return true;
5159   case AsmToken::Identifier: {
5160     // If we've seen a branch mnemonic, the next operand must be a label.  This
5161     // is true even if the label is a register name.  So "br r1" means branch to
5162     // label "r1".
5163     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5164     if (!ExpectLabel) {
5165       if (!tryParseRegisterWithWriteBack(Operands))
5166         return false;
5167       int Res = tryParseShiftRegister(Operands);
5168       if (Res == 0) // success
5169         return false;
5170       else if (Res == -1) // irrecoverable error
5171         return true;
5172       // If this is VMRS, check for the apsr_nzcv operand.
5173       if (Mnemonic == "vmrs" &&
5174           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5175         S = Parser.getTok().getLoc();
5176         Parser.Lex();
5177         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5178         return false;
5179       }
5180     }
5181 
5182     // Fall though for the Identifier case that is not a register or a
5183     // special name.
5184   }
5185   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5186   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5187   case AsmToken::String:  // quoted label names.
5188   case AsmToken::Dot: {   // . as a branch target
5189     // This was not a register so parse other operands that start with an
5190     // identifier (like labels) as expressions and create them as immediates.
5191     const MCExpr *IdVal;
5192     S = Parser.getTok().getLoc();
5193     if (getParser().parseExpression(IdVal))
5194       return true;
5195     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5196     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5197     return false;
5198   }
5199   case AsmToken::LBrac:
5200     return parseMemory(Operands);
5201   case AsmToken::LCurly:
5202     return parseRegisterList(Operands);
5203   case AsmToken::Dollar:
5204   case AsmToken::Hash: {
5205     // #42 -> immediate.
5206     S = Parser.getTok().getLoc();
5207     Parser.Lex();
5208 
5209     if (Parser.getTok().isNot(AsmToken::Colon)) {
5210       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5211       const MCExpr *ImmVal;
5212       if (getParser().parseExpression(ImmVal))
5213         return true;
5214       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5215       if (CE) {
5216         int32_t Val = CE->getValue();
5217         if (isNegative && Val == 0)
5218           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5219       }
5220       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5221       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5222 
5223       // There can be a trailing '!' on operands that we want as a separate
5224       // '!' Token operand. Handle that here. For example, the compatibility
5225       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5226       if (Parser.getTok().is(AsmToken::Exclaim)) {
5227         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5228                                                    Parser.getTok().getLoc()));
5229         Parser.Lex(); // Eat exclaim token
5230       }
5231       return false;
5232     }
5233     // w/ a ':' after the '#', it's just like a plain ':'.
5234     // FALLTHROUGH
5235   }
5236   case AsmToken::Colon: {
5237     S = Parser.getTok().getLoc();
5238     // ":lower16:" and ":upper16:" expression prefixes
5239     // FIXME: Check it's an expression prefix,
5240     // e.g. (FOO - :lower16:BAR) isn't legal.
5241     ARMMCExpr::VariantKind RefKind;
5242     if (parsePrefix(RefKind))
5243       return true;
5244 
5245     const MCExpr *SubExprVal;
5246     if (getParser().parseExpression(SubExprVal))
5247       return true;
5248 
5249     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5250                                               getContext());
5251     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5252     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5253     return false;
5254   }
5255   case AsmToken::Equal: {
5256     S = Parser.getTok().getLoc();
5257     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5258       return Error(S, "unexpected token in operand");
5259     Parser.Lex(); // Eat '='
5260     const MCExpr *SubExprVal;
5261     if (getParser().parseExpression(SubExprVal))
5262       return true;
5263     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5264     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5265     return false;
5266   }
5267   }
5268 }
5269 
5270 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5271 //  :lower16: and :upper16:.
5272 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5273   MCAsmParser &Parser = getParser();
5274   RefKind = ARMMCExpr::VK_ARM_None;
5275 
5276   // consume an optional '#' (GNU compatibility)
5277   if (getLexer().is(AsmToken::Hash))
5278     Parser.Lex();
5279 
5280   // :lower16: and :upper16: modifiers
5281   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5282   Parser.Lex(); // Eat ':'
5283 
5284   if (getLexer().isNot(AsmToken::Identifier)) {
5285     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5286     return true;
5287   }
5288 
5289   enum {
5290     COFF = (1 << MCObjectFileInfo::IsCOFF),
5291     ELF = (1 << MCObjectFileInfo::IsELF),
5292     MACHO = (1 << MCObjectFileInfo::IsMachO)
5293   };
5294   static const struct PrefixEntry {
5295     const char *Spelling;
5296     ARMMCExpr::VariantKind VariantKind;
5297     uint8_t SupportedFormats;
5298   } PrefixEntries[] = {
5299     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5300     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5301   };
5302 
5303   StringRef IDVal = Parser.getTok().getIdentifier();
5304 
5305   const auto &Prefix =
5306       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5307                    [&IDVal](const PrefixEntry &PE) {
5308                       return PE.Spelling == IDVal;
5309                    });
5310   if (Prefix == std::end(PrefixEntries)) {
5311     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5312     return true;
5313   }
5314 
5315   uint8_t CurrentFormat;
5316   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5317   case MCObjectFileInfo::IsMachO:
5318     CurrentFormat = MACHO;
5319     break;
5320   case MCObjectFileInfo::IsELF:
5321     CurrentFormat = ELF;
5322     break;
5323   case MCObjectFileInfo::IsCOFF:
5324     CurrentFormat = COFF;
5325     break;
5326   }
5327 
5328   if (~Prefix->SupportedFormats & CurrentFormat) {
5329     Error(Parser.getTok().getLoc(),
5330           "cannot represent relocation in the current file format");
5331     return true;
5332   }
5333 
5334   RefKind = Prefix->VariantKind;
5335   Parser.Lex();
5336 
5337   if (getLexer().isNot(AsmToken::Colon)) {
5338     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5339     return true;
5340   }
5341   Parser.Lex(); // Eat the last ':'
5342 
5343   return false;
5344 }
5345 
5346 /// \brief Given a mnemonic, split out possible predication code and carry
5347 /// setting letters to form a canonical mnemonic and flags.
5348 //
5349 // FIXME: Would be nice to autogen this.
5350 // FIXME: This is a bit of a maze of special cases.
5351 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5352                                       unsigned &PredicationCode,
5353                                       bool &CarrySetting,
5354                                       unsigned &ProcessorIMod,
5355                                       StringRef &ITMask) {
5356   PredicationCode = ARMCC::AL;
5357   CarrySetting = false;
5358   ProcessorIMod = 0;
5359 
5360   // Ignore some mnemonics we know aren't predicated forms.
5361   //
5362   // FIXME: Would be nice to autogen this.
5363   if ((Mnemonic == "movs" && isThumb()) ||
5364       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5365       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5366       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5367       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5368       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5369       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5370       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5371       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5372       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5373       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5374       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5375       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5376       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5377       Mnemonic == "bxns"  || Mnemonic == "blxns")
5378     return Mnemonic;
5379 
5380   // First, split out any predication code. Ignore mnemonics we know aren't
5381   // predicated but do have a carry-set and so weren't caught above.
5382   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5383       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5384       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5385       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5386     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5387       .Case("eq", ARMCC::EQ)
5388       .Case("ne", ARMCC::NE)
5389       .Case("hs", ARMCC::HS)
5390       .Case("cs", ARMCC::HS)
5391       .Case("lo", ARMCC::LO)
5392       .Case("cc", ARMCC::LO)
5393       .Case("mi", ARMCC::MI)
5394       .Case("pl", ARMCC::PL)
5395       .Case("vs", ARMCC::VS)
5396       .Case("vc", ARMCC::VC)
5397       .Case("hi", ARMCC::HI)
5398       .Case("ls", ARMCC::LS)
5399       .Case("ge", ARMCC::GE)
5400       .Case("lt", ARMCC::LT)
5401       .Case("gt", ARMCC::GT)
5402       .Case("le", ARMCC::LE)
5403       .Case("al", ARMCC::AL)
5404       .Default(~0U);
5405     if (CC != ~0U) {
5406       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5407       PredicationCode = CC;
5408     }
5409   }
5410 
5411   // Next, determine if we have a carry setting bit. We explicitly ignore all
5412   // the instructions we know end in 's'.
5413   if (Mnemonic.endswith("s") &&
5414       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5415         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5416         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5417         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5418         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5419         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5420         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5421         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5422         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5423         (Mnemonic == "movs" && isThumb()))) {
5424     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5425     CarrySetting = true;
5426   }
5427 
5428   // The "cps" instruction can have a interrupt mode operand which is glued into
5429   // the mnemonic. Check if this is the case, split it and parse the imod op
5430   if (Mnemonic.startswith("cps")) {
5431     // Split out any imod code.
5432     unsigned IMod =
5433       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5434       .Case("ie", ARM_PROC::IE)
5435       .Case("id", ARM_PROC::ID)
5436       .Default(~0U);
5437     if (IMod != ~0U) {
5438       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5439       ProcessorIMod = IMod;
5440     }
5441   }
5442 
5443   // The "it" instruction has the condition mask on the end of the mnemonic.
5444   if (Mnemonic.startswith("it")) {
5445     ITMask = Mnemonic.slice(2, Mnemonic.size());
5446     Mnemonic = Mnemonic.slice(0, 2);
5447   }
5448 
5449   return Mnemonic;
5450 }
5451 
5452 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5453 /// inclusion of carry set or predication code operands.
5454 //
5455 // FIXME: It would be nice to autogen this.
5456 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5457                                          bool &CanAcceptCarrySet,
5458                                          bool &CanAcceptPredicationCode) {
5459   CanAcceptCarrySet =
5460       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5461       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5462       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5463       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5464       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5465       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5466       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5467       (!isThumb() &&
5468        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5469         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5470 
5471   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5472       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5473       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5474       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5475       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5476       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5477       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5478       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5479       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5480       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5481       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5482       Mnemonic == "vmovx" || Mnemonic == "vins") {
5483     // These mnemonics are never predicable
5484     CanAcceptPredicationCode = false;
5485   } else if (!isThumb()) {
5486     // Some instructions are only predicable in Thumb mode
5487     CanAcceptPredicationCode =
5488         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5489         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5490         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5491         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5492         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5493         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5494         !Mnemonic.startswith("srs");
5495   } else if (isThumbOne()) {
5496     if (hasV6MOps())
5497       CanAcceptPredicationCode = Mnemonic != "movs";
5498     else
5499       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5500   } else
5501     CanAcceptPredicationCode = true;
5502 }
5503 
5504 // \brief Some Thumb instructions have two operand forms that are not
5505 // available as three operand, convert to two operand form if possible.
5506 //
5507 // FIXME: We would really like to be able to tablegen'erate this.
5508 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5509                                                  bool CarrySetting,
5510                                                  OperandVector &Operands) {
5511   if (Operands.size() != 6)
5512     return;
5513 
5514   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5515         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5516   if (!Op3.isReg() || !Op4.isReg())
5517     return;
5518 
5519   auto Op3Reg = Op3.getReg();
5520   auto Op4Reg = Op4.getReg();
5521 
5522   // For most Thumb2 cases we just generate the 3 operand form and reduce
5523   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5524   // won't accept SP or PC so we do the transformation here taking care
5525   // with immediate range in the 'add sp, sp #imm' case.
5526   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5527   if (isThumbTwo()) {
5528     if (Mnemonic != "add")
5529       return;
5530     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5531                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5532     if (!TryTransform) {
5533       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5534                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5535                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5536                        Op5.isImm() && !Op5.isImm0_508s4());
5537     }
5538     if (!TryTransform)
5539       return;
5540   } else if (!isThumbOne())
5541     return;
5542 
5543   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5544         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5545         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5546         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5547     return;
5548 
5549   // If first 2 operands of a 3 operand instruction are the same
5550   // then transform to 2 operand version of the same instruction
5551   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5552   bool Transform = Op3Reg == Op4Reg;
5553 
5554   // For communtative operations, we might be able to transform if we swap
5555   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5556   // as tADDrsp.
5557   const ARMOperand *LastOp = &Op5;
5558   bool Swap = false;
5559   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5560       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5561        Mnemonic == "and" || Mnemonic == "eor" ||
5562        Mnemonic == "adc" || Mnemonic == "orr")) {
5563     Swap = true;
5564     LastOp = &Op4;
5565     Transform = true;
5566   }
5567 
5568   // If both registers are the same then remove one of them from
5569   // the operand list, with certain exceptions.
5570   if (Transform) {
5571     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5572     // 2 operand forms don't exist.
5573     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5574         LastOp->isReg())
5575       Transform = false;
5576 
5577     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5578     // 3-bits because the ARMARM says not to.
5579     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5580       Transform = false;
5581   }
5582 
5583   if (Transform) {
5584     if (Swap)
5585       std::swap(Op4, Op5);
5586     Operands.erase(Operands.begin() + 3);
5587   }
5588 }
5589 
5590 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5591                                           OperandVector &Operands) {
5592   // FIXME: This is all horribly hacky. We really need a better way to deal
5593   // with optional operands like this in the matcher table.
5594 
5595   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5596   // another does not. Specifically, the MOVW instruction does not. So we
5597   // special case it here and remove the defaulted (non-setting) cc_out
5598   // operand if that's the instruction we're trying to match.
5599   //
5600   // We do this as post-processing of the explicit operands rather than just
5601   // conditionally adding the cc_out in the first place because we need
5602   // to check the type of the parsed immediate operand.
5603   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5604       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5605       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5606       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5607     return true;
5608 
5609   // Register-register 'add' for thumb does not have a cc_out operand
5610   // when there are only two register operands.
5611   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5612       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5613       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5614       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5615     return true;
5616   // Register-register 'add' for thumb does not have a cc_out operand
5617   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5618   // have to check the immediate range here since Thumb2 has a variant
5619   // that can handle a different range and has a cc_out operand.
5620   if (((isThumb() && Mnemonic == "add") ||
5621        (isThumbTwo() && Mnemonic == "sub")) &&
5622       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5623       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5624       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5625       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5626       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5627        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5628     return true;
5629   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5630   // imm0_4095 variant. That's the least-preferred variant when
5631   // selecting via the generic "add" mnemonic, so to know that we
5632   // should remove the cc_out operand, we have to explicitly check that
5633   // it's not one of the other variants. Ugh.
5634   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5635       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5636       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5637       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5638     // Nest conditions rather than one big 'if' statement for readability.
5639     //
5640     // If both registers are low, we're in an IT block, and the immediate is
5641     // in range, we should use encoding T1 instead, which has a cc_out.
5642     if (inITBlock() &&
5643         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5644         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5645         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5646       return false;
5647     // Check against T3. If the second register is the PC, this is an
5648     // alternate form of ADR, which uses encoding T4, so check for that too.
5649     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5650         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5651       return false;
5652 
5653     // Otherwise, we use encoding T4, which does not have a cc_out
5654     // operand.
5655     return true;
5656   }
5657 
5658   // The thumb2 multiply instruction doesn't have a CCOut register, so
5659   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5660   // use the 16-bit encoding or not.
5661   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5662       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5663       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5664       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5665       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5666       // If the registers aren't low regs, the destination reg isn't the
5667       // same as one of the source regs, or the cc_out operand is zero
5668       // outside of an IT block, we have to use the 32-bit encoding, so
5669       // remove the cc_out operand.
5670       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5671        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5672        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5673        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5674                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5675                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5676                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5677     return true;
5678 
5679   // Also check the 'mul' syntax variant that doesn't specify an explicit
5680   // destination register.
5681   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5682       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5683       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5684       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5685       // If the registers aren't low regs  or the cc_out operand is zero
5686       // outside of an IT block, we have to use the 32-bit encoding, so
5687       // remove the cc_out operand.
5688       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5689        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5690        !inITBlock()))
5691     return true;
5692 
5693 
5694 
5695   // Register-register 'add/sub' for thumb does not have a cc_out operand
5696   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5697   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5698   // right, this will result in better diagnostics (which operand is off)
5699   // anyway.
5700   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5701       (Operands.size() == 5 || Operands.size() == 6) &&
5702       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5703       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5704       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5705       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5706        (Operands.size() == 6 &&
5707         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5708     return true;
5709 
5710   return false;
5711 }
5712 
5713 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5714                                               OperandVector &Operands) {
5715   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5716   unsigned RegIdx = 3;
5717   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5718       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5719        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5720     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5721         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5722          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5723       RegIdx = 4;
5724 
5725     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5726         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5727              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5728          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5729              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5730       return true;
5731   }
5732   return false;
5733 }
5734 
5735 static bool isDataTypeToken(StringRef Tok) {
5736   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5737     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5738     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5739     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5740     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5741     Tok == ".f" || Tok == ".d";
5742 }
5743 
5744 // FIXME: This bit should probably be handled via an explicit match class
5745 // in the .td files that matches the suffix instead of having it be
5746 // a literal string token the way it is now.
5747 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5748   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5749 }
5750 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5751                                  unsigned VariantID);
5752 
5753 static bool RequiresVFPRegListValidation(StringRef Inst,
5754                                          bool &AcceptSinglePrecisionOnly,
5755                                          bool &AcceptDoublePrecisionOnly) {
5756   if (Inst.size() < 7)
5757     return false;
5758 
5759   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5760     StringRef AddressingMode = Inst.substr(4, 2);
5761     if (AddressingMode == "ia" || AddressingMode == "db" ||
5762         AddressingMode == "ea" || AddressingMode == "fd") {
5763       AcceptSinglePrecisionOnly = Inst[6] == 's';
5764       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5765       return true;
5766     }
5767   }
5768 
5769   return false;
5770 }
5771 
5772 /// Parse an arm instruction mnemonic followed by its operands.
5773 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5774                                     SMLoc NameLoc, OperandVector &Operands) {
5775   MCAsmParser &Parser = getParser();
5776   // FIXME: Can this be done via tablegen in some fashion?
5777   bool RequireVFPRegisterListCheck;
5778   bool AcceptSinglePrecisionOnly;
5779   bool AcceptDoublePrecisionOnly;
5780   RequireVFPRegisterListCheck =
5781     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5782                                  AcceptDoublePrecisionOnly);
5783 
5784   // Apply mnemonic aliases before doing anything else, as the destination
5785   // mnemonic may include suffices and we want to handle them normally.
5786   // The generic tblgen'erated code does this later, at the start of
5787   // MatchInstructionImpl(), but that's too late for aliases that include
5788   // any sort of suffix.
5789   uint64_t AvailableFeatures = getAvailableFeatures();
5790   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5791   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5792 
5793   // First check for the ARM-specific .req directive.
5794   if (Parser.getTok().is(AsmToken::Identifier) &&
5795       Parser.getTok().getIdentifier() == ".req") {
5796     parseDirectiveReq(Name, NameLoc);
5797     // We always return 'error' for this, as we're done with this
5798     // statement and don't need to match the 'instruction."
5799     return true;
5800   }
5801 
5802   // Create the leading tokens for the mnemonic, split by '.' characters.
5803   size_t Start = 0, Next = Name.find('.');
5804   StringRef Mnemonic = Name.slice(Start, Next);
5805 
5806   // Split out the predication code and carry setting flag from the mnemonic.
5807   unsigned PredicationCode;
5808   unsigned ProcessorIMod;
5809   bool CarrySetting;
5810   StringRef ITMask;
5811   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5812                            ProcessorIMod, ITMask);
5813 
5814   // In Thumb1, only the branch (B) instruction can be predicated.
5815   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5816     Parser.eatToEndOfStatement();
5817     return Error(NameLoc, "conditional execution not supported in Thumb1");
5818   }
5819 
5820   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5821 
5822   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5823   // is the mask as it will be for the IT encoding if the conditional
5824   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5825   // where the conditional bit0 is zero, the instruction post-processing
5826   // will adjust the mask accordingly.
5827   if (Mnemonic == "it") {
5828     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5829     if (ITMask.size() > 3) {
5830       Parser.eatToEndOfStatement();
5831       return Error(Loc, "too many conditions on IT instruction");
5832     }
5833     unsigned Mask = 8;
5834     for (unsigned i = ITMask.size(); i != 0; --i) {
5835       char pos = ITMask[i - 1];
5836       if (pos != 't' && pos != 'e') {
5837         Parser.eatToEndOfStatement();
5838         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5839       }
5840       Mask >>= 1;
5841       if (ITMask[i - 1] == 't')
5842         Mask |= 8;
5843     }
5844     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5845   }
5846 
5847   // FIXME: This is all a pretty gross hack. We should automatically handle
5848   // optional operands like this via tblgen.
5849 
5850   // Next, add the CCOut and ConditionCode operands, if needed.
5851   //
5852   // For mnemonics which can ever incorporate a carry setting bit or predication
5853   // code, our matching model involves us always generating CCOut and
5854   // ConditionCode operands to match the mnemonic "as written" and then we let
5855   // the matcher deal with finding the right instruction or generating an
5856   // appropriate error.
5857   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5858   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5859 
5860   // If we had a carry-set on an instruction that can't do that, issue an
5861   // error.
5862   if (!CanAcceptCarrySet && CarrySetting) {
5863     Parser.eatToEndOfStatement();
5864     return Error(NameLoc, "instruction '" + Mnemonic +
5865                  "' can not set flags, but 's' suffix specified");
5866   }
5867   // If we had a predication code on an instruction that can't do that, issue an
5868   // error.
5869   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5870     Parser.eatToEndOfStatement();
5871     return Error(NameLoc, "instruction '" + Mnemonic +
5872                  "' is not predicable, but condition code specified");
5873   }
5874 
5875   // Add the carry setting operand, if necessary.
5876   if (CanAcceptCarrySet) {
5877     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5878     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5879                                                Loc));
5880   }
5881 
5882   // Add the predication code operand, if necessary.
5883   if (CanAcceptPredicationCode) {
5884     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5885                                       CarrySetting);
5886     Operands.push_back(ARMOperand::CreateCondCode(
5887                          ARMCC::CondCodes(PredicationCode), Loc));
5888   }
5889 
5890   // Add the processor imod operand, if necessary.
5891   if (ProcessorIMod) {
5892     Operands.push_back(ARMOperand::CreateImm(
5893           MCConstantExpr::create(ProcessorIMod, getContext()),
5894                                  NameLoc, NameLoc));
5895   } else if (Mnemonic == "cps" && isMClass()) {
5896     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5897   }
5898 
5899   // Add the remaining tokens in the mnemonic.
5900   while (Next != StringRef::npos) {
5901     Start = Next;
5902     Next = Name.find('.', Start + 1);
5903     StringRef ExtraToken = Name.slice(Start, Next);
5904 
5905     // Some NEON instructions have an optional datatype suffix that is
5906     // completely ignored. Check for that.
5907     if (isDataTypeToken(ExtraToken) &&
5908         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5909       continue;
5910 
5911     // For for ARM mode generate an error if the .n qualifier is used.
5912     if (ExtraToken == ".n" && !isThumb()) {
5913       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5914       Parser.eatToEndOfStatement();
5915       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5916                    "arm mode");
5917     }
5918 
5919     // The .n qualifier is always discarded as that is what the tables
5920     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5921     // so discard it to avoid errors that can be caused by the matcher.
5922     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5923       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5924       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5925     }
5926   }
5927 
5928   // Read the remaining operands.
5929   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5930     // Read the first operand.
5931     if (parseOperand(Operands, Mnemonic)) {
5932       Parser.eatToEndOfStatement();
5933       return true;
5934     }
5935 
5936     while (getLexer().is(AsmToken::Comma)) {
5937       Parser.Lex();  // Eat the comma.
5938 
5939       // Parse and remember the operand.
5940       if (parseOperand(Operands, Mnemonic)) {
5941         Parser.eatToEndOfStatement();
5942         return true;
5943       }
5944     }
5945   }
5946 
5947   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5948     SMLoc Loc = getLexer().getLoc();
5949     Parser.eatToEndOfStatement();
5950     return Error(Loc, "unexpected token in argument list");
5951   }
5952 
5953   Parser.Lex(); // Consume the EndOfStatement
5954 
5955   if (RequireVFPRegisterListCheck) {
5956     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5957     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5958       return Error(Op.getStartLoc(),
5959                    "VFP/Neon single precision register expected");
5960     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5961       return Error(Op.getStartLoc(),
5962                    "VFP/Neon double precision register expected");
5963   }
5964 
5965   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
5966 
5967   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5968   // do and don't have a cc_out optional-def operand. With some spot-checks
5969   // of the operand list, we can figure out which variant we're trying to
5970   // parse and adjust accordingly before actually matching. We shouldn't ever
5971   // try to remove a cc_out operand that was explicitly set on the
5972   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5973   // table driven matcher doesn't fit well with the ARM instruction set.
5974   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
5975     Operands.erase(Operands.begin() + 1);
5976 
5977   // Some instructions have the same mnemonic, but don't always
5978   // have a predicate. Distinguish them here and delete the
5979   // predicate if needed.
5980   if (shouldOmitPredicateOperand(Mnemonic, Operands))
5981     Operands.erase(Operands.begin() + 1);
5982 
5983   // ARM mode 'blx' need special handling, as the register operand version
5984   // is predicable, but the label operand version is not. So, we can't rely
5985   // on the Mnemonic based checking to correctly figure out when to put
5986   // a k_CondCode operand in the list. If we're trying to match the label
5987   // version, remove the k_CondCode operand here.
5988   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
5989       static_cast<ARMOperand &>(*Operands[2]).isImm())
5990     Operands.erase(Operands.begin() + 1);
5991 
5992   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
5993   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
5994   // a single GPRPair reg operand is used in the .td file to replace the two
5995   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
5996   // expressed as a GPRPair, so we have to manually merge them.
5997   // FIXME: We would really like to be able to tablegen'erate this.
5998   if (!isThumb() && Operands.size() > 4 &&
5999       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6000        Mnemonic == "stlexd")) {
6001     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6002     unsigned Idx = isLoad ? 2 : 3;
6003     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6004     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6005 
6006     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6007     // Adjust only if Op1 and Op2 are GPRs.
6008     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6009         MRC.contains(Op2.getReg())) {
6010       unsigned Reg1 = Op1.getReg();
6011       unsigned Reg2 = Op2.getReg();
6012       unsigned Rt = MRI->getEncodingValue(Reg1);
6013       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6014 
6015       // Rt2 must be Rt + 1 and Rt must be even.
6016       if (Rt + 1 != Rt2 || (Rt & 1)) {
6017         Error(Op2.getStartLoc(), isLoad
6018                                      ? "destination operands must be sequential"
6019                                      : "source operands must be sequential");
6020         return true;
6021       }
6022       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6023           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6024       Operands[Idx] =
6025           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6026       Operands.erase(Operands.begin() + Idx + 1);
6027     }
6028   }
6029 
6030   // GNU Assembler extension (compatibility)
6031   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
6032     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6033     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6034     if (Op3.isMem()) {
6035       assert(Op2.isReg() && "expected register argument");
6036 
6037       unsigned SuperReg = MRI->getMatchingSuperReg(
6038           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
6039 
6040       assert(SuperReg && "expected register pair");
6041 
6042       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
6043 
6044       Operands.insert(
6045           Operands.begin() + 3,
6046           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6047     }
6048   }
6049 
6050   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6051   // does not fit with other "subs" and tblgen.
6052   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6053   // so the Mnemonic is the original name "subs" and delete the predicate
6054   // operand so it will match the table entry.
6055   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6056       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6057       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6058       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6059       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6060       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6061     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6062     Operands.erase(Operands.begin() + 1);
6063   }
6064   return false;
6065 }
6066 
6067 // Validate context-sensitive operand constraints.
6068 
6069 // return 'true' if register list contains non-low GPR registers,
6070 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6071 // 'containsReg' to true.
6072 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6073                                  unsigned Reg, unsigned HiReg,
6074                                  bool &containsReg) {
6075   containsReg = false;
6076   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6077     unsigned OpReg = Inst.getOperand(i).getReg();
6078     if (OpReg == Reg)
6079       containsReg = true;
6080     // Anything other than a low register isn't legal here.
6081     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6082       return true;
6083   }
6084   return false;
6085 }
6086 
6087 // Check if the specified regisgter is in the register list of the inst,
6088 // starting at the indicated operand number.
6089 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6090   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6091     unsigned OpReg = Inst.getOperand(i).getReg();
6092     if (OpReg == Reg)
6093       return true;
6094   }
6095   return false;
6096 }
6097 
6098 // Return true if instruction has the interesting property of being
6099 // allowed in IT blocks, but not being predicable.
6100 static bool instIsBreakpoint(const MCInst &Inst) {
6101     return Inst.getOpcode() == ARM::tBKPT ||
6102            Inst.getOpcode() == ARM::BKPT ||
6103            Inst.getOpcode() == ARM::tHLT ||
6104            Inst.getOpcode() == ARM::HLT;
6105 
6106 }
6107 
6108 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6109                                        const OperandVector &Operands,
6110                                        unsigned ListNo, bool IsARPop) {
6111   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6112   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6113 
6114   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6115   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6116   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6117 
6118   if (!IsARPop && ListContainsSP)
6119     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6120                  "SP may not be in the register list");
6121   else if (ListContainsPC && ListContainsLR)
6122     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6123                  "PC and LR may not be in the register list simultaneously");
6124   else if (inITBlock() && !lastInITBlock() && ListContainsPC)
6125     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6126                  "instruction must be outside of IT block or the last "
6127                  "instruction in an IT block");
6128   return false;
6129 }
6130 
6131 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6132                                        const OperandVector &Operands,
6133                                        unsigned ListNo) {
6134   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6135   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6136 
6137   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6138   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6139 
6140   if (ListContainsSP && ListContainsPC)
6141     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6142                  "SP and PC may not be in the register list");
6143   else if (ListContainsSP)
6144     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6145                  "SP may not be in the register list");
6146   else if (ListContainsPC)
6147     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6148                  "PC may not be in the register list");
6149   return false;
6150 }
6151 
6152 // FIXME: We would really like to be able to tablegen'erate this.
6153 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6154                                        const OperandVector &Operands) {
6155   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6156   SMLoc Loc = Operands[0]->getStartLoc();
6157 
6158   // Check the IT block state first.
6159   // NOTE: BKPT and HLT instructions have the interesting property of being
6160   // allowed in IT blocks, but not being predicable. They just always execute.
6161   if (inITBlock() && !instIsBreakpoint(Inst)) {
6162     unsigned Bit = 1;
6163     if (ITState.FirstCond)
6164       ITState.FirstCond = false;
6165     else
6166       Bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
6167     // The instruction must be predicable.
6168     if (!MCID.isPredicable())
6169       return Error(Loc, "instructions in IT block must be predicable");
6170     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6171     unsigned ITCond = Bit ? ITState.Cond :
6172       ARMCC::getOppositeCondition(ITState.Cond);
6173     if (Cond != ITCond) {
6174       // Find the condition code Operand to get its SMLoc information.
6175       SMLoc CondLoc;
6176       for (unsigned I = 1; I < Operands.size(); ++I)
6177         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6178           CondLoc = Operands[I]->getStartLoc();
6179       return Error(CondLoc, "incorrect condition in IT block; got '" +
6180                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6181                    "', but expected '" +
6182                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
6183     }
6184   // Check for non-'al' condition codes outside of the IT block.
6185   } else if (isThumbTwo() && MCID.isPredicable() &&
6186              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6187              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6188              Inst.getOpcode() != ARM::t2Bcc)
6189     return Error(Loc, "predicated instructions must be in IT block");
6190 
6191   const unsigned Opcode = Inst.getOpcode();
6192   switch (Opcode) {
6193   case ARM::LDRD:
6194   case ARM::LDRD_PRE:
6195   case ARM::LDRD_POST: {
6196     const unsigned RtReg = Inst.getOperand(0).getReg();
6197 
6198     // Rt can't be R14.
6199     if (RtReg == ARM::LR)
6200       return Error(Operands[3]->getStartLoc(),
6201                    "Rt can't be R14");
6202 
6203     const unsigned Rt = MRI->getEncodingValue(RtReg);
6204     // Rt must be even-numbered.
6205     if ((Rt & 1) == 1)
6206       return Error(Operands[3]->getStartLoc(),
6207                    "Rt must be even-numbered");
6208 
6209     // Rt2 must be Rt + 1.
6210     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6211     if (Rt2 != Rt + 1)
6212       return Error(Operands[3]->getStartLoc(),
6213                    "destination operands must be sequential");
6214 
6215     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6216       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6217       // For addressing modes with writeback, the base register needs to be
6218       // different from the destination registers.
6219       if (Rn == Rt || Rn == Rt2)
6220         return Error(Operands[3]->getStartLoc(),
6221                      "base register needs to be different from destination "
6222                      "registers");
6223     }
6224 
6225     return false;
6226   }
6227   case ARM::t2LDRDi8:
6228   case ARM::t2LDRD_PRE:
6229   case ARM::t2LDRD_POST: {
6230     // Rt2 must be different from Rt.
6231     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6232     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6233     if (Rt2 == Rt)
6234       return Error(Operands[3]->getStartLoc(),
6235                    "destination operands can't be identical");
6236     return false;
6237   }
6238   case ARM::t2BXJ: {
6239     const unsigned RmReg = Inst.getOperand(0).getReg();
6240     // Rm = SP is no longer unpredictable in v8-A
6241     if (RmReg == ARM::SP && !hasV8Ops())
6242       return Error(Operands[2]->getStartLoc(),
6243                    "r13 (SP) is an unpredictable operand to BXJ");
6244     return false;
6245   }
6246   case ARM::STRD: {
6247     // Rt2 must be Rt + 1.
6248     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6249     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6250     if (Rt2 != Rt + 1)
6251       return Error(Operands[3]->getStartLoc(),
6252                    "source operands must be sequential");
6253     return false;
6254   }
6255   case ARM::STRD_PRE:
6256   case ARM::STRD_POST: {
6257     // Rt2 must be Rt + 1.
6258     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6259     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6260     if (Rt2 != Rt + 1)
6261       return Error(Operands[3]->getStartLoc(),
6262                    "source operands must be sequential");
6263     return false;
6264   }
6265   case ARM::STR_PRE_IMM:
6266   case ARM::STR_PRE_REG:
6267   case ARM::STR_POST_IMM:
6268   case ARM::STR_POST_REG:
6269   case ARM::STRH_PRE:
6270   case ARM::STRH_POST:
6271   case ARM::STRB_PRE_IMM:
6272   case ARM::STRB_PRE_REG:
6273   case ARM::STRB_POST_IMM:
6274   case ARM::STRB_POST_REG: {
6275     // Rt must be different from Rn.
6276     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6277     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6278 
6279     if (Rt == Rn)
6280       return Error(Operands[3]->getStartLoc(),
6281                    "source register and base register can't be identical");
6282     return false;
6283   }
6284   case ARM::LDR_PRE_IMM:
6285   case ARM::LDR_PRE_REG:
6286   case ARM::LDR_POST_IMM:
6287   case ARM::LDR_POST_REG:
6288   case ARM::LDRH_PRE:
6289   case ARM::LDRH_POST:
6290   case ARM::LDRSH_PRE:
6291   case ARM::LDRSH_POST:
6292   case ARM::LDRB_PRE_IMM:
6293   case ARM::LDRB_PRE_REG:
6294   case ARM::LDRB_POST_IMM:
6295   case ARM::LDRB_POST_REG:
6296   case ARM::LDRSB_PRE:
6297   case ARM::LDRSB_POST: {
6298     // Rt must be different from Rn.
6299     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6300     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6301 
6302     if (Rt == Rn)
6303       return Error(Operands[3]->getStartLoc(),
6304                    "destination register and base register can't be identical");
6305     return false;
6306   }
6307   case ARM::SBFX:
6308   case ARM::UBFX: {
6309     // Width must be in range [1, 32-lsb].
6310     unsigned LSB = Inst.getOperand(2).getImm();
6311     unsigned Widthm1 = Inst.getOperand(3).getImm();
6312     if (Widthm1 >= 32 - LSB)
6313       return Error(Operands[5]->getStartLoc(),
6314                    "bitfield width must be in range [1,32-lsb]");
6315     return false;
6316   }
6317   // Notionally handles ARM::tLDMIA_UPD too.
6318   case ARM::tLDMIA: {
6319     // If we're parsing Thumb2, the .w variant is available and handles
6320     // most cases that are normally illegal for a Thumb1 LDM instruction.
6321     // We'll make the transformation in processInstruction() if necessary.
6322     //
6323     // Thumb LDM instructions are writeback iff the base register is not
6324     // in the register list.
6325     unsigned Rn = Inst.getOperand(0).getReg();
6326     bool HasWritebackToken =
6327         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6328          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6329     bool ListContainsBase;
6330     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6331       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6332                    "registers must be in range r0-r7");
6333     // If we should have writeback, then there should be a '!' token.
6334     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6335       return Error(Operands[2]->getStartLoc(),
6336                    "writeback operator '!' expected");
6337     // If we should not have writeback, there must not be a '!'. This is
6338     // true even for the 32-bit wide encodings.
6339     if (ListContainsBase && HasWritebackToken)
6340       return Error(Operands[3]->getStartLoc(),
6341                    "writeback operator '!' not allowed when base register "
6342                    "in register list");
6343 
6344     if (validatetLDMRegList(Inst, Operands, 3))
6345       return true;
6346     break;
6347   }
6348   case ARM::LDMIA_UPD:
6349   case ARM::LDMDB_UPD:
6350   case ARM::LDMIB_UPD:
6351   case ARM::LDMDA_UPD:
6352     // ARM variants loading and updating the same register are only officially
6353     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6354     if (!hasV7Ops())
6355       break;
6356     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6357       return Error(Operands.back()->getStartLoc(),
6358                    "writeback register not allowed in register list");
6359     break;
6360   case ARM::t2LDMIA:
6361   case ARM::t2LDMDB:
6362     if (validatetLDMRegList(Inst, Operands, 3))
6363       return true;
6364     break;
6365   case ARM::t2STMIA:
6366   case ARM::t2STMDB:
6367     if (validatetSTMRegList(Inst, Operands, 3))
6368       return true;
6369     break;
6370   case ARM::t2LDMIA_UPD:
6371   case ARM::t2LDMDB_UPD:
6372   case ARM::t2STMIA_UPD:
6373   case ARM::t2STMDB_UPD: {
6374     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6375       return Error(Operands.back()->getStartLoc(),
6376                    "writeback register not allowed in register list");
6377 
6378     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6379       if (validatetLDMRegList(Inst, Operands, 3))
6380         return true;
6381     } else {
6382       if (validatetSTMRegList(Inst, Operands, 3))
6383         return true;
6384     }
6385     break;
6386   }
6387   case ARM::sysLDMIA_UPD:
6388   case ARM::sysLDMDA_UPD:
6389   case ARM::sysLDMDB_UPD:
6390   case ARM::sysLDMIB_UPD:
6391     if (!listContainsReg(Inst, 3, ARM::PC))
6392       return Error(Operands[4]->getStartLoc(),
6393                    "writeback register only allowed on system LDM "
6394                    "if PC in register-list");
6395     break;
6396   case ARM::sysSTMIA_UPD:
6397   case ARM::sysSTMDA_UPD:
6398   case ARM::sysSTMDB_UPD:
6399   case ARM::sysSTMIB_UPD:
6400     return Error(Operands[2]->getStartLoc(),
6401                  "system STM cannot have writeback register");
6402   case ARM::tMUL: {
6403     // The second source operand must be the same register as the destination
6404     // operand.
6405     //
6406     // In this case, we must directly check the parsed operands because the
6407     // cvtThumbMultiply() function is written in such a way that it guarantees
6408     // this first statement is always true for the new Inst.  Essentially, the
6409     // destination is unconditionally copied into the second source operand
6410     // without checking to see if it matches what we actually parsed.
6411     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6412                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6413         (((ARMOperand &)*Operands[3]).getReg() !=
6414          ((ARMOperand &)*Operands[4]).getReg())) {
6415       return Error(Operands[3]->getStartLoc(),
6416                    "destination register must match source register");
6417     }
6418     break;
6419   }
6420   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6421   // so only issue a diagnostic for thumb1. The instructions will be
6422   // switched to the t2 encodings in processInstruction() if necessary.
6423   case ARM::tPOP: {
6424     bool ListContainsBase;
6425     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6426         !isThumbTwo())
6427       return Error(Operands[2]->getStartLoc(),
6428                    "registers must be in range r0-r7 or pc");
6429     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6430       return true;
6431     break;
6432   }
6433   case ARM::tPUSH: {
6434     bool ListContainsBase;
6435     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6436         !isThumbTwo())
6437       return Error(Operands[2]->getStartLoc(),
6438                    "registers must be in range r0-r7 or lr");
6439     if (validatetSTMRegList(Inst, Operands, 2))
6440       return true;
6441     break;
6442   }
6443   case ARM::tSTMIA_UPD: {
6444     bool ListContainsBase, InvalidLowList;
6445     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6446                                           0, ListContainsBase);
6447     if (InvalidLowList && !isThumbTwo())
6448       return Error(Operands[4]->getStartLoc(),
6449                    "registers must be in range r0-r7");
6450 
6451     // This would be converted to a 32-bit stm, but that's not valid if the
6452     // writeback register is in the list.
6453     if (InvalidLowList && ListContainsBase)
6454       return Error(Operands[4]->getStartLoc(),
6455                    "writeback operator '!' not allowed when base register "
6456                    "in register list");
6457 
6458     if (validatetSTMRegList(Inst, Operands, 4))
6459       return true;
6460     break;
6461   }
6462   case ARM::tADDrSP: {
6463     // If the non-SP source operand and the destination operand are not the
6464     // same, we need thumb2 (for the wide encoding), or we have an error.
6465     if (!isThumbTwo() &&
6466         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6467       return Error(Operands[4]->getStartLoc(),
6468                    "source register must be the same as destination");
6469     }
6470     break;
6471   }
6472   // Final range checking for Thumb unconditional branch instructions.
6473   case ARM::tB:
6474     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6475       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6476     break;
6477   case ARM::t2B: {
6478     int op = (Operands[2]->isImm()) ? 2 : 3;
6479     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6480       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6481     break;
6482   }
6483   // Final range checking for Thumb conditional branch instructions.
6484   case ARM::tBcc:
6485     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6486       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6487     break;
6488   case ARM::t2Bcc: {
6489     int Op = (Operands[2]->isImm()) ? 2 : 3;
6490     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6491       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6492     break;
6493   }
6494   case ARM::MOVi16:
6495   case ARM::t2MOVi16:
6496   case ARM::t2MOVTi16:
6497     {
6498     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6499     // especially when we turn it into a movw and the expression <symbol> does
6500     // not have a :lower16: or :upper16 as part of the expression.  We don't
6501     // want the behavior of silently truncating, which can be unexpected and
6502     // lead to bugs that are difficult to find since this is an easy mistake
6503     // to make.
6504     int i = (Operands[3]->isImm()) ? 3 : 4;
6505     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6506     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6507     if (CE) break;
6508     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6509     if (!E) break;
6510     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6511     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6512                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6513       return Error(
6514           Op.getStartLoc(),
6515           "immediate expression for mov requires :lower16: or :upper16");
6516     break;
6517   }
6518   case ARM::HINT:
6519   case ARM::t2HINT: {
6520     if (hasRAS()) {
6521       // ESB is not predicable (pred must be AL)
6522       unsigned Imm8 = Inst.getOperand(0).getImm();
6523       unsigned Pred = Inst.getOperand(1).getImm();
6524       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6525         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6526                                                  "predicable, but condition "
6527                                                  "code specified");
6528     }
6529     // Without the RAS extension, this behaves as any other unallocated hint.
6530     break;
6531   }
6532   }
6533 
6534   return false;
6535 }
6536 
6537 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6538   switch(Opc) {
6539   default: llvm_unreachable("unexpected opcode!");
6540   // VST1LN
6541   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6542   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6543   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6544   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6545   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6546   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6547   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6548   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6549   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6550 
6551   // VST2LN
6552   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6553   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6554   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6555   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6556   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6557 
6558   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6559   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6560   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6561   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6562   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6563 
6564   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6565   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6566   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6567   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6568   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6569 
6570   // VST3LN
6571   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6572   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6573   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6574   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6575   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6576   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6577   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6578   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6579   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6580   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6581   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6582   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6583   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6584   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6585   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6586 
6587   // VST3
6588   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6589   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6590   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6591   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6592   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6593   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6594   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6595   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6596   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6597   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6598   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6599   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6600   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6601   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6602   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6603   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6604   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6605   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6606 
6607   // VST4LN
6608   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6609   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6610   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6611   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6612   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6613   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6614   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6615   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6616   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6617   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6618   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6619   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6620   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6621   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6622   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6623 
6624   // VST4
6625   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6626   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6627   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6628   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6629   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6630   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6631   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6632   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6633   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6634   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6635   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6636   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6637   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6638   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6639   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6640   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6641   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6642   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6643   }
6644 }
6645 
6646 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6647   switch(Opc) {
6648   default: llvm_unreachable("unexpected opcode!");
6649   // VLD1LN
6650   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6651   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6652   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6653   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6654   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6655   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6656   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6657   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6658   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6659 
6660   // VLD2LN
6661   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6662   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6663   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6664   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6665   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6666   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6667   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6668   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6669   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6670   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6671   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6672   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6673   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6674   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6675   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6676 
6677   // VLD3DUP
6678   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6679   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6680   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6681   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6682   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6683   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6684   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6685   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6686   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6687   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6688   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6689   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6690   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6691   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6692   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6693   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6694   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6695   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6696 
6697   // VLD3LN
6698   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6699   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6700   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6701   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6702   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6703   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6704   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6705   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6706   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6707   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6708   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6709   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6710   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6711   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6712   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6713 
6714   // VLD3
6715   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6716   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6717   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6718   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6719   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6720   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6721   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6722   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6723   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6724   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6725   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6726   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6727   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6728   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6729   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6730   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6731   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6732   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6733 
6734   // VLD4LN
6735   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6736   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6737   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6738   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6739   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6740   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6741   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6742   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6743   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6744   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6745   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6746   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6747   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6748   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6749   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6750 
6751   // VLD4DUP
6752   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6753   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6754   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6755   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6756   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6757   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6758   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6759   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6760   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6761   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6762   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6763   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6764   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6765   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6766   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6767   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6768   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6769   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6770 
6771   // VLD4
6772   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6773   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6774   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6775   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6776   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6777   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6778   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6779   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6780   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6781   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6782   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6783   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6784   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6785   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6786   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6787   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6788   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6789   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6790   }
6791 }
6792 
6793 bool ARMAsmParser::processInstruction(MCInst &Inst,
6794                                       const OperandVector &Operands,
6795                                       MCStreamer &Out) {
6796   switch (Inst.getOpcode()) {
6797   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6798   case ARM::LDRT_POST:
6799   case ARM::LDRBT_POST: {
6800     const unsigned Opcode =
6801       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6802                                            : ARM::LDRBT_POST_IMM;
6803     MCInst TmpInst;
6804     TmpInst.setOpcode(Opcode);
6805     TmpInst.addOperand(Inst.getOperand(0));
6806     TmpInst.addOperand(Inst.getOperand(1));
6807     TmpInst.addOperand(Inst.getOperand(1));
6808     TmpInst.addOperand(MCOperand::createReg(0));
6809     TmpInst.addOperand(MCOperand::createImm(0));
6810     TmpInst.addOperand(Inst.getOperand(2));
6811     TmpInst.addOperand(Inst.getOperand(3));
6812     Inst = TmpInst;
6813     return true;
6814   }
6815   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6816   case ARM::STRT_POST:
6817   case ARM::STRBT_POST: {
6818     const unsigned Opcode =
6819       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6820                                            : ARM::STRBT_POST_IMM;
6821     MCInst TmpInst;
6822     TmpInst.setOpcode(Opcode);
6823     TmpInst.addOperand(Inst.getOperand(1));
6824     TmpInst.addOperand(Inst.getOperand(0));
6825     TmpInst.addOperand(Inst.getOperand(1));
6826     TmpInst.addOperand(MCOperand::createReg(0));
6827     TmpInst.addOperand(MCOperand::createImm(0));
6828     TmpInst.addOperand(Inst.getOperand(2));
6829     TmpInst.addOperand(Inst.getOperand(3));
6830     Inst = TmpInst;
6831     return true;
6832   }
6833   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6834   case ARM::ADDri: {
6835     if (Inst.getOperand(1).getReg() != ARM::PC ||
6836         Inst.getOperand(5).getReg() != 0 ||
6837         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6838       return false;
6839     MCInst TmpInst;
6840     TmpInst.setOpcode(ARM::ADR);
6841     TmpInst.addOperand(Inst.getOperand(0));
6842     if (Inst.getOperand(2).isImm()) {
6843       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6844       // before passing it to the ADR instruction.
6845       unsigned Enc = Inst.getOperand(2).getImm();
6846       TmpInst.addOperand(MCOperand::createImm(
6847         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6848     } else {
6849       // Turn PC-relative expression into absolute expression.
6850       // Reading PC provides the start of the current instruction + 8 and
6851       // the transform to adr is biased by that.
6852       MCSymbol *Dot = getContext().createTempSymbol();
6853       Out.EmitLabel(Dot);
6854       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6855       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6856                                                      MCSymbolRefExpr::VK_None,
6857                                                      getContext());
6858       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6859       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6860                                                      getContext());
6861       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6862                                                         getContext());
6863       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6864     }
6865     TmpInst.addOperand(Inst.getOperand(3));
6866     TmpInst.addOperand(Inst.getOperand(4));
6867     Inst = TmpInst;
6868     return true;
6869   }
6870   // Aliases for alternate PC+imm syntax of LDR instructions.
6871   case ARM::t2LDRpcrel:
6872     // Select the narrow version if the immediate will fit.
6873     if (Inst.getOperand(1).getImm() > 0 &&
6874         Inst.getOperand(1).getImm() <= 0xff &&
6875         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6876           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
6877       Inst.setOpcode(ARM::tLDRpci);
6878     else
6879       Inst.setOpcode(ARM::t2LDRpci);
6880     return true;
6881   case ARM::t2LDRBpcrel:
6882     Inst.setOpcode(ARM::t2LDRBpci);
6883     return true;
6884   case ARM::t2LDRHpcrel:
6885     Inst.setOpcode(ARM::t2LDRHpci);
6886     return true;
6887   case ARM::t2LDRSBpcrel:
6888     Inst.setOpcode(ARM::t2LDRSBpci);
6889     return true;
6890   case ARM::t2LDRSHpcrel:
6891     Inst.setOpcode(ARM::t2LDRSHpci);
6892     return true;
6893   case ARM::LDRConstPool:
6894   case ARM::tLDRConstPool:
6895   case ARM::t2LDRConstPool: {
6896     // Pseudo instruction ldr rt, =immediate is converted to a
6897     // MOV rt, immediate if immediate is known and representable
6898     // otherwise we create a constant pool entry that we load from.
6899     MCInst TmpInst;
6900     if (Inst.getOpcode() == ARM::LDRConstPool)
6901       TmpInst.setOpcode(ARM::LDRi12);
6902     else if (Inst.getOpcode() == ARM::tLDRConstPool)
6903       TmpInst.setOpcode(ARM::tLDRpci);
6904     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
6905       TmpInst.setOpcode(ARM::t2LDRpci);
6906     const ARMOperand &PoolOperand =
6907       static_cast<ARMOperand &>(*Operands[3]);
6908     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
6909     // If SubExprVal is a constant we may be able to use a MOV
6910     if (isa<MCConstantExpr>(SubExprVal) &&
6911         Inst.getOperand(0).getReg() != ARM::PC &&
6912         Inst.getOperand(0).getReg() != ARM::SP) {
6913       int64_t Value =
6914         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
6915       bool UseMov  = true;
6916       bool MovHasS = true;
6917       if (Inst.getOpcode() == ARM::LDRConstPool) {
6918         // ARM Constant
6919         if (ARM_AM::getSOImmVal(Value) != -1) {
6920           Value = ARM_AM::getSOImmVal(Value);
6921           TmpInst.setOpcode(ARM::MOVi);
6922         }
6923         else if (ARM_AM::getSOImmVal(~Value) != -1) {
6924           Value = ARM_AM::getSOImmVal(~Value);
6925           TmpInst.setOpcode(ARM::MVNi);
6926         }
6927         else if (hasV6T2Ops() &&
6928                  Value >=0 && Value < 65536) {
6929           TmpInst.setOpcode(ARM::MOVi16);
6930           MovHasS = false;
6931         }
6932         else
6933           UseMov = false;
6934       }
6935       else {
6936         // Thumb/Thumb2 Constant
6937         if (hasThumb2() &&
6938             ARM_AM::getT2SOImmVal(Value) != -1)
6939           TmpInst.setOpcode(ARM::t2MOVi);
6940         else if (hasThumb2() &&
6941                  ARM_AM::getT2SOImmVal(~Value) != -1) {
6942           TmpInst.setOpcode(ARM::t2MVNi);
6943           Value = ~Value;
6944         }
6945         else if (hasV8MBaseline() &&
6946                  Value >=0 && Value < 65536) {
6947           TmpInst.setOpcode(ARM::t2MOVi16);
6948           MovHasS = false;
6949         }
6950         else
6951           UseMov = false;
6952       }
6953       if (UseMov) {
6954         TmpInst.addOperand(Inst.getOperand(0));           // Rt
6955         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
6956         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
6957         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
6958         if (MovHasS)
6959           TmpInst.addOperand(MCOperand::createReg(0));    // S
6960         Inst = TmpInst;
6961         return true;
6962       }
6963     }
6964     // No opportunity to use MOV/MVN create constant pool
6965     const MCExpr *CPLoc =
6966       getTargetStreamer().addConstantPoolEntry(SubExprVal,
6967                                                PoolOperand.getStartLoc());
6968     TmpInst.addOperand(Inst.getOperand(0));           // Rt
6969     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
6970     if (TmpInst.getOpcode() == ARM::LDRi12)
6971       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
6972     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
6973     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
6974     Inst = TmpInst;
6975     return true;
6976   }
6977   // Handle NEON VST complex aliases.
6978   case ARM::VST1LNdWB_register_Asm_8:
6979   case ARM::VST1LNdWB_register_Asm_16:
6980   case ARM::VST1LNdWB_register_Asm_32: {
6981     MCInst TmpInst;
6982     // Shuffle the operands around so the lane index operand is in the
6983     // right place.
6984     unsigned Spacing;
6985     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6986     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6987     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6988     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6989     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6990     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6991     TmpInst.addOperand(Inst.getOperand(1)); // lane
6992     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6993     TmpInst.addOperand(Inst.getOperand(6));
6994     Inst = TmpInst;
6995     return true;
6996   }
6997 
6998   case ARM::VST2LNdWB_register_Asm_8:
6999   case ARM::VST2LNdWB_register_Asm_16:
7000   case ARM::VST2LNdWB_register_Asm_32:
7001   case ARM::VST2LNqWB_register_Asm_16:
7002   case ARM::VST2LNqWB_register_Asm_32: {
7003     MCInst TmpInst;
7004     // Shuffle the operands around so the lane index operand is in the
7005     // right place.
7006     unsigned Spacing;
7007     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7008     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7009     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7010     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7011     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7012     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7013     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7014                                             Spacing));
7015     TmpInst.addOperand(Inst.getOperand(1)); // lane
7016     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7017     TmpInst.addOperand(Inst.getOperand(6));
7018     Inst = TmpInst;
7019     return true;
7020   }
7021 
7022   case ARM::VST3LNdWB_register_Asm_8:
7023   case ARM::VST3LNdWB_register_Asm_16:
7024   case ARM::VST3LNdWB_register_Asm_32:
7025   case ARM::VST3LNqWB_register_Asm_16:
7026   case ARM::VST3LNqWB_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(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7032     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7033     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7034     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7035     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7036     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7037     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7038                                             Spacing));
7039     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7040                                             Spacing * 2));
7041     TmpInst.addOperand(Inst.getOperand(1)); // lane
7042     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7043     TmpInst.addOperand(Inst.getOperand(6));
7044     Inst = TmpInst;
7045     return true;
7046   }
7047 
7048   case ARM::VST4LNdWB_register_Asm_8:
7049   case ARM::VST4LNdWB_register_Asm_16:
7050   case ARM::VST4LNdWB_register_Asm_32:
7051   case ARM::VST4LNqWB_register_Asm_16:
7052   case ARM::VST4LNqWB_register_Asm_32: {
7053     MCInst TmpInst;
7054     // Shuffle the operands around so the lane index operand is in the
7055     // right place.
7056     unsigned Spacing;
7057     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), 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)); // Vd
7063     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7064                                             Spacing));
7065     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7066                                             Spacing * 2));
7067     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7068                                             Spacing * 3));
7069     TmpInst.addOperand(Inst.getOperand(1)); // lane
7070     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7071     TmpInst.addOperand(Inst.getOperand(6));
7072     Inst = TmpInst;
7073     return true;
7074   }
7075 
7076   case ARM::VST1LNdWB_fixed_Asm_8:
7077   case ARM::VST1LNdWB_fixed_Asm_16:
7078   case ARM::VST1LNdWB_fixed_Asm_32: {
7079     MCInst TmpInst;
7080     // Shuffle the operands around so the lane index operand is in the
7081     // right place.
7082     unsigned Spacing;
7083     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7084     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7085     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7086     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7087     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7088     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7089     TmpInst.addOperand(Inst.getOperand(1)); // lane
7090     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7091     TmpInst.addOperand(Inst.getOperand(5));
7092     Inst = TmpInst;
7093     return true;
7094   }
7095 
7096   case ARM::VST2LNdWB_fixed_Asm_8:
7097   case ARM::VST2LNdWB_fixed_Asm_16:
7098   case ARM::VST2LNdWB_fixed_Asm_32:
7099   case ARM::VST2LNqWB_fixed_Asm_16:
7100   case ARM::VST2LNqWB_fixed_Asm_32: {
7101     MCInst TmpInst;
7102     // Shuffle the operands around so the lane index operand is in the
7103     // right place.
7104     unsigned Spacing;
7105     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7106     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7107     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7108     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7109     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7110     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7111     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7112                                             Spacing));
7113     TmpInst.addOperand(Inst.getOperand(1)); // lane
7114     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7115     TmpInst.addOperand(Inst.getOperand(5));
7116     Inst = TmpInst;
7117     return true;
7118   }
7119 
7120   case ARM::VST3LNdWB_fixed_Asm_8:
7121   case ARM::VST3LNdWB_fixed_Asm_16:
7122   case ARM::VST3LNdWB_fixed_Asm_32:
7123   case ARM::VST3LNqWB_fixed_Asm_16:
7124   case ARM::VST3LNqWB_fixed_Asm_32: {
7125     MCInst TmpInst;
7126     // Shuffle the operands around so the lane index operand is in the
7127     // right place.
7128     unsigned Spacing;
7129     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7130     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7131     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7132     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7133     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7134     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7135     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7136                                             Spacing));
7137     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7138                                             Spacing * 2));
7139     TmpInst.addOperand(Inst.getOperand(1)); // lane
7140     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7141     TmpInst.addOperand(Inst.getOperand(5));
7142     Inst = TmpInst;
7143     return true;
7144   }
7145 
7146   case ARM::VST4LNdWB_fixed_Asm_8:
7147   case ARM::VST4LNdWB_fixed_Asm_16:
7148   case ARM::VST4LNdWB_fixed_Asm_32:
7149   case ARM::VST4LNqWB_fixed_Asm_16:
7150   case ARM::VST4LNqWB_fixed_Asm_32: {
7151     MCInst TmpInst;
7152     // Shuffle the operands around so the lane index operand is in the
7153     // right place.
7154     unsigned Spacing;
7155     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7156     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7157     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7158     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7159     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7160     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7161     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7162                                             Spacing));
7163     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7164                                             Spacing * 2));
7165     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7166                                             Spacing * 3));
7167     TmpInst.addOperand(Inst.getOperand(1)); // lane
7168     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7169     TmpInst.addOperand(Inst.getOperand(5));
7170     Inst = TmpInst;
7171     return true;
7172   }
7173 
7174   case ARM::VST1LNdAsm_8:
7175   case ARM::VST1LNdAsm_16:
7176   case ARM::VST1LNdAsm_32: {
7177     MCInst TmpInst;
7178     // Shuffle the operands around so the lane index operand is in the
7179     // right place.
7180     unsigned Spacing;
7181     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7182     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7183     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7184     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7185     TmpInst.addOperand(Inst.getOperand(1)); // lane
7186     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7187     TmpInst.addOperand(Inst.getOperand(5));
7188     Inst = TmpInst;
7189     return true;
7190   }
7191 
7192   case ARM::VST2LNdAsm_8:
7193   case ARM::VST2LNdAsm_16:
7194   case ARM::VST2LNdAsm_32:
7195   case ARM::VST2LNqAsm_16:
7196   case ARM::VST2LNqAsm_32: {
7197     MCInst TmpInst;
7198     // Shuffle the operands around so the lane index operand is in the
7199     // right place.
7200     unsigned Spacing;
7201     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7202     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7203     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7204     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7205     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7206                                             Spacing));
7207     TmpInst.addOperand(Inst.getOperand(1)); // lane
7208     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7209     TmpInst.addOperand(Inst.getOperand(5));
7210     Inst = TmpInst;
7211     return true;
7212   }
7213 
7214   case ARM::VST3LNdAsm_8:
7215   case ARM::VST3LNdAsm_16:
7216   case ARM::VST3LNdAsm_32:
7217   case ARM::VST3LNqAsm_16:
7218   case ARM::VST3LNqAsm_32: {
7219     MCInst TmpInst;
7220     // Shuffle the operands around so the lane index operand is in the
7221     // right place.
7222     unsigned Spacing;
7223     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7224     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7225     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7226     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7227     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7228                                             Spacing));
7229     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7230                                             Spacing * 2));
7231     TmpInst.addOperand(Inst.getOperand(1)); // lane
7232     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7233     TmpInst.addOperand(Inst.getOperand(5));
7234     Inst = TmpInst;
7235     return true;
7236   }
7237 
7238   case ARM::VST4LNdAsm_8:
7239   case ARM::VST4LNdAsm_16:
7240   case ARM::VST4LNdAsm_32:
7241   case ARM::VST4LNqAsm_16:
7242   case ARM::VST4LNqAsm_32: {
7243     MCInst TmpInst;
7244     // Shuffle the operands around so the lane index operand is in the
7245     // right place.
7246     unsigned Spacing;
7247     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7248     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7249     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7250     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7251     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7252                                             Spacing));
7253     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7254                                             Spacing * 2));
7255     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7256                                             Spacing * 3));
7257     TmpInst.addOperand(Inst.getOperand(1)); // lane
7258     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7259     TmpInst.addOperand(Inst.getOperand(5));
7260     Inst = TmpInst;
7261     return true;
7262   }
7263 
7264   // Handle NEON VLD complex aliases.
7265   case ARM::VLD1LNdWB_register_Asm_8:
7266   case ARM::VLD1LNdWB_register_Asm_16:
7267   case ARM::VLD1LNdWB_register_Asm_32: {
7268     MCInst TmpInst;
7269     // Shuffle the operands around so the lane index operand is in the
7270     // right place.
7271     unsigned Spacing;
7272     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7273     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7274     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7275     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7276     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7277     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7278     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7279     TmpInst.addOperand(Inst.getOperand(1)); // lane
7280     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7281     TmpInst.addOperand(Inst.getOperand(6));
7282     Inst = TmpInst;
7283     return true;
7284   }
7285 
7286   case ARM::VLD2LNdWB_register_Asm_8:
7287   case ARM::VLD2LNdWB_register_Asm_16:
7288   case ARM::VLD2LNdWB_register_Asm_32:
7289   case ARM::VLD2LNqWB_register_Asm_16:
7290   case ARM::VLD2LNqWB_register_Asm_32: {
7291     MCInst TmpInst;
7292     // Shuffle the operands around so the lane index operand is in the
7293     // right place.
7294     unsigned Spacing;
7295     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7296     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7297     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7298                                             Spacing));
7299     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7300     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7301     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7302     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7303     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7304     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7305                                             Spacing));
7306     TmpInst.addOperand(Inst.getOperand(1)); // lane
7307     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7308     TmpInst.addOperand(Inst.getOperand(6));
7309     Inst = TmpInst;
7310     return true;
7311   }
7312 
7313   case ARM::VLD3LNdWB_register_Asm_8:
7314   case ARM::VLD3LNdWB_register_Asm_16:
7315   case ARM::VLD3LNdWB_register_Asm_32:
7316   case ARM::VLD3LNqWB_register_Asm_16:
7317   case ARM::VLD3LNqWB_register_Asm_32: {
7318     MCInst TmpInst;
7319     // Shuffle the operands around so the lane index operand is in the
7320     // right place.
7321     unsigned Spacing;
7322     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7323     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7324     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7325                                             Spacing));
7326     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7327                                             Spacing * 2));
7328     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7329     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7330     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7331     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7332     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7333     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7334                                             Spacing));
7335     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7336                                             Spacing * 2));
7337     TmpInst.addOperand(Inst.getOperand(1)); // lane
7338     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7339     TmpInst.addOperand(Inst.getOperand(6));
7340     Inst = TmpInst;
7341     return true;
7342   }
7343 
7344   case ARM::VLD4LNdWB_register_Asm_8:
7345   case ARM::VLD4LNdWB_register_Asm_16:
7346   case ARM::VLD4LNdWB_register_Asm_32:
7347   case ARM::VLD4LNqWB_register_Asm_16:
7348   case ARM::VLD4LNqWB_register_Asm_32: {
7349     MCInst TmpInst;
7350     // Shuffle the operands around so the lane index operand is in the
7351     // right place.
7352     unsigned Spacing;
7353     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7354     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7355     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7356                                             Spacing));
7357     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7358                                             Spacing * 2));
7359     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7360                                             Spacing * 3));
7361     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7362     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7363     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7364     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7365     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7366     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7367                                             Spacing));
7368     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7369                                             Spacing * 2));
7370     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7371                                             Spacing * 3));
7372     TmpInst.addOperand(Inst.getOperand(1)); // lane
7373     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7374     TmpInst.addOperand(Inst.getOperand(6));
7375     Inst = TmpInst;
7376     return true;
7377   }
7378 
7379   case ARM::VLD1LNdWB_fixed_Asm_8:
7380   case ARM::VLD1LNdWB_fixed_Asm_16:
7381   case ARM::VLD1LNdWB_fixed_Asm_32: {
7382     MCInst TmpInst;
7383     // Shuffle the operands around so the lane index operand is in the
7384     // right place.
7385     unsigned Spacing;
7386     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7387     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7388     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7389     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7390     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7391     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7392     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7393     TmpInst.addOperand(Inst.getOperand(1)); // lane
7394     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7395     TmpInst.addOperand(Inst.getOperand(5));
7396     Inst = TmpInst;
7397     return true;
7398   }
7399 
7400   case ARM::VLD2LNdWB_fixed_Asm_8:
7401   case ARM::VLD2LNdWB_fixed_Asm_16:
7402   case ARM::VLD2LNdWB_fixed_Asm_32:
7403   case ARM::VLD2LNqWB_fixed_Asm_16:
7404   case ARM::VLD2LNqWB_fixed_Asm_32: {
7405     MCInst TmpInst;
7406     // Shuffle the operands around so the lane index operand is in the
7407     // right place.
7408     unsigned Spacing;
7409     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7410     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7411     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7412                                             Spacing));
7413     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7414     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7415     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7416     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7417     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7418     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7419                                             Spacing));
7420     TmpInst.addOperand(Inst.getOperand(1)); // lane
7421     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7422     TmpInst.addOperand(Inst.getOperand(5));
7423     Inst = TmpInst;
7424     return true;
7425   }
7426 
7427   case ARM::VLD3LNdWB_fixed_Asm_8:
7428   case ARM::VLD3LNdWB_fixed_Asm_16:
7429   case ARM::VLD3LNdWB_fixed_Asm_32:
7430   case ARM::VLD3LNqWB_fixed_Asm_16:
7431   case ARM::VLD3LNqWB_fixed_Asm_32: {
7432     MCInst TmpInst;
7433     // Shuffle the operands around so the lane index operand is in the
7434     // right place.
7435     unsigned Spacing;
7436     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7437     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7438     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7439                                             Spacing));
7440     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7441                                             Spacing * 2));
7442     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7443     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7444     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7445     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7446     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7447     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7448                                             Spacing));
7449     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7450                                             Spacing * 2));
7451     TmpInst.addOperand(Inst.getOperand(1)); // lane
7452     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7453     TmpInst.addOperand(Inst.getOperand(5));
7454     Inst = TmpInst;
7455     return true;
7456   }
7457 
7458   case ARM::VLD4LNdWB_fixed_Asm_8:
7459   case ARM::VLD4LNdWB_fixed_Asm_16:
7460   case ARM::VLD4LNdWB_fixed_Asm_32:
7461   case ARM::VLD4LNqWB_fixed_Asm_16:
7462   case ARM::VLD4LNqWB_fixed_Asm_32: {
7463     MCInst TmpInst;
7464     // Shuffle the operands around so the lane index operand is in the
7465     // right place.
7466     unsigned Spacing;
7467     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7468     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7469     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7470                                             Spacing));
7471     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7472                                             Spacing * 2));
7473     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7474                                             Spacing * 3));
7475     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7476     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7477     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7478     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7479     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7480     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7481                                             Spacing));
7482     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7483                                             Spacing * 2));
7484     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7485                                             Spacing * 3));
7486     TmpInst.addOperand(Inst.getOperand(1)); // lane
7487     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7488     TmpInst.addOperand(Inst.getOperand(5));
7489     Inst = TmpInst;
7490     return true;
7491   }
7492 
7493   case ARM::VLD1LNdAsm_8:
7494   case ARM::VLD1LNdAsm_16:
7495   case ARM::VLD1LNdAsm_32: {
7496     MCInst TmpInst;
7497     // Shuffle the operands around so the lane index operand is in the
7498     // right place.
7499     unsigned Spacing;
7500     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7501     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7502     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7503     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7504     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7505     TmpInst.addOperand(Inst.getOperand(1)); // lane
7506     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7507     TmpInst.addOperand(Inst.getOperand(5));
7508     Inst = TmpInst;
7509     return true;
7510   }
7511 
7512   case ARM::VLD2LNdAsm_8:
7513   case ARM::VLD2LNdAsm_16:
7514   case ARM::VLD2LNdAsm_32:
7515   case ARM::VLD2LNqAsm_16:
7516   case ARM::VLD2LNqAsm_32: {
7517     MCInst TmpInst;
7518     // Shuffle the operands around so the lane index operand is in the
7519     // right place.
7520     unsigned Spacing;
7521     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7522     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7523     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7524                                             Spacing));
7525     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7526     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7527     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7528     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7529                                             Spacing));
7530     TmpInst.addOperand(Inst.getOperand(1)); // lane
7531     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7532     TmpInst.addOperand(Inst.getOperand(5));
7533     Inst = TmpInst;
7534     return true;
7535   }
7536 
7537   case ARM::VLD3LNdAsm_8:
7538   case ARM::VLD3LNdAsm_16:
7539   case ARM::VLD3LNdAsm_32:
7540   case ARM::VLD3LNqAsm_16:
7541   case ARM::VLD3LNqAsm_32: {
7542     MCInst TmpInst;
7543     // Shuffle the operands around so the lane index operand is in the
7544     // right place.
7545     unsigned Spacing;
7546     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7547     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7548     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7549                                             Spacing));
7550     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7551                                             Spacing * 2));
7552     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7553     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7554     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7555     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7556                                             Spacing));
7557     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7558                                             Spacing * 2));
7559     TmpInst.addOperand(Inst.getOperand(1)); // lane
7560     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7561     TmpInst.addOperand(Inst.getOperand(5));
7562     Inst = TmpInst;
7563     return true;
7564   }
7565 
7566   case ARM::VLD4LNdAsm_8:
7567   case ARM::VLD4LNdAsm_16:
7568   case ARM::VLD4LNdAsm_32:
7569   case ARM::VLD4LNqAsm_16:
7570   case ARM::VLD4LNqAsm_32: {
7571     MCInst TmpInst;
7572     // Shuffle the operands around so the lane index operand is in the
7573     // right place.
7574     unsigned Spacing;
7575     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7576     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7577     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7578                                             Spacing));
7579     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7580                                             Spacing * 2));
7581     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7582                                             Spacing * 3));
7583     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7584     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7585     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7586     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7587                                             Spacing));
7588     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7589                                             Spacing * 2));
7590     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7591                                             Spacing * 3));
7592     TmpInst.addOperand(Inst.getOperand(1)); // lane
7593     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7594     TmpInst.addOperand(Inst.getOperand(5));
7595     Inst = TmpInst;
7596     return true;
7597   }
7598 
7599   // VLD3DUP single 3-element structure to all lanes instructions.
7600   case ARM::VLD3DUPdAsm_8:
7601   case ARM::VLD3DUPdAsm_16:
7602   case ARM::VLD3DUPdAsm_32:
7603   case ARM::VLD3DUPqAsm_8:
7604   case ARM::VLD3DUPqAsm_16:
7605   case ARM::VLD3DUPqAsm_32: {
7606     MCInst TmpInst;
7607     unsigned Spacing;
7608     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7609     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7610     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7611                                             Spacing));
7612     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7613                                             Spacing * 2));
7614     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7615     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7616     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7617     TmpInst.addOperand(Inst.getOperand(4));
7618     Inst = TmpInst;
7619     return true;
7620   }
7621 
7622   case ARM::VLD3DUPdWB_fixed_Asm_8:
7623   case ARM::VLD3DUPdWB_fixed_Asm_16:
7624   case ARM::VLD3DUPdWB_fixed_Asm_32:
7625   case ARM::VLD3DUPqWB_fixed_Asm_8:
7626   case ARM::VLD3DUPqWB_fixed_Asm_16:
7627   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7628     MCInst TmpInst;
7629     unsigned Spacing;
7630     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7631     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7632     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7633                                             Spacing));
7634     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7635                                             Spacing * 2));
7636     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7637     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7638     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7639     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7640     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7641     TmpInst.addOperand(Inst.getOperand(4));
7642     Inst = TmpInst;
7643     return true;
7644   }
7645 
7646   case ARM::VLD3DUPdWB_register_Asm_8:
7647   case ARM::VLD3DUPdWB_register_Asm_16:
7648   case ARM::VLD3DUPdWB_register_Asm_32:
7649   case ARM::VLD3DUPqWB_register_Asm_8:
7650   case ARM::VLD3DUPqWB_register_Asm_16:
7651   case ARM::VLD3DUPqWB_register_Asm_32: {
7652     MCInst TmpInst;
7653     unsigned Spacing;
7654     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7655     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7656     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7657                                             Spacing));
7658     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7659                                             Spacing * 2));
7660     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7661     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7662     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7663     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7664     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7665     TmpInst.addOperand(Inst.getOperand(5));
7666     Inst = TmpInst;
7667     return true;
7668   }
7669 
7670   // VLD3 multiple 3-element structure instructions.
7671   case ARM::VLD3dAsm_8:
7672   case ARM::VLD3dAsm_16:
7673   case ARM::VLD3dAsm_32:
7674   case ARM::VLD3qAsm_8:
7675   case ARM::VLD3qAsm_16:
7676   case ARM::VLD3qAsm_32: {
7677     MCInst TmpInst;
7678     unsigned Spacing;
7679     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7680     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7681     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7682                                             Spacing));
7683     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7684                                             Spacing * 2));
7685     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7686     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7687     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7688     TmpInst.addOperand(Inst.getOperand(4));
7689     Inst = TmpInst;
7690     return true;
7691   }
7692 
7693   case ARM::VLD3dWB_fixed_Asm_8:
7694   case ARM::VLD3dWB_fixed_Asm_16:
7695   case ARM::VLD3dWB_fixed_Asm_32:
7696   case ARM::VLD3qWB_fixed_Asm_8:
7697   case ARM::VLD3qWB_fixed_Asm_16:
7698   case ARM::VLD3qWB_fixed_Asm_32: {
7699     MCInst TmpInst;
7700     unsigned Spacing;
7701     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7702     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7703     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7704                                             Spacing));
7705     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7706                                             Spacing * 2));
7707     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7708     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7709     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7710     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7711     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7712     TmpInst.addOperand(Inst.getOperand(4));
7713     Inst = TmpInst;
7714     return true;
7715   }
7716 
7717   case ARM::VLD3dWB_register_Asm_8:
7718   case ARM::VLD3dWB_register_Asm_16:
7719   case ARM::VLD3dWB_register_Asm_32:
7720   case ARM::VLD3qWB_register_Asm_8:
7721   case ARM::VLD3qWB_register_Asm_16:
7722   case ARM::VLD3qWB_register_Asm_32: {
7723     MCInst TmpInst;
7724     unsigned Spacing;
7725     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7726     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7727     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7728                                             Spacing));
7729     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7730                                             Spacing * 2));
7731     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7732     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7733     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7734     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7735     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7736     TmpInst.addOperand(Inst.getOperand(5));
7737     Inst = TmpInst;
7738     return true;
7739   }
7740 
7741   // VLD4DUP single 3-element structure to all lanes instructions.
7742   case ARM::VLD4DUPdAsm_8:
7743   case ARM::VLD4DUPdAsm_16:
7744   case ARM::VLD4DUPdAsm_32:
7745   case ARM::VLD4DUPqAsm_8:
7746   case ARM::VLD4DUPqAsm_16:
7747   case ARM::VLD4DUPqAsm_32: {
7748     MCInst TmpInst;
7749     unsigned Spacing;
7750     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7751     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7752     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7753                                             Spacing));
7754     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7755                                             Spacing * 2));
7756     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7757                                             Spacing * 3));
7758     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7759     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7760     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7761     TmpInst.addOperand(Inst.getOperand(4));
7762     Inst = TmpInst;
7763     return true;
7764   }
7765 
7766   case ARM::VLD4DUPdWB_fixed_Asm_8:
7767   case ARM::VLD4DUPdWB_fixed_Asm_16:
7768   case ARM::VLD4DUPdWB_fixed_Asm_32:
7769   case ARM::VLD4DUPqWB_fixed_Asm_8:
7770   case ARM::VLD4DUPqWB_fixed_Asm_16:
7771   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7772     MCInst TmpInst;
7773     unsigned Spacing;
7774     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7775     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7776     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7777                                             Spacing));
7778     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7779                                             Spacing * 2));
7780     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7781                                             Spacing * 3));
7782     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7783     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7784     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7785     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7786     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7787     TmpInst.addOperand(Inst.getOperand(4));
7788     Inst = TmpInst;
7789     return true;
7790   }
7791 
7792   case ARM::VLD4DUPdWB_register_Asm_8:
7793   case ARM::VLD4DUPdWB_register_Asm_16:
7794   case ARM::VLD4DUPdWB_register_Asm_32:
7795   case ARM::VLD4DUPqWB_register_Asm_8:
7796   case ARM::VLD4DUPqWB_register_Asm_16:
7797   case ARM::VLD4DUPqWB_register_Asm_32: {
7798     MCInst TmpInst;
7799     unsigned Spacing;
7800     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7801     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7802     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7803                                             Spacing));
7804     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7805                                             Spacing * 2));
7806     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7807                                             Spacing * 3));
7808     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7809     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7810     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7811     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7812     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7813     TmpInst.addOperand(Inst.getOperand(5));
7814     Inst = TmpInst;
7815     return true;
7816   }
7817 
7818   // VLD4 multiple 4-element structure instructions.
7819   case ARM::VLD4dAsm_8:
7820   case ARM::VLD4dAsm_16:
7821   case ARM::VLD4dAsm_32:
7822   case ARM::VLD4qAsm_8:
7823   case ARM::VLD4qAsm_16:
7824   case ARM::VLD4qAsm_32: {
7825     MCInst TmpInst;
7826     unsigned Spacing;
7827     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7828     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7829     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7830                                             Spacing));
7831     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7832                                             Spacing * 2));
7833     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7834                                             Spacing * 3));
7835     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7836     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7837     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7838     TmpInst.addOperand(Inst.getOperand(4));
7839     Inst = TmpInst;
7840     return true;
7841   }
7842 
7843   case ARM::VLD4dWB_fixed_Asm_8:
7844   case ARM::VLD4dWB_fixed_Asm_16:
7845   case ARM::VLD4dWB_fixed_Asm_32:
7846   case ARM::VLD4qWB_fixed_Asm_8:
7847   case ARM::VLD4qWB_fixed_Asm_16:
7848   case ARM::VLD4qWB_fixed_Asm_32: {
7849     MCInst TmpInst;
7850     unsigned Spacing;
7851     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7852     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7853     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7854                                             Spacing));
7855     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7856                                             Spacing * 2));
7857     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7858                                             Spacing * 3));
7859     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7860     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7861     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7862     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7863     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7864     TmpInst.addOperand(Inst.getOperand(4));
7865     Inst = TmpInst;
7866     return true;
7867   }
7868 
7869   case ARM::VLD4dWB_register_Asm_8:
7870   case ARM::VLD4dWB_register_Asm_16:
7871   case ARM::VLD4dWB_register_Asm_32:
7872   case ARM::VLD4qWB_register_Asm_8:
7873   case ARM::VLD4qWB_register_Asm_16:
7874   case ARM::VLD4qWB_register_Asm_32: {
7875     MCInst TmpInst;
7876     unsigned Spacing;
7877     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7878     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7879     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7880                                             Spacing));
7881     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7882                                             Spacing * 2));
7883     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7884                                             Spacing * 3));
7885     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7886     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7887     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7888     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7889     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7890     TmpInst.addOperand(Inst.getOperand(5));
7891     Inst = TmpInst;
7892     return true;
7893   }
7894 
7895   // VST3 multiple 3-element structure instructions.
7896   case ARM::VST3dAsm_8:
7897   case ARM::VST3dAsm_16:
7898   case ARM::VST3dAsm_32:
7899   case ARM::VST3qAsm_8:
7900   case ARM::VST3qAsm_16:
7901   case ARM::VST3qAsm_32: {
7902     MCInst TmpInst;
7903     unsigned Spacing;
7904     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7905     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7906     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7907     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7908     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7909                                             Spacing));
7910     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7911                                             Spacing * 2));
7912     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7913     TmpInst.addOperand(Inst.getOperand(4));
7914     Inst = TmpInst;
7915     return true;
7916   }
7917 
7918   case ARM::VST3dWB_fixed_Asm_8:
7919   case ARM::VST3dWB_fixed_Asm_16:
7920   case ARM::VST3dWB_fixed_Asm_32:
7921   case ARM::VST3qWB_fixed_Asm_8:
7922   case ARM::VST3qWB_fixed_Asm_16:
7923   case ARM::VST3qWB_fixed_Asm_32: {
7924     MCInst TmpInst;
7925     unsigned Spacing;
7926     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7927     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7928     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7929     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7930     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7931     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7932     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7933                                             Spacing));
7934     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7935                                             Spacing * 2));
7936     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7937     TmpInst.addOperand(Inst.getOperand(4));
7938     Inst = TmpInst;
7939     return true;
7940   }
7941 
7942   case ARM::VST3dWB_register_Asm_8:
7943   case ARM::VST3dWB_register_Asm_16:
7944   case ARM::VST3dWB_register_Asm_32:
7945   case ARM::VST3qWB_register_Asm_8:
7946   case ARM::VST3qWB_register_Asm_16:
7947   case ARM::VST3qWB_register_Asm_32: {
7948     MCInst TmpInst;
7949     unsigned Spacing;
7950     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7951     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7952     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7953     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7954     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7955     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7956     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7957                                             Spacing));
7958     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7959                                             Spacing * 2));
7960     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7961     TmpInst.addOperand(Inst.getOperand(5));
7962     Inst = TmpInst;
7963     return true;
7964   }
7965 
7966   // VST4 multiple 3-element structure instructions.
7967   case ARM::VST4dAsm_8:
7968   case ARM::VST4dAsm_16:
7969   case ARM::VST4dAsm_32:
7970   case ARM::VST4qAsm_8:
7971   case ARM::VST4qAsm_16:
7972   case ARM::VST4qAsm_32: {
7973     MCInst TmpInst;
7974     unsigned Spacing;
7975     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7976     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7977     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7978     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7979     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7980                                             Spacing));
7981     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7982                                             Spacing * 2));
7983     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7984                                             Spacing * 3));
7985     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7986     TmpInst.addOperand(Inst.getOperand(4));
7987     Inst = TmpInst;
7988     return true;
7989   }
7990 
7991   case ARM::VST4dWB_fixed_Asm_8:
7992   case ARM::VST4dWB_fixed_Asm_16:
7993   case ARM::VST4dWB_fixed_Asm_32:
7994   case ARM::VST4qWB_fixed_Asm_8:
7995   case ARM::VST4qWB_fixed_Asm_16:
7996   case ARM::VST4qWB_fixed_Asm_32: {
7997     MCInst TmpInst;
7998     unsigned Spacing;
7999     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8000     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8001     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8002     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8003     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8004     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8005     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8006                                             Spacing));
8007     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8008                                             Spacing * 2));
8009     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8010                                             Spacing * 3));
8011     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8012     TmpInst.addOperand(Inst.getOperand(4));
8013     Inst = TmpInst;
8014     return true;
8015   }
8016 
8017   case ARM::VST4dWB_register_Asm_8:
8018   case ARM::VST4dWB_register_Asm_16:
8019   case ARM::VST4dWB_register_Asm_32:
8020   case ARM::VST4qWB_register_Asm_8:
8021   case ARM::VST4qWB_register_Asm_16:
8022   case ARM::VST4qWB_register_Asm_32: {
8023     MCInst TmpInst;
8024     unsigned Spacing;
8025     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8026     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8027     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8028     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8029     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8030     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8031     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8032                                             Spacing));
8033     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8034                                             Spacing * 2));
8035     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8036                                             Spacing * 3));
8037     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8038     TmpInst.addOperand(Inst.getOperand(5));
8039     Inst = TmpInst;
8040     return true;
8041   }
8042 
8043   // Handle encoding choice for the shift-immediate instructions.
8044   case ARM::t2LSLri:
8045   case ARM::t2LSRri:
8046   case ARM::t2ASRri: {
8047     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8048         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8049         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8050         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8051           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
8052       unsigned NewOpc;
8053       switch (Inst.getOpcode()) {
8054       default: llvm_unreachable("unexpected opcode");
8055       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8056       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8057       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8058       }
8059       // The Thumb1 operands aren't in the same order. Awesome, eh?
8060       MCInst TmpInst;
8061       TmpInst.setOpcode(NewOpc);
8062       TmpInst.addOperand(Inst.getOperand(0));
8063       TmpInst.addOperand(Inst.getOperand(5));
8064       TmpInst.addOperand(Inst.getOperand(1));
8065       TmpInst.addOperand(Inst.getOperand(2));
8066       TmpInst.addOperand(Inst.getOperand(3));
8067       TmpInst.addOperand(Inst.getOperand(4));
8068       Inst = TmpInst;
8069       return true;
8070     }
8071     return false;
8072   }
8073 
8074   // Handle the Thumb2 mode MOV complex aliases.
8075   case ARM::t2MOVsr:
8076   case ARM::t2MOVSsr: {
8077     // Which instruction to expand to depends on the CCOut operand and
8078     // whether we're in an IT block if the register operands are low
8079     // registers.
8080     bool isNarrow = false;
8081     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8082         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8083         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8084         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8085         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
8086       isNarrow = true;
8087     MCInst TmpInst;
8088     unsigned newOpc;
8089     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8090     default: llvm_unreachable("unexpected opcode!");
8091     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8092     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8093     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8094     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8095     }
8096     TmpInst.setOpcode(newOpc);
8097     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8098     if (isNarrow)
8099       TmpInst.addOperand(MCOperand::createReg(
8100           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8101     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8102     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8103     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8104     TmpInst.addOperand(Inst.getOperand(5));
8105     if (!isNarrow)
8106       TmpInst.addOperand(MCOperand::createReg(
8107           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8108     Inst = TmpInst;
8109     return true;
8110   }
8111   case ARM::t2MOVsi:
8112   case ARM::t2MOVSsi: {
8113     // Which instruction to expand to depends on the CCOut operand and
8114     // whether we're in an IT block if the register operands are low
8115     // registers.
8116     bool isNarrow = false;
8117     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8118         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8119         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
8120       isNarrow = true;
8121     MCInst TmpInst;
8122     unsigned newOpc;
8123     switch(ARM_AM::getSORegShOp(Inst.getOperand(2).getImm())) {
8124     default: llvm_unreachable("unexpected opcode!");
8125     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8126     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8127     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8128     case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8129     case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8130     }
8131     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8132     if (Amount == 32) Amount = 0;
8133     TmpInst.setOpcode(newOpc);
8134     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8135     if (isNarrow)
8136       TmpInst.addOperand(MCOperand::createReg(
8137           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8138     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8139     if (newOpc != ARM::t2RRX)
8140       TmpInst.addOperand(MCOperand::createImm(Amount));
8141     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8142     TmpInst.addOperand(Inst.getOperand(4));
8143     if (!isNarrow)
8144       TmpInst.addOperand(MCOperand::createReg(
8145           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8146     Inst = TmpInst;
8147     return true;
8148   }
8149   // Handle the ARM mode MOV complex aliases.
8150   case ARM::ASRr:
8151   case ARM::LSRr:
8152   case ARM::LSLr:
8153   case ARM::RORr: {
8154     ARM_AM::ShiftOpc ShiftTy;
8155     switch(Inst.getOpcode()) {
8156     default: llvm_unreachable("unexpected opcode!");
8157     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8158     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8159     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8160     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8161     }
8162     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8163     MCInst TmpInst;
8164     TmpInst.setOpcode(ARM::MOVsr);
8165     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8166     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8167     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8168     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8169     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8170     TmpInst.addOperand(Inst.getOperand(4));
8171     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8172     Inst = TmpInst;
8173     return true;
8174   }
8175   case ARM::ASRi:
8176   case ARM::LSRi:
8177   case ARM::LSLi:
8178   case ARM::RORi: {
8179     ARM_AM::ShiftOpc ShiftTy;
8180     switch(Inst.getOpcode()) {
8181     default: llvm_unreachable("unexpected opcode!");
8182     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8183     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8184     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8185     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8186     }
8187     // A shift by zero is a plain MOVr, not a MOVsi.
8188     unsigned Amt = Inst.getOperand(2).getImm();
8189     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8190     // A shift by 32 should be encoded as 0 when permitted
8191     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8192       Amt = 0;
8193     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8194     MCInst TmpInst;
8195     TmpInst.setOpcode(Opc);
8196     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8197     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8198     if (Opc == ARM::MOVsi)
8199       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8200     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8201     TmpInst.addOperand(Inst.getOperand(4));
8202     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8203     Inst = TmpInst;
8204     return true;
8205   }
8206   case ARM::RRXi: {
8207     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8208     MCInst TmpInst;
8209     TmpInst.setOpcode(ARM::MOVsi);
8210     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8211     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8212     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8213     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8214     TmpInst.addOperand(Inst.getOperand(3));
8215     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8216     Inst = TmpInst;
8217     return true;
8218   }
8219   case ARM::t2LDMIA_UPD: {
8220     // If this is a load of a single register, then we should use
8221     // a post-indexed LDR instruction instead, per the ARM ARM.
8222     if (Inst.getNumOperands() != 5)
8223       return false;
8224     MCInst TmpInst;
8225     TmpInst.setOpcode(ARM::t2LDR_POST);
8226     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8227     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8228     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8229     TmpInst.addOperand(MCOperand::createImm(4));
8230     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8231     TmpInst.addOperand(Inst.getOperand(3));
8232     Inst = TmpInst;
8233     return true;
8234   }
8235   case ARM::t2STMDB_UPD: {
8236     // If this is a store of a single register, then we should use
8237     // a pre-indexed STR instruction instead, per the ARM ARM.
8238     if (Inst.getNumOperands() != 5)
8239       return false;
8240     MCInst TmpInst;
8241     TmpInst.setOpcode(ARM::t2STR_PRE);
8242     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8243     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8244     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8245     TmpInst.addOperand(MCOperand::createImm(-4));
8246     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8247     TmpInst.addOperand(Inst.getOperand(3));
8248     Inst = TmpInst;
8249     return true;
8250   }
8251   case ARM::LDMIA_UPD:
8252     // If this is a load of a single register via a 'pop', then we should use
8253     // a post-indexed LDR instruction instead, per the ARM ARM.
8254     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8255         Inst.getNumOperands() == 5) {
8256       MCInst TmpInst;
8257       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8258       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8259       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8260       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8261       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8262       TmpInst.addOperand(MCOperand::createImm(4));
8263       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8264       TmpInst.addOperand(Inst.getOperand(3));
8265       Inst = TmpInst;
8266       return true;
8267     }
8268     break;
8269   case ARM::STMDB_UPD:
8270     // If this is a store of a single register via a 'push', then we should use
8271     // a pre-indexed STR instruction instead, per the ARM ARM.
8272     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8273         Inst.getNumOperands() == 5) {
8274       MCInst TmpInst;
8275       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8276       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8277       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8278       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8279       TmpInst.addOperand(MCOperand::createImm(-4));
8280       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8281       TmpInst.addOperand(Inst.getOperand(3));
8282       Inst = TmpInst;
8283     }
8284     break;
8285   case ARM::t2ADDri12:
8286     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8287     // mnemonic was used (not "addw"), encoding T3 is preferred.
8288     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8289         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8290       break;
8291     Inst.setOpcode(ARM::t2ADDri);
8292     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8293     break;
8294   case ARM::t2SUBri12:
8295     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8296     // mnemonic was used (not "subw"), encoding T3 is preferred.
8297     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8298         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8299       break;
8300     Inst.setOpcode(ARM::t2SUBri);
8301     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8302     break;
8303   case ARM::tADDi8:
8304     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8305     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8306     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8307     // to encoding T1 if <Rd> is omitted."
8308     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8309       Inst.setOpcode(ARM::tADDi3);
8310       return true;
8311     }
8312     break;
8313   case ARM::tSUBi8:
8314     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8315     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8316     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8317     // to encoding T1 if <Rd> is omitted."
8318     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8319       Inst.setOpcode(ARM::tSUBi3);
8320       return true;
8321     }
8322     break;
8323   case ARM::t2ADDri:
8324   case ARM::t2SUBri: {
8325     // If the destination and first source operand are the same, and
8326     // the flags are compatible with the current IT status, use encoding T2
8327     // instead of T3. For compatibility with the system 'as'. Make sure the
8328     // wide encoding wasn't explicit.
8329     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8330         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8331         (unsigned)Inst.getOperand(2).getImm() > 255 ||
8332         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
8333          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
8334         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8335          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8336       break;
8337     MCInst TmpInst;
8338     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8339                       ARM::tADDi8 : ARM::tSUBi8);
8340     TmpInst.addOperand(Inst.getOperand(0));
8341     TmpInst.addOperand(Inst.getOperand(5));
8342     TmpInst.addOperand(Inst.getOperand(0));
8343     TmpInst.addOperand(Inst.getOperand(2));
8344     TmpInst.addOperand(Inst.getOperand(3));
8345     TmpInst.addOperand(Inst.getOperand(4));
8346     Inst = TmpInst;
8347     return true;
8348   }
8349   case ARM::t2ADDrr: {
8350     // If the destination and first source operand are the same, and
8351     // there's no setting of the flags, use encoding T2 instead of T3.
8352     // Note that this is only for ADD, not SUB. This mirrors the system
8353     // 'as' behaviour.  Also take advantage of ADD being commutative.
8354     // Make sure the wide encoding wasn't explicit.
8355     bool Swap = false;
8356     auto DestReg = Inst.getOperand(0).getReg();
8357     bool Transform = DestReg == Inst.getOperand(1).getReg();
8358     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8359       Transform = true;
8360       Swap = true;
8361     }
8362     if (!Transform ||
8363         Inst.getOperand(5).getReg() != 0 ||
8364         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8365          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8366       break;
8367     MCInst TmpInst;
8368     TmpInst.setOpcode(ARM::tADDhirr);
8369     TmpInst.addOperand(Inst.getOperand(0));
8370     TmpInst.addOperand(Inst.getOperand(0));
8371     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8372     TmpInst.addOperand(Inst.getOperand(3));
8373     TmpInst.addOperand(Inst.getOperand(4));
8374     Inst = TmpInst;
8375     return true;
8376   }
8377   case ARM::tADDrSP: {
8378     // If the non-SP source operand and the destination operand are not the
8379     // same, we need to use the 32-bit encoding if it's available.
8380     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8381       Inst.setOpcode(ARM::t2ADDrr);
8382       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8383       return true;
8384     }
8385     break;
8386   }
8387   case ARM::tB:
8388     // A Thumb conditional branch outside of an IT block is a tBcc.
8389     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8390       Inst.setOpcode(ARM::tBcc);
8391       return true;
8392     }
8393     break;
8394   case ARM::t2B:
8395     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8396     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8397       Inst.setOpcode(ARM::t2Bcc);
8398       return true;
8399     }
8400     break;
8401   case ARM::t2Bcc:
8402     // If the conditional is AL or we're in an IT block, we really want t2B.
8403     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8404       Inst.setOpcode(ARM::t2B);
8405       return true;
8406     }
8407     break;
8408   case ARM::tBcc:
8409     // If the conditional is AL, we really want tB.
8410     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8411       Inst.setOpcode(ARM::tB);
8412       return true;
8413     }
8414     break;
8415   case ARM::tLDMIA: {
8416     // If the register list contains any high registers, or if the writeback
8417     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8418     // instead if we're in Thumb2. Otherwise, this should have generated
8419     // an error in validateInstruction().
8420     unsigned Rn = Inst.getOperand(0).getReg();
8421     bool hasWritebackToken =
8422         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8423          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8424     bool listContainsBase;
8425     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8426         (!listContainsBase && !hasWritebackToken) ||
8427         (listContainsBase && hasWritebackToken)) {
8428       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8429       assert (isThumbTwo());
8430       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8431       // If we're switching to the updating version, we need to insert
8432       // the writeback tied operand.
8433       if (hasWritebackToken)
8434         Inst.insert(Inst.begin(),
8435                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8436       return true;
8437     }
8438     break;
8439   }
8440   case ARM::tSTMIA_UPD: {
8441     // If the register list contains any high registers, we need to use
8442     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8443     // should have generated an error in validateInstruction().
8444     unsigned Rn = Inst.getOperand(0).getReg();
8445     bool listContainsBase;
8446     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8447       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8448       assert (isThumbTwo());
8449       Inst.setOpcode(ARM::t2STMIA_UPD);
8450       return true;
8451     }
8452     break;
8453   }
8454   case ARM::tPOP: {
8455     bool listContainsBase;
8456     // If the register list contains any high registers, we need to use
8457     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8458     // should have generated an error in validateInstruction().
8459     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8460       return false;
8461     assert (isThumbTwo());
8462     Inst.setOpcode(ARM::t2LDMIA_UPD);
8463     // Add the base register and writeback operands.
8464     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8465     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8466     return true;
8467   }
8468   case ARM::tPUSH: {
8469     bool listContainsBase;
8470     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8471       return false;
8472     assert (isThumbTwo());
8473     Inst.setOpcode(ARM::t2STMDB_UPD);
8474     // Add the base register and writeback operands.
8475     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8476     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8477     return true;
8478   }
8479   case ARM::t2MOVi: {
8480     // If we can use the 16-bit encoding and the user didn't explicitly
8481     // request the 32-bit variant, transform it here.
8482     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8483         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8484         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8485           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8486          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8487         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8488          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8489       // The operands aren't in the same order for tMOVi8...
8490       MCInst TmpInst;
8491       TmpInst.setOpcode(ARM::tMOVi8);
8492       TmpInst.addOperand(Inst.getOperand(0));
8493       TmpInst.addOperand(Inst.getOperand(4));
8494       TmpInst.addOperand(Inst.getOperand(1));
8495       TmpInst.addOperand(Inst.getOperand(2));
8496       TmpInst.addOperand(Inst.getOperand(3));
8497       Inst = TmpInst;
8498       return true;
8499     }
8500     break;
8501   }
8502   case ARM::t2MOVr: {
8503     // If we can use the 16-bit encoding and the user didn't explicitly
8504     // request the 32-bit variant, transform it here.
8505     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8506         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8507         Inst.getOperand(2).getImm() == ARMCC::AL &&
8508         Inst.getOperand(4).getReg() == ARM::CPSR &&
8509         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8510          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8511       // The operands aren't the same for tMOV[S]r... (no cc_out)
8512       MCInst TmpInst;
8513       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8514       TmpInst.addOperand(Inst.getOperand(0));
8515       TmpInst.addOperand(Inst.getOperand(1));
8516       TmpInst.addOperand(Inst.getOperand(2));
8517       TmpInst.addOperand(Inst.getOperand(3));
8518       Inst = TmpInst;
8519       return true;
8520     }
8521     break;
8522   }
8523   case ARM::t2SXTH:
8524   case ARM::t2SXTB:
8525   case ARM::t2UXTH:
8526   case ARM::t2UXTB: {
8527     // If we can use the 16-bit encoding and the user didn't explicitly
8528     // request the 32-bit variant, transform it here.
8529     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8530         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8531         Inst.getOperand(2).getImm() == 0 &&
8532         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8533          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8534       unsigned NewOpc;
8535       switch (Inst.getOpcode()) {
8536       default: llvm_unreachable("Illegal opcode!");
8537       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8538       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8539       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8540       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8541       }
8542       // The operands aren't the same for thumb1 (no rotate operand).
8543       MCInst TmpInst;
8544       TmpInst.setOpcode(NewOpc);
8545       TmpInst.addOperand(Inst.getOperand(0));
8546       TmpInst.addOperand(Inst.getOperand(1));
8547       TmpInst.addOperand(Inst.getOperand(3));
8548       TmpInst.addOperand(Inst.getOperand(4));
8549       Inst = TmpInst;
8550       return true;
8551     }
8552     break;
8553   }
8554   case ARM::MOVsi: {
8555     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8556     // rrx shifts and asr/lsr of #32 is encoded as 0
8557     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8558       return false;
8559     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8560       // Shifting by zero is accepted as a vanilla 'MOVr'
8561       MCInst TmpInst;
8562       TmpInst.setOpcode(ARM::MOVr);
8563       TmpInst.addOperand(Inst.getOperand(0));
8564       TmpInst.addOperand(Inst.getOperand(1));
8565       TmpInst.addOperand(Inst.getOperand(3));
8566       TmpInst.addOperand(Inst.getOperand(4));
8567       TmpInst.addOperand(Inst.getOperand(5));
8568       Inst = TmpInst;
8569       return true;
8570     }
8571     return false;
8572   }
8573   case ARM::ANDrsi:
8574   case ARM::ORRrsi:
8575   case ARM::EORrsi:
8576   case ARM::BICrsi:
8577   case ARM::SUBrsi:
8578   case ARM::ADDrsi: {
8579     unsigned newOpc;
8580     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8581     if (SOpc == ARM_AM::rrx) return false;
8582     switch (Inst.getOpcode()) {
8583     default: llvm_unreachable("unexpected opcode!");
8584     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8585     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8586     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8587     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8588     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8589     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8590     }
8591     // If the shift is by zero, use the non-shifted instruction definition.
8592     // The exception is for right shifts, where 0 == 32
8593     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8594         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8595       MCInst TmpInst;
8596       TmpInst.setOpcode(newOpc);
8597       TmpInst.addOperand(Inst.getOperand(0));
8598       TmpInst.addOperand(Inst.getOperand(1));
8599       TmpInst.addOperand(Inst.getOperand(2));
8600       TmpInst.addOperand(Inst.getOperand(4));
8601       TmpInst.addOperand(Inst.getOperand(5));
8602       TmpInst.addOperand(Inst.getOperand(6));
8603       Inst = TmpInst;
8604       return true;
8605     }
8606     return false;
8607   }
8608   case ARM::ITasm:
8609   case ARM::t2IT: {
8610     // The mask bits for all but the first condition are represented as
8611     // the low bit of the condition code value implies 't'. We currently
8612     // always have 1 implies 't', so XOR toggle the bits if the low bit
8613     // of the condition code is zero.
8614     MCOperand &MO = Inst.getOperand(1);
8615     unsigned Mask = MO.getImm();
8616     unsigned OrigMask = Mask;
8617     unsigned TZ = countTrailingZeros(Mask);
8618     if ((Inst.getOperand(0).getImm() & 1) == 0) {
8619       assert(Mask && TZ <= 3 && "illegal IT mask value!");
8620       Mask ^= (0xE << TZ) & 0xF;
8621     }
8622     MO.setImm(Mask);
8623 
8624     // Set up the IT block state according to the IT instruction we just
8625     // matched.
8626     assert(!inITBlock() && "nested IT blocks?!");
8627     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8628     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
8629     ITState.CurPosition = 0;
8630     ITState.FirstCond = true;
8631     break;
8632   }
8633   case ARM::t2LSLrr:
8634   case ARM::t2LSRrr:
8635   case ARM::t2ASRrr:
8636   case ARM::t2SBCrr:
8637   case ARM::t2RORrr:
8638   case ARM::t2BICrr:
8639   {
8640     // Assemblers should use the narrow encodings of these instructions when permissible.
8641     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8642          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8643         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8644         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8645          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8646         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8647          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8648              ".w"))) {
8649       unsigned NewOpc;
8650       switch (Inst.getOpcode()) {
8651         default: llvm_unreachable("unexpected opcode");
8652         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8653         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8654         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8655         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8656         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8657         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8658       }
8659       MCInst TmpInst;
8660       TmpInst.setOpcode(NewOpc);
8661       TmpInst.addOperand(Inst.getOperand(0));
8662       TmpInst.addOperand(Inst.getOperand(5));
8663       TmpInst.addOperand(Inst.getOperand(1));
8664       TmpInst.addOperand(Inst.getOperand(2));
8665       TmpInst.addOperand(Inst.getOperand(3));
8666       TmpInst.addOperand(Inst.getOperand(4));
8667       Inst = TmpInst;
8668       return true;
8669     }
8670     return false;
8671   }
8672   case ARM::t2ANDrr:
8673   case ARM::t2EORrr:
8674   case ARM::t2ADCrr:
8675   case ARM::t2ORRrr:
8676   {
8677     // Assemblers should use the narrow encodings of these instructions when permissible.
8678     // These instructions are special in that they are commutable, so shorter encodings
8679     // are available more often.
8680     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8681          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8682         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8683          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8684         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8685          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8686         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8687          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8688              ".w"))) {
8689       unsigned NewOpc;
8690       switch (Inst.getOpcode()) {
8691         default: llvm_unreachable("unexpected opcode");
8692         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8693         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8694         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8695         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8696       }
8697       MCInst TmpInst;
8698       TmpInst.setOpcode(NewOpc);
8699       TmpInst.addOperand(Inst.getOperand(0));
8700       TmpInst.addOperand(Inst.getOperand(5));
8701       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8702         TmpInst.addOperand(Inst.getOperand(1));
8703         TmpInst.addOperand(Inst.getOperand(2));
8704       } else {
8705         TmpInst.addOperand(Inst.getOperand(2));
8706         TmpInst.addOperand(Inst.getOperand(1));
8707       }
8708       TmpInst.addOperand(Inst.getOperand(3));
8709       TmpInst.addOperand(Inst.getOperand(4));
8710       Inst = TmpInst;
8711       return true;
8712     }
8713     return false;
8714   }
8715   }
8716   return false;
8717 }
8718 
8719 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8720   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8721   // suffix depending on whether they're in an IT block or not.
8722   unsigned Opc = Inst.getOpcode();
8723   const MCInstrDesc &MCID = MII.get(Opc);
8724   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8725     assert(MCID.hasOptionalDef() &&
8726            "optionally flag setting instruction missing optional def operand");
8727     assert(MCID.NumOperands == Inst.getNumOperands() &&
8728            "operand count mismatch!");
8729     // Find the optional-def operand (cc_out).
8730     unsigned OpNo;
8731     for (OpNo = 0;
8732          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8733          ++OpNo)
8734       ;
8735     // If we're parsing Thumb1, reject it completely.
8736     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8737       return Match_MnemonicFail;
8738     // If we're parsing Thumb2, which form is legal depends on whether we're
8739     // in an IT block.
8740     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8741         !inITBlock())
8742       return Match_RequiresITBlock;
8743     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8744         inITBlock())
8745       return Match_RequiresNotITBlock;
8746   } else if (isThumbOne()) {
8747     // Some high-register supporting Thumb1 encodings only allow both registers
8748     // to be from r0-r7 when in Thumb2.
8749     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8750         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8751         isARMLowRegister(Inst.getOperand(2).getReg()))
8752       return Match_RequiresThumb2;
8753     // Others only require ARMv6 or later.
8754     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8755              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8756              isARMLowRegister(Inst.getOperand(1).getReg()))
8757       return Match_RequiresV6;
8758   }
8759 
8760   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8761     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8762       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8763       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8764         return Match_RequiresV8;
8765       else if (Inst.getOperand(I).getReg() == ARM::PC)
8766         return Match_InvalidOperand;
8767     }
8768 
8769   return Match_Success;
8770 }
8771 
8772 namespace llvm {
8773 template <> inline bool IsCPSRDead<MCInst>(MCInst *Instr) {
8774   return true; // In an assembly source, no need to second-guess
8775 }
8776 }
8777 
8778 static const char *getSubtargetFeatureName(uint64_t Val);
8779 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8780                                            OperandVector &Operands,
8781                                            MCStreamer &Out, uint64_t &ErrorInfo,
8782                                            bool MatchingInlineAsm) {
8783   MCInst Inst;
8784   unsigned MatchResult;
8785 
8786   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
8787                                      MatchingInlineAsm);
8788   switch (MatchResult) {
8789   case Match_Success:
8790     // Context sensitive operand constraints aren't handled by the matcher,
8791     // so check them here.
8792     if (validateInstruction(Inst, Operands)) {
8793       // Still progress the IT block, otherwise one wrong condition causes
8794       // nasty cascading errors.
8795       forwardITPosition();
8796       return true;
8797     }
8798 
8799     { // processInstruction() updates inITBlock state, we need to save it away
8800       bool wasInITBlock = inITBlock();
8801 
8802       // Some instructions need post-processing to, for example, tweak which
8803       // encoding is selected. Loop on it while changes happen so the
8804       // individual transformations can chain off each other. E.g.,
8805       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
8806       while (processInstruction(Inst, Operands, Out))
8807         ;
8808 
8809       // Only after the instruction is fully processed, we can validate it
8810       if (wasInITBlock && hasV8Ops() && isThumb() &&
8811           !isV8EligibleForIT(&Inst)) {
8812         Warning(IDLoc, "deprecated instruction in IT block");
8813       }
8814     }
8815 
8816     // Only move forward at the very end so that everything in validate
8817     // and process gets a consistent answer about whether we're in an IT
8818     // block.
8819     forwardITPosition();
8820 
8821     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
8822     // doesn't actually encode.
8823     if (Inst.getOpcode() == ARM::ITasm)
8824       return false;
8825 
8826     Inst.setLoc(IDLoc);
8827     Out.EmitInstruction(Inst, getSTI());
8828     return false;
8829   case Match_MissingFeature: {
8830     assert(ErrorInfo && "Unknown missing feature!");
8831     // Special case the error message for the very common case where only
8832     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
8833     std::string Msg = "instruction requires:";
8834     uint64_t Mask = 1;
8835     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
8836       if (ErrorInfo & Mask) {
8837         Msg += " ";
8838         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
8839       }
8840       Mask <<= 1;
8841     }
8842     return Error(IDLoc, Msg);
8843   }
8844   case Match_InvalidOperand: {
8845     SMLoc ErrorLoc = IDLoc;
8846     if (ErrorInfo != ~0ULL) {
8847       if (ErrorInfo >= Operands.size())
8848         return Error(IDLoc, "too few operands for instruction");
8849 
8850       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8851       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8852     }
8853 
8854     return Error(ErrorLoc, "invalid operand for instruction");
8855   }
8856   case Match_MnemonicFail:
8857     return Error(IDLoc, "invalid instruction",
8858                  ((ARMOperand &)*Operands[0]).getLocRange());
8859   case Match_RequiresNotITBlock:
8860     return Error(IDLoc, "flag setting instruction only valid outside IT block");
8861   case Match_RequiresITBlock:
8862     return Error(IDLoc, "instruction only valid inside IT block");
8863   case Match_RequiresV6:
8864     return Error(IDLoc, "instruction variant requires ARMv6 or later");
8865   case Match_RequiresThumb2:
8866     return Error(IDLoc, "instruction variant requires Thumb2");
8867   case Match_RequiresV8:
8868     return Error(IDLoc, "instruction variant requires ARMv8 or later");
8869   case Match_ImmRange0_15: {
8870     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8871     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8872     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
8873   }
8874   case Match_ImmRange0_239: {
8875     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8876     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8877     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
8878   }
8879   case Match_AlignedMemoryRequiresNone:
8880   case Match_DupAlignedMemoryRequiresNone:
8881   case Match_AlignedMemoryRequires16:
8882   case Match_DupAlignedMemoryRequires16:
8883   case Match_AlignedMemoryRequires32:
8884   case Match_DupAlignedMemoryRequires32:
8885   case Match_AlignedMemoryRequires64:
8886   case Match_DupAlignedMemoryRequires64:
8887   case Match_AlignedMemoryRequires64or128:
8888   case Match_DupAlignedMemoryRequires64or128:
8889   case Match_AlignedMemoryRequires64or128or256:
8890   {
8891     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
8892     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8893     switch (MatchResult) {
8894       default:
8895         llvm_unreachable("Missing Match_Aligned type");
8896       case Match_AlignedMemoryRequiresNone:
8897       case Match_DupAlignedMemoryRequiresNone:
8898         return Error(ErrorLoc, "alignment must be omitted");
8899       case Match_AlignedMemoryRequires16:
8900       case Match_DupAlignedMemoryRequires16:
8901         return Error(ErrorLoc, "alignment must be 16 or omitted");
8902       case Match_AlignedMemoryRequires32:
8903       case Match_DupAlignedMemoryRequires32:
8904         return Error(ErrorLoc, "alignment must be 32 or omitted");
8905       case Match_AlignedMemoryRequires64:
8906       case Match_DupAlignedMemoryRequires64:
8907         return Error(ErrorLoc, "alignment must be 64 or omitted");
8908       case Match_AlignedMemoryRequires64or128:
8909       case Match_DupAlignedMemoryRequires64or128:
8910         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
8911       case Match_AlignedMemoryRequires64or128or256:
8912         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
8913     }
8914   }
8915   }
8916 
8917   llvm_unreachable("Implement any new match types added!");
8918 }
8919 
8920 /// parseDirective parses the arm specific directives
8921 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
8922   const MCObjectFileInfo::Environment Format =
8923     getContext().getObjectFileInfo()->getObjectFileType();
8924   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8925   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
8926 
8927   StringRef IDVal = DirectiveID.getIdentifier();
8928   if (IDVal == ".word")
8929     return parseLiteralValues(4, DirectiveID.getLoc());
8930   else if (IDVal == ".short" || IDVal == ".hword")
8931     return parseLiteralValues(2, DirectiveID.getLoc());
8932   else if (IDVal == ".thumb")
8933     return parseDirectiveThumb(DirectiveID.getLoc());
8934   else if (IDVal == ".arm")
8935     return parseDirectiveARM(DirectiveID.getLoc());
8936   else if (IDVal == ".thumb_func")
8937     return parseDirectiveThumbFunc(DirectiveID.getLoc());
8938   else if (IDVal == ".code")
8939     return parseDirectiveCode(DirectiveID.getLoc());
8940   else if (IDVal == ".syntax")
8941     return parseDirectiveSyntax(DirectiveID.getLoc());
8942   else if (IDVal == ".unreq")
8943     return parseDirectiveUnreq(DirectiveID.getLoc());
8944   else if (IDVal == ".fnend")
8945     return parseDirectiveFnEnd(DirectiveID.getLoc());
8946   else if (IDVal == ".cantunwind")
8947     return parseDirectiveCantUnwind(DirectiveID.getLoc());
8948   else if (IDVal == ".personality")
8949     return parseDirectivePersonality(DirectiveID.getLoc());
8950   else if (IDVal == ".handlerdata")
8951     return parseDirectiveHandlerData(DirectiveID.getLoc());
8952   else if (IDVal == ".setfp")
8953     return parseDirectiveSetFP(DirectiveID.getLoc());
8954   else if (IDVal == ".pad")
8955     return parseDirectivePad(DirectiveID.getLoc());
8956   else if (IDVal == ".save")
8957     return parseDirectiveRegSave(DirectiveID.getLoc(), false);
8958   else if (IDVal == ".vsave")
8959     return parseDirectiveRegSave(DirectiveID.getLoc(), true);
8960   else if (IDVal == ".ltorg" || IDVal == ".pool")
8961     return parseDirectiveLtorg(DirectiveID.getLoc());
8962   else if (IDVal == ".even")
8963     return parseDirectiveEven(DirectiveID.getLoc());
8964   else if (IDVal == ".personalityindex")
8965     return parseDirectivePersonalityIndex(DirectiveID.getLoc());
8966   else if (IDVal == ".unwind_raw")
8967     return parseDirectiveUnwindRaw(DirectiveID.getLoc());
8968   else if (IDVal == ".movsp")
8969     return parseDirectiveMovSP(DirectiveID.getLoc());
8970   else if (IDVal == ".arch_extension")
8971     return parseDirectiveArchExtension(DirectiveID.getLoc());
8972   else if (IDVal == ".align")
8973     return parseDirectiveAlign(DirectiveID.getLoc());
8974   else if (IDVal == ".thumb_set")
8975     return parseDirectiveThumbSet(DirectiveID.getLoc());
8976 
8977   if (!IsMachO && !IsCOFF) {
8978     if (IDVal == ".arch")
8979       return parseDirectiveArch(DirectiveID.getLoc());
8980     else if (IDVal == ".cpu")
8981       return parseDirectiveCPU(DirectiveID.getLoc());
8982     else if (IDVal == ".eabi_attribute")
8983       return parseDirectiveEabiAttr(DirectiveID.getLoc());
8984     else if (IDVal == ".fpu")
8985       return parseDirectiveFPU(DirectiveID.getLoc());
8986     else if (IDVal == ".fnstart")
8987       return parseDirectiveFnStart(DirectiveID.getLoc());
8988     else if (IDVal == ".inst")
8989       return parseDirectiveInst(DirectiveID.getLoc());
8990     else if (IDVal == ".inst.n")
8991       return parseDirectiveInst(DirectiveID.getLoc(), 'n');
8992     else if (IDVal == ".inst.w")
8993       return parseDirectiveInst(DirectiveID.getLoc(), 'w');
8994     else if (IDVal == ".object_arch")
8995       return parseDirectiveObjectArch(DirectiveID.getLoc());
8996     else if (IDVal == ".tlsdescseq")
8997       return parseDirectiveTLSDescSeq(DirectiveID.getLoc());
8998   }
8999 
9000   return true;
9001 }
9002 
9003 /// parseLiteralValues
9004 ///  ::= .hword expression [, expression]*
9005 ///  ::= .short expression [, expression]*
9006 ///  ::= .word expression [, expression]*
9007 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9008   MCAsmParser &Parser = getParser();
9009   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9010     for (;;) {
9011       const MCExpr *Value;
9012       if (getParser().parseExpression(Value)) {
9013         Parser.eatToEndOfStatement();
9014         return false;
9015       }
9016 
9017       getParser().getStreamer().EmitValue(Value, Size, L);
9018 
9019       if (getLexer().is(AsmToken::EndOfStatement))
9020         break;
9021 
9022       // FIXME: Improve diagnostic.
9023       if (getLexer().isNot(AsmToken::Comma)) {
9024         Error(L, "unexpected token in directive");
9025         return false;
9026       }
9027       Parser.Lex();
9028     }
9029   }
9030 
9031   Parser.Lex();
9032   return false;
9033 }
9034 
9035 /// parseDirectiveThumb
9036 ///  ::= .thumb
9037 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9038   MCAsmParser &Parser = getParser();
9039   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9040     Error(L, "unexpected token in directive");
9041     return false;
9042   }
9043   Parser.Lex();
9044 
9045   if (!hasThumb()) {
9046     Error(L, "target does not support Thumb mode");
9047     return false;
9048   }
9049 
9050   if (!isThumb())
9051     SwitchMode();
9052 
9053   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9054   return false;
9055 }
9056 
9057 /// parseDirectiveARM
9058 ///  ::= .arm
9059 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9060   MCAsmParser &Parser = getParser();
9061   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9062     Error(L, "unexpected token in directive");
9063     return false;
9064   }
9065   Parser.Lex();
9066 
9067   if (!hasARM()) {
9068     Error(L, "target does not support ARM mode");
9069     return false;
9070   }
9071 
9072   if (isThumb())
9073     SwitchMode();
9074 
9075   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9076   return false;
9077 }
9078 
9079 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9080   if (NextSymbolIsThumb) {
9081     getParser().getStreamer().EmitThumbFunc(Symbol);
9082     NextSymbolIsThumb = false;
9083   }
9084 }
9085 
9086 /// parseDirectiveThumbFunc
9087 ///  ::= .thumbfunc symbol_name
9088 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9089   MCAsmParser &Parser = getParser();
9090   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9091   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9092 
9093   // Darwin asm has (optionally) function name after .thumb_func direction
9094   // ELF doesn't
9095   if (IsMachO) {
9096     const AsmToken &Tok = Parser.getTok();
9097     if (Tok.isNot(AsmToken::EndOfStatement)) {
9098       if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String)) {
9099         Error(L, "unexpected token in .thumb_func directive");
9100         return false;
9101       }
9102 
9103       MCSymbol *Func =
9104           getParser().getContext().getOrCreateSymbol(Tok.getIdentifier());
9105       getParser().getStreamer().EmitThumbFunc(Func);
9106       Parser.Lex(); // Consume the identifier token.
9107       return false;
9108     }
9109   }
9110 
9111   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9112     Error(Parser.getTok().getLoc(), "unexpected token in directive");
9113     Parser.eatToEndOfStatement();
9114     return false;
9115   }
9116 
9117   NextSymbolIsThumb = true;
9118   return false;
9119 }
9120 
9121 /// parseDirectiveSyntax
9122 ///  ::= .syntax unified | divided
9123 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9124   MCAsmParser &Parser = getParser();
9125   const AsmToken &Tok = Parser.getTok();
9126   if (Tok.isNot(AsmToken::Identifier)) {
9127     Error(L, "unexpected token in .syntax directive");
9128     return false;
9129   }
9130 
9131   StringRef Mode = Tok.getString();
9132   if (Mode == "unified" || Mode == "UNIFIED") {
9133     Parser.Lex();
9134   } else if (Mode == "divided" || Mode == "DIVIDED") {
9135     Error(L, "'.syntax divided' arm asssembly not supported");
9136     return false;
9137   } else {
9138     Error(L, "unrecognized syntax mode in .syntax directive");
9139     return false;
9140   }
9141 
9142   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9143     Error(Parser.getTok().getLoc(), "unexpected token in directive");
9144     return false;
9145   }
9146   Parser.Lex();
9147 
9148   // TODO tell the MC streamer the mode
9149   // getParser().getStreamer().Emit???();
9150   return false;
9151 }
9152 
9153 /// parseDirectiveCode
9154 ///  ::= .code 16 | 32
9155 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9156   MCAsmParser &Parser = getParser();
9157   const AsmToken &Tok = Parser.getTok();
9158   if (Tok.isNot(AsmToken::Integer)) {
9159     Error(L, "unexpected token in .code directive");
9160     return false;
9161   }
9162   int64_t Val = Parser.getTok().getIntVal();
9163   if (Val != 16 && Val != 32) {
9164     Error(L, "invalid operand to .code directive");
9165     return false;
9166   }
9167   Parser.Lex();
9168 
9169   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9170     Error(Parser.getTok().getLoc(), "unexpected token in directive");
9171     return false;
9172   }
9173   Parser.Lex();
9174 
9175   if (Val == 16) {
9176     if (!hasThumb()) {
9177       Error(L, "target does not support Thumb mode");
9178       return false;
9179     }
9180 
9181     if (!isThumb())
9182       SwitchMode();
9183     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9184   } else {
9185     if (!hasARM()) {
9186       Error(L, "target does not support ARM mode");
9187       return false;
9188     }
9189 
9190     if (isThumb())
9191       SwitchMode();
9192     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9193   }
9194 
9195   return false;
9196 }
9197 
9198 /// parseDirectiveReq
9199 ///  ::= name .req registername
9200 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9201   MCAsmParser &Parser = getParser();
9202   Parser.Lex(); // Eat the '.req' token.
9203   unsigned Reg;
9204   SMLoc SRegLoc, ERegLoc;
9205   if (ParseRegister(Reg, SRegLoc, ERegLoc)) {
9206     Parser.eatToEndOfStatement();
9207     Error(SRegLoc, "register name expected");
9208     return false;
9209   }
9210 
9211   // Shouldn't be anything else.
9212   if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
9213     Parser.eatToEndOfStatement();
9214     Error(Parser.getTok().getLoc(), "unexpected input in .req directive.");
9215     return false;
9216   }
9217 
9218   Parser.Lex(); // Consume the EndOfStatement
9219 
9220   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg) {
9221     Error(SRegLoc, "redefinition of '" + Name + "' does not match original.");
9222     return false;
9223   }
9224 
9225   return false;
9226 }
9227 
9228 /// parseDirectiveUneq
9229 ///  ::= .unreq registername
9230 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9231   MCAsmParser &Parser = getParser();
9232   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9233     Parser.eatToEndOfStatement();
9234     Error(L, "unexpected input in .unreq directive.");
9235     return false;
9236   }
9237   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9238   Parser.Lex(); // Eat the identifier.
9239   return false;
9240 }
9241 
9242 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9243 // before, if supported by the new target, or emit mapping symbols for the mode
9244 // switch.
9245 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9246   if (WasThumb != isThumb()) {
9247     if (WasThumb && hasThumb()) {
9248       // Stay in Thumb mode
9249       SwitchMode();
9250     } else if (!WasThumb && hasARM()) {
9251       // Stay in ARM mode
9252       SwitchMode();
9253     } else {
9254       // Mode switch forced, because the new arch doesn't support the old mode.
9255       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9256                                                             : MCAF_Code32);
9257       // Warn about the implcit mode switch. GAS does not switch modes here,
9258       // but instead stays in the old mode, reporting an error on any following
9259       // instructions as the mode does not exist on the target.
9260       Warning(Loc, Twine("new target does not support ") +
9261                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9262                        (!WasThumb ? "thumb" : "arm") + " mode");
9263     }
9264   }
9265 }
9266 
9267 /// parseDirectiveArch
9268 ///  ::= .arch token
9269 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9270   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9271 
9272   unsigned ID = ARM::parseArch(Arch);
9273 
9274   if (ID == ARM::AK_INVALID) {
9275     Error(L, "Unknown arch name");
9276     return false;
9277   }
9278 
9279   bool WasThumb = isThumb();
9280   Triple T;
9281   MCSubtargetInfo &STI = copySTI();
9282   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9283   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9284   FixModeAfterArchChange(WasThumb, L);
9285 
9286   getTargetStreamer().emitArch(ID);
9287   return false;
9288 }
9289 
9290 /// parseDirectiveEabiAttr
9291 ///  ::= .eabi_attribute int, int [, "str"]
9292 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9293 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9294   MCAsmParser &Parser = getParser();
9295   int64_t Tag;
9296   SMLoc TagLoc;
9297   TagLoc = Parser.getTok().getLoc();
9298   if (Parser.getTok().is(AsmToken::Identifier)) {
9299     StringRef Name = Parser.getTok().getIdentifier();
9300     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9301     if (Tag == -1) {
9302       Error(TagLoc, "attribute name not recognised: " + Name);
9303       Parser.eatToEndOfStatement();
9304       return false;
9305     }
9306     Parser.Lex();
9307   } else {
9308     const MCExpr *AttrExpr;
9309 
9310     TagLoc = Parser.getTok().getLoc();
9311     if (Parser.parseExpression(AttrExpr)) {
9312       Parser.eatToEndOfStatement();
9313       return false;
9314     }
9315 
9316     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9317     if (!CE) {
9318       Error(TagLoc, "expected numeric constant");
9319       Parser.eatToEndOfStatement();
9320       return false;
9321     }
9322 
9323     Tag = CE->getValue();
9324   }
9325 
9326   if (Parser.getTok().isNot(AsmToken::Comma)) {
9327     Error(Parser.getTok().getLoc(), "comma expected");
9328     Parser.eatToEndOfStatement();
9329     return false;
9330   }
9331   Parser.Lex(); // skip comma
9332 
9333   StringRef StringValue = "";
9334   bool IsStringValue = false;
9335 
9336   int64_t IntegerValue = 0;
9337   bool IsIntegerValue = false;
9338 
9339   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9340     IsStringValue = true;
9341   else if (Tag == ARMBuildAttrs::compatibility) {
9342     IsStringValue = true;
9343     IsIntegerValue = true;
9344   } else if (Tag < 32 || Tag % 2 == 0)
9345     IsIntegerValue = true;
9346   else if (Tag % 2 == 1)
9347     IsStringValue = true;
9348   else
9349     llvm_unreachable("invalid tag type");
9350 
9351   if (IsIntegerValue) {
9352     const MCExpr *ValueExpr;
9353     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9354     if (Parser.parseExpression(ValueExpr)) {
9355       Parser.eatToEndOfStatement();
9356       return false;
9357     }
9358 
9359     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9360     if (!CE) {
9361       Error(ValueExprLoc, "expected numeric constant");
9362       Parser.eatToEndOfStatement();
9363       return false;
9364     }
9365 
9366     IntegerValue = CE->getValue();
9367   }
9368 
9369   if (Tag == ARMBuildAttrs::compatibility) {
9370     if (Parser.getTok().isNot(AsmToken::Comma))
9371       IsStringValue = false;
9372     if (Parser.getTok().isNot(AsmToken::Comma)) {
9373       Error(Parser.getTok().getLoc(), "comma expected");
9374       Parser.eatToEndOfStatement();
9375       return false;
9376     } else {
9377        Parser.Lex();
9378     }
9379   }
9380 
9381   if (IsStringValue) {
9382     if (Parser.getTok().isNot(AsmToken::String)) {
9383       Error(Parser.getTok().getLoc(), "bad string constant");
9384       Parser.eatToEndOfStatement();
9385       return false;
9386     }
9387 
9388     StringValue = Parser.getTok().getStringContents();
9389     Parser.Lex();
9390   }
9391 
9392   if (IsIntegerValue && IsStringValue) {
9393     assert(Tag == ARMBuildAttrs::compatibility);
9394     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9395   } else if (IsIntegerValue)
9396     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9397   else if (IsStringValue)
9398     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9399   return false;
9400 }
9401 
9402 /// parseDirectiveCPU
9403 ///  ::= .cpu str
9404 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9405   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9406   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9407 
9408   // FIXME: This is using table-gen data, but should be moved to
9409   // ARMTargetParser once that is table-gen'd.
9410   if (!getSTI().isCPUStringValid(CPU)) {
9411     Error(L, "Unknown CPU name");
9412     return false;
9413   }
9414 
9415   bool WasThumb = isThumb();
9416   MCSubtargetInfo &STI = copySTI();
9417   STI.setDefaultFeatures(CPU, "");
9418   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9419   FixModeAfterArchChange(WasThumb, L);
9420 
9421   return false;
9422 }
9423 /// parseDirectiveFPU
9424 ///  ::= .fpu str
9425 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9426   SMLoc FPUNameLoc = getTok().getLoc();
9427   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9428 
9429   unsigned ID = ARM::parseFPU(FPU);
9430   std::vector<const char *> Features;
9431   if (!ARM::getFPUFeatures(ID, Features)) {
9432     Error(FPUNameLoc, "Unknown FPU name");
9433     return false;
9434   }
9435 
9436   MCSubtargetInfo &STI = copySTI();
9437   for (auto Feature : Features)
9438     STI.ApplyFeatureFlag(Feature);
9439   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9440 
9441   getTargetStreamer().emitFPU(ID);
9442   return false;
9443 }
9444 
9445 /// parseDirectiveFnStart
9446 ///  ::= .fnstart
9447 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9448   if (UC.hasFnStart()) {
9449     Error(L, ".fnstart starts before the end of previous one");
9450     UC.emitFnStartLocNotes();
9451     return false;
9452   }
9453 
9454   // Reset the unwind directives parser state
9455   UC.reset();
9456 
9457   getTargetStreamer().emitFnStart();
9458 
9459   UC.recordFnStart(L);
9460   return false;
9461 }
9462 
9463 /// parseDirectiveFnEnd
9464 ///  ::= .fnend
9465 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9466   // Check the ordering of unwind directives
9467   if (!UC.hasFnStart()) {
9468     Error(L, ".fnstart must precede .fnend directive");
9469     return false;
9470   }
9471 
9472   // Reset the unwind directives parser state
9473   getTargetStreamer().emitFnEnd();
9474 
9475   UC.reset();
9476   return false;
9477 }
9478 
9479 /// parseDirectiveCantUnwind
9480 ///  ::= .cantunwind
9481 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9482   UC.recordCantUnwind(L);
9483 
9484   // Check the ordering of unwind directives
9485   if (!UC.hasFnStart()) {
9486     Error(L, ".fnstart must precede .cantunwind directive");
9487     return false;
9488   }
9489   if (UC.hasHandlerData()) {
9490     Error(L, ".cantunwind can't be used with .handlerdata directive");
9491     UC.emitHandlerDataLocNotes();
9492     return false;
9493   }
9494   if (UC.hasPersonality()) {
9495     Error(L, ".cantunwind can't be used with .personality directive");
9496     UC.emitPersonalityLocNotes();
9497     return false;
9498   }
9499 
9500   getTargetStreamer().emitCantUnwind();
9501   return false;
9502 }
9503 
9504 /// parseDirectivePersonality
9505 ///  ::= .personality name
9506 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9507   MCAsmParser &Parser = getParser();
9508   bool HasExistingPersonality = UC.hasPersonality();
9509 
9510   UC.recordPersonality(L);
9511 
9512   // Check the ordering of unwind directives
9513   if (!UC.hasFnStart()) {
9514     Error(L, ".fnstart must precede .personality directive");
9515     return false;
9516   }
9517   if (UC.cantUnwind()) {
9518     Error(L, ".personality can't be used with .cantunwind directive");
9519     UC.emitCantUnwindLocNotes();
9520     return false;
9521   }
9522   if (UC.hasHandlerData()) {
9523     Error(L, ".personality must precede .handlerdata directive");
9524     UC.emitHandlerDataLocNotes();
9525     return false;
9526   }
9527   if (HasExistingPersonality) {
9528     Parser.eatToEndOfStatement();
9529     Error(L, "multiple personality directives");
9530     UC.emitPersonalityLocNotes();
9531     return false;
9532   }
9533 
9534   // Parse the name of the personality routine
9535   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9536     Parser.eatToEndOfStatement();
9537     Error(L, "unexpected input in .personality directive.");
9538     return false;
9539   }
9540   StringRef Name(Parser.getTok().getIdentifier());
9541   Parser.Lex();
9542 
9543   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9544   getTargetStreamer().emitPersonality(PR);
9545   return false;
9546 }
9547 
9548 /// parseDirectiveHandlerData
9549 ///  ::= .handlerdata
9550 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9551   UC.recordHandlerData(L);
9552 
9553   // Check the ordering of unwind directives
9554   if (!UC.hasFnStart()) {
9555     Error(L, ".fnstart must precede .personality directive");
9556     return false;
9557   }
9558   if (UC.cantUnwind()) {
9559     Error(L, ".handlerdata can't be used with .cantunwind directive");
9560     UC.emitCantUnwindLocNotes();
9561     return false;
9562   }
9563 
9564   getTargetStreamer().emitHandlerData();
9565   return false;
9566 }
9567 
9568 /// parseDirectiveSetFP
9569 ///  ::= .setfp fpreg, spreg [, offset]
9570 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9571   MCAsmParser &Parser = getParser();
9572   // Check the ordering of unwind directives
9573   if (!UC.hasFnStart()) {
9574     Error(L, ".fnstart must precede .setfp directive");
9575     return false;
9576   }
9577   if (UC.hasHandlerData()) {
9578     Error(L, ".setfp must precede .handlerdata directive");
9579     return false;
9580   }
9581 
9582   // Parse fpreg
9583   SMLoc FPRegLoc = Parser.getTok().getLoc();
9584   int FPReg = tryParseRegister();
9585   if (FPReg == -1) {
9586     Error(FPRegLoc, "frame pointer register expected");
9587     return false;
9588   }
9589 
9590   // Consume comma
9591   if (Parser.getTok().isNot(AsmToken::Comma)) {
9592     Error(Parser.getTok().getLoc(), "comma expected");
9593     return false;
9594   }
9595   Parser.Lex(); // skip comma
9596 
9597   // Parse spreg
9598   SMLoc SPRegLoc = Parser.getTok().getLoc();
9599   int SPReg = tryParseRegister();
9600   if (SPReg == -1) {
9601     Error(SPRegLoc, "stack pointer register expected");
9602     return false;
9603   }
9604 
9605   if (SPReg != ARM::SP && SPReg != UC.getFPReg()) {
9606     Error(SPRegLoc, "register should be either $sp or the latest fp register");
9607     return false;
9608   }
9609 
9610   // Update the frame pointer register
9611   UC.saveFPReg(FPReg);
9612 
9613   // Parse offset
9614   int64_t Offset = 0;
9615   if (Parser.getTok().is(AsmToken::Comma)) {
9616     Parser.Lex(); // skip comma
9617 
9618     if (Parser.getTok().isNot(AsmToken::Hash) &&
9619         Parser.getTok().isNot(AsmToken::Dollar)) {
9620       Error(Parser.getTok().getLoc(), "'#' expected");
9621       return false;
9622     }
9623     Parser.Lex(); // skip hash token.
9624 
9625     const MCExpr *OffsetExpr;
9626     SMLoc ExLoc = Parser.getTok().getLoc();
9627     SMLoc EndLoc;
9628     if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9629       Error(ExLoc, "malformed setfp offset");
9630       return false;
9631     }
9632     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9633     if (!CE) {
9634       Error(ExLoc, "setfp offset must be an immediate");
9635       return false;
9636     }
9637 
9638     Offset = CE->getValue();
9639   }
9640 
9641   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9642                                 static_cast<unsigned>(SPReg), Offset);
9643   return false;
9644 }
9645 
9646 /// parseDirective
9647 ///  ::= .pad offset
9648 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9649   MCAsmParser &Parser = getParser();
9650   // Check the ordering of unwind directives
9651   if (!UC.hasFnStart()) {
9652     Error(L, ".fnstart must precede .pad directive");
9653     return false;
9654   }
9655   if (UC.hasHandlerData()) {
9656     Error(L, ".pad must precede .handlerdata directive");
9657     return false;
9658   }
9659 
9660   // Parse the offset
9661   if (Parser.getTok().isNot(AsmToken::Hash) &&
9662       Parser.getTok().isNot(AsmToken::Dollar)) {
9663     Error(Parser.getTok().getLoc(), "'#' expected");
9664     return false;
9665   }
9666   Parser.Lex(); // skip hash token.
9667 
9668   const MCExpr *OffsetExpr;
9669   SMLoc ExLoc = Parser.getTok().getLoc();
9670   SMLoc EndLoc;
9671   if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9672     Error(ExLoc, "malformed pad offset");
9673     return false;
9674   }
9675   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9676   if (!CE) {
9677     Error(ExLoc, "pad offset must be an immediate");
9678     return false;
9679   }
9680 
9681   getTargetStreamer().emitPad(CE->getValue());
9682   return false;
9683 }
9684 
9685 /// parseDirectiveRegSave
9686 ///  ::= .save  { registers }
9687 ///  ::= .vsave { registers }
9688 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9689   // Check the ordering of unwind directives
9690   if (!UC.hasFnStart()) {
9691     Error(L, ".fnstart must precede .save or .vsave directives");
9692     return false;
9693   }
9694   if (UC.hasHandlerData()) {
9695     Error(L, ".save or .vsave must precede .handlerdata directive");
9696     return false;
9697   }
9698 
9699   // RAII object to make sure parsed operands are deleted.
9700   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9701 
9702   // Parse the register list
9703   if (parseRegisterList(Operands))
9704     return false;
9705   ARMOperand &Op = (ARMOperand &)*Operands[0];
9706   if (!IsVector && !Op.isRegList()) {
9707     Error(L, ".save expects GPR registers");
9708     return false;
9709   }
9710   if (IsVector && !Op.isDPRRegList()) {
9711     Error(L, ".vsave expects DPR registers");
9712     return false;
9713   }
9714 
9715   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9716   return false;
9717 }
9718 
9719 /// parseDirectiveInst
9720 ///  ::= .inst opcode [, ...]
9721 ///  ::= .inst.n opcode [, ...]
9722 ///  ::= .inst.w opcode [, ...]
9723 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9724   MCAsmParser &Parser = getParser();
9725   int Width;
9726 
9727   if (isThumb()) {
9728     switch (Suffix) {
9729     case 'n':
9730       Width = 2;
9731       break;
9732     case 'w':
9733       Width = 4;
9734       break;
9735     default:
9736       Parser.eatToEndOfStatement();
9737       Error(Loc, "cannot determine Thumb instruction size, "
9738                  "use inst.n/inst.w instead");
9739       return false;
9740     }
9741   } else {
9742     if (Suffix) {
9743       Parser.eatToEndOfStatement();
9744       Error(Loc, "width suffixes are invalid in ARM mode");
9745       return false;
9746     }
9747     Width = 4;
9748   }
9749 
9750   if (getLexer().is(AsmToken::EndOfStatement)) {
9751     Parser.eatToEndOfStatement();
9752     Error(Loc, "expected expression following directive");
9753     return false;
9754   }
9755 
9756   for (;;) {
9757     const MCExpr *Expr;
9758 
9759     if (getParser().parseExpression(Expr)) {
9760       Error(Loc, "expected expression");
9761       return false;
9762     }
9763 
9764     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9765     if (!Value) {
9766       Error(Loc, "expected constant expression");
9767       return false;
9768     }
9769 
9770     switch (Width) {
9771     case 2:
9772       if (Value->getValue() > 0xffff) {
9773         Error(Loc, "inst.n operand is too big, use inst.w instead");
9774         return false;
9775       }
9776       break;
9777     case 4:
9778       if (Value->getValue() > 0xffffffff) {
9779         Error(Loc,
9780               StringRef(Suffix ? "inst.w" : "inst") + " operand is too big");
9781         return false;
9782       }
9783       break;
9784     default:
9785       llvm_unreachable("only supported widths are 2 and 4");
9786     }
9787 
9788     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9789 
9790     if (getLexer().is(AsmToken::EndOfStatement))
9791       break;
9792 
9793     if (getLexer().isNot(AsmToken::Comma)) {
9794       Error(Loc, "unexpected token in directive");
9795       return false;
9796     }
9797 
9798     Parser.Lex();
9799   }
9800 
9801   Parser.Lex();
9802   return false;
9803 }
9804 
9805 /// parseDirectiveLtorg
9806 ///  ::= .ltorg | .pool
9807 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9808   getTargetStreamer().emitCurrentConstantPool();
9809   return false;
9810 }
9811 
9812 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9813   const MCSection *Section = getStreamer().getCurrentSection().first;
9814 
9815   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9816     TokError("unexpected token in directive");
9817     return false;
9818   }
9819 
9820   if (!Section) {
9821     getStreamer().InitSections(false);
9822     Section = getStreamer().getCurrentSection().first;
9823   }
9824 
9825   assert(Section && "must have section to emit alignment");
9826   if (Section->UseCodeAlign())
9827     getStreamer().EmitCodeAlignment(2);
9828   else
9829     getStreamer().EmitValueToAlignment(2);
9830 
9831   return false;
9832 }
9833 
9834 /// parseDirectivePersonalityIndex
9835 ///   ::= .personalityindex index
9836 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9837   MCAsmParser &Parser = getParser();
9838   bool HasExistingPersonality = UC.hasPersonality();
9839 
9840   UC.recordPersonalityIndex(L);
9841 
9842   if (!UC.hasFnStart()) {
9843     Parser.eatToEndOfStatement();
9844     Error(L, ".fnstart must precede .personalityindex directive");
9845     return false;
9846   }
9847   if (UC.cantUnwind()) {
9848     Parser.eatToEndOfStatement();
9849     Error(L, ".personalityindex cannot be used with .cantunwind");
9850     UC.emitCantUnwindLocNotes();
9851     return false;
9852   }
9853   if (UC.hasHandlerData()) {
9854     Parser.eatToEndOfStatement();
9855     Error(L, ".personalityindex must precede .handlerdata directive");
9856     UC.emitHandlerDataLocNotes();
9857     return false;
9858   }
9859   if (HasExistingPersonality) {
9860     Parser.eatToEndOfStatement();
9861     Error(L, "multiple personality directives");
9862     UC.emitPersonalityLocNotes();
9863     return false;
9864   }
9865 
9866   const MCExpr *IndexExpression;
9867   SMLoc IndexLoc = Parser.getTok().getLoc();
9868   if (Parser.parseExpression(IndexExpression)) {
9869     Parser.eatToEndOfStatement();
9870     return false;
9871   }
9872 
9873   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9874   if (!CE) {
9875     Parser.eatToEndOfStatement();
9876     Error(IndexLoc, "index must be a constant number");
9877     return false;
9878   }
9879   if (CE->getValue() < 0 ||
9880       CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX) {
9881     Parser.eatToEndOfStatement();
9882     Error(IndexLoc, "personality routine index should be in range [0-3]");
9883     return false;
9884   }
9885 
9886   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9887   return false;
9888 }
9889 
9890 /// parseDirectiveUnwindRaw
9891 ///   ::= .unwind_raw offset, opcode [, opcode...]
9892 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9893   MCAsmParser &Parser = getParser();
9894   if (!UC.hasFnStart()) {
9895     Parser.eatToEndOfStatement();
9896     Error(L, ".fnstart must precede .unwind_raw directives");
9897     return false;
9898   }
9899 
9900   int64_t StackOffset;
9901 
9902   const MCExpr *OffsetExpr;
9903   SMLoc OffsetLoc = getLexer().getLoc();
9904   if (getLexer().is(AsmToken::EndOfStatement) ||
9905       getParser().parseExpression(OffsetExpr)) {
9906     Error(OffsetLoc, "expected expression");
9907     Parser.eatToEndOfStatement();
9908     return false;
9909   }
9910 
9911   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9912   if (!CE) {
9913     Error(OffsetLoc, "offset must be a constant");
9914     Parser.eatToEndOfStatement();
9915     return false;
9916   }
9917 
9918   StackOffset = CE->getValue();
9919 
9920   if (getLexer().isNot(AsmToken::Comma)) {
9921     Error(getLexer().getLoc(), "expected comma");
9922     Parser.eatToEndOfStatement();
9923     return false;
9924   }
9925   Parser.Lex();
9926 
9927   SmallVector<uint8_t, 16> Opcodes;
9928   for (;;) {
9929     const MCExpr *OE;
9930 
9931     SMLoc OpcodeLoc = getLexer().getLoc();
9932     if (getLexer().is(AsmToken::EndOfStatement) || Parser.parseExpression(OE)) {
9933       Error(OpcodeLoc, "expected opcode expression");
9934       Parser.eatToEndOfStatement();
9935       return false;
9936     }
9937 
9938     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9939     if (!OC) {
9940       Error(OpcodeLoc, "opcode value must be a constant");
9941       Parser.eatToEndOfStatement();
9942       return false;
9943     }
9944 
9945     const int64_t Opcode = OC->getValue();
9946     if (Opcode & ~0xff) {
9947       Error(OpcodeLoc, "invalid opcode");
9948       Parser.eatToEndOfStatement();
9949       return false;
9950     }
9951 
9952     Opcodes.push_back(uint8_t(Opcode));
9953 
9954     if (getLexer().is(AsmToken::EndOfStatement))
9955       break;
9956 
9957     if (getLexer().isNot(AsmToken::Comma)) {
9958       Error(getLexer().getLoc(), "unexpected token in directive");
9959       Parser.eatToEndOfStatement();
9960       return false;
9961     }
9962 
9963     Parser.Lex();
9964   }
9965 
9966   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9967 
9968   Parser.Lex();
9969   return false;
9970 }
9971 
9972 /// parseDirectiveTLSDescSeq
9973 ///   ::= .tlsdescseq tls-variable
9974 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9975   MCAsmParser &Parser = getParser();
9976 
9977   if (getLexer().isNot(AsmToken::Identifier)) {
9978     TokError("expected variable after '.tlsdescseq' directive");
9979     Parser.eatToEndOfStatement();
9980     return false;
9981   }
9982 
9983   const MCSymbolRefExpr *SRE =
9984     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
9985                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9986   Lex();
9987 
9988   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9989     Error(Parser.getTok().getLoc(), "unexpected token");
9990     Parser.eatToEndOfStatement();
9991     return false;
9992   }
9993 
9994   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9995   return false;
9996 }
9997 
9998 /// parseDirectiveMovSP
9999 ///  ::= .movsp reg [, #offset]
10000 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10001   MCAsmParser &Parser = getParser();
10002   if (!UC.hasFnStart()) {
10003     Parser.eatToEndOfStatement();
10004     Error(L, ".fnstart must precede .movsp directives");
10005     return false;
10006   }
10007   if (UC.getFPReg() != ARM::SP) {
10008     Parser.eatToEndOfStatement();
10009     Error(L, "unexpected .movsp directive");
10010     return false;
10011   }
10012 
10013   SMLoc SPRegLoc = Parser.getTok().getLoc();
10014   int SPReg = tryParseRegister();
10015   if (SPReg == -1) {
10016     Parser.eatToEndOfStatement();
10017     Error(SPRegLoc, "register expected");
10018     return false;
10019   }
10020 
10021   if (SPReg == ARM::SP || SPReg == ARM::PC) {
10022     Parser.eatToEndOfStatement();
10023     Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10024     return false;
10025   }
10026 
10027   int64_t Offset = 0;
10028   if (Parser.getTok().is(AsmToken::Comma)) {
10029     Parser.Lex();
10030 
10031     if (Parser.getTok().isNot(AsmToken::Hash)) {
10032       Error(Parser.getTok().getLoc(), "expected #constant");
10033       Parser.eatToEndOfStatement();
10034       return false;
10035     }
10036     Parser.Lex();
10037 
10038     const MCExpr *OffsetExpr;
10039     SMLoc OffsetLoc = Parser.getTok().getLoc();
10040     if (Parser.parseExpression(OffsetExpr)) {
10041       Parser.eatToEndOfStatement();
10042       Error(OffsetLoc, "malformed offset expression");
10043       return false;
10044     }
10045 
10046     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10047     if (!CE) {
10048       Parser.eatToEndOfStatement();
10049       Error(OffsetLoc, "offset must be an immediate constant");
10050       return false;
10051     }
10052 
10053     Offset = CE->getValue();
10054   }
10055 
10056   getTargetStreamer().emitMovSP(SPReg, Offset);
10057   UC.saveFPReg(SPReg);
10058 
10059   return false;
10060 }
10061 
10062 /// parseDirectiveObjectArch
10063 ///   ::= .object_arch name
10064 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10065   MCAsmParser &Parser = getParser();
10066   if (getLexer().isNot(AsmToken::Identifier)) {
10067     Error(getLexer().getLoc(), "unexpected token");
10068     Parser.eatToEndOfStatement();
10069     return false;
10070   }
10071 
10072   StringRef Arch = Parser.getTok().getString();
10073   SMLoc ArchLoc = Parser.getTok().getLoc();
10074   getLexer().Lex();
10075 
10076   unsigned ID = ARM::parseArch(Arch);
10077 
10078   if (ID == ARM::AK_INVALID) {
10079     Error(ArchLoc, "unknown architecture '" + Arch + "'");
10080     Parser.eatToEndOfStatement();
10081     return false;
10082   }
10083 
10084   getTargetStreamer().emitObjectArch(ID);
10085 
10086   if (getLexer().isNot(AsmToken::EndOfStatement)) {
10087     Error(getLexer().getLoc(), "unexpected token");
10088     Parser.eatToEndOfStatement();
10089   }
10090 
10091   return false;
10092 }
10093 
10094 /// parseDirectiveAlign
10095 ///   ::= .align
10096 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10097   // NOTE: if this is not the end of the statement, fall back to the target
10098   // agnostic handling for this directive which will correctly handle this.
10099   if (getLexer().isNot(AsmToken::EndOfStatement))
10100     return true;
10101 
10102   // '.align' is target specifically handled to mean 2**2 byte alignment.
10103   const MCSection *Section = getStreamer().getCurrentSection().first;
10104   assert(Section && "must have section to emit alignment");
10105   if (Section->UseCodeAlign())
10106     getStreamer().EmitCodeAlignment(4, 0);
10107   else
10108     getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10109 
10110   return false;
10111 }
10112 
10113 /// parseDirectiveThumbSet
10114 ///  ::= .thumb_set name, value
10115 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10116   MCAsmParser &Parser = getParser();
10117 
10118   StringRef Name;
10119   if (Parser.parseIdentifier(Name)) {
10120     TokError("expected identifier after '.thumb_set'");
10121     Parser.eatToEndOfStatement();
10122     return false;
10123   }
10124 
10125   if (getLexer().isNot(AsmToken::Comma)) {
10126     TokError("expected comma after name '" + Name + "'");
10127     Parser.eatToEndOfStatement();
10128     return false;
10129   }
10130   Lex();
10131 
10132   MCSymbol *Sym;
10133   const MCExpr *Value;
10134   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10135                                                Parser, Sym, Value))
10136     return true;
10137 
10138   getTargetStreamer().emitThumbSet(Sym, Value);
10139   return false;
10140 }
10141 
10142 /// Force static initialization.
10143 extern "C" void LLVMInitializeARMAsmParser() {
10144   RegisterMCAsmParser<ARMAsmParser> X(TheARMLETarget);
10145   RegisterMCAsmParser<ARMAsmParser> Y(TheARMBETarget);
10146   RegisterMCAsmParser<ARMAsmParser> A(TheThumbLETarget);
10147   RegisterMCAsmParser<ARMAsmParser> B(TheThumbBETarget);
10148 }
10149 
10150 #define GET_REGISTER_MATCHER
10151 #define GET_SUBTARGET_FEATURE_NAME
10152 #define GET_MATCHER_IMPLEMENTATION
10153 #include "ARMGenAsmMatcher.inc"
10154 
10155 // FIXME: This structure should be moved inside ARMTargetParser
10156 // when we start to table-generate them, and we can use the ARM
10157 // flags below, that were generated by table-gen.
10158 static const struct {
10159   const unsigned Kind;
10160   const uint64_t ArchCheck;
10161   const FeatureBitset Features;
10162 } Extensions[] = {
10163   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10164   { ARM::AEK_CRYPTO,  Feature_HasV8,
10165     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10166   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10167   { (ARM::AEK_HWDIV | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10168     {ARM::FeatureHWDiv, ARM::FeatureHWDivARM} },
10169   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10170   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10171   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10172   // FIXME: Only available in A-class, isel not predicated
10173   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10174   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10175   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10176   // FIXME: Unsupported extensions.
10177   { ARM::AEK_OS, Feature_None, {} },
10178   { ARM::AEK_IWMMXT, Feature_None, {} },
10179   { ARM::AEK_IWMMXT2, Feature_None, {} },
10180   { ARM::AEK_MAVERICK, Feature_None, {} },
10181   { ARM::AEK_XSCALE, Feature_None, {} },
10182 };
10183 
10184 /// parseDirectiveArchExtension
10185 ///   ::= .arch_extension [no]feature
10186 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10187   MCAsmParser &Parser = getParser();
10188 
10189   if (getLexer().isNot(AsmToken::Identifier)) {
10190     Error(getLexer().getLoc(), "unexpected token");
10191     Parser.eatToEndOfStatement();
10192     return false;
10193   }
10194 
10195   StringRef Name = Parser.getTok().getString();
10196   SMLoc ExtLoc = Parser.getTok().getLoc();
10197   getLexer().Lex();
10198 
10199   bool EnableFeature = true;
10200   if (Name.startswith_lower("no")) {
10201     EnableFeature = false;
10202     Name = Name.substr(2);
10203   }
10204   unsigned FeatureKind = ARM::parseArchExt(Name);
10205   if (FeatureKind == ARM::AEK_INVALID)
10206     Error(ExtLoc, "unknown architectural extension: " + Name);
10207 
10208   for (const auto &Extension : Extensions) {
10209     if (Extension.Kind != FeatureKind)
10210       continue;
10211 
10212     if (Extension.Features.none())
10213       report_fatal_error("unsupported architectural extension: " + Name);
10214 
10215     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck) {
10216       Error(ExtLoc, "architectural extension '" + Name + "' is not "
10217             "allowed for the current base architecture");
10218       return false;
10219     }
10220 
10221     MCSubtargetInfo &STI = copySTI();
10222     FeatureBitset ToggleFeatures = EnableFeature
10223       ? (~STI.getFeatureBits() & Extension.Features)
10224       : ( STI.getFeatureBits() & Extension.Features);
10225 
10226     uint64_t Features =
10227         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10228     setAvailableFeatures(Features);
10229     return false;
10230   }
10231 
10232   Error(ExtLoc, "unknown architectural extension: " + Name);
10233   Parser.eatToEndOfStatement();
10234   return false;
10235 }
10236 
10237 // Define this matcher function after the auto-generated include so we
10238 // have the match class enum definitions.
10239 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10240                                                   unsigned Kind) {
10241   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10242   // If the kind is a token for a literal immediate, check if our asm
10243   // operand matches. This is for InstAliases which have a fixed-value
10244   // immediate in the syntax.
10245   switch (Kind) {
10246   default: break;
10247   case MCK__35_0:
10248     if (Op.isImm())
10249       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10250         if (CE->getValue() == 0)
10251           return Match_Success;
10252     break;
10253   case MCK_ModImm:
10254     if (Op.isImm()) {
10255       const MCExpr *SOExpr = Op.getImm();
10256       int64_t Value;
10257       if (!SOExpr->evaluateAsAbsolute(Value))
10258         return Match_Success;
10259       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
10260              "expression value must be representable in 32 bits");
10261     }
10262     break;
10263   case MCK_rGPR:
10264     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10265       return Match_Success;
10266     break;
10267   case MCK_GPRPair:
10268     if (Op.isReg() &&
10269         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10270       return Match_Success;
10271     break;
10272   }
10273   return Match_InvalidOperand;
10274 }
10275