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