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