[MCTargetAsmParser] Move the member varialbes that reference
[oota-llvm.git] / lib / Target / ARM / AsmParser / ARMAsmParser.cpp
1 //===-- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "ARMFeatures.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMMCExpr.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCELFStreamer.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCObjectFileInfo.h"
30 #include "llvm/MC/MCParser/MCAsmLexer.h"
31 #include "llvm/MC/MCParser/MCAsmParser.h"
32 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
33 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
34 #include "llvm/MC/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/TargetParser.h"
43 #include "llvm/Support/COFF.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ELF.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/raw_ostream.h"
50
51 using namespace llvm;
52
53 namespace {
54
55 class ARMOperand;
56
57 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
58
59 class UnwindContext {
60   MCAsmParser &Parser;
61
62   typedef SmallVector<SMLoc, 4> Locs;
63
64   Locs FnStartLocs;
65   Locs CantUnwindLocs;
66   Locs PersonalityLocs;
67   Locs PersonalityIndexLocs;
68   Locs HandlerDataLocs;
69   int FPReg;
70
71 public:
72   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
73
74   bool hasFnStart() const { return !FnStartLocs.empty(); }
75   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
76   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
77   bool hasPersonality() const {
78     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
79   }
80
81   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
82   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
83   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
84   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
85   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
86
87   void saveFPReg(int Reg) { FPReg = Reg; }
88   int getFPReg() const { return FPReg; }
89
90   void emitFnStartLocNotes() const {
91     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
92          FI != FE; ++FI)
93       Parser.Note(*FI, ".fnstart was specified here");
94   }
95   void emitCantUnwindLocNotes() const {
96     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
97                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
98       Parser.Note(*UI, ".cantunwind was specified here");
99   }
100   void emitHandlerDataLocNotes() const {
101     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
102                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
103       Parser.Note(*HI, ".handlerdata was specified here");
104   }
105   void emitPersonalityLocNotes() const {
106     for (Locs::const_iterator PI = PersonalityLocs.begin(),
107                               PE = PersonalityLocs.end(),
108                               PII = PersonalityIndexLocs.begin(),
109                               PIE = PersonalityIndexLocs.end();
110          PI != PE || PII != PIE;) {
111       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
112         Parser.Note(*PI++, ".personality was specified here");
113       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
114         Parser.Note(*PII++, ".personalityindex was specified here");
115       else
116         llvm_unreachable(".personality and .personalityindex cannot be "
117                          "at the same location");
118     }
119   }
120
121   void reset() {
122     FnStartLocs = Locs();
123     CantUnwindLocs = Locs();
124     PersonalityLocs = Locs();
125     HandlerDataLocs = Locs();
126     PersonalityIndexLocs = Locs();
127     FPReg = ARM::SP;
128   }
129 };
130
131 class ARMAsmParser : public MCTargetAsmParser {
132   const MCInstrInfo &MII;
133   const MCRegisterInfo *MRI;
134   UnwindContext UC;
135
136   ARMTargetStreamer &getTargetStreamer() {
137     assert(getParser().getStreamer().getTargetStreamer() &&
138            "do not have a target streamer");
139     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
140     return static_cast<ARMTargetStreamer &>(TS);
141   }
142
143   // Map of register aliases registers via the .req directive.
144   StringMap<unsigned> RegisterReqs;
145
146   bool NextSymbolIsThumb;
147
148   struct {
149     ARMCC::CondCodes Cond;    // Condition for IT block.
150     unsigned Mask:4;          // Condition mask for instructions.
151                               // Starting at first 1 (from lsb).
152                               //   '1'  condition as indicated in IT.
153                               //   '0'  inverse of condition (else).
154                               // Count of instructions in IT block is
155                               // 4 - trailingzeroes(mask)
156
157     bool FirstCond;           // Explicit flag for when we're parsing the
158                               // First instruction in the IT block. It's
159                               // implied in the mask, so needs special
160                               // handling.
161
162     unsigned CurPosition;     // Current position in parsing of IT
163                               // block. In range [0,3]. Initialized
164                               // according to count of instructions in block.
165                               // ~0U if no active IT block.
166   } ITState;
167   bool inITBlock() { return ITState.CurPosition != ~0U; }
168   bool lastInITBlock() {
169     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
170   }
171   void forwardITPosition() {
172     if (!inITBlock()) return;
173     // Move to the next instruction in the IT block, if there is one. If not,
174     // mark the block as done.
175     unsigned TZ = countTrailingZeros(ITState.Mask);
176     if (++ITState.CurPosition == 5 - TZ)
177       ITState.CurPosition = ~0U; // Done with the IT block after this.
178   }
179
180   void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None) {
181     return getParser().Note(L, Msg, Ranges);
182   }
183   bool Warning(SMLoc L, const Twine &Msg,
184                ArrayRef<SMRange> Ranges = None) {
185     return getParser().Warning(L, Msg, Ranges);
186   }
187   bool Error(SMLoc L, const Twine &Msg,
188              ArrayRef<SMRange> Ranges = None) {
189     return getParser().Error(L, Msg, Ranges);
190   }
191
192   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
193                            unsigned ListNo, bool IsARPop = false);
194   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
195                            unsigned ListNo);
196
197   int tryParseRegister();
198   bool tryParseRegisterWithWriteBack(OperandVector &);
199   int tryParseShiftRegister(OperandVector &);
200   bool parseRegisterList(OperandVector &);
201   bool parseMemory(OperandVector &);
202   bool parseOperand(OperandVector &, StringRef Mnemonic);
203   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
204   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
205                               unsigned &ShiftAmount);
206   bool parseLiteralValues(unsigned Size, SMLoc L);
207   bool parseDirectiveThumb(SMLoc L);
208   bool parseDirectiveARM(SMLoc L);
209   bool parseDirectiveThumbFunc(SMLoc L);
210   bool parseDirectiveCode(SMLoc L);
211   bool parseDirectiveSyntax(SMLoc L);
212   bool parseDirectiveReq(StringRef Name, SMLoc L);
213   bool parseDirectiveUnreq(SMLoc L);
214   bool parseDirectiveArch(SMLoc L);
215   bool parseDirectiveEabiAttr(SMLoc L);
216   bool parseDirectiveCPU(SMLoc L);
217   bool parseDirectiveFPU(SMLoc L);
218   bool parseDirectiveFnStart(SMLoc L);
219   bool parseDirectiveFnEnd(SMLoc L);
220   bool parseDirectiveCantUnwind(SMLoc L);
221   bool parseDirectivePersonality(SMLoc L);
222   bool parseDirectiveHandlerData(SMLoc L);
223   bool parseDirectiveSetFP(SMLoc L);
224   bool parseDirectivePad(SMLoc L);
225   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
226   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
227   bool parseDirectiveLtorg(SMLoc L);
228   bool parseDirectiveEven(SMLoc L);
229   bool parseDirectivePersonalityIndex(SMLoc L);
230   bool parseDirectiveUnwindRaw(SMLoc L);
231   bool parseDirectiveTLSDescSeq(SMLoc L);
232   bool parseDirectiveMovSP(SMLoc L);
233   bool parseDirectiveObjectArch(SMLoc L);
234   bool parseDirectiveArchExtension(SMLoc L);
235   bool parseDirectiveAlign(SMLoc L);
236   bool parseDirectiveThumbSet(SMLoc L);
237
238   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
239                           bool &CarrySetting, unsigned &ProcessorIMod,
240                           StringRef &ITMask);
241   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
242                              bool &CanAcceptCarrySet,
243                              bool &CanAcceptPredicationCode);
244
245   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
246                                      OperandVector &Operands);
247   bool isThumb() const {
248     // FIXME: Can tablegen auto-generate this?
249     return getSTI().getFeatureBits()[ARM::ModeThumb];
250   }
251   bool isThumbOne() const {
252     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
253   }
254   bool isThumbTwo() const {
255     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
256   }
257   bool hasThumb() const {
258     return getSTI().getFeatureBits()[ARM::HasV4TOps];
259   }
260   bool hasV6Ops() const {
261     return getSTI().getFeatureBits()[ARM::HasV6Ops];
262   }
263   bool hasV6MOps() const {
264     return getSTI().getFeatureBits()[ARM::HasV6MOps];
265   }
266   bool hasV7Ops() const {
267     return getSTI().getFeatureBits()[ARM::HasV7Ops];
268   }
269   bool hasV8Ops() const {
270     return getSTI().getFeatureBits()[ARM::HasV8Ops];
271   }
272   bool hasARM() const {
273     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
274   }
275   bool hasDSP() const {
276     return getSTI().getFeatureBits()[ARM::FeatureDSP];
277   }
278   bool hasD16() const {
279     return getSTI().getFeatureBits()[ARM::FeatureD16];
280   }
281   bool hasV8_1aOps() const {
282     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
283   }
284
285   void SwitchMode() {
286     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
287     setAvailableFeatures(FB);
288   }
289   bool isMClass() const {
290     return getSTI().getFeatureBits()[ARM::FeatureMClass];
291   }
292
293   /// @name Auto-generated Match Functions
294   /// {
295
296 #define GET_ASSEMBLER_HEADER
297 #include "ARMGenAsmMatcher.inc"
298
299   /// }
300
301   OperandMatchResultTy parseITCondCode(OperandVector &);
302   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
303   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
304   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
305   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
306   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
307   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
308   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
309   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
310   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
311                                    int High);
312   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
313     return parsePKHImm(O, "lsl", 0, 31);
314   }
315   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
316     return parsePKHImm(O, "asr", 1, 32);
317   }
318   OperandMatchResultTy parseSetEndImm(OperandVector &);
319   OperandMatchResultTy parseShifterImm(OperandVector &);
320   OperandMatchResultTy parseRotImm(OperandVector &);
321   OperandMatchResultTy parseModImm(OperandVector &);
322   OperandMatchResultTy parseBitfield(OperandVector &);
323   OperandMatchResultTy parsePostIdxReg(OperandVector &);
324   OperandMatchResultTy parseAM3Offset(OperandVector &);
325   OperandMatchResultTy parseFPImm(OperandVector &);
326   OperandMatchResultTy parseVectorList(OperandVector &);
327   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
328                                        SMLoc &EndLoc);
329
330   // Asm Match Converter Methods
331   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
332   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
333
334   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
335   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
336   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
337   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
338
339 public:
340   enum ARMMatchResultTy {
341     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
342     Match_RequiresNotITBlock,
343     Match_RequiresV6,
344     Match_RequiresThumb2,
345     Match_RequiresV8,
346 #define GET_OPERAND_DIAGNOSTIC_TYPES
347 #include "ARMGenAsmMatcher.inc"
348
349   };
350
351   ARMAsmParser(MCSubtargetInfo &STI, MCAsmParser &Parser,
352                const MCInstrInfo &MII, const MCTargetOptions &Options)
353     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
354     MCAsmParserExtension::Initialize(Parser);
355
356     // Cache the MCRegisterInfo.
357     MRI = getContext().getRegisterInfo();
358
359     // Initialize the set of available features.
360     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
361
362     // Not in an ITBlock to start with.
363     ITState.CurPosition = ~0U;
364
365     NextSymbolIsThumb = false;
366   }
367
368   // Implementation of the MCTargetAsmParser interface:
369   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
370   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
371                         SMLoc NameLoc, OperandVector &Operands) override;
372   bool ParseDirective(AsmToken DirectiveID) override;
373
374   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
375                                       unsigned Kind) override;
376   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
377
378   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
379                                OperandVector &Operands, MCStreamer &Out,
380                                uint64_t &ErrorInfo,
381                                bool MatchingInlineAsm) override;
382   void onLabelParsed(MCSymbol *Symbol) override;
383 };
384 } // end anonymous namespace
385
386 namespace {
387
388 /// ARMOperand - Instances of this class represent a parsed ARM machine
389 /// operand.
390 class ARMOperand : public MCParsedAsmOperand {
391   enum KindTy {
392     k_CondCode,
393     k_CCOut,
394     k_ITCondMask,
395     k_CoprocNum,
396     k_CoprocReg,
397     k_CoprocOption,
398     k_Immediate,
399     k_MemBarrierOpt,
400     k_InstSyncBarrierOpt,
401     k_Memory,
402     k_PostIndexRegister,
403     k_MSRMask,
404     k_BankedReg,
405     k_ProcIFlags,
406     k_VectorIndex,
407     k_Register,
408     k_RegisterList,
409     k_DPRRegisterList,
410     k_SPRRegisterList,
411     k_VectorList,
412     k_VectorListAllLanes,
413     k_VectorListIndexed,
414     k_ShiftedRegister,
415     k_ShiftedImmediate,
416     k_ShifterImmediate,
417     k_RotateImmediate,
418     k_ModifiedImmediate,
419     k_BitfieldDescriptor,
420     k_Token
421   } Kind;
422
423   SMLoc StartLoc, EndLoc, AlignmentLoc;
424   SmallVector<unsigned, 8> Registers;
425
426   struct CCOp {
427     ARMCC::CondCodes Val;
428   };
429
430   struct CopOp {
431     unsigned Val;
432   };
433
434   struct CoprocOptionOp {
435     unsigned Val;
436   };
437
438   struct ITMaskOp {
439     unsigned Mask:4;
440   };
441
442   struct MBOptOp {
443     ARM_MB::MemBOpt Val;
444   };
445
446   struct ISBOptOp {
447     ARM_ISB::InstSyncBOpt Val;
448   };
449
450   struct IFlagsOp {
451     ARM_PROC::IFlags Val;
452   };
453
454   struct MMaskOp {
455     unsigned Val;
456   };
457
458   struct BankedRegOp {
459     unsigned Val;
460   };
461
462   struct TokOp {
463     const char *Data;
464     unsigned Length;
465   };
466
467   struct RegOp {
468     unsigned RegNum;
469   };
470
471   // A vector register list is a sequential list of 1 to 4 registers.
472   struct VectorListOp {
473     unsigned RegNum;
474     unsigned Count;
475     unsigned LaneIndex;
476     bool isDoubleSpaced;
477   };
478
479   struct VectorIndexOp {
480     unsigned Val;
481   };
482
483   struct ImmOp {
484     const MCExpr *Val;
485   };
486
487   /// Combined record for all forms of ARM address expressions.
488   struct MemoryOp {
489     unsigned BaseRegNum;
490     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
491     // was specified.
492     const MCConstantExpr *OffsetImm;  // Offset immediate value
493     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
494     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
495     unsigned ShiftImm;        // shift for OffsetReg.
496     unsigned Alignment;       // 0 = no alignment specified
497     // n = alignment in bytes (2, 4, 8, 16, or 32)
498     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
499   };
500
501   struct PostIdxRegOp {
502     unsigned RegNum;
503     bool isAdd;
504     ARM_AM::ShiftOpc ShiftTy;
505     unsigned ShiftImm;
506   };
507
508   struct ShifterImmOp {
509     bool isASR;
510     unsigned Imm;
511   };
512
513   struct RegShiftedRegOp {
514     ARM_AM::ShiftOpc ShiftTy;
515     unsigned SrcReg;
516     unsigned ShiftReg;
517     unsigned ShiftImm;
518   };
519
520   struct RegShiftedImmOp {
521     ARM_AM::ShiftOpc ShiftTy;
522     unsigned SrcReg;
523     unsigned ShiftImm;
524   };
525
526   struct RotImmOp {
527     unsigned Imm;
528   };
529
530   struct ModImmOp {
531     unsigned Bits;
532     unsigned Rot;
533   };
534
535   struct BitfieldOp {
536     unsigned LSB;
537     unsigned Width;
538   };
539
540   union {
541     struct CCOp CC;
542     struct CopOp Cop;
543     struct CoprocOptionOp CoprocOption;
544     struct MBOptOp MBOpt;
545     struct ISBOptOp ISBOpt;
546     struct ITMaskOp ITMask;
547     struct IFlagsOp IFlags;
548     struct MMaskOp MMask;
549     struct BankedRegOp BankedReg;
550     struct TokOp Tok;
551     struct RegOp Reg;
552     struct VectorListOp VectorList;
553     struct VectorIndexOp VectorIndex;
554     struct ImmOp Imm;
555     struct MemoryOp Memory;
556     struct PostIdxRegOp PostIdxReg;
557     struct ShifterImmOp ShifterImm;
558     struct RegShiftedRegOp RegShiftedReg;
559     struct RegShiftedImmOp RegShiftedImm;
560     struct RotImmOp RotImm;
561     struct ModImmOp ModImm;
562     struct BitfieldOp Bitfield;
563   };
564
565 public:
566   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
567
568   /// getStartLoc - Get the location of the first token of this operand.
569   SMLoc getStartLoc() const override { return StartLoc; }
570   /// getEndLoc - Get the location of the last token of this operand.
571   SMLoc getEndLoc() const override { return EndLoc; }
572   /// getLocRange - Get the range between the first and last token of this
573   /// operand.
574   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
575
576   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
577   SMLoc getAlignmentLoc() const {
578     assert(Kind == k_Memory && "Invalid access!");
579     return AlignmentLoc;
580   }
581
582   ARMCC::CondCodes getCondCode() const {
583     assert(Kind == k_CondCode && "Invalid access!");
584     return CC.Val;
585   }
586
587   unsigned getCoproc() const {
588     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
589     return Cop.Val;
590   }
591
592   StringRef getToken() const {
593     assert(Kind == k_Token && "Invalid access!");
594     return StringRef(Tok.Data, Tok.Length);
595   }
596
597   unsigned getReg() const override {
598     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
599     return Reg.RegNum;
600   }
601
602   const SmallVectorImpl<unsigned> &getRegList() const {
603     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
604             Kind == k_SPRRegisterList) && "Invalid access!");
605     return Registers;
606   }
607
608   const MCExpr *getImm() const {
609     assert(isImm() && "Invalid access!");
610     return Imm.Val;
611   }
612
613   unsigned getVectorIndex() const {
614     assert(Kind == k_VectorIndex && "Invalid access!");
615     return VectorIndex.Val;
616   }
617
618   ARM_MB::MemBOpt getMemBarrierOpt() const {
619     assert(Kind == k_MemBarrierOpt && "Invalid access!");
620     return MBOpt.Val;
621   }
622
623   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
624     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
625     return ISBOpt.Val;
626   }
627
628   ARM_PROC::IFlags getProcIFlags() const {
629     assert(Kind == k_ProcIFlags && "Invalid access!");
630     return IFlags.Val;
631   }
632
633   unsigned getMSRMask() const {
634     assert(Kind == k_MSRMask && "Invalid access!");
635     return MMask.Val;
636   }
637
638   unsigned getBankedReg() const {
639     assert(Kind == k_BankedReg && "Invalid access!");
640     return BankedReg.Val;
641   }
642
643   bool isCoprocNum() const { return Kind == k_CoprocNum; }
644   bool isCoprocReg() const { return Kind == k_CoprocReg; }
645   bool isCoprocOption() const { return Kind == k_CoprocOption; }
646   bool isCondCode() const { return Kind == k_CondCode; }
647   bool isCCOut() const { return Kind == k_CCOut; }
648   bool isITMask() const { return Kind == k_ITCondMask; }
649   bool isITCondCode() const { return Kind == k_CondCode; }
650   bool isImm() const override { return Kind == k_Immediate; }
651   // checks whether this operand is an unsigned offset which fits is a field
652   // of specified width and scaled by a specific number of bits
653   template<unsigned width, unsigned scale>
654   bool isUnsignedOffset() const {
655     if (!isImm()) return false;
656     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
657     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
658       int64_t Val = CE->getValue();
659       int64_t Align = 1LL << scale;
660       int64_t Max = Align * ((1LL << width) - 1);
661       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
662     }
663     return false;
664   }
665   // checks whether this operand is an signed offset which fits is a field
666   // of specified width and scaled by a specific number of bits
667   template<unsigned width, unsigned scale>
668   bool isSignedOffset() const {
669     if (!isImm()) return false;
670     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
671     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
672       int64_t Val = CE->getValue();
673       int64_t Align = 1LL << scale;
674       int64_t Max = Align * ((1LL << (width-1)) - 1);
675       int64_t Min = -Align * (1LL << (width-1));
676       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
677     }
678     return false;
679   }
680
681   // checks whether this operand is a memory operand computed as an offset
682   // applied to PC. the offset may have 8 bits of magnitude and is represented
683   // with two bits of shift. textually it may be either [pc, #imm], #imm or 
684   // relocable expression...
685   bool isThumbMemPC() const {
686     int64_t Val = 0;
687     if (isImm()) {
688       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
689       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
690       if (!CE) return false;
691       Val = CE->getValue();
692     }
693     else if (isMem()) {
694       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
695       if(Memory.BaseRegNum != ARM::PC) return false;
696       Val = Memory.OffsetImm->getValue();
697     }
698     else return false;
699     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
700   }
701   bool isFPImm() const {
702     if (!isImm()) return false;
703     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
704     if (!CE) return false;
705     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
706     return Val != -1;
707   }
708   bool isFBits16() const {
709     if (!isImm()) return false;
710     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
711     if (!CE) return false;
712     int64_t Value = CE->getValue();
713     return Value >= 0 && Value <= 16;
714   }
715   bool isFBits32() const {
716     if (!isImm()) return false;
717     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
718     if (!CE) return false;
719     int64_t Value = CE->getValue();
720     return Value >= 1 && Value <= 32;
721   }
722   bool isImm8s4() const {
723     if (!isImm()) return false;
724     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
725     if (!CE) return false;
726     int64_t Value = CE->getValue();
727     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
728   }
729   bool isImm0_1020s4() const {
730     if (!isImm()) return false;
731     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
732     if (!CE) return false;
733     int64_t Value = CE->getValue();
734     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
735   }
736   bool isImm0_508s4() const {
737     if (!isImm()) return false;
738     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
739     if (!CE) return false;
740     int64_t Value = CE->getValue();
741     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
742   }
743   bool isImm0_508s4Neg() const {
744     if (!isImm()) return false;
745     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
746     if (!CE) return false;
747     int64_t Value = -CE->getValue();
748     // explicitly exclude zero. we want that to use the normal 0_508 version.
749     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
750   }
751   bool isImm0_239() const {
752     if (!isImm()) return false;
753     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
754     if (!CE) return false;
755     int64_t Value = CE->getValue();
756     return Value >= 0 && Value < 240;
757   }
758   bool isImm0_255() const {
759     if (!isImm()) return false;
760     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
761     if (!CE) return false;
762     int64_t Value = CE->getValue();
763     return Value >= 0 && Value < 256;
764   }
765   bool isImm0_4095() const {
766     if (!isImm()) return false;
767     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
768     if (!CE) return false;
769     int64_t Value = CE->getValue();
770     return Value >= 0 && Value < 4096;
771   }
772   bool isImm0_4095Neg() const {
773     if (!isImm()) return false;
774     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
775     if (!CE) return false;
776     int64_t Value = -CE->getValue();
777     return Value > 0 && Value < 4096;
778   }
779   bool isImm0_1() const {
780     if (!isImm()) return false;
781     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
782     if (!CE) return false;
783     int64_t Value = CE->getValue();
784     return Value >= 0 && Value < 2;
785   }
786   bool isImm0_3() const {
787     if (!isImm()) return false;
788     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
789     if (!CE) return false;
790     int64_t Value = CE->getValue();
791     return Value >= 0 && Value < 4;
792   }
793   bool isImm0_7() const {
794     if (!isImm()) return false;
795     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
796     if (!CE) return false;
797     int64_t Value = CE->getValue();
798     return Value >= 0 && Value < 8;
799   }
800   bool isImm0_15() const {
801     if (!isImm()) return false;
802     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
803     if (!CE) return false;
804     int64_t Value = CE->getValue();
805     return Value >= 0 && Value < 16;
806   }
807   bool isImm0_31() const {
808     if (!isImm()) return false;
809     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
810     if (!CE) return false;
811     int64_t Value = CE->getValue();
812     return Value >= 0 && Value < 32;
813   }
814   bool isImm0_63() const {
815     if (!isImm()) return false;
816     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
817     if (!CE) return false;
818     int64_t Value = CE->getValue();
819     return Value >= 0 && Value < 64;
820   }
821   bool isImm8() const {
822     if (!isImm()) return false;
823     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
824     if (!CE) return false;
825     int64_t Value = CE->getValue();
826     return Value == 8;
827   }
828   bool isImm16() const {
829     if (!isImm()) return false;
830     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
831     if (!CE) return false;
832     int64_t Value = CE->getValue();
833     return Value == 16;
834   }
835   bool isImm32() const {
836     if (!isImm()) return false;
837     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
838     if (!CE) return false;
839     int64_t Value = CE->getValue();
840     return Value == 32;
841   }
842   bool isShrImm8() const {
843     if (!isImm()) return false;
844     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
845     if (!CE) return false;
846     int64_t Value = CE->getValue();
847     return Value > 0 && Value <= 8;
848   }
849   bool isShrImm16() const {
850     if (!isImm()) return false;
851     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
852     if (!CE) return false;
853     int64_t Value = CE->getValue();
854     return Value > 0 && Value <= 16;
855   }
856   bool isShrImm32() const {
857     if (!isImm()) return false;
858     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
859     if (!CE) return false;
860     int64_t Value = CE->getValue();
861     return Value > 0 && Value <= 32;
862   }
863   bool isShrImm64() const {
864     if (!isImm()) return false;
865     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
866     if (!CE) return false;
867     int64_t Value = CE->getValue();
868     return Value > 0 && Value <= 64;
869   }
870   bool isImm1_7() const {
871     if (!isImm()) return false;
872     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
873     if (!CE) return false;
874     int64_t Value = CE->getValue();
875     return Value > 0 && Value < 8;
876   }
877   bool isImm1_15() const {
878     if (!isImm()) return false;
879     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
880     if (!CE) return false;
881     int64_t Value = CE->getValue();
882     return Value > 0 && Value < 16;
883   }
884   bool isImm1_31() const {
885     if (!isImm()) return false;
886     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
887     if (!CE) return false;
888     int64_t Value = CE->getValue();
889     return Value > 0 && Value < 32;
890   }
891   bool isImm1_16() const {
892     if (!isImm()) return false;
893     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
894     if (!CE) return false;
895     int64_t Value = CE->getValue();
896     return Value > 0 && Value < 17;
897   }
898   bool isImm1_32() const {
899     if (!isImm()) return false;
900     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
901     if (!CE) return false;
902     int64_t Value = CE->getValue();
903     return Value > 0 && Value < 33;
904   }
905   bool isImm0_32() const {
906     if (!isImm()) return false;
907     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
908     if (!CE) return false;
909     int64_t Value = CE->getValue();
910     return Value >= 0 && Value < 33;
911   }
912   bool isImm0_65535() const {
913     if (!isImm()) return false;
914     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
915     if (!CE) return false;
916     int64_t Value = CE->getValue();
917     return Value >= 0 && Value < 65536;
918   }
919   bool isImm256_65535Expr() const {
920     if (!isImm()) return false;
921     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
922     // If it's not a constant expression, it'll generate a fixup and be
923     // handled later.
924     if (!CE) return true;
925     int64_t Value = CE->getValue();
926     return Value >= 256 && Value < 65536;
927   }
928   bool isImm0_65535Expr() const {
929     if (!isImm()) return false;
930     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
931     // If it's not a constant expression, it'll generate a fixup and be
932     // handled later.
933     if (!CE) return true;
934     int64_t Value = CE->getValue();
935     return Value >= 0 && Value < 65536;
936   }
937   bool isImm24bit() 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 <= 0xffffff;
943   }
944   bool isImmThumbSR() 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 < 33;
950   }
951   bool isPKHLSLImm() 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 isPKHASRImm() 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 <= 32;
964   }
965   bool isAdrLabel() const {
966     // If we have an immediate that's not a constant, treat it as a label
967     // reference needing a fixup.
968     if (isImm() && !isa<MCConstantExpr>(getImm()))
969       return true;
970
971     // If it is a constant, it must fit into a modified immediate encoding.
972     if (!isImm()) return false;
973     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
974     if (!CE) return false;
975     int64_t Value = CE->getValue();
976     return (ARM_AM::getSOImmVal(Value) != -1 ||
977             ARM_AM::getSOImmVal(-Value) != -1);
978   }
979   bool isT2SOImm() 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 ARM_AM::getT2SOImmVal(Value) != -1;
985   }
986   bool isT2SOImmNot() const {
987     if (!isImm()) return false;
988     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
989     if (!CE) return false;
990     int64_t Value = CE->getValue();
991     return ARM_AM::getT2SOImmVal(Value) == -1 &&
992       ARM_AM::getT2SOImmVal(~Value) != -1;
993   }
994   bool isT2SOImmNeg() const {
995     if (!isImm()) return false;
996     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
997     if (!CE) return false;
998     int64_t Value = CE->getValue();
999     // Only use this when not representable as a plain so_imm.
1000     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1001       ARM_AM::getT2SOImmVal(-Value) != -1;
1002   }
1003   bool isSetEndImm() const {
1004     if (!isImm()) return false;
1005     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1006     if (!CE) return false;
1007     int64_t Value = CE->getValue();
1008     return Value == 1 || Value == 0;
1009   }
1010   bool isReg() const override { return Kind == k_Register; }
1011   bool isRegList() const { return Kind == k_RegisterList; }
1012   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1013   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1014   bool isToken() const override { return Kind == k_Token; }
1015   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1016   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1017   bool isMem() const override { return Kind == k_Memory; }
1018   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1019   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1020   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1021   bool isRotImm() const { return Kind == k_RotateImmediate; }
1022   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1023   bool isModImmNot() const {
1024     if (!isImm()) return false;
1025     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1026     if (!CE) return false;
1027     int64_t Value = CE->getValue();
1028     return ARM_AM::getSOImmVal(~Value) != -1;
1029   }
1030   bool isModImmNeg() const {
1031     if (!isImm()) return false;
1032     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1033     if (!CE) return false;
1034     int64_t Value = CE->getValue();
1035     return ARM_AM::getSOImmVal(Value) == -1 &&
1036       ARM_AM::getSOImmVal(-Value) != -1;
1037   }
1038   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1039   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1040   bool isPostIdxReg() const {
1041     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1042   }
1043   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1044     if (!isMem())
1045       return false;
1046     // No offset of any kind.
1047     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1048      (alignOK || Memory.Alignment == Alignment);
1049   }
1050   bool isMemPCRelImm12() const {
1051     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1052       return false;
1053     // Base register must be PC.
1054     if (Memory.BaseRegNum != ARM::PC)
1055       return false;
1056     // Immediate offset in range [-4095, 4095].
1057     if (!Memory.OffsetImm) return true;
1058     int64_t Val = Memory.OffsetImm->getValue();
1059     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1060   }
1061   bool isAlignedMemory() const {
1062     return isMemNoOffset(true);
1063   }
1064   bool isAlignedMemoryNone() const {
1065     return isMemNoOffset(false, 0);
1066   }
1067   bool isDupAlignedMemoryNone() const {
1068     return isMemNoOffset(false, 0);
1069   }
1070   bool isAlignedMemory16() const {
1071     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1072       return true;
1073     return isMemNoOffset(false, 0);
1074   }
1075   bool isDupAlignedMemory16() const {
1076     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1077       return true;
1078     return isMemNoOffset(false, 0);
1079   }
1080   bool isAlignedMemory32() const {
1081     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1082       return true;
1083     return isMemNoOffset(false, 0);
1084   }
1085   bool isDupAlignedMemory32() const {
1086     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1087       return true;
1088     return isMemNoOffset(false, 0);
1089   }
1090   bool isAlignedMemory64() const {
1091     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1092       return true;
1093     return isMemNoOffset(false, 0);
1094   }
1095   bool isDupAlignedMemory64() const {
1096     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1097       return true;
1098     return isMemNoOffset(false, 0);
1099   }
1100   bool isAlignedMemory64or128() const {
1101     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1102       return true;
1103     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1104       return true;
1105     return isMemNoOffset(false, 0);
1106   }
1107   bool isDupAlignedMemory64or128() const {
1108     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1109       return true;
1110     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1111       return true;
1112     return isMemNoOffset(false, 0);
1113   }
1114   bool isAlignedMemory64or128or256() const {
1115     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1116       return true;
1117     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1118       return true;
1119     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1120       return true;
1121     return isMemNoOffset(false, 0);
1122   }
1123   bool isAddrMode2() const {
1124     if (!isMem() || Memory.Alignment != 0) return false;
1125     // Check for register offset.
1126     if (Memory.OffsetRegNum) return true;
1127     // Immediate offset in range [-4095, 4095].
1128     if (!Memory.OffsetImm) return true;
1129     int64_t Val = Memory.OffsetImm->getValue();
1130     return Val > -4096 && Val < 4096;
1131   }
1132   bool isAM2OffsetImm() const {
1133     if (!isImm()) return false;
1134     // Immediate offset in range [-4095, 4095].
1135     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1136     if (!CE) return false;
1137     int64_t Val = CE->getValue();
1138     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1139   }
1140   bool isAddrMode3() const {
1141     // If we have an immediate that's not a constant, treat it as a label
1142     // reference needing a fixup. If it is a constant, it's something else
1143     // and we reject it.
1144     if (isImm() && !isa<MCConstantExpr>(getImm()))
1145       return true;
1146     if (!isMem() || Memory.Alignment != 0) return false;
1147     // No shifts are legal for AM3.
1148     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1149     // Check for register offset.
1150     if (Memory.OffsetRegNum) return true;
1151     // Immediate offset in range [-255, 255].
1152     if (!Memory.OffsetImm) return true;
1153     int64_t Val = Memory.OffsetImm->getValue();
1154     // The #-0 offset is encoded as INT32_MIN, and we have to check 
1155     // for this too.
1156     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1157   }
1158   bool isAM3Offset() const {
1159     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1160       return false;
1161     if (Kind == k_PostIndexRegister)
1162       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1163     // Immediate offset in range [-255, 255].
1164     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1165     if (!CE) return false;
1166     int64_t Val = CE->getValue();
1167     // Special case, #-0 is INT32_MIN.
1168     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1169   }
1170   bool isAddrMode5() const {
1171     // If we have an immediate that's not a constant, treat it as a label
1172     // reference needing a fixup. If it is a constant, it's something else
1173     // and we reject it.
1174     if (isImm() && !isa<MCConstantExpr>(getImm()))
1175       return true;
1176     if (!isMem() || Memory.Alignment != 0) return false;
1177     // Check for register offset.
1178     if (Memory.OffsetRegNum) return false;
1179     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1180     if (!Memory.OffsetImm) return true;
1181     int64_t Val = Memory.OffsetImm->getValue();
1182     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1183       Val == INT32_MIN;
1184   }
1185   bool isMemTBB() const {
1186     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1187         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1188       return false;
1189     return true;
1190   }
1191   bool isMemTBH() const {
1192     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1193         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1194         Memory.Alignment != 0 )
1195       return false;
1196     return true;
1197   }
1198   bool isMemRegOffset() const {
1199     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1200       return false;
1201     return true;
1202   }
1203   bool isT2MemRegOffset() const {
1204     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1205         Memory.Alignment != 0)
1206       return false;
1207     // Only lsl #{0, 1, 2, 3} allowed.
1208     if (Memory.ShiftType == ARM_AM::no_shift)
1209       return true;
1210     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1211       return false;
1212     return true;
1213   }
1214   bool isMemThumbRR() const {
1215     // Thumb reg+reg addressing is simple. Just two registers, a base and
1216     // an offset. No shifts, negations or any other complicating factors.
1217     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1218         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1219       return false;
1220     return isARMLowRegister(Memory.BaseRegNum) &&
1221       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1222   }
1223   bool isMemThumbRIs4() const {
1224     if (!isMem() || Memory.OffsetRegNum != 0 ||
1225         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1226       return false;
1227     // Immediate offset, multiple of 4 in range [0, 124].
1228     if (!Memory.OffsetImm) return true;
1229     int64_t Val = Memory.OffsetImm->getValue();
1230     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1231   }
1232   bool isMemThumbRIs2() const {
1233     if (!isMem() || Memory.OffsetRegNum != 0 ||
1234         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1235       return false;
1236     // Immediate offset, multiple of 4 in range [0, 62].
1237     if (!Memory.OffsetImm) return true;
1238     int64_t Val = Memory.OffsetImm->getValue();
1239     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1240   }
1241   bool isMemThumbRIs1() const {
1242     if (!isMem() || Memory.OffsetRegNum != 0 ||
1243         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1244       return false;
1245     // Immediate offset in range [0, 31].
1246     if (!Memory.OffsetImm) return true;
1247     int64_t Val = Memory.OffsetImm->getValue();
1248     return Val >= 0 && Val <= 31;
1249   }
1250   bool isMemThumbSPI() const {
1251     if (!isMem() || Memory.OffsetRegNum != 0 ||
1252         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1253       return false;
1254     // Immediate offset, multiple of 4 in range [0, 1020].
1255     if (!Memory.OffsetImm) return true;
1256     int64_t Val = Memory.OffsetImm->getValue();
1257     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1258   }
1259   bool isMemImm8s4Offset() const {
1260     // If we have an immediate that's not a constant, treat it as a label
1261     // reference needing a fixup. If it is a constant, it's something else
1262     // and we reject it.
1263     if (isImm() && !isa<MCConstantExpr>(getImm()))
1264       return true;
1265     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1266       return false;
1267     // Immediate offset a multiple of 4 in range [-1020, 1020].
1268     if (!Memory.OffsetImm) return true;
1269     int64_t Val = Memory.OffsetImm->getValue();
1270     // Special case, #-0 is INT32_MIN.
1271     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1272   }
1273   bool isMemImm0_1020s4Offset() const {
1274     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1275       return false;
1276     // Immediate offset a multiple of 4 in range [0, 1020].
1277     if (!Memory.OffsetImm) return true;
1278     int64_t Val = Memory.OffsetImm->getValue();
1279     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1280   }
1281   bool isMemImm8Offset() const {
1282     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1283       return false;
1284     // Base reg of PC isn't allowed for these encodings.
1285     if (Memory.BaseRegNum == ARM::PC) return false;
1286     // Immediate offset in range [-255, 255].
1287     if (!Memory.OffsetImm) return true;
1288     int64_t Val = Memory.OffsetImm->getValue();
1289     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1290   }
1291   bool isMemPosImm8Offset() const {
1292     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1293       return false;
1294     // Immediate offset in range [0, 255].
1295     if (!Memory.OffsetImm) return true;
1296     int64_t Val = Memory.OffsetImm->getValue();
1297     return Val >= 0 && Val < 256;
1298   }
1299   bool isMemNegImm8Offset() const {
1300     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1301       return false;
1302     // Base reg of PC isn't allowed for these encodings.
1303     if (Memory.BaseRegNum == ARM::PC) return false;
1304     // Immediate offset in range [-255, -1].
1305     if (!Memory.OffsetImm) return false;
1306     int64_t Val = Memory.OffsetImm->getValue();
1307     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1308   }
1309   bool isMemUImm12Offset() const {
1310     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1311       return false;
1312     // Immediate offset in range [0, 4095].
1313     if (!Memory.OffsetImm) return true;
1314     int64_t Val = Memory.OffsetImm->getValue();
1315     return (Val >= 0 && Val < 4096);
1316   }
1317   bool isMemImm12Offset() const {
1318     // If we have an immediate that's not a constant, treat it as a label
1319     // reference needing a fixup. If it is a constant, it's something else
1320     // and we reject it.
1321     if (isImm() && !isa<MCConstantExpr>(getImm()))
1322       return true;
1323
1324     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1325       return false;
1326     // Immediate offset in range [-4095, 4095].
1327     if (!Memory.OffsetImm) return true;
1328     int64_t Val = Memory.OffsetImm->getValue();
1329     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1330   }
1331   bool isPostIdxImm8() const {
1332     if (!isImm()) return false;
1333     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1334     if (!CE) return false;
1335     int64_t Val = CE->getValue();
1336     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1337   }
1338   bool isPostIdxImm8s4() const {
1339     if (!isImm()) return false;
1340     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1341     if (!CE) return false;
1342     int64_t Val = CE->getValue();
1343     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1344       (Val == INT32_MIN);
1345   }
1346
1347   bool isMSRMask() const { return Kind == k_MSRMask; }
1348   bool isBankedReg() const { return Kind == k_BankedReg; }
1349   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1350
1351   // NEON operands.
1352   bool isSingleSpacedVectorList() const {
1353     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1354   }
1355   bool isDoubleSpacedVectorList() const {
1356     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1357   }
1358   bool isVecListOneD() const {
1359     if (!isSingleSpacedVectorList()) return false;
1360     return VectorList.Count == 1;
1361   }
1362
1363   bool isVecListDPair() const {
1364     if (!isSingleSpacedVectorList()) return false;
1365     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1366               .contains(VectorList.RegNum));
1367   }
1368
1369   bool isVecListThreeD() const {
1370     if (!isSingleSpacedVectorList()) return false;
1371     return VectorList.Count == 3;
1372   }
1373
1374   bool isVecListFourD() const {
1375     if (!isSingleSpacedVectorList()) return false;
1376     return VectorList.Count == 4;
1377   }
1378
1379   bool isVecListDPairSpaced() const {
1380     if (Kind != k_VectorList) return false;
1381     if (isSingleSpacedVectorList()) return false;
1382     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1383               .contains(VectorList.RegNum));
1384   }
1385
1386   bool isVecListThreeQ() const {
1387     if (!isDoubleSpacedVectorList()) return false;
1388     return VectorList.Count == 3;
1389   }
1390
1391   bool isVecListFourQ() const {
1392     if (!isDoubleSpacedVectorList()) return false;
1393     return VectorList.Count == 4;
1394   }
1395
1396   bool isSingleSpacedVectorAllLanes() const {
1397     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1398   }
1399   bool isDoubleSpacedVectorAllLanes() const {
1400     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1401   }
1402   bool isVecListOneDAllLanes() const {
1403     if (!isSingleSpacedVectorAllLanes()) return false;
1404     return VectorList.Count == 1;
1405   }
1406
1407   bool isVecListDPairAllLanes() const {
1408     if (!isSingleSpacedVectorAllLanes()) return false;
1409     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1410               .contains(VectorList.RegNum));
1411   }
1412
1413   bool isVecListDPairSpacedAllLanes() const {
1414     if (!isDoubleSpacedVectorAllLanes()) return false;
1415     return VectorList.Count == 2;
1416   }
1417
1418   bool isVecListThreeDAllLanes() const {
1419     if (!isSingleSpacedVectorAllLanes()) return false;
1420     return VectorList.Count == 3;
1421   }
1422
1423   bool isVecListThreeQAllLanes() const {
1424     if (!isDoubleSpacedVectorAllLanes()) return false;
1425     return VectorList.Count == 3;
1426   }
1427
1428   bool isVecListFourDAllLanes() const {
1429     if (!isSingleSpacedVectorAllLanes()) return false;
1430     return VectorList.Count == 4;
1431   }
1432
1433   bool isVecListFourQAllLanes() const {
1434     if (!isDoubleSpacedVectorAllLanes()) return false;
1435     return VectorList.Count == 4;
1436   }
1437
1438   bool isSingleSpacedVectorIndexed() const {
1439     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1440   }
1441   bool isDoubleSpacedVectorIndexed() const {
1442     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1443   }
1444   bool isVecListOneDByteIndexed() const {
1445     if (!isSingleSpacedVectorIndexed()) return false;
1446     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1447   }
1448
1449   bool isVecListOneDHWordIndexed() const {
1450     if (!isSingleSpacedVectorIndexed()) return false;
1451     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1452   }
1453
1454   bool isVecListOneDWordIndexed() const {
1455     if (!isSingleSpacedVectorIndexed()) return false;
1456     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1457   }
1458
1459   bool isVecListTwoDByteIndexed() const {
1460     if (!isSingleSpacedVectorIndexed()) return false;
1461     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1462   }
1463
1464   bool isVecListTwoDHWordIndexed() const {
1465     if (!isSingleSpacedVectorIndexed()) return false;
1466     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1467   }
1468
1469   bool isVecListTwoQWordIndexed() const {
1470     if (!isDoubleSpacedVectorIndexed()) return false;
1471     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1472   }
1473
1474   bool isVecListTwoQHWordIndexed() const {
1475     if (!isDoubleSpacedVectorIndexed()) return false;
1476     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1477   }
1478
1479   bool isVecListTwoDWordIndexed() const {
1480     if (!isSingleSpacedVectorIndexed()) return false;
1481     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1482   }
1483
1484   bool isVecListThreeDByteIndexed() const {
1485     if (!isSingleSpacedVectorIndexed()) return false;
1486     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1487   }
1488
1489   bool isVecListThreeDHWordIndexed() const {
1490     if (!isSingleSpacedVectorIndexed()) return false;
1491     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1492   }
1493
1494   bool isVecListThreeQWordIndexed() const {
1495     if (!isDoubleSpacedVectorIndexed()) return false;
1496     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1497   }
1498
1499   bool isVecListThreeQHWordIndexed() const {
1500     if (!isDoubleSpacedVectorIndexed()) return false;
1501     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1502   }
1503
1504   bool isVecListThreeDWordIndexed() const {
1505     if (!isSingleSpacedVectorIndexed()) return false;
1506     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1507   }
1508
1509   bool isVecListFourDByteIndexed() const {
1510     if (!isSingleSpacedVectorIndexed()) return false;
1511     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1512   }
1513
1514   bool isVecListFourDHWordIndexed() const {
1515     if (!isSingleSpacedVectorIndexed()) return false;
1516     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1517   }
1518
1519   bool isVecListFourQWordIndexed() const {
1520     if (!isDoubleSpacedVectorIndexed()) return false;
1521     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1522   }
1523
1524   bool isVecListFourQHWordIndexed() const {
1525     if (!isDoubleSpacedVectorIndexed()) return false;
1526     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1527   }
1528
1529   bool isVecListFourDWordIndexed() const {
1530     if (!isSingleSpacedVectorIndexed()) return false;
1531     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1532   }
1533
1534   bool isVectorIndex8() const {
1535     if (Kind != k_VectorIndex) return false;
1536     return VectorIndex.Val < 8;
1537   }
1538   bool isVectorIndex16() const {
1539     if (Kind != k_VectorIndex) return false;
1540     return VectorIndex.Val < 4;
1541   }
1542   bool isVectorIndex32() const {
1543     if (Kind != k_VectorIndex) return false;
1544     return VectorIndex.Val < 2;
1545   }
1546
1547   bool isNEONi8splat() const {
1548     if (!isImm()) return false;
1549     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1550     // Must be a constant.
1551     if (!CE) return false;
1552     int64_t Value = CE->getValue();
1553     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1554     // value.
1555     return Value >= 0 && Value < 256;
1556   }
1557
1558   bool isNEONi16splat() const {
1559     if (isNEONByteReplicate(2))
1560       return false; // Leave that for bytes replication and forbid by default.
1561     if (!isImm())
1562       return false;
1563     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1564     // Must be a constant.
1565     if (!CE) return false;
1566     unsigned Value = CE->getValue();
1567     return ARM_AM::isNEONi16splat(Value);
1568   }
1569
1570   bool isNEONi16splatNot() const {
1571     if (!isImm())
1572       return false;
1573     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1574     // Must be a constant.
1575     if (!CE) return false;
1576     unsigned Value = CE->getValue();
1577     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1578   }
1579
1580   bool isNEONi32splat() const {
1581     if (isNEONByteReplicate(4))
1582       return false; // Leave that for bytes replication and forbid by default.
1583     if (!isImm())
1584       return false;
1585     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1586     // Must be a constant.
1587     if (!CE) return false;
1588     unsigned Value = CE->getValue();
1589     return ARM_AM::isNEONi32splat(Value);
1590   }
1591
1592   bool isNEONi32splatNot() const {
1593     if (!isImm())
1594       return false;
1595     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1596     // Must be a constant.
1597     if (!CE) return false;
1598     unsigned Value = CE->getValue();
1599     return ARM_AM::isNEONi32splat(~Value);
1600   }
1601
1602   bool isNEONByteReplicate(unsigned NumBytes) const {
1603     if (!isImm())
1604       return false;
1605     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1606     // Must be a constant.
1607     if (!CE)
1608       return false;
1609     int64_t Value = CE->getValue();
1610     if (!Value)
1611       return false; // Don't bother with zero.
1612
1613     unsigned char B = Value & 0xff;
1614     for (unsigned i = 1; i < NumBytes; ++i) {
1615       Value >>= 8;
1616       if ((Value & 0xff) != B)
1617         return false;
1618     }
1619     return true;
1620   }
1621   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1622   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1623   bool isNEONi32vmov() const {
1624     if (isNEONByteReplicate(4))
1625       return false; // Let it to be classified as byte-replicate case.
1626     if (!isImm())
1627       return false;
1628     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1629     // Must be a constant.
1630     if (!CE)
1631       return false;
1632     int64_t Value = CE->getValue();
1633     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1634     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1635     // FIXME: This is probably wrong and a copy and paste from previous example
1636     return (Value >= 0 && Value < 256) ||
1637       (Value >= 0x0100 && Value <= 0xff00) ||
1638       (Value >= 0x010000 && Value <= 0xff0000) ||
1639       (Value >= 0x01000000 && Value <= 0xff000000) ||
1640       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1641       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1642   }
1643   bool isNEONi32vmovNeg() const {
1644     if (!isImm()) return false;
1645     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1646     // Must be a constant.
1647     if (!CE) return false;
1648     int64_t Value = ~CE->getValue();
1649     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1650     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1651     // FIXME: This is probably wrong and a copy and paste from previous example
1652     return (Value >= 0 && Value < 256) ||
1653       (Value >= 0x0100 && Value <= 0xff00) ||
1654       (Value >= 0x010000 && Value <= 0xff0000) ||
1655       (Value >= 0x01000000 && Value <= 0xff000000) ||
1656       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1657       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1658   }
1659
1660   bool isNEONi64splat() const {
1661     if (!isImm()) return false;
1662     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1663     // Must be a constant.
1664     if (!CE) return false;
1665     uint64_t Value = CE->getValue();
1666     // i64 value with each byte being either 0 or 0xff.
1667     for (unsigned i = 0; i < 8; ++i)
1668       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1669     return true;
1670   }
1671
1672   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1673     // Add as immediates when possible.  Null MCExpr = 0.
1674     if (!Expr)
1675       Inst.addOperand(MCOperand::createImm(0));
1676     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1677       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1678     else
1679       Inst.addOperand(MCOperand::createExpr(Expr));
1680   }
1681
1682   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1683     assert(N == 2 && "Invalid number of operands!");
1684     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1685     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1686     Inst.addOperand(MCOperand::createReg(RegNum));
1687   }
1688
1689   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1690     assert(N == 1 && "Invalid number of operands!");
1691     Inst.addOperand(MCOperand::createImm(getCoproc()));
1692   }
1693
1694   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1695     assert(N == 1 && "Invalid number of operands!");
1696     Inst.addOperand(MCOperand::createImm(getCoproc()));
1697   }
1698
1699   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1700     assert(N == 1 && "Invalid number of operands!");
1701     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1702   }
1703
1704   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1705     assert(N == 1 && "Invalid number of operands!");
1706     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1707   }
1708
1709   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1710     assert(N == 1 && "Invalid number of operands!");
1711     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1712   }
1713
1714   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1715     assert(N == 1 && "Invalid number of operands!");
1716     Inst.addOperand(MCOperand::createReg(getReg()));
1717   }
1718
1719   void addRegOperands(MCInst &Inst, unsigned N) const {
1720     assert(N == 1 && "Invalid number of operands!");
1721     Inst.addOperand(MCOperand::createReg(getReg()));
1722   }
1723
1724   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1725     assert(N == 3 && "Invalid number of operands!");
1726     assert(isRegShiftedReg() &&
1727            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1728     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1729     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1730     Inst.addOperand(MCOperand::createImm(
1731       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1732   }
1733
1734   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1735     assert(N == 2 && "Invalid number of operands!");
1736     assert(isRegShiftedImm() &&
1737            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1738     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1739     // Shift of #32 is encoded as 0 where permitted
1740     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1741     Inst.addOperand(MCOperand::createImm(
1742       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1743   }
1744
1745   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1746     assert(N == 1 && "Invalid number of operands!");
1747     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1748                                          ShifterImm.Imm));
1749   }
1750
1751   void addRegListOperands(MCInst &Inst, unsigned N) const {
1752     assert(N == 1 && "Invalid number of operands!");
1753     const SmallVectorImpl<unsigned> &RegList = getRegList();
1754     for (SmallVectorImpl<unsigned>::const_iterator
1755            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1756       Inst.addOperand(MCOperand::createReg(*I));
1757   }
1758
1759   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1760     addRegListOperands(Inst, N);
1761   }
1762
1763   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1764     addRegListOperands(Inst, N);
1765   }
1766
1767   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1768     assert(N == 1 && "Invalid number of operands!");
1769     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1770     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1771   }
1772
1773   void addModImmOperands(MCInst &Inst, unsigned N) const {
1774     assert(N == 1 && "Invalid number of operands!");
1775
1776     // Support for fixups (MCFixup)
1777     if (isImm())
1778       return addImmOperands(Inst, N);
1779
1780     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
1781   }
1782
1783   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1784     assert(N == 1 && "Invalid number of operands!");
1785     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1786     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1787     Inst.addOperand(MCOperand::createImm(Enc));
1788   }
1789
1790   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1791     assert(N == 1 && "Invalid number of operands!");
1792     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1793     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1794     Inst.addOperand(MCOperand::createImm(Enc));
1795   }
1796
1797   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1798     assert(N == 1 && "Invalid number of operands!");
1799     // Munge the lsb/width into a bitfield mask.
1800     unsigned lsb = Bitfield.LSB;
1801     unsigned width = Bitfield.Width;
1802     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1803     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1804                       (32 - (lsb + width)));
1805     Inst.addOperand(MCOperand::createImm(Mask));
1806   }
1807
1808   void addImmOperands(MCInst &Inst, unsigned N) const {
1809     assert(N == 1 && "Invalid number of operands!");
1810     addExpr(Inst, getImm());
1811   }
1812
1813   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1814     assert(N == 1 && "Invalid number of operands!");
1815     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1816     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
1817   }
1818
1819   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1820     assert(N == 1 && "Invalid number of operands!");
1821     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1822     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
1823   }
1824
1825   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1826     assert(N == 1 && "Invalid number of operands!");
1827     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1828     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1829     Inst.addOperand(MCOperand::createImm(Val));
1830   }
1831
1832   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1833     assert(N == 1 && "Invalid number of operands!");
1834     // FIXME: We really want to scale the value here, but the LDRD/STRD
1835     // instruction don't encode operands that way yet.
1836     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1837     Inst.addOperand(MCOperand::createImm(CE->getValue()));
1838   }
1839
1840   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1841     assert(N == 1 && "Invalid number of operands!");
1842     // The immediate is scaled by four in the encoding and is stored
1843     // in the MCInst as such. Lop off the low two bits here.
1844     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1845     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1846   }
1847
1848   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1849     assert(N == 1 && "Invalid number of operands!");
1850     // The immediate is scaled by four in the encoding and is stored
1851     // in the MCInst as such. Lop off the low two bits here.
1852     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1853     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
1854   }
1855
1856   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1857     assert(N == 1 && "Invalid number of operands!");
1858     // The immediate is scaled by four in the encoding and is stored
1859     // in the MCInst as such. Lop off the low two bits here.
1860     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1861     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1862   }
1863
1864   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1865     assert(N == 1 && "Invalid number of operands!");
1866     // The constant encodes as the immediate-1, and we store in the instruction
1867     // the bits as encoded, so subtract off one here.
1868     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1869     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1870   }
1871
1872   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1873     assert(N == 1 && "Invalid number of operands!");
1874     // The constant encodes as the immediate-1, and we store in the instruction
1875     // the bits as encoded, so subtract off one here.
1876     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1877     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1878   }
1879
1880   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1881     assert(N == 1 && "Invalid number of operands!");
1882     // The constant encodes as the immediate, except for 32, which encodes as
1883     // zero.
1884     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1885     unsigned Imm = CE->getValue();
1886     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
1887   }
1888
1889   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1890     assert(N == 1 && "Invalid number of operands!");
1891     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1892     // the instruction as well.
1893     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1894     int Val = CE->getValue();
1895     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
1896   }
1897
1898   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
1899     assert(N == 1 && "Invalid number of operands!");
1900     // The operand is actually a t2_so_imm, but we have its bitwise
1901     // negation in the assembly source, so twiddle it here.
1902     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1903     Inst.addOperand(MCOperand::createImm(~CE->getValue()));
1904   }
1905
1906   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
1907     assert(N == 1 && "Invalid number of operands!");
1908     // The operand is actually a t2_so_imm, but we have its
1909     // negation in the assembly source, so twiddle it here.
1910     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1911     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1912   }
1913
1914   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
1915     assert(N == 1 && "Invalid number of operands!");
1916     // The operand is actually an imm0_4095, but we have its
1917     // negation in the assembly source, so twiddle it here.
1918     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1919     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1920   }
1921
1922   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
1923     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
1924       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
1925       return;
1926     }
1927
1928     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1929     assert(SR && "Unknown value type!");
1930     Inst.addOperand(MCOperand::createExpr(SR));
1931   }
1932
1933   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
1934     assert(N == 1 && "Invalid number of operands!");
1935     if (isImm()) {
1936       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1937       if (CE) {
1938         Inst.addOperand(MCOperand::createImm(CE->getValue()));
1939         return;
1940       }
1941
1942       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1943       assert(SR && "Unknown value type!");
1944       Inst.addOperand(MCOperand::createExpr(SR));
1945       return;
1946     }
1947
1948     assert(isMem()  && "Unknown value type!");
1949     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
1950     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
1951   }
1952
1953   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
1954     assert(N == 1 && "Invalid number of operands!");
1955     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
1956   }
1957
1958   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
1959     assert(N == 1 && "Invalid number of operands!");
1960     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
1961   }
1962
1963   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
1964     assert(N == 1 && "Invalid number of operands!");
1965     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
1966   }
1967
1968   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
1969     assert(N == 1 && "Invalid number of operands!");
1970     int32_t Imm = Memory.OffsetImm->getValue();
1971     Inst.addOperand(MCOperand::createImm(Imm));
1972   }
1973
1974   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
1975     assert(N == 1 && "Invalid number of operands!");
1976     assert(isImm() && "Not an immediate!");
1977
1978     // If we have an immediate that's not a constant, treat it as a label
1979     // reference needing a fixup. 
1980     if (!isa<MCConstantExpr>(getImm())) {
1981       Inst.addOperand(MCOperand::createExpr(getImm()));
1982       return;
1983     }
1984
1985     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1986     int Val = CE->getValue();
1987     Inst.addOperand(MCOperand::createImm(Val));
1988   }
1989
1990   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
1991     assert(N == 2 && "Invalid number of operands!");
1992     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
1993     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
1994   }
1995
1996   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
1997     addAlignedMemoryOperands(Inst, N);
1998   }
1999
2000   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2001     addAlignedMemoryOperands(Inst, N);
2002   }
2003
2004   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2005     addAlignedMemoryOperands(Inst, N);
2006   }
2007
2008   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2009     addAlignedMemoryOperands(Inst, N);
2010   }
2011
2012   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2013     addAlignedMemoryOperands(Inst, N);
2014   }
2015
2016   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2017     addAlignedMemoryOperands(Inst, N);
2018   }
2019
2020   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2021     addAlignedMemoryOperands(Inst, N);
2022   }
2023
2024   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2025     addAlignedMemoryOperands(Inst, N);
2026   }
2027
2028   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2029     addAlignedMemoryOperands(Inst, N);
2030   }
2031
2032   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2033     addAlignedMemoryOperands(Inst, N);
2034   }
2035
2036   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2037     addAlignedMemoryOperands(Inst, N);
2038   }
2039
2040   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2041     assert(N == 3 && "Invalid number of operands!");
2042     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2043     if (!Memory.OffsetRegNum) {
2044       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2045       // Special case for #-0
2046       if (Val == INT32_MIN) Val = 0;
2047       if (Val < 0) Val = -Val;
2048       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2049     } else {
2050       // For register offset, we encode the shift type and negation flag
2051       // here.
2052       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2053                               Memory.ShiftImm, Memory.ShiftType);
2054     }
2055     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2056     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2057     Inst.addOperand(MCOperand::createImm(Val));
2058   }
2059
2060   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2061     assert(N == 2 && "Invalid number of operands!");
2062     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2063     assert(CE && "non-constant AM2OffsetImm operand!");
2064     int32_t Val = CE->getValue();
2065     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2066     // Special case for #-0
2067     if (Val == INT32_MIN) Val = 0;
2068     if (Val < 0) Val = -Val;
2069     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2070     Inst.addOperand(MCOperand::createReg(0));
2071     Inst.addOperand(MCOperand::createImm(Val));
2072   }
2073
2074   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2075     assert(N == 3 && "Invalid number of operands!");
2076     // If we have an immediate that's not a constant, treat it as a label
2077     // reference needing a fixup. If it is a constant, it's something else
2078     // and we reject it.
2079     if (isImm()) {
2080       Inst.addOperand(MCOperand::createExpr(getImm()));
2081       Inst.addOperand(MCOperand::createReg(0));
2082       Inst.addOperand(MCOperand::createImm(0));
2083       return;
2084     }
2085
2086     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2087     if (!Memory.OffsetRegNum) {
2088       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2089       // Special case for #-0
2090       if (Val == INT32_MIN) Val = 0;
2091       if (Val < 0) Val = -Val;
2092       Val = ARM_AM::getAM3Opc(AddSub, Val);
2093     } else {
2094       // For register offset, we encode the shift type and negation flag
2095       // here.
2096       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2097     }
2098     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2099     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2100     Inst.addOperand(MCOperand::createImm(Val));
2101   }
2102
2103   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2104     assert(N == 2 && "Invalid number of operands!");
2105     if (Kind == k_PostIndexRegister) {
2106       int32_t Val =
2107         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2108       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2109       Inst.addOperand(MCOperand::createImm(Val));
2110       return;
2111     }
2112
2113     // Constant offset.
2114     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2115     int32_t Val = CE->getValue();
2116     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2117     // Special case for #-0
2118     if (Val == INT32_MIN) Val = 0;
2119     if (Val < 0) Val = -Val;
2120     Val = ARM_AM::getAM3Opc(AddSub, Val);
2121     Inst.addOperand(MCOperand::createReg(0));
2122     Inst.addOperand(MCOperand::createImm(Val));
2123   }
2124
2125   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2126     assert(N == 2 && "Invalid number of operands!");
2127     // If we have an immediate that's not a constant, treat it as a label
2128     // reference needing a fixup. If it is a constant, it's something else
2129     // and we reject it.
2130     if (isImm()) {
2131       Inst.addOperand(MCOperand::createExpr(getImm()));
2132       Inst.addOperand(MCOperand::createImm(0));
2133       return;
2134     }
2135
2136     // The lower two bits are always zero and as such are not encoded.
2137     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2138     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2139     // Special case for #-0
2140     if (Val == INT32_MIN) Val = 0;
2141     if (Val < 0) Val = -Val;
2142     Val = ARM_AM::getAM5Opc(AddSub, Val);
2143     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2144     Inst.addOperand(MCOperand::createImm(Val));
2145   }
2146
2147   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2148     assert(N == 2 && "Invalid number of operands!");
2149     // If we have an immediate that's not a constant, treat it as a label
2150     // reference needing a fixup. If it is a constant, it's something else
2151     // and we reject it.
2152     if (isImm()) {
2153       Inst.addOperand(MCOperand::createExpr(getImm()));
2154       Inst.addOperand(MCOperand::createImm(0));
2155       return;
2156     }
2157
2158     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2159     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2160     Inst.addOperand(MCOperand::createImm(Val));
2161   }
2162
2163   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2164     assert(N == 2 && "Invalid number of operands!");
2165     // The lower two bits are always zero and as such are not encoded.
2166     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2167     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2168     Inst.addOperand(MCOperand::createImm(Val));
2169   }
2170
2171   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2172     assert(N == 2 && "Invalid number of operands!");
2173     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2174     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2175     Inst.addOperand(MCOperand::createImm(Val));
2176   }
2177
2178   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2179     addMemImm8OffsetOperands(Inst, N);
2180   }
2181
2182   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2183     addMemImm8OffsetOperands(Inst, N);
2184   }
2185
2186   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2187     assert(N == 2 && "Invalid number of operands!");
2188     // If this is an immediate, it's a label reference.
2189     if (isImm()) {
2190       addExpr(Inst, getImm());
2191       Inst.addOperand(MCOperand::createImm(0));
2192       return;
2193     }
2194
2195     // Otherwise, it's a normal memory reg+offset.
2196     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2197     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2198     Inst.addOperand(MCOperand::createImm(Val));
2199   }
2200
2201   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2202     assert(N == 2 && "Invalid number of operands!");
2203     // If this is an immediate, it's a label reference.
2204     if (isImm()) {
2205       addExpr(Inst, getImm());
2206       Inst.addOperand(MCOperand::createImm(0));
2207       return;
2208     }
2209
2210     // Otherwise, it's a normal memory reg+offset.
2211     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2212     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2213     Inst.addOperand(MCOperand::createImm(Val));
2214   }
2215
2216   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2217     assert(N == 2 && "Invalid number of operands!");
2218     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2219     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2220   }
2221
2222   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2223     assert(N == 2 && "Invalid number of operands!");
2224     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2225     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2226   }
2227
2228   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2229     assert(N == 3 && "Invalid number of operands!");
2230     unsigned Val =
2231       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2232                         Memory.ShiftImm, Memory.ShiftType);
2233     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2234     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2235     Inst.addOperand(MCOperand::createImm(Val));
2236   }
2237
2238   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2239     assert(N == 3 && "Invalid number of operands!");
2240     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2241     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2242     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2243   }
2244
2245   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2246     assert(N == 2 && "Invalid number of operands!");
2247     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2248     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2249   }
2250
2251   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2252     assert(N == 2 && "Invalid number of operands!");
2253     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2254     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2255     Inst.addOperand(MCOperand::createImm(Val));
2256   }
2257
2258   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2259     assert(N == 2 && "Invalid number of operands!");
2260     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2261     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2262     Inst.addOperand(MCOperand::createImm(Val));
2263   }
2264
2265   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2266     assert(N == 2 && "Invalid number of operands!");
2267     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2268     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2269     Inst.addOperand(MCOperand::createImm(Val));
2270   }
2271
2272   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2273     assert(N == 2 && "Invalid number of operands!");
2274     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2275     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2276     Inst.addOperand(MCOperand::createImm(Val));
2277   }
2278
2279   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2280     assert(N == 1 && "Invalid number of operands!");
2281     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2282     assert(CE && "non-constant post-idx-imm8 operand!");
2283     int Imm = CE->getValue();
2284     bool isAdd = Imm >= 0;
2285     if (Imm == INT32_MIN) Imm = 0;
2286     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2287     Inst.addOperand(MCOperand::createImm(Imm));
2288   }
2289
2290   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2291     assert(N == 1 && "Invalid number of operands!");
2292     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2293     assert(CE && "non-constant post-idx-imm8s4 operand!");
2294     int Imm = CE->getValue();
2295     bool isAdd = Imm >= 0;
2296     if (Imm == INT32_MIN) Imm = 0;
2297     // Immediate is scaled by 4.
2298     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2299     Inst.addOperand(MCOperand::createImm(Imm));
2300   }
2301
2302   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2303     assert(N == 2 && "Invalid number of operands!");
2304     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2305     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2306   }
2307
2308   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2309     assert(N == 2 && "Invalid number of operands!");
2310     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2311     // The sign, shift type, and shift amount are encoded in a single operand
2312     // using the AM2 encoding helpers.
2313     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2314     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2315                                      PostIdxReg.ShiftTy);
2316     Inst.addOperand(MCOperand::createImm(Imm));
2317   }
2318
2319   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2320     assert(N == 1 && "Invalid number of operands!");
2321     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2322   }
2323
2324   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2325     assert(N == 1 && "Invalid number of operands!");
2326     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2327   }
2328
2329   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2330     assert(N == 1 && "Invalid number of operands!");
2331     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2332   }
2333
2334   void addVecListOperands(MCInst &Inst, unsigned N) const {
2335     assert(N == 1 && "Invalid number of operands!");
2336     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2337   }
2338
2339   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2340     assert(N == 2 && "Invalid number of operands!");
2341     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2342     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2343   }
2344
2345   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2346     assert(N == 1 && "Invalid number of operands!");
2347     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2348   }
2349
2350   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2351     assert(N == 1 && "Invalid number of operands!");
2352     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2353   }
2354
2355   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2356     assert(N == 1 && "Invalid number of operands!");
2357     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2358   }
2359
2360   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2361     assert(N == 1 && "Invalid number of operands!");
2362     // The immediate encodes the type of constant as well as the value.
2363     // Mask in that this is an i8 splat.
2364     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2365     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2366   }
2367
2368   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2369     assert(N == 1 && "Invalid number of operands!");
2370     // The immediate encodes the type of constant as well as the value.
2371     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2372     unsigned Value = CE->getValue();
2373     Value = ARM_AM::encodeNEONi16splat(Value);
2374     Inst.addOperand(MCOperand::createImm(Value));
2375   }
2376
2377   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2378     assert(N == 1 && "Invalid number of operands!");
2379     // The immediate encodes the type of constant as well as the value.
2380     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2381     unsigned Value = CE->getValue();
2382     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2383     Inst.addOperand(MCOperand::createImm(Value));
2384   }
2385
2386   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2387     assert(N == 1 && "Invalid number of operands!");
2388     // The immediate encodes the type of constant as well as the value.
2389     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2390     unsigned Value = CE->getValue();
2391     Value = ARM_AM::encodeNEONi32splat(Value);
2392     Inst.addOperand(MCOperand::createImm(Value));
2393   }
2394
2395   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2396     assert(N == 1 && "Invalid number of operands!");
2397     // The immediate encodes the type of constant as well as the value.
2398     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2399     unsigned Value = CE->getValue();
2400     Value = ARM_AM::encodeNEONi32splat(~Value);
2401     Inst.addOperand(MCOperand::createImm(Value));
2402   }
2403
2404   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2405     assert(N == 1 && "Invalid number of operands!");
2406     // The immediate encodes the type of constant as well as the value.
2407     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2408     unsigned Value = CE->getValue();
2409     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2410             Inst.getOpcode() == ARM::VMOVv16i8) &&
2411            "All vmvn instructions that wants to replicate non-zero byte "
2412            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2413     unsigned B = ((~Value) & 0xff);
2414     B |= 0xe00; // cmode = 0b1110
2415     Inst.addOperand(MCOperand::createImm(B));
2416   }
2417   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2418     assert(N == 1 && "Invalid number of operands!");
2419     // The immediate encodes the type of constant as well as the value.
2420     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2421     unsigned Value = CE->getValue();
2422     if (Value >= 256 && Value <= 0xffff)
2423       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2424     else if (Value > 0xffff && Value <= 0xffffff)
2425       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2426     else if (Value > 0xffffff)
2427       Value = (Value >> 24) | 0x600;
2428     Inst.addOperand(MCOperand::createImm(Value));
2429   }
2430
2431   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2432     assert(N == 1 && "Invalid number of operands!");
2433     // The immediate encodes the type of constant as well as the value.
2434     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2435     unsigned Value = CE->getValue();
2436     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2437             Inst.getOpcode() == ARM::VMOVv16i8) &&
2438            "All instructions that wants to replicate non-zero byte "
2439            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2440     unsigned B = Value & 0xff;
2441     B |= 0xe00; // cmode = 0b1110
2442     Inst.addOperand(MCOperand::createImm(B));
2443   }
2444   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2445     assert(N == 1 && "Invalid number of operands!");
2446     // The immediate encodes the type of constant as well as the value.
2447     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2448     unsigned Value = ~CE->getValue();
2449     if (Value >= 256 && Value <= 0xffff)
2450       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2451     else if (Value > 0xffff && Value <= 0xffffff)
2452       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2453     else if (Value > 0xffffff)
2454       Value = (Value >> 24) | 0x600;
2455     Inst.addOperand(MCOperand::createImm(Value));
2456   }
2457
2458   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2459     assert(N == 1 && "Invalid number of operands!");
2460     // The immediate encodes the type of constant as well as the value.
2461     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2462     uint64_t Value = CE->getValue();
2463     unsigned Imm = 0;
2464     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2465       Imm |= (Value & 1) << i;
2466     }
2467     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2468   }
2469
2470   void print(raw_ostream &OS) const override;
2471
2472   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2473     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2474     Op->ITMask.Mask = Mask;
2475     Op->StartLoc = S;
2476     Op->EndLoc = S;
2477     return Op;
2478   }
2479
2480   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2481                                                     SMLoc S) {
2482     auto Op = make_unique<ARMOperand>(k_CondCode);
2483     Op->CC.Val = CC;
2484     Op->StartLoc = S;
2485     Op->EndLoc = S;
2486     return Op;
2487   }
2488
2489   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2490     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2491     Op->Cop.Val = CopVal;
2492     Op->StartLoc = S;
2493     Op->EndLoc = S;
2494     return Op;
2495   }
2496
2497   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2498     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2499     Op->Cop.Val = CopVal;
2500     Op->StartLoc = S;
2501     Op->EndLoc = S;
2502     return Op;
2503   }
2504
2505   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2506                                                         SMLoc E) {
2507     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2508     Op->Cop.Val = Val;
2509     Op->StartLoc = S;
2510     Op->EndLoc = E;
2511     return Op;
2512   }
2513
2514   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2515     auto Op = make_unique<ARMOperand>(k_CCOut);
2516     Op->Reg.RegNum = RegNum;
2517     Op->StartLoc = S;
2518     Op->EndLoc = S;
2519     return Op;
2520   }
2521
2522   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2523     auto Op = make_unique<ARMOperand>(k_Token);
2524     Op->Tok.Data = Str.data();
2525     Op->Tok.Length = Str.size();
2526     Op->StartLoc = S;
2527     Op->EndLoc = S;
2528     return Op;
2529   }
2530
2531   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2532                                                SMLoc E) {
2533     auto Op = make_unique<ARMOperand>(k_Register);
2534     Op->Reg.RegNum = RegNum;
2535     Op->StartLoc = S;
2536     Op->EndLoc = E;
2537     return Op;
2538   }
2539
2540   static std::unique_ptr<ARMOperand>
2541   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2542                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2543                         SMLoc E) {
2544     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2545     Op->RegShiftedReg.ShiftTy = ShTy;
2546     Op->RegShiftedReg.SrcReg = SrcReg;
2547     Op->RegShiftedReg.ShiftReg = ShiftReg;
2548     Op->RegShiftedReg.ShiftImm = ShiftImm;
2549     Op->StartLoc = S;
2550     Op->EndLoc = E;
2551     return Op;
2552   }
2553
2554   static std::unique_ptr<ARMOperand>
2555   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2556                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2557     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2558     Op->RegShiftedImm.ShiftTy = ShTy;
2559     Op->RegShiftedImm.SrcReg = SrcReg;
2560     Op->RegShiftedImm.ShiftImm = ShiftImm;
2561     Op->StartLoc = S;
2562     Op->EndLoc = E;
2563     return Op;
2564   }
2565
2566   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2567                                                       SMLoc S, SMLoc E) {
2568     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2569     Op->ShifterImm.isASR = isASR;
2570     Op->ShifterImm.Imm = Imm;
2571     Op->StartLoc = S;
2572     Op->EndLoc = E;
2573     return Op;
2574   }
2575
2576   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2577                                                   SMLoc E) {
2578     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2579     Op->RotImm.Imm = Imm;
2580     Op->StartLoc = S;
2581     Op->EndLoc = E;
2582     return Op;
2583   }
2584
2585   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2586                                                   SMLoc S, SMLoc E) {
2587     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2588     Op->ModImm.Bits = Bits;
2589     Op->ModImm.Rot = Rot;
2590     Op->StartLoc = S;
2591     Op->EndLoc = E;
2592     return Op;
2593   }
2594
2595   static std::unique_ptr<ARMOperand>
2596   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2597     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2598     Op->Bitfield.LSB = LSB;
2599     Op->Bitfield.Width = Width;
2600     Op->StartLoc = S;
2601     Op->EndLoc = E;
2602     return Op;
2603   }
2604
2605   static std::unique_ptr<ARMOperand>
2606   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2607                 SMLoc StartLoc, SMLoc EndLoc) {
2608     assert (Regs.size() > 0 && "RegList contains no registers?");
2609     KindTy Kind = k_RegisterList;
2610
2611     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2612       Kind = k_DPRRegisterList;
2613     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2614              contains(Regs.front().second))
2615       Kind = k_SPRRegisterList;
2616
2617     // Sort based on the register encoding values.
2618     array_pod_sort(Regs.begin(), Regs.end());
2619
2620     auto Op = make_unique<ARMOperand>(Kind);
2621     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2622            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2623       Op->Registers.push_back(I->second);
2624     Op->StartLoc = StartLoc;
2625     Op->EndLoc = EndLoc;
2626     return Op;
2627   }
2628
2629   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2630                                                       unsigned Count,
2631                                                       bool isDoubleSpaced,
2632                                                       SMLoc S, SMLoc E) {
2633     auto Op = make_unique<ARMOperand>(k_VectorList);
2634     Op->VectorList.RegNum = RegNum;
2635     Op->VectorList.Count = Count;
2636     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2637     Op->StartLoc = S;
2638     Op->EndLoc = E;
2639     return Op;
2640   }
2641
2642   static std::unique_ptr<ARMOperand>
2643   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2644                            SMLoc S, SMLoc E) {
2645     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2646     Op->VectorList.RegNum = RegNum;
2647     Op->VectorList.Count = Count;
2648     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2649     Op->StartLoc = S;
2650     Op->EndLoc = E;
2651     return Op;
2652   }
2653
2654   static std::unique_ptr<ARMOperand>
2655   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2656                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2657     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2658     Op->VectorList.RegNum = RegNum;
2659     Op->VectorList.Count = Count;
2660     Op->VectorList.LaneIndex = Index;
2661     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2662     Op->StartLoc = S;
2663     Op->EndLoc = E;
2664     return Op;
2665   }
2666
2667   static std::unique_ptr<ARMOperand>
2668   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2669     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2670     Op->VectorIndex.Val = Idx;
2671     Op->StartLoc = S;
2672     Op->EndLoc = E;
2673     return Op;
2674   }
2675
2676   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2677                                                SMLoc E) {
2678     auto Op = make_unique<ARMOperand>(k_Immediate);
2679     Op->Imm.Val = Val;
2680     Op->StartLoc = S;
2681     Op->EndLoc = E;
2682     return Op;
2683   }
2684
2685   static std::unique_ptr<ARMOperand>
2686   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2687             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2688             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2689             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2690     auto Op = make_unique<ARMOperand>(k_Memory);
2691     Op->Memory.BaseRegNum = BaseRegNum;
2692     Op->Memory.OffsetImm = OffsetImm;
2693     Op->Memory.OffsetRegNum = OffsetRegNum;
2694     Op->Memory.ShiftType = ShiftType;
2695     Op->Memory.ShiftImm = ShiftImm;
2696     Op->Memory.Alignment = Alignment;
2697     Op->Memory.isNegative = isNegative;
2698     Op->StartLoc = S;
2699     Op->EndLoc = E;
2700     Op->AlignmentLoc = AlignmentLoc;
2701     return Op;
2702   }
2703
2704   static std::unique_ptr<ARMOperand>
2705   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2706                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2707     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2708     Op->PostIdxReg.RegNum = RegNum;
2709     Op->PostIdxReg.isAdd = isAdd;
2710     Op->PostIdxReg.ShiftTy = ShiftTy;
2711     Op->PostIdxReg.ShiftImm = ShiftImm;
2712     Op->StartLoc = S;
2713     Op->EndLoc = E;
2714     return Op;
2715   }
2716
2717   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2718                                                          SMLoc S) {
2719     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2720     Op->MBOpt.Val = Opt;
2721     Op->StartLoc = S;
2722     Op->EndLoc = S;
2723     return Op;
2724   }
2725
2726   static std::unique_ptr<ARMOperand>
2727   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2728     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2729     Op->ISBOpt.Val = Opt;
2730     Op->StartLoc = S;
2731     Op->EndLoc = S;
2732     return Op;
2733   }
2734
2735   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2736                                                       SMLoc S) {
2737     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2738     Op->IFlags.Val = IFlags;
2739     Op->StartLoc = S;
2740     Op->EndLoc = S;
2741     return Op;
2742   }
2743
2744   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2745     auto Op = make_unique<ARMOperand>(k_MSRMask);
2746     Op->MMask.Val = MMask;
2747     Op->StartLoc = S;
2748     Op->EndLoc = S;
2749     return Op;
2750   }
2751
2752   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2753     auto Op = make_unique<ARMOperand>(k_BankedReg);
2754     Op->BankedReg.Val = Reg;
2755     Op->StartLoc = S;
2756     Op->EndLoc = S;
2757     return Op;
2758   }
2759 };
2760
2761 } // end anonymous namespace.
2762
2763 void ARMOperand::print(raw_ostream &OS) const {
2764   switch (Kind) {
2765   case k_CondCode:
2766     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2767     break;
2768   case k_CCOut:
2769     OS << "<ccout " << getReg() << ">";
2770     break;
2771   case k_ITCondMask: {
2772     static const char *const MaskStr[] = {
2773       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2774       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2775     };
2776     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2777     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2778     break;
2779   }
2780   case k_CoprocNum:
2781     OS << "<coprocessor number: " << getCoproc() << ">";
2782     break;
2783   case k_CoprocReg:
2784     OS << "<coprocessor register: " << getCoproc() << ">";
2785     break;
2786   case k_CoprocOption:
2787     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2788     break;
2789   case k_MSRMask:
2790     OS << "<mask: " << getMSRMask() << ">";
2791     break;
2792   case k_BankedReg:
2793     OS << "<banked reg: " << getBankedReg() << ">";
2794     break;
2795   case k_Immediate:
2796     OS << *getImm();
2797     break;
2798   case k_MemBarrierOpt:
2799     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2800     break;
2801   case k_InstSyncBarrierOpt:
2802     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2803     break;
2804   case k_Memory:
2805     OS << "<memory "
2806        << " base:" << Memory.BaseRegNum;
2807     OS << ">";
2808     break;
2809   case k_PostIndexRegister:
2810     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2811        << PostIdxReg.RegNum;
2812     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2813       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2814          << PostIdxReg.ShiftImm;
2815     OS << ">";
2816     break;
2817   case k_ProcIFlags: {
2818     OS << "<ARM_PROC::";
2819     unsigned IFlags = getProcIFlags();
2820     for (int i=2; i >= 0; --i)
2821       if (IFlags & (1 << i))
2822         OS << ARM_PROC::IFlagsToString(1 << i);
2823     OS << ">";
2824     break;
2825   }
2826   case k_Register:
2827     OS << "<register " << getReg() << ">";
2828     break;
2829   case k_ShifterImmediate:
2830     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2831        << " #" << ShifterImm.Imm << ">";
2832     break;
2833   case k_ShiftedRegister:
2834     OS << "<so_reg_reg "
2835        << RegShiftedReg.SrcReg << " "
2836        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2837        << " " << RegShiftedReg.ShiftReg << ">";
2838     break;
2839   case k_ShiftedImmediate:
2840     OS << "<so_reg_imm "
2841        << RegShiftedImm.SrcReg << " "
2842        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2843        << " #" << RegShiftedImm.ShiftImm << ">";
2844     break;
2845   case k_RotateImmediate:
2846     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2847     break;
2848   case k_ModifiedImmediate:
2849     OS << "<mod_imm #" << ModImm.Bits << ", #"
2850        <<  ModImm.Rot << ")>";
2851     break;
2852   case k_BitfieldDescriptor:
2853     OS << "<bitfield " << "lsb: " << Bitfield.LSB
2854        << ", width: " << Bitfield.Width << ">";
2855     break;
2856   case k_RegisterList:
2857   case k_DPRRegisterList:
2858   case k_SPRRegisterList: {
2859     OS << "<register_list ";
2860
2861     const SmallVectorImpl<unsigned> &RegList = getRegList();
2862     for (SmallVectorImpl<unsigned>::const_iterator
2863            I = RegList.begin(), E = RegList.end(); I != E; ) {
2864       OS << *I;
2865       if (++I < E) OS << ", ";
2866     }
2867
2868     OS << ">";
2869     break;
2870   }
2871   case k_VectorList:
2872     OS << "<vector_list " << VectorList.Count << " * "
2873        << VectorList.RegNum << ">";
2874     break;
2875   case k_VectorListAllLanes:
2876     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
2877        << VectorList.RegNum << ">";
2878     break;
2879   case k_VectorListIndexed:
2880     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
2881        << VectorList.Count << " * " << VectorList.RegNum << ">";
2882     break;
2883   case k_Token:
2884     OS << "'" << getToken() << "'";
2885     break;
2886   case k_VectorIndex:
2887     OS << "<vectorindex " << getVectorIndex() << ">";
2888     break;
2889   }
2890 }
2891
2892 /// @name Auto-generated Match Functions
2893 /// {
2894
2895 static unsigned MatchRegisterName(StringRef Name);
2896
2897 /// }
2898
2899 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
2900                                  SMLoc &StartLoc, SMLoc &EndLoc) {
2901   const AsmToken &Tok = getParser().getTok();
2902   StartLoc = Tok.getLoc();
2903   EndLoc = Tok.getEndLoc();
2904   RegNo = tryParseRegister();
2905
2906   return (RegNo == (unsigned)-1);
2907 }
2908
2909 /// Try to parse a register name.  The token must be an Identifier when called,
2910 /// and if it is a register name the token is eaten and the register number is
2911 /// returned.  Otherwise return -1.
2912 ///
2913 int ARMAsmParser::tryParseRegister() {
2914   MCAsmParser &Parser = getParser();
2915   const AsmToken &Tok = Parser.getTok();
2916   if (Tok.isNot(AsmToken::Identifier)) return -1;
2917
2918   std::string lowerCase = Tok.getString().lower();
2919   unsigned RegNum = MatchRegisterName(lowerCase);
2920   if (!RegNum) {
2921     RegNum = StringSwitch<unsigned>(lowerCase)
2922       .Case("r13", ARM::SP)
2923       .Case("r14", ARM::LR)
2924       .Case("r15", ARM::PC)
2925       .Case("ip", ARM::R12)
2926       // Additional register name aliases for 'gas' compatibility.
2927       .Case("a1", ARM::R0)
2928       .Case("a2", ARM::R1)
2929       .Case("a3", ARM::R2)
2930       .Case("a4", ARM::R3)
2931       .Case("v1", ARM::R4)
2932       .Case("v2", ARM::R5)
2933       .Case("v3", ARM::R6)
2934       .Case("v4", ARM::R7)
2935       .Case("v5", ARM::R8)
2936       .Case("v6", ARM::R9)
2937       .Case("v7", ARM::R10)
2938       .Case("v8", ARM::R11)
2939       .Case("sb", ARM::R9)
2940       .Case("sl", ARM::R10)
2941       .Case("fp", ARM::R11)
2942       .Default(0);
2943   }
2944   if (!RegNum) {
2945     // Check for aliases registered via .req. Canonicalize to lower case.
2946     // That's more consistent since register names are case insensitive, and
2947     // it's how the original entry was passed in from MC/MCParser/AsmParser.
2948     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
2949     // If no match, return failure.
2950     if (Entry == RegisterReqs.end())
2951       return -1;
2952     Parser.Lex(); // Eat identifier token.
2953     return Entry->getValue();
2954   }
2955
2956   // Some FPUs only have 16 D registers, so D16-D31 are invalid
2957   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
2958     return -1;
2959
2960   Parser.Lex(); // Eat identifier token.
2961
2962   return RegNum;
2963 }
2964
2965 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
2966 // If a recoverable error occurs, return 1. If an irrecoverable error
2967 // occurs, return -1. An irrecoverable error is one where tokens have been
2968 // consumed in the process of trying to parse the shifter (i.e., when it is
2969 // indeed a shifter operand, but malformed).
2970 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
2971   MCAsmParser &Parser = getParser();
2972   SMLoc S = Parser.getTok().getLoc();
2973   const AsmToken &Tok = Parser.getTok();
2974   if (Tok.isNot(AsmToken::Identifier))
2975     return -1; 
2976
2977   std::string lowerCase = Tok.getString().lower();
2978   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
2979       .Case("asl", ARM_AM::lsl)
2980       .Case("lsl", ARM_AM::lsl)
2981       .Case("lsr", ARM_AM::lsr)
2982       .Case("asr", ARM_AM::asr)
2983       .Case("ror", ARM_AM::ror)
2984       .Case("rrx", ARM_AM::rrx)
2985       .Default(ARM_AM::no_shift);
2986
2987   if (ShiftTy == ARM_AM::no_shift)
2988     return 1;
2989
2990   Parser.Lex(); // Eat the operator.
2991
2992   // The source register for the shift has already been added to the
2993   // operand list, so we need to pop it off and combine it into the shifted
2994   // register operand instead.
2995   std::unique_ptr<ARMOperand> PrevOp(
2996       (ARMOperand *)Operands.pop_back_val().release());
2997   if (!PrevOp->isReg())
2998     return Error(PrevOp->getStartLoc(), "shift must be of a register");
2999   int SrcReg = PrevOp->getReg();
3000
3001   SMLoc EndLoc;
3002   int64_t Imm = 0;
3003   int ShiftReg = 0;
3004   if (ShiftTy == ARM_AM::rrx) {
3005     // RRX Doesn't have an explicit shift amount. The encoder expects
3006     // the shift register to be the same as the source register. Seems odd,
3007     // but OK.
3008     ShiftReg = SrcReg;
3009   } else {
3010     // Figure out if this is shifted by a constant or a register (for non-RRX).
3011     if (Parser.getTok().is(AsmToken::Hash) ||
3012         Parser.getTok().is(AsmToken::Dollar)) {
3013       Parser.Lex(); // Eat hash.
3014       SMLoc ImmLoc = Parser.getTok().getLoc();
3015       const MCExpr *ShiftExpr = nullptr;
3016       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3017         Error(ImmLoc, "invalid immediate shift value");
3018         return -1;
3019       }
3020       // The expression must be evaluatable as an immediate.
3021       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3022       if (!CE) {
3023         Error(ImmLoc, "invalid immediate shift value");
3024         return -1;
3025       }
3026       // Range check the immediate.
3027       // lsl, ror: 0 <= imm <= 31
3028       // lsr, asr: 0 <= imm <= 32
3029       Imm = CE->getValue();
3030       if (Imm < 0 ||
3031           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3032           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3033         Error(ImmLoc, "immediate shift value out of range");
3034         return -1;
3035       }
3036       // shift by zero is a nop. Always send it through as lsl.
3037       // ('as' compatibility)
3038       if (Imm == 0)
3039         ShiftTy = ARM_AM::lsl;
3040     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3041       SMLoc L = Parser.getTok().getLoc();
3042       EndLoc = Parser.getTok().getEndLoc();
3043       ShiftReg = tryParseRegister();
3044       if (ShiftReg == -1) {
3045         Error(L, "expected immediate or register in shift operand");
3046         return -1;
3047       }
3048     } else {
3049       Error(Parser.getTok().getLoc(),
3050             "expected immediate or register in shift operand");
3051       return -1;
3052     }
3053   }
3054
3055   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3056     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3057                                                          ShiftReg, Imm,
3058                                                          S, EndLoc));
3059   else
3060     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3061                                                           S, EndLoc));
3062
3063   return 0;
3064 }
3065
3066
3067 /// Try to parse a register name.  The token must be an Identifier when called.
3068 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3069 /// if there is a "writeback". 'true' if it's not a register.
3070 ///
3071 /// TODO this is likely to change to allow different register types and or to
3072 /// parse for a specific register type.
3073 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3074   MCAsmParser &Parser = getParser();
3075   const AsmToken &RegTok = Parser.getTok();
3076   int RegNo = tryParseRegister();
3077   if (RegNo == -1)
3078     return true;
3079
3080   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3081                                            RegTok.getEndLoc()));
3082
3083   const AsmToken &ExclaimTok = Parser.getTok();
3084   if (ExclaimTok.is(AsmToken::Exclaim)) {
3085     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3086                                                ExclaimTok.getLoc()));
3087     Parser.Lex(); // Eat exclaim token
3088     return false;
3089   }
3090
3091   // Also check for an index operand. This is only legal for vector registers,
3092   // but that'll get caught OK in operand matching, so we don't need to
3093   // explicitly filter everything else out here.
3094   if (Parser.getTok().is(AsmToken::LBrac)) {
3095     SMLoc SIdx = Parser.getTok().getLoc();
3096     Parser.Lex(); // Eat left bracket token.
3097
3098     const MCExpr *ImmVal;
3099     if (getParser().parseExpression(ImmVal))
3100       return true;
3101     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3102     if (!MCE)
3103       return TokError("immediate value expected for vector index");
3104
3105     if (Parser.getTok().isNot(AsmToken::RBrac))
3106       return Error(Parser.getTok().getLoc(), "']' expected");
3107
3108     SMLoc E = Parser.getTok().getEndLoc();
3109     Parser.Lex(); // Eat right bracket token.
3110
3111     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3112                                                      SIdx, E,
3113                                                      getContext()));
3114   }
3115
3116   return false;
3117 }
3118
3119 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3120 /// instruction with a symbolic operand name.
3121 /// We accept "crN" syntax for GAS compatibility.
3122 /// <operand-name> ::= <prefix><number>
3123 /// If CoprocOp is 'c', then:
3124 ///   <prefix> ::= c | cr
3125 /// If CoprocOp is 'p', then :
3126 ///   <prefix> ::= p
3127 /// <number> ::= integer in range [0, 15]
3128 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3129   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3130   // but efficient.
3131   if (Name.size() < 2 || Name[0] != CoprocOp)
3132     return -1;
3133   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3134
3135   switch (Name.size()) {
3136   default: return -1;
3137   case 1:
3138     switch (Name[0]) {
3139     default:  return -1;
3140     case '0': return 0;
3141     case '1': return 1;
3142     case '2': return 2;
3143     case '3': return 3;
3144     case '4': return 4;
3145     case '5': return 5;
3146     case '6': return 6;
3147     case '7': return 7;
3148     case '8': return 8;
3149     case '9': return 9;
3150     }
3151   case 2:
3152     if (Name[0] != '1')
3153       return -1;
3154     switch (Name[1]) {
3155     default:  return -1;
3156     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3157     // However, old cores (v5/v6) did use them in that way.
3158     case '0': return 10;
3159     case '1': return 11;
3160     case '2': return 12;
3161     case '3': return 13;
3162     case '4': return 14;
3163     case '5': return 15;
3164     }
3165   }
3166 }
3167
3168 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3169 ARMAsmParser::OperandMatchResultTy
3170 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3171   MCAsmParser &Parser = getParser();
3172   SMLoc S = Parser.getTok().getLoc();
3173   const AsmToken &Tok = Parser.getTok();
3174   if (!Tok.is(AsmToken::Identifier))
3175     return MatchOperand_NoMatch;
3176   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3177     .Case("eq", ARMCC::EQ)
3178     .Case("ne", ARMCC::NE)
3179     .Case("hs", ARMCC::HS)
3180     .Case("cs", ARMCC::HS)
3181     .Case("lo", ARMCC::LO)
3182     .Case("cc", ARMCC::LO)
3183     .Case("mi", ARMCC::MI)
3184     .Case("pl", ARMCC::PL)
3185     .Case("vs", ARMCC::VS)
3186     .Case("vc", ARMCC::VC)
3187     .Case("hi", ARMCC::HI)
3188     .Case("ls", ARMCC::LS)
3189     .Case("ge", ARMCC::GE)
3190     .Case("lt", ARMCC::LT)
3191     .Case("gt", ARMCC::GT)
3192     .Case("le", ARMCC::LE)
3193     .Case("al", ARMCC::AL)
3194     .Default(~0U);
3195   if (CC == ~0U)
3196     return MatchOperand_NoMatch;
3197   Parser.Lex(); // Eat the token.
3198
3199   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3200
3201   return MatchOperand_Success;
3202 }
3203
3204 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3205 /// token must be an Identifier when called, and if it is a coprocessor
3206 /// number, the token is eaten and the operand is added to the operand list.
3207 ARMAsmParser::OperandMatchResultTy
3208 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3209   MCAsmParser &Parser = getParser();
3210   SMLoc S = Parser.getTok().getLoc();
3211   const AsmToken &Tok = Parser.getTok();
3212   if (Tok.isNot(AsmToken::Identifier))
3213     return MatchOperand_NoMatch;
3214
3215   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3216   if (Num == -1)
3217     return MatchOperand_NoMatch;
3218   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3219   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3220     return MatchOperand_NoMatch;
3221
3222   Parser.Lex(); // Eat identifier token.
3223   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3224   return MatchOperand_Success;
3225 }
3226
3227 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3228 /// token must be an Identifier when called, and if it is a coprocessor
3229 /// number, the token is eaten and the operand is added to the operand list.
3230 ARMAsmParser::OperandMatchResultTy
3231 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3232   MCAsmParser &Parser = getParser();
3233   SMLoc S = Parser.getTok().getLoc();
3234   const AsmToken &Tok = Parser.getTok();
3235   if (Tok.isNot(AsmToken::Identifier))
3236     return MatchOperand_NoMatch;
3237
3238   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3239   if (Reg == -1)
3240     return MatchOperand_NoMatch;
3241
3242   Parser.Lex(); // Eat identifier token.
3243   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3244   return MatchOperand_Success;
3245 }
3246
3247 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3248 /// coproc_option : '{' imm0_255 '}'
3249 ARMAsmParser::OperandMatchResultTy
3250 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3251   MCAsmParser &Parser = getParser();
3252   SMLoc S = Parser.getTok().getLoc();
3253
3254   // If this isn't a '{', this isn't a coprocessor immediate operand.
3255   if (Parser.getTok().isNot(AsmToken::LCurly))
3256     return MatchOperand_NoMatch;
3257   Parser.Lex(); // Eat the '{'
3258
3259   const MCExpr *Expr;
3260   SMLoc Loc = Parser.getTok().getLoc();
3261   if (getParser().parseExpression(Expr)) {
3262     Error(Loc, "illegal expression");
3263     return MatchOperand_ParseFail;
3264   }
3265   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3266   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3267     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3268     return MatchOperand_ParseFail;
3269   }
3270   int Val = CE->getValue();
3271
3272   // Check for and consume the closing '}'
3273   if (Parser.getTok().isNot(AsmToken::RCurly))
3274     return MatchOperand_ParseFail;
3275   SMLoc E = Parser.getTok().getEndLoc();
3276   Parser.Lex(); // Eat the '}'
3277
3278   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3279   return MatchOperand_Success;
3280 }
3281
3282 // For register list parsing, we need to map from raw GPR register numbering
3283 // to the enumeration values. The enumeration values aren't sorted by
3284 // register number due to our using "sp", "lr" and "pc" as canonical names.
3285 static unsigned getNextRegister(unsigned Reg) {
3286   // If this is a GPR, we need to do it manually, otherwise we can rely
3287   // on the sort ordering of the enumeration since the other reg-classes
3288   // are sane.
3289   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3290     return Reg + 1;
3291   switch(Reg) {
3292   default: llvm_unreachable("Invalid GPR number!");
3293   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3294   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3295   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3296   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3297   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3298   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3299   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3300   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3301   }
3302 }
3303
3304 // Return the low-subreg of a given Q register.
3305 static unsigned getDRegFromQReg(unsigned QReg) {
3306   switch (QReg) {
3307   default: llvm_unreachable("expected a Q register!");
3308   case ARM::Q0:  return ARM::D0;
3309   case ARM::Q1:  return ARM::D2;
3310   case ARM::Q2:  return ARM::D4;
3311   case ARM::Q3:  return ARM::D6;
3312   case ARM::Q4:  return ARM::D8;
3313   case ARM::Q5:  return ARM::D10;
3314   case ARM::Q6:  return ARM::D12;
3315   case ARM::Q7:  return ARM::D14;
3316   case ARM::Q8:  return ARM::D16;
3317   case ARM::Q9:  return ARM::D18;
3318   case ARM::Q10: return ARM::D20;
3319   case ARM::Q11: return ARM::D22;
3320   case ARM::Q12: return ARM::D24;
3321   case ARM::Q13: return ARM::D26;
3322   case ARM::Q14: return ARM::D28;
3323   case ARM::Q15: return ARM::D30;
3324   }
3325 }
3326
3327 /// Parse a register list.
3328 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3329   MCAsmParser &Parser = getParser();
3330   assert(Parser.getTok().is(AsmToken::LCurly) &&
3331          "Token is not a Left Curly Brace");
3332   SMLoc S = Parser.getTok().getLoc();
3333   Parser.Lex(); // Eat '{' token.
3334   SMLoc RegLoc = Parser.getTok().getLoc();
3335
3336   // Check the first register in the list to see what register class
3337   // this is a list of.
3338   int Reg = tryParseRegister();
3339   if (Reg == -1)
3340     return Error(RegLoc, "register expected");
3341
3342   // The reglist instructions have at most 16 registers, so reserve
3343   // space for that many.
3344   int EReg = 0;
3345   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3346
3347   // Allow Q regs and just interpret them as the two D sub-registers.
3348   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3349     Reg = getDRegFromQReg(Reg);
3350     EReg = MRI->getEncodingValue(Reg);
3351     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3352     ++Reg;
3353   }
3354   const MCRegisterClass *RC;
3355   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3356     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3357   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3358     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3359   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3360     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3361   else
3362     return Error(RegLoc, "invalid register in register list");
3363
3364   // Store the register.
3365   EReg = MRI->getEncodingValue(Reg);
3366   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3367
3368   // This starts immediately after the first register token in the list,
3369   // so we can see either a comma or a minus (range separator) as a legal
3370   // next token.
3371   while (Parser.getTok().is(AsmToken::Comma) ||
3372          Parser.getTok().is(AsmToken::Minus)) {
3373     if (Parser.getTok().is(AsmToken::Minus)) {
3374       Parser.Lex(); // Eat the minus.
3375       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3376       int EndReg = tryParseRegister();
3377       if (EndReg == -1)
3378         return Error(AfterMinusLoc, "register expected");
3379       // Allow Q regs and just interpret them as the two D sub-registers.
3380       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3381         EndReg = getDRegFromQReg(EndReg) + 1;
3382       // If the register is the same as the start reg, there's nothing
3383       // more to do.
3384       if (Reg == EndReg)
3385         continue;
3386       // The register must be in the same register class as the first.
3387       if (!RC->contains(EndReg))
3388         return Error(AfterMinusLoc, "invalid register in register list");
3389       // Ranges must go from low to high.
3390       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3391         return Error(AfterMinusLoc, "bad range in register list");
3392
3393       // Add all the registers in the range to the register list.
3394       while (Reg != EndReg) {
3395         Reg = getNextRegister(Reg);
3396         EReg = MRI->getEncodingValue(Reg);
3397         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3398       }
3399       continue;
3400     }
3401     Parser.Lex(); // Eat the comma.
3402     RegLoc = Parser.getTok().getLoc();
3403     int OldReg = Reg;
3404     const AsmToken RegTok = Parser.getTok();
3405     Reg = tryParseRegister();
3406     if (Reg == -1)
3407       return Error(RegLoc, "register expected");
3408     // Allow Q regs and just interpret them as the two D sub-registers.
3409     bool isQReg = false;
3410     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3411       Reg = getDRegFromQReg(Reg);
3412       isQReg = true;
3413     }
3414     // The register must be in the same register class as the first.
3415     if (!RC->contains(Reg))
3416       return Error(RegLoc, "invalid register in register list");
3417     // List must be monotonically increasing.
3418     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3419       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3420         Warning(RegLoc, "register list not in ascending order");
3421       else
3422         return Error(RegLoc, "register list not in ascending order");
3423     }
3424     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3425       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3426               ") in register list");
3427       continue;
3428     }
3429     // VFP register lists must also be contiguous.
3430     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3431         Reg != OldReg + 1)
3432       return Error(RegLoc, "non-contiguous register range");
3433     EReg = MRI->getEncodingValue(Reg);
3434     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3435     if (isQReg) {
3436       EReg = MRI->getEncodingValue(++Reg);
3437       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3438     }
3439   }
3440
3441   if (Parser.getTok().isNot(AsmToken::RCurly))
3442     return Error(Parser.getTok().getLoc(), "'}' expected");
3443   SMLoc E = Parser.getTok().getEndLoc();
3444   Parser.Lex(); // Eat '}' token.
3445
3446   // Push the register list operand.
3447   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3448
3449   // The ARM system instruction variants for LDM/STM have a '^' token here.
3450   if (Parser.getTok().is(AsmToken::Caret)) {
3451     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3452     Parser.Lex(); // Eat '^' token.
3453   }
3454
3455   return false;
3456 }
3457
3458 // Helper function to parse the lane index for vector lists.
3459 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3460 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3461   MCAsmParser &Parser = getParser();
3462   Index = 0; // Always return a defined index value.
3463   if (Parser.getTok().is(AsmToken::LBrac)) {
3464     Parser.Lex(); // Eat the '['.
3465     if (Parser.getTok().is(AsmToken::RBrac)) {
3466       // "Dn[]" is the 'all lanes' syntax.
3467       LaneKind = AllLanes;
3468       EndLoc = Parser.getTok().getEndLoc();
3469       Parser.Lex(); // Eat the ']'.
3470       return MatchOperand_Success;
3471     }
3472
3473     // There's an optional '#' token here. Normally there wouldn't be, but
3474     // inline assemble puts one in, and it's friendly to accept that.
3475     if (Parser.getTok().is(AsmToken::Hash))
3476       Parser.Lex(); // Eat '#' or '$'.
3477
3478     const MCExpr *LaneIndex;
3479     SMLoc Loc = Parser.getTok().getLoc();
3480     if (getParser().parseExpression(LaneIndex)) {
3481       Error(Loc, "illegal expression");
3482       return MatchOperand_ParseFail;
3483     }
3484     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3485     if (!CE) {
3486       Error(Loc, "lane index must be empty or an integer");
3487       return MatchOperand_ParseFail;
3488     }
3489     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3490       Error(Parser.getTok().getLoc(), "']' expected");
3491       return MatchOperand_ParseFail;
3492     }
3493     EndLoc = Parser.getTok().getEndLoc();
3494     Parser.Lex(); // Eat the ']'.
3495     int64_t Val = CE->getValue();
3496
3497     // FIXME: Make this range check context sensitive for .8, .16, .32.
3498     if (Val < 0 || Val > 7) {
3499       Error(Parser.getTok().getLoc(), "lane index out of range");
3500       return MatchOperand_ParseFail;
3501     }
3502     Index = Val;
3503     LaneKind = IndexedLane;
3504     return MatchOperand_Success;
3505   }
3506   LaneKind = NoLanes;
3507   return MatchOperand_Success;
3508 }
3509
3510 // parse a vector register list
3511 ARMAsmParser::OperandMatchResultTy
3512 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3513   MCAsmParser &Parser = getParser();
3514   VectorLaneTy LaneKind;
3515   unsigned LaneIndex;
3516   SMLoc S = Parser.getTok().getLoc();
3517   // As an extension (to match gas), support a plain D register or Q register
3518   // (without encosing curly braces) as a single or double entry list,
3519   // respectively.
3520   if (Parser.getTok().is(AsmToken::Identifier)) {
3521     SMLoc E = Parser.getTok().getEndLoc();
3522     int Reg = tryParseRegister();
3523     if (Reg == -1)
3524       return MatchOperand_NoMatch;
3525     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3526       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3527       if (Res != MatchOperand_Success)
3528         return Res;
3529       switch (LaneKind) {
3530       case NoLanes:
3531         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3532         break;
3533       case AllLanes:
3534         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3535                                                                 S, E));
3536         break;
3537       case IndexedLane:
3538         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3539                                                                LaneIndex,
3540                                                                false, S, E));
3541         break;
3542       }
3543       return MatchOperand_Success;
3544     }
3545     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3546       Reg = getDRegFromQReg(Reg);
3547       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3548       if (Res != MatchOperand_Success)
3549         return Res;
3550       switch (LaneKind) {
3551       case NoLanes:
3552         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3553                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3554         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3555         break;
3556       case AllLanes:
3557         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3558                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3559         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3560                                                                 S, E));
3561         break;
3562       case IndexedLane:
3563         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3564                                                                LaneIndex,
3565                                                                false, S, E));
3566         break;
3567       }
3568       return MatchOperand_Success;
3569     }
3570     Error(S, "vector register expected");
3571     return MatchOperand_ParseFail;
3572   }
3573
3574   if (Parser.getTok().isNot(AsmToken::LCurly))
3575     return MatchOperand_NoMatch;
3576
3577   Parser.Lex(); // Eat '{' token.
3578   SMLoc RegLoc = Parser.getTok().getLoc();
3579
3580   int Reg = tryParseRegister();
3581   if (Reg == -1) {
3582     Error(RegLoc, "register expected");
3583     return MatchOperand_ParseFail;
3584   }
3585   unsigned Count = 1;
3586   int Spacing = 0;
3587   unsigned FirstReg = Reg;
3588   // The list is of D registers, but we also allow Q regs and just interpret
3589   // them as the two D sub-registers.
3590   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3591     FirstReg = Reg = getDRegFromQReg(Reg);
3592     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3593                  // it's ambiguous with four-register single spaced.
3594     ++Reg;
3595     ++Count;
3596   }
3597
3598   SMLoc E;
3599   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3600     return MatchOperand_ParseFail;
3601
3602   while (Parser.getTok().is(AsmToken::Comma) ||
3603          Parser.getTok().is(AsmToken::Minus)) {
3604     if (Parser.getTok().is(AsmToken::Minus)) {
3605       if (!Spacing)
3606         Spacing = 1; // Register range implies a single spaced list.
3607       else if (Spacing == 2) {
3608         Error(Parser.getTok().getLoc(),
3609               "sequential registers in double spaced list");
3610         return MatchOperand_ParseFail;
3611       }
3612       Parser.Lex(); // Eat the minus.
3613       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3614       int EndReg = tryParseRegister();
3615       if (EndReg == -1) {
3616         Error(AfterMinusLoc, "register expected");
3617         return MatchOperand_ParseFail;
3618       }
3619       // Allow Q regs and just interpret them as the two D sub-registers.
3620       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3621         EndReg = getDRegFromQReg(EndReg) + 1;
3622       // If the register is the same as the start reg, there's nothing
3623       // more to do.
3624       if (Reg == EndReg)
3625         continue;
3626       // The register must be in the same register class as the first.
3627       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3628         Error(AfterMinusLoc, "invalid register in register list");
3629         return MatchOperand_ParseFail;
3630       }
3631       // Ranges must go from low to high.
3632       if (Reg > EndReg) {
3633         Error(AfterMinusLoc, "bad range in register list");
3634         return MatchOperand_ParseFail;
3635       }
3636       // Parse the lane specifier if present.
3637       VectorLaneTy NextLaneKind;
3638       unsigned NextLaneIndex;
3639       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3640           MatchOperand_Success)
3641         return MatchOperand_ParseFail;
3642       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3643         Error(AfterMinusLoc, "mismatched lane index in register list");
3644         return MatchOperand_ParseFail;
3645       }
3646
3647       // Add all the registers in the range to the register list.
3648       Count += EndReg - Reg;
3649       Reg = EndReg;
3650       continue;
3651     }
3652     Parser.Lex(); // Eat the comma.
3653     RegLoc = Parser.getTok().getLoc();
3654     int OldReg = Reg;
3655     Reg = tryParseRegister();
3656     if (Reg == -1) {
3657       Error(RegLoc, "register expected");
3658       return MatchOperand_ParseFail;
3659     }
3660     // vector register lists must be contiguous.
3661     // It's OK to use the enumeration values directly here rather, as the
3662     // VFP register classes have the enum sorted properly.
3663     //
3664     // The list is of D registers, but we also allow Q regs and just interpret
3665     // them as the two D sub-registers.
3666     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3667       if (!Spacing)
3668         Spacing = 1; // Register range implies a single spaced list.
3669       else if (Spacing == 2) {
3670         Error(RegLoc,
3671               "invalid register in double-spaced list (must be 'D' register')");
3672         return MatchOperand_ParseFail;
3673       }
3674       Reg = getDRegFromQReg(Reg);
3675       if (Reg != OldReg + 1) {
3676         Error(RegLoc, "non-contiguous register range");
3677         return MatchOperand_ParseFail;
3678       }
3679       ++Reg;
3680       Count += 2;
3681       // Parse the lane specifier if present.
3682       VectorLaneTy NextLaneKind;
3683       unsigned NextLaneIndex;
3684       SMLoc LaneLoc = Parser.getTok().getLoc();
3685       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3686           MatchOperand_Success)
3687         return MatchOperand_ParseFail;
3688       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3689         Error(LaneLoc, "mismatched lane index in register list");
3690         return MatchOperand_ParseFail;
3691       }
3692       continue;
3693     }
3694     // Normal D register.
3695     // Figure out the register spacing (single or double) of the list if
3696     // we don't know it already.
3697     if (!Spacing)
3698       Spacing = 1 + (Reg == OldReg + 2);
3699
3700     // Just check that it's contiguous and keep going.
3701     if (Reg != OldReg + Spacing) {
3702       Error(RegLoc, "non-contiguous register range");
3703       return MatchOperand_ParseFail;
3704     }
3705     ++Count;
3706     // Parse the lane specifier if present.
3707     VectorLaneTy NextLaneKind;
3708     unsigned NextLaneIndex;
3709     SMLoc EndLoc = Parser.getTok().getLoc();
3710     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3711       return MatchOperand_ParseFail;
3712     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3713       Error(EndLoc, "mismatched lane index in register list");
3714       return MatchOperand_ParseFail;
3715     }
3716   }
3717
3718   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3719     Error(Parser.getTok().getLoc(), "'}' expected");
3720     return MatchOperand_ParseFail;
3721   }
3722   E = Parser.getTok().getEndLoc();
3723   Parser.Lex(); // Eat '}' token.
3724
3725   switch (LaneKind) {
3726   case NoLanes:
3727     // Two-register operands have been converted to the
3728     // composite register classes.
3729     if (Count == 2) {
3730       const MCRegisterClass *RC = (Spacing == 1) ?
3731         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3732         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3733       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3734     }
3735
3736     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3737                                                     (Spacing == 2), S, E));
3738     break;
3739   case AllLanes:
3740     // Two-register operands have been converted to the
3741     // composite register classes.
3742     if (Count == 2) {
3743       const MCRegisterClass *RC = (Spacing == 1) ?
3744         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3745         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3746       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3747     }
3748     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3749                                                             (Spacing == 2),
3750                                                             S, E));
3751     break;
3752   case IndexedLane:
3753     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3754                                                            LaneIndex,
3755                                                            (Spacing == 2),
3756                                                            S, E));
3757     break;
3758   }
3759   return MatchOperand_Success;
3760 }
3761
3762 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3763 ARMAsmParser::OperandMatchResultTy
3764 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3765   MCAsmParser &Parser = getParser();
3766   SMLoc S = Parser.getTok().getLoc();
3767   const AsmToken &Tok = Parser.getTok();
3768   unsigned Opt;
3769
3770   if (Tok.is(AsmToken::Identifier)) {
3771     StringRef OptStr = Tok.getString();
3772
3773     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3774       .Case("sy",    ARM_MB::SY)
3775       .Case("st",    ARM_MB::ST)
3776       .Case("ld",    ARM_MB::LD)
3777       .Case("sh",    ARM_MB::ISH)
3778       .Case("ish",   ARM_MB::ISH)
3779       .Case("shst",  ARM_MB::ISHST)
3780       .Case("ishst", ARM_MB::ISHST)
3781       .Case("ishld", ARM_MB::ISHLD)
3782       .Case("nsh",   ARM_MB::NSH)
3783       .Case("un",    ARM_MB::NSH)
3784       .Case("nshst", ARM_MB::NSHST)
3785       .Case("nshld", ARM_MB::NSHLD)
3786       .Case("unst",  ARM_MB::NSHST)
3787       .Case("osh",   ARM_MB::OSH)
3788       .Case("oshst", ARM_MB::OSHST)
3789       .Case("oshld", ARM_MB::OSHLD)
3790       .Default(~0U);
3791
3792     // ishld, oshld, nshld and ld are only available from ARMv8.
3793     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3794                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3795       Opt = ~0U;
3796
3797     if (Opt == ~0U)
3798       return MatchOperand_NoMatch;
3799
3800     Parser.Lex(); // Eat identifier token.
3801   } else if (Tok.is(AsmToken::Hash) ||
3802              Tok.is(AsmToken::Dollar) ||
3803              Tok.is(AsmToken::Integer)) {
3804     if (Parser.getTok().isNot(AsmToken::Integer))
3805       Parser.Lex(); // Eat '#' or '$'.
3806     SMLoc Loc = Parser.getTok().getLoc();
3807
3808     const MCExpr *MemBarrierID;
3809     if (getParser().parseExpression(MemBarrierID)) {
3810       Error(Loc, "illegal expression");
3811       return MatchOperand_ParseFail;
3812     }
3813
3814     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3815     if (!CE) {
3816       Error(Loc, "constant expression expected");
3817       return MatchOperand_ParseFail;
3818     }
3819
3820     int Val = CE->getValue();
3821     if (Val & ~0xf) {
3822       Error(Loc, "immediate value out of range");
3823       return MatchOperand_ParseFail;
3824     }
3825
3826     Opt = ARM_MB::RESERVED_0 + Val;
3827   } else
3828     return MatchOperand_ParseFail;
3829
3830   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3831   return MatchOperand_Success;
3832 }
3833
3834 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3835 ARMAsmParser::OperandMatchResultTy
3836 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3837   MCAsmParser &Parser = getParser();
3838   SMLoc S = Parser.getTok().getLoc();
3839   const AsmToken &Tok = Parser.getTok();
3840   unsigned Opt;
3841
3842   if (Tok.is(AsmToken::Identifier)) {
3843     StringRef OptStr = Tok.getString();
3844
3845     if (OptStr.equals_lower("sy"))
3846       Opt = ARM_ISB::SY;
3847     else
3848       return MatchOperand_NoMatch;
3849
3850     Parser.Lex(); // Eat identifier token.
3851   } else if (Tok.is(AsmToken::Hash) ||
3852              Tok.is(AsmToken::Dollar) ||
3853              Tok.is(AsmToken::Integer)) {
3854     if (Parser.getTok().isNot(AsmToken::Integer))
3855       Parser.Lex(); // Eat '#' or '$'.
3856     SMLoc Loc = Parser.getTok().getLoc();
3857
3858     const MCExpr *ISBarrierID;
3859     if (getParser().parseExpression(ISBarrierID)) {
3860       Error(Loc, "illegal expression");
3861       return MatchOperand_ParseFail;
3862     }
3863
3864     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
3865     if (!CE) {
3866       Error(Loc, "constant expression expected");
3867       return MatchOperand_ParseFail;
3868     }
3869
3870     int Val = CE->getValue();
3871     if (Val & ~0xf) {
3872       Error(Loc, "immediate value out of range");
3873       return MatchOperand_ParseFail;
3874     }
3875
3876     Opt = ARM_ISB::RESERVED_0 + Val;
3877   } else
3878     return MatchOperand_ParseFail;
3879
3880   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
3881           (ARM_ISB::InstSyncBOpt)Opt, S));
3882   return MatchOperand_Success;
3883 }
3884
3885
3886 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
3887 ARMAsmParser::OperandMatchResultTy
3888 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
3889   MCAsmParser &Parser = getParser();
3890   SMLoc S = Parser.getTok().getLoc();
3891   const AsmToken &Tok = Parser.getTok();
3892   if (!Tok.is(AsmToken::Identifier)) 
3893     return MatchOperand_NoMatch;
3894   StringRef IFlagsStr = Tok.getString();
3895
3896   // An iflags string of "none" is interpreted to mean that none of the AIF
3897   // bits are set.  Not a terribly useful instruction, but a valid encoding.
3898   unsigned IFlags = 0;
3899   if (IFlagsStr != "none") {
3900         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
3901       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
3902         .Case("a", ARM_PROC::A)
3903         .Case("i", ARM_PROC::I)
3904         .Case("f", ARM_PROC::F)
3905         .Default(~0U);
3906
3907       // If some specific iflag is already set, it means that some letter is
3908       // present more than once, this is not acceptable.
3909       if (Flag == ~0U || (IFlags & Flag))
3910         return MatchOperand_NoMatch;
3911
3912       IFlags |= Flag;
3913     }
3914   }
3915
3916   Parser.Lex(); // Eat identifier token.
3917   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
3918   return MatchOperand_Success;
3919 }
3920
3921 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
3922 ARMAsmParser::OperandMatchResultTy
3923 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
3924   MCAsmParser &Parser = getParser();
3925   SMLoc S = Parser.getTok().getLoc();
3926   const AsmToken &Tok = Parser.getTok();
3927   if (!Tok.is(AsmToken::Identifier))
3928     return MatchOperand_NoMatch;
3929   StringRef Mask = Tok.getString();
3930
3931   if (isMClass()) {
3932     // See ARMv6-M 10.1.1
3933     std::string Name = Mask.lower();
3934     unsigned FlagsVal = StringSwitch<unsigned>(Name)
3935       // Note: in the documentation:
3936       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
3937       //  for MSR APSR_nzcvq.
3938       // but we do make it an alias here.  This is so to get the "mask encoding"
3939       // bits correct on MSR APSR writes.
3940       //
3941       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
3942       // should really only be allowed when writing a special register.  Note
3943       // they get dropped in the MRS instruction reading a special register as
3944       // the SYSm field is only 8 bits.
3945       .Case("apsr", 0x800)
3946       .Case("apsr_nzcvq", 0x800)
3947       .Case("apsr_g", 0x400)
3948       .Case("apsr_nzcvqg", 0xc00)
3949       .Case("iapsr", 0x801)
3950       .Case("iapsr_nzcvq", 0x801)
3951       .Case("iapsr_g", 0x401)
3952       .Case("iapsr_nzcvqg", 0xc01)
3953       .Case("eapsr", 0x802)
3954       .Case("eapsr_nzcvq", 0x802)
3955       .Case("eapsr_g", 0x402)
3956       .Case("eapsr_nzcvqg", 0xc02)
3957       .Case("xpsr", 0x803)
3958       .Case("xpsr_nzcvq", 0x803)
3959       .Case("xpsr_g", 0x403)
3960       .Case("xpsr_nzcvqg", 0xc03)
3961       .Case("ipsr", 0x805)
3962       .Case("epsr", 0x806)
3963       .Case("iepsr", 0x807)
3964       .Case("msp", 0x808)
3965       .Case("psp", 0x809)
3966       .Case("primask", 0x810)
3967       .Case("basepri", 0x811)
3968       .Case("basepri_max", 0x812)
3969       .Case("faultmask", 0x813)
3970       .Case("control", 0x814)
3971       .Default(~0U);
3972
3973     if (FlagsVal == ~0U)
3974       return MatchOperand_NoMatch;
3975
3976     if (!hasDSP() && (FlagsVal & 0x400))
3977       // The _g and _nzcvqg versions are only valid if the DSP extension is
3978       // available.
3979       return MatchOperand_NoMatch;
3980
3981     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
3982       // basepri, basepri_max and faultmask only valid for V7m.
3983       return MatchOperand_NoMatch;
3984
3985     Parser.Lex(); // Eat identifier token.
3986     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
3987     return MatchOperand_Success;
3988   }
3989
3990   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
3991   size_t Start = 0, Next = Mask.find('_');
3992   StringRef Flags = "";
3993   std::string SpecReg = Mask.slice(Start, Next).lower();
3994   if (Next != StringRef::npos)
3995     Flags = Mask.slice(Next+1, Mask.size());
3996
3997   // FlagsVal contains the complete mask:
3998   // 3-0: Mask
3999   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4000   unsigned FlagsVal = 0;
4001
4002   if (SpecReg == "apsr") {
4003     FlagsVal = StringSwitch<unsigned>(Flags)
4004     .Case("nzcvq",  0x8) // same as CPSR_f
4005     .Case("g",      0x4) // same as CPSR_s
4006     .Case("nzcvqg", 0xc) // same as CPSR_fs
4007     .Default(~0U);
4008
4009     if (FlagsVal == ~0U) {
4010       if (!Flags.empty())
4011         return MatchOperand_NoMatch;
4012       else
4013         FlagsVal = 8; // No flag
4014     }
4015   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4016     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4017     if (Flags == "all" || Flags == "")
4018       Flags = "fc";
4019     for (int i = 0, e = Flags.size(); i != e; ++i) {
4020       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4021       .Case("c", 1)
4022       .Case("x", 2)
4023       .Case("s", 4)
4024       .Case("f", 8)
4025       .Default(~0U);
4026
4027       // If some specific flag is already set, it means that some letter is
4028       // present more than once, this is not acceptable.
4029       if (FlagsVal == ~0U || (FlagsVal & Flag))
4030         return MatchOperand_NoMatch;
4031       FlagsVal |= Flag;
4032     }
4033   } else // No match for special register.
4034     return MatchOperand_NoMatch;
4035
4036   // Special register without flags is NOT equivalent to "fc" flags.
4037   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4038   // two lines would enable gas compatibility at the expense of breaking
4039   // round-tripping.
4040   //
4041   // if (!FlagsVal)
4042   //  FlagsVal = 0x9;
4043
4044   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4045   if (SpecReg == "spsr")
4046     FlagsVal |= 16;
4047
4048   Parser.Lex(); // Eat identifier token.
4049   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4050   return MatchOperand_Success;
4051 }
4052
4053 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4054 /// use in the MRS/MSR instructions added to support virtualization.
4055 ARMAsmParser::OperandMatchResultTy
4056 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4057   MCAsmParser &Parser = getParser();
4058   SMLoc S = Parser.getTok().getLoc();
4059   const AsmToken &Tok = Parser.getTok();
4060   if (!Tok.is(AsmToken::Identifier))
4061     return MatchOperand_NoMatch;
4062   StringRef RegName = Tok.getString();
4063
4064   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4065   // and bit 5 is R.
4066   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4067                           .Case("r8_usr", 0x00)
4068                           .Case("r9_usr", 0x01)
4069                           .Case("r10_usr", 0x02)
4070                           .Case("r11_usr", 0x03)
4071                           .Case("r12_usr", 0x04)
4072                           .Case("sp_usr", 0x05)
4073                           .Case("lr_usr", 0x06)
4074                           .Case("r8_fiq", 0x08)
4075                           .Case("r9_fiq", 0x09)
4076                           .Case("r10_fiq", 0x0a)
4077                           .Case("r11_fiq", 0x0b)
4078                           .Case("r12_fiq", 0x0c)
4079                           .Case("sp_fiq", 0x0d)
4080                           .Case("lr_fiq", 0x0e)
4081                           .Case("lr_irq", 0x10)
4082                           .Case("sp_irq", 0x11)
4083                           .Case("lr_svc", 0x12)
4084                           .Case("sp_svc", 0x13)
4085                           .Case("lr_abt", 0x14)
4086                           .Case("sp_abt", 0x15)
4087                           .Case("lr_und", 0x16)
4088                           .Case("sp_und", 0x17)
4089                           .Case("lr_mon", 0x1c)
4090                           .Case("sp_mon", 0x1d)
4091                           .Case("elr_hyp", 0x1e)
4092                           .Case("sp_hyp", 0x1f)
4093                           .Case("spsr_fiq", 0x2e)
4094                           .Case("spsr_irq", 0x30)
4095                           .Case("spsr_svc", 0x32)
4096                           .Case("spsr_abt", 0x34)
4097                           .Case("spsr_und", 0x36)
4098                           .Case("spsr_mon", 0x3c)
4099                           .Case("spsr_hyp", 0x3e)
4100                           .Default(~0U);
4101
4102   if (Encoding == ~0U)
4103     return MatchOperand_NoMatch;
4104
4105   Parser.Lex(); // Eat identifier token.
4106   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4107   return MatchOperand_Success;
4108 }
4109
4110 ARMAsmParser::OperandMatchResultTy
4111 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4112                           int High) {
4113   MCAsmParser &Parser = getParser();
4114   const AsmToken &Tok = Parser.getTok();
4115   if (Tok.isNot(AsmToken::Identifier)) {
4116     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4117     return MatchOperand_ParseFail;
4118   }
4119   StringRef ShiftName = Tok.getString();
4120   std::string LowerOp = Op.lower();
4121   std::string UpperOp = Op.upper();
4122   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4123     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4124     return MatchOperand_ParseFail;
4125   }
4126   Parser.Lex(); // Eat shift type token.
4127
4128   // There must be a '#' and a shift amount.
4129   if (Parser.getTok().isNot(AsmToken::Hash) &&
4130       Parser.getTok().isNot(AsmToken::Dollar)) {
4131     Error(Parser.getTok().getLoc(), "'#' expected");
4132     return MatchOperand_ParseFail;
4133   }
4134   Parser.Lex(); // Eat hash token.
4135
4136   const MCExpr *ShiftAmount;
4137   SMLoc Loc = Parser.getTok().getLoc();
4138   SMLoc EndLoc;
4139   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4140     Error(Loc, "illegal expression");
4141     return MatchOperand_ParseFail;
4142   }
4143   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4144   if (!CE) {
4145     Error(Loc, "constant expression expected");
4146     return MatchOperand_ParseFail;
4147   }
4148   int Val = CE->getValue();
4149   if (Val < Low || Val > High) {
4150     Error(Loc, "immediate value out of range");
4151     return MatchOperand_ParseFail;
4152   }
4153
4154   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4155
4156   return MatchOperand_Success;
4157 }
4158
4159 ARMAsmParser::OperandMatchResultTy
4160 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4161   MCAsmParser &Parser = getParser();
4162   const AsmToken &Tok = Parser.getTok();
4163   SMLoc S = Tok.getLoc();
4164   if (Tok.isNot(AsmToken::Identifier)) {
4165     Error(S, "'be' or 'le' operand expected");
4166     return MatchOperand_ParseFail;
4167   }
4168   int Val = StringSwitch<int>(Tok.getString().lower())
4169     .Case("be", 1)
4170     .Case("le", 0)
4171     .Default(-1);
4172   Parser.Lex(); // Eat the token.
4173
4174   if (Val == -1) {
4175     Error(S, "'be' or 'le' operand expected");
4176     return MatchOperand_ParseFail;
4177   }
4178   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4179                                                                   getContext()),
4180                                            S, Tok.getEndLoc()));
4181   return MatchOperand_Success;
4182 }
4183
4184 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4185 /// instructions. Legal values are:
4186 ///     lsl #n  'n' in [0,31]
4187 ///     asr #n  'n' in [1,32]
4188 ///             n == 32 encoded as n == 0.
4189 ARMAsmParser::OperandMatchResultTy
4190 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4191   MCAsmParser &Parser = getParser();
4192   const AsmToken &Tok = Parser.getTok();
4193   SMLoc S = Tok.getLoc();
4194   if (Tok.isNot(AsmToken::Identifier)) {
4195     Error(S, "shift operator 'asr' or 'lsl' expected");
4196     return MatchOperand_ParseFail;
4197   }
4198   StringRef ShiftName = Tok.getString();
4199   bool isASR;
4200   if (ShiftName == "lsl" || ShiftName == "LSL")
4201     isASR = false;
4202   else if (ShiftName == "asr" || ShiftName == "ASR")
4203     isASR = true;
4204   else {
4205     Error(S, "shift operator 'asr' or 'lsl' expected");
4206     return MatchOperand_ParseFail;
4207   }
4208   Parser.Lex(); // Eat the operator.
4209
4210   // A '#' and a shift amount.
4211   if (Parser.getTok().isNot(AsmToken::Hash) &&
4212       Parser.getTok().isNot(AsmToken::Dollar)) {
4213     Error(Parser.getTok().getLoc(), "'#' expected");
4214     return MatchOperand_ParseFail;
4215   }
4216   Parser.Lex(); // Eat hash token.
4217   SMLoc ExLoc = Parser.getTok().getLoc();
4218
4219   const MCExpr *ShiftAmount;
4220   SMLoc EndLoc;
4221   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4222     Error(ExLoc, "malformed shift expression");
4223     return MatchOperand_ParseFail;
4224   }
4225   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4226   if (!CE) {
4227     Error(ExLoc, "shift amount must be an immediate");
4228     return MatchOperand_ParseFail;
4229   }
4230
4231   int64_t Val = CE->getValue();
4232   if (isASR) {
4233     // Shift amount must be in [1,32]
4234     if (Val < 1 || Val > 32) {
4235       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4236       return MatchOperand_ParseFail;
4237     }
4238     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4239     if (isThumb() && Val == 32) {
4240       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4241       return MatchOperand_ParseFail;
4242     }
4243     if (Val == 32) Val = 0;
4244   } else {
4245     // Shift amount must be in [1,32]
4246     if (Val < 0 || Val > 31) {
4247       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4248       return MatchOperand_ParseFail;
4249     }
4250   }
4251
4252   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4253
4254   return MatchOperand_Success;
4255 }
4256
4257 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4258 /// of instructions. Legal values are:
4259 ///     ror #n  'n' in {0, 8, 16, 24}
4260 ARMAsmParser::OperandMatchResultTy
4261 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4262   MCAsmParser &Parser = getParser();
4263   const AsmToken &Tok = Parser.getTok();
4264   SMLoc S = Tok.getLoc();
4265   if (Tok.isNot(AsmToken::Identifier))
4266     return MatchOperand_NoMatch;
4267   StringRef ShiftName = Tok.getString();
4268   if (ShiftName != "ror" && ShiftName != "ROR")
4269     return MatchOperand_NoMatch;
4270   Parser.Lex(); // Eat the operator.
4271
4272   // A '#' and a rotate amount.
4273   if (Parser.getTok().isNot(AsmToken::Hash) &&
4274       Parser.getTok().isNot(AsmToken::Dollar)) {
4275     Error(Parser.getTok().getLoc(), "'#' expected");
4276     return MatchOperand_ParseFail;
4277   }
4278   Parser.Lex(); // Eat hash token.
4279   SMLoc ExLoc = Parser.getTok().getLoc();
4280
4281   const MCExpr *ShiftAmount;
4282   SMLoc EndLoc;
4283   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4284     Error(ExLoc, "malformed rotate expression");
4285     return MatchOperand_ParseFail;
4286   }
4287   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4288   if (!CE) {
4289     Error(ExLoc, "rotate amount must be an immediate");
4290     return MatchOperand_ParseFail;
4291   }
4292
4293   int64_t Val = CE->getValue();
4294   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4295   // normally, zero is represented in asm by omitting the rotate operand
4296   // entirely.
4297   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4298     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4299     return MatchOperand_ParseFail;
4300   }
4301
4302   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4303
4304   return MatchOperand_Success;
4305 }
4306
4307 ARMAsmParser::OperandMatchResultTy
4308 ARMAsmParser::parseModImm(OperandVector &Operands) {
4309   MCAsmParser &Parser = getParser();
4310   MCAsmLexer &Lexer = getLexer();
4311   int64_t Imm1, Imm2;
4312
4313   SMLoc S = Parser.getTok().getLoc();
4314
4315   // 1) A mod_imm operand can appear in the place of a register name:
4316   //   add r0, #mod_imm
4317   //   add r0, r0, #mod_imm
4318   // to correctly handle the latter, we bail out as soon as we see an
4319   // identifier.
4320   //
4321   // 2) Similarly, we do not want to parse into complex operands:
4322   //   mov r0, #mod_imm
4323   //   mov r0, :lower16:(_foo)
4324   if (Parser.getTok().is(AsmToken::Identifier) ||
4325       Parser.getTok().is(AsmToken::Colon))
4326     return MatchOperand_NoMatch;
4327
4328   // Hash (dollar) is optional as per the ARMARM
4329   if (Parser.getTok().is(AsmToken::Hash) ||
4330       Parser.getTok().is(AsmToken::Dollar)) {
4331     // Avoid parsing into complex operands (#:)
4332     if (Lexer.peekTok().is(AsmToken::Colon))
4333       return MatchOperand_NoMatch;
4334
4335     // Eat the hash (dollar)
4336     Parser.Lex();
4337   }
4338
4339   SMLoc Sx1, Ex1;
4340   Sx1 = Parser.getTok().getLoc();
4341   const MCExpr *Imm1Exp;
4342   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4343     Error(Sx1, "malformed expression");
4344     return MatchOperand_ParseFail;
4345   }
4346
4347   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4348
4349   if (CE) {
4350     // Immediate must fit within 32-bits
4351     Imm1 = CE->getValue();
4352     int Enc = ARM_AM::getSOImmVal(Imm1);
4353     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4354       // We have a match!
4355       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4356                                                   (Enc & 0xF00) >> 7,
4357                                                   Sx1, Ex1));
4358       return MatchOperand_Success;
4359     }
4360
4361     // We have parsed an immediate which is not for us, fallback to a plain
4362     // immediate. This can happen for instruction aliases. For an example,
4363     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4364     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4365     // instruction with a mod_imm operand. The alias is defined such that the
4366     // parser method is shared, that's why we have to do this here.
4367     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4368       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4369       return MatchOperand_Success;
4370     }
4371   } else {
4372     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4373     // MCFixup). Fallback to a plain immediate.
4374     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4375     return MatchOperand_Success;
4376   }
4377
4378   // From this point onward, we expect the input to be a (#bits, #rot) pair
4379   if (Parser.getTok().isNot(AsmToken::Comma)) {
4380     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4381     return MatchOperand_ParseFail;
4382   }
4383
4384   if (Imm1 & ~0xFF) {
4385     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4386     return MatchOperand_ParseFail;
4387   }
4388
4389   // Eat the comma
4390   Parser.Lex();
4391
4392   // Repeat for #rot
4393   SMLoc Sx2, Ex2;
4394   Sx2 = Parser.getTok().getLoc();
4395
4396   // Eat the optional hash (dollar)
4397   if (Parser.getTok().is(AsmToken::Hash) ||
4398       Parser.getTok().is(AsmToken::Dollar))
4399     Parser.Lex();
4400
4401   const MCExpr *Imm2Exp;
4402   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4403     Error(Sx2, "malformed expression");
4404     return MatchOperand_ParseFail;
4405   }
4406
4407   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4408
4409   if (CE) {
4410     Imm2 = CE->getValue();
4411     if (!(Imm2 & ~0x1E)) {
4412       // We have a match!
4413       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4414       return MatchOperand_Success;
4415     }
4416     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4417     return MatchOperand_ParseFail;
4418   } else {
4419     Error(Sx2, "constant expression expected");
4420     return MatchOperand_ParseFail;
4421   }
4422 }
4423
4424 ARMAsmParser::OperandMatchResultTy
4425 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4426   MCAsmParser &Parser = getParser();
4427   SMLoc S = Parser.getTok().getLoc();
4428   // The bitfield descriptor is really two operands, the LSB and the width.
4429   if (Parser.getTok().isNot(AsmToken::Hash) &&
4430       Parser.getTok().isNot(AsmToken::Dollar)) {
4431     Error(Parser.getTok().getLoc(), "'#' expected");
4432     return MatchOperand_ParseFail;
4433   }
4434   Parser.Lex(); // Eat hash token.
4435
4436   const MCExpr *LSBExpr;
4437   SMLoc E = Parser.getTok().getLoc();
4438   if (getParser().parseExpression(LSBExpr)) {
4439     Error(E, "malformed immediate expression");
4440     return MatchOperand_ParseFail;
4441   }
4442   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4443   if (!CE) {
4444     Error(E, "'lsb' operand must be an immediate");
4445     return MatchOperand_ParseFail;
4446   }
4447
4448   int64_t LSB = CE->getValue();
4449   // The LSB must be in the range [0,31]
4450   if (LSB < 0 || LSB > 31) {
4451     Error(E, "'lsb' operand must be in the range [0,31]");
4452     return MatchOperand_ParseFail;
4453   }
4454   E = Parser.getTok().getLoc();
4455
4456   // Expect another immediate operand.
4457   if (Parser.getTok().isNot(AsmToken::Comma)) {
4458     Error(Parser.getTok().getLoc(), "too few operands");
4459     return MatchOperand_ParseFail;
4460   }
4461   Parser.Lex(); // Eat hash token.
4462   if (Parser.getTok().isNot(AsmToken::Hash) &&
4463       Parser.getTok().isNot(AsmToken::Dollar)) {
4464     Error(Parser.getTok().getLoc(), "'#' expected");
4465     return MatchOperand_ParseFail;
4466   }
4467   Parser.Lex(); // Eat hash token.
4468
4469   const MCExpr *WidthExpr;
4470   SMLoc EndLoc;
4471   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4472     Error(E, "malformed immediate expression");
4473     return MatchOperand_ParseFail;
4474   }
4475   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4476   if (!CE) {
4477     Error(E, "'width' operand must be an immediate");
4478     return MatchOperand_ParseFail;
4479   }
4480
4481   int64_t Width = CE->getValue();
4482   // The LSB must be in the range [1,32-lsb]
4483   if (Width < 1 || Width > 32 - LSB) {
4484     Error(E, "'width' operand must be in the range [1,32-lsb]");
4485     return MatchOperand_ParseFail;
4486   }
4487
4488   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4489
4490   return MatchOperand_Success;
4491 }
4492
4493 ARMAsmParser::OperandMatchResultTy
4494 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4495   // Check for a post-index addressing register operand. Specifically:
4496   // postidx_reg := '+' register {, shift}
4497   //              | '-' register {, shift}
4498   //              | register {, shift}
4499
4500   // This method must return MatchOperand_NoMatch without consuming any tokens
4501   // in the case where there is no match, as other alternatives take other
4502   // parse methods.
4503   MCAsmParser &Parser = getParser();
4504   AsmToken Tok = Parser.getTok();
4505   SMLoc S = Tok.getLoc();
4506   bool haveEaten = false;
4507   bool isAdd = true;
4508   if (Tok.is(AsmToken::Plus)) {
4509     Parser.Lex(); // Eat the '+' token.
4510     haveEaten = true;
4511   } else if (Tok.is(AsmToken::Minus)) {
4512     Parser.Lex(); // Eat the '-' token.
4513     isAdd = false;
4514     haveEaten = true;
4515   }
4516
4517   SMLoc E = Parser.getTok().getEndLoc();
4518   int Reg = tryParseRegister();
4519   if (Reg == -1) {
4520     if (!haveEaten)
4521       return MatchOperand_NoMatch;
4522     Error(Parser.getTok().getLoc(), "register expected");
4523     return MatchOperand_ParseFail;
4524   }
4525
4526   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4527   unsigned ShiftImm = 0;
4528   if (Parser.getTok().is(AsmToken::Comma)) {
4529     Parser.Lex(); // Eat the ','.
4530     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4531       return MatchOperand_ParseFail;
4532
4533     // FIXME: Only approximates end...may include intervening whitespace.
4534     E = Parser.getTok().getLoc();
4535   }
4536
4537   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4538                                                   ShiftImm, S, E));
4539
4540   return MatchOperand_Success;
4541 }
4542
4543 ARMAsmParser::OperandMatchResultTy
4544 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4545   // Check for a post-index addressing register operand. Specifically:
4546   // am3offset := '+' register
4547   //              | '-' register
4548   //              | register
4549   //              | # imm
4550   //              | # + imm
4551   //              | # - imm
4552
4553   // This method must return MatchOperand_NoMatch without consuming any tokens
4554   // in the case where there is no match, as other alternatives take other
4555   // parse methods.
4556   MCAsmParser &Parser = getParser();
4557   AsmToken Tok = Parser.getTok();
4558   SMLoc S = Tok.getLoc();
4559
4560   // Do immediates first, as we always parse those if we have a '#'.
4561   if (Parser.getTok().is(AsmToken::Hash) ||
4562       Parser.getTok().is(AsmToken::Dollar)) {
4563     Parser.Lex(); // Eat '#' or '$'.
4564     // Explicitly look for a '-', as we need to encode negative zero
4565     // differently.
4566     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4567     const MCExpr *Offset;
4568     SMLoc E;
4569     if (getParser().parseExpression(Offset, E))
4570       return MatchOperand_ParseFail;
4571     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4572     if (!CE) {
4573       Error(S, "constant expression expected");
4574       return MatchOperand_ParseFail;
4575     }
4576     // Negative zero is encoded as the flag value INT32_MIN.
4577     int32_t Val = CE->getValue();
4578     if (isNegative && Val == 0)
4579       Val = INT32_MIN;
4580
4581     Operands.push_back(
4582       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4583
4584     return MatchOperand_Success;
4585   }
4586
4587
4588   bool haveEaten = false;
4589   bool isAdd = true;
4590   if (Tok.is(AsmToken::Plus)) {
4591     Parser.Lex(); // Eat the '+' token.
4592     haveEaten = true;
4593   } else if (Tok.is(AsmToken::Minus)) {
4594     Parser.Lex(); // Eat the '-' token.
4595     isAdd = false;
4596     haveEaten = true;
4597   }
4598
4599   Tok = Parser.getTok();
4600   int Reg = tryParseRegister();
4601   if (Reg == -1) {
4602     if (!haveEaten)
4603       return MatchOperand_NoMatch;
4604     Error(Tok.getLoc(), "register expected");
4605     return MatchOperand_ParseFail;
4606   }
4607
4608   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4609                                                   0, S, Tok.getEndLoc()));
4610
4611   return MatchOperand_Success;
4612 }
4613
4614 /// Convert parsed operands to MCInst.  Needed here because this instruction
4615 /// only has two register operands, but multiplication is commutative so
4616 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4617 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4618                                     const OperandVector &Operands) {
4619   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4620   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4621   // If we have a three-operand form, make sure to set Rn to be the operand
4622   // that isn't the same as Rd.
4623   unsigned RegOp = 4;
4624   if (Operands.size() == 6 &&
4625       ((ARMOperand &)*Operands[4]).getReg() ==
4626           ((ARMOperand &)*Operands[3]).getReg())
4627     RegOp = 5;
4628   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4629   Inst.addOperand(Inst.getOperand(0));
4630   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4631 }
4632
4633 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4634                                     const OperandVector &Operands) {
4635   int CondOp = -1, ImmOp = -1;
4636   switch(Inst.getOpcode()) {
4637     case ARM::tB:
4638     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4639
4640     case ARM::t2B:
4641     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4642
4643     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4644   }
4645   // first decide whether or not the branch should be conditional
4646   // by looking at it's location relative to an IT block
4647   if(inITBlock()) {
4648     // inside an IT block we cannot have any conditional branches. any 
4649     // such instructions needs to be converted to unconditional form
4650     switch(Inst.getOpcode()) {
4651       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4652       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4653     }
4654   } else {
4655     // outside IT blocks we can only have unconditional branches with AL
4656     // condition code or conditional branches with non-AL condition code
4657     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4658     switch(Inst.getOpcode()) {
4659       case ARM::tB:
4660       case ARM::tBcc: 
4661         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc); 
4662         break;
4663       case ARM::t2B:
4664       case ARM::t2Bcc: 
4665         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4666         break;
4667     }
4668   }
4669
4670   // now decide on encoding size based on branch target range
4671   switch(Inst.getOpcode()) {
4672     // classify tB as either t2B or t1B based on range of immediate operand
4673     case ARM::tB: {
4674       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4675       if (!op.isSignedOffset<11, 1>() && isThumbTwo())
4676         Inst.setOpcode(ARM::t2B);
4677       break;
4678     }
4679     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4680     case ARM::tBcc: {
4681       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4682       if (!op.isSignedOffset<8, 1>() && isThumbTwo())
4683         Inst.setOpcode(ARM::t2Bcc);
4684       break;
4685     }
4686   }
4687   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4688   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4689 }
4690
4691 /// Parse an ARM memory expression, return false if successful else return true
4692 /// or an error.  The first token must be a '[' when called.
4693 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4694   MCAsmParser &Parser = getParser();
4695   SMLoc S, E;
4696   assert(Parser.getTok().is(AsmToken::LBrac) &&
4697          "Token is not a Left Bracket");
4698   S = Parser.getTok().getLoc();
4699   Parser.Lex(); // Eat left bracket token.
4700
4701   const AsmToken &BaseRegTok = Parser.getTok();
4702   int BaseRegNum = tryParseRegister();
4703   if (BaseRegNum == -1)
4704     return Error(BaseRegTok.getLoc(), "register expected");
4705
4706   // The next token must either be a comma, a colon or a closing bracket.
4707   const AsmToken &Tok = Parser.getTok();
4708   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4709       !Tok.is(AsmToken::RBrac))
4710     return Error(Tok.getLoc(), "malformed memory operand");
4711
4712   if (Tok.is(AsmToken::RBrac)) {
4713     E = Tok.getEndLoc();
4714     Parser.Lex(); // Eat right bracket token.
4715
4716     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4717                                              ARM_AM::no_shift, 0, 0, false,
4718                                              S, E));
4719
4720     // If there's a pre-indexing writeback marker, '!', just add it as a token
4721     // operand. It's rather odd, but syntactically valid.
4722     if (Parser.getTok().is(AsmToken::Exclaim)) {
4723       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4724       Parser.Lex(); // Eat the '!'.
4725     }
4726
4727     return false;
4728   }
4729
4730   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4731          "Lost colon or comma in memory operand?!");
4732   if (Tok.is(AsmToken::Comma)) {
4733     Parser.Lex(); // Eat the comma.
4734   }
4735
4736   // If we have a ':', it's an alignment specifier.
4737   if (Parser.getTok().is(AsmToken::Colon)) {
4738     Parser.Lex(); // Eat the ':'.
4739     E = Parser.getTok().getLoc();
4740     SMLoc AlignmentLoc = Tok.getLoc();
4741
4742     const MCExpr *Expr;
4743     if (getParser().parseExpression(Expr))
4744      return true;
4745
4746     // The expression has to be a constant. Memory references with relocations
4747     // don't come through here, as they use the <label> forms of the relevant
4748     // instructions.
4749     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4750     if (!CE)
4751       return Error (E, "constant expression expected");
4752
4753     unsigned Align = 0;
4754     switch (CE->getValue()) {
4755     default:
4756       return Error(E,
4757                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4758     case 16:  Align = 2; break;
4759     case 32:  Align = 4; break;
4760     case 64:  Align = 8; break;
4761     case 128: Align = 16; break;
4762     case 256: Align = 32; break;
4763     }
4764
4765     // Now we should have the closing ']'
4766     if (Parser.getTok().isNot(AsmToken::RBrac))
4767       return Error(Parser.getTok().getLoc(), "']' expected");
4768     E = Parser.getTok().getEndLoc();
4769     Parser.Lex(); // Eat right bracket token.
4770
4771     // Don't worry about range checking the value here. That's handled by
4772     // the is*() predicates.
4773     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4774                                              ARM_AM::no_shift, 0, Align,
4775                                              false, S, E, AlignmentLoc));
4776
4777     // If there's a pre-indexing writeback marker, '!', just add it as a token
4778     // operand.
4779     if (Parser.getTok().is(AsmToken::Exclaim)) {
4780       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4781       Parser.Lex(); // Eat the '!'.
4782     }
4783
4784     return false;
4785   }
4786
4787   // If we have a '#', it's an immediate offset, else assume it's a register
4788   // offset. Be friendly and also accept a plain integer (without a leading
4789   // hash) for gas compatibility.
4790   if (Parser.getTok().is(AsmToken::Hash) ||
4791       Parser.getTok().is(AsmToken::Dollar) ||
4792       Parser.getTok().is(AsmToken::Integer)) {
4793     if (Parser.getTok().isNot(AsmToken::Integer))
4794       Parser.Lex(); // Eat '#' or '$'.
4795     E = Parser.getTok().getLoc();
4796
4797     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4798     const MCExpr *Offset;
4799     if (getParser().parseExpression(Offset))
4800      return true;
4801
4802     // The expression has to be a constant. Memory references with relocations
4803     // don't come through here, as they use the <label> forms of the relevant
4804     // instructions.
4805     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4806     if (!CE)
4807       return Error (E, "constant expression expected");
4808
4809     // If the constant was #-0, represent it as INT32_MIN.
4810     int32_t Val = CE->getValue();
4811     if (isNegative && Val == 0)
4812       CE = MCConstantExpr::create(INT32_MIN, getContext());
4813
4814     // Now we should have the closing ']'
4815     if (Parser.getTok().isNot(AsmToken::RBrac))
4816       return Error(Parser.getTok().getLoc(), "']' expected");
4817     E = Parser.getTok().getEndLoc();
4818     Parser.Lex(); // Eat right bracket token.
4819
4820     // Don't worry about range checking the value here. That's handled by
4821     // the is*() predicates.
4822     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4823                                              ARM_AM::no_shift, 0, 0,
4824                                              false, S, E));
4825
4826     // If there's a pre-indexing writeback marker, '!', just add it as a token
4827     // operand.
4828     if (Parser.getTok().is(AsmToken::Exclaim)) {
4829       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4830       Parser.Lex(); // Eat the '!'.
4831     }
4832
4833     return false;
4834   }
4835
4836   // The register offset is optionally preceded by a '+' or '-'
4837   bool isNegative = false;
4838   if (Parser.getTok().is(AsmToken::Minus)) {
4839     isNegative = true;
4840     Parser.Lex(); // Eat the '-'.
4841   } else if (Parser.getTok().is(AsmToken::Plus)) {
4842     // Nothing to do.
4843     Parser.Lex(); // Eat the '+'.
4844   }
4845
4846   E = Parser.getTok().getLoc();
4847   int OffsetRegNum = tryParseRegister();
4848   if (OffsetRegNum == -1)
4849     return Error(E, "register expected");
4850
4851   // If there's a shift operator, handle it.
4852   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4853   unsigned ShiftImm = 0;
4854   if (Parser.getTok().is(AsmToken::Comma)) {
4855     Parser.Lex(); // Eat the ','.
4856     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4857       return true;
4858   }
4859
4860   // Now we should have the closing ']'
4861   if (Parser.getTok().isNot(AsmToken::RBrac))
4862     return Error(Parser.getTok().getLoc(), "']' expected");
4863   E = Parser.getTok().getEndLoc();
4864   Parser.Lex(); // Eat right bracket token.
4865
4866   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
4867                                            ShiftType, ShiftImm, 0, isNegative,
4868                                            S, E));
4869
4870   // If there's a pre-indexing writeback marker, '!', just add it as a token
4871   // operand.
4872   if (Parser.getTok().is(AsmToken::Exclaim)) {
4873     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4874     Parser.Lex(); // Eat the '!'.
4875   }
4876
4877   return false;
4878 }
4879
4880 /// parseMemRegOffsetShift - one of these two:
4881 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4882 ///   rrx
4883 /// return true if it parses a shift otherwise it returns false.
4884 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4885                                           unsigned &Amount) {
4886   MCAsmParser &Parser = getParser();
4887   SMLoc Loc = Parser.getTok().getLoc();
4888   const AsmToken &Tok = Parser.getTok();
4889   if (Tok.isNot(AsmToken::Identifier))
4890     return true;
4891   StringRef ShiftName = Tok.getString();
4892   if (ShiftName == "lsl" || ShiftName == "LSL" ||
4893       ShiftName == "asl" || ShiftName == "ASL")
4894     St = ARM_AM::lsl;
4895   else if (ShiftName == "lsr" || ShiftName == "LSR")
4896     St = ARM_AM::lsr;
4897   else if (ShiftName == "asr" || ShiftName == "ASR")
4898     St = ARM_AM::asr;
4899   else if (ShiftName == "ror" || ShiftName == "ROR")
4900     St = ARM_AM::ror;
4901   else if (ShiftName == "rrx" || ShiftName == "RRX")
4902     St = ARM_AM::rrx;
4903   else
4904     return Error(Loc, "illegal shift operator");
4905   Parser.Lex(); // Eat shift type token.
4906
4907   // rrx stands alone.
4908   Amount = 0;
4909   if (St != ARM_AM::rrx) {
4910     Loc = Parser.getTok().getLoc();
4911     // A '#' and a shift amount.
4912     const AsmToken &HashTok = Parser.getTok();
4913     if (HashTok.isNot(AsmToken::Hash) &&
4914         HashTok.isNot(AsmToken::Dollar))
4915       return Error(HashTok.getLoc(), "'#' expected");
4916     Parser.Lex(); // Eat hash token.
4917
4918     const MCExpr *Expr;
4919     if (getParser().parseExpression(Expr))
4920       return true;
4921     // Range check the immediate.
4922     // lsl, ror: 0 <= imm <= 31
4923     // lsr, asr: 0 <= imm <= 32
4924     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4925     if (!CE)
4926       return Error(Loc, "shift amount must be an immediate");
4927     int64_t Imm = CE->getValue();
4928     if (Imm < 0 ||
4929         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
4930         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
4931       return Error(Loc, "immediate shift value out of range");
4932     // If <ShiftTy> #0, turn it into a no_shift.
4933     if (Imm == 0)
4934       St = ARM_AM::lsl;
4935     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
4936     if (Imm == 32)
4937       Imm = 0;
4938     Amount = Imm;
4939   }
4940
4941   return false;
4942 }
4943
4944 /// parseFPImm - A floating point immediate expression operand.
4945 ARMAsmParser::OperandMatchResultTy
4946 ARMAsmParser::parseFPImm(OperandVector &Operands) {
4947   MCAsmParser &Parser = getParser();
4948   // Anything that can accept a floating point constant as an operand
4949   // needs to go through here, as the regular parseExpression is
4950   // integer only.
4951   //
4952   // This routine still creates a generic Immediate operand, containing
4953   // a bitcast of the 64-bit floating point value. The various operands
4954   // that accept floats can check whether the value is valid for them
4955   // via the standard is*() predicates.
4956
4957   SMLoc S = Parser.getTok().getLoc();
4958
4959   if (Parser.getTok().isNot(AsmToken::Hash) &&
4960       Parser.getTok().isNot(AsmToken::Dollar))
4961     return MatchOperand_NoMatch;
4962
4963   // Disambiguate the VMOV forms that can accept an FP immediate.
4964   // vmov.f32 <sreg>, #imm
4965   // vmov.f64 <dreg>, #imm
4966   // vmov.f32 <dreg>, #imm  @ vector f32x2
4967   // vmov.f32 <qreg>, #imm  @ vector f32x4
4968   //
4969   // There are also the NEON VMOV instructions which expect an
4970   // integer constant. Make sure we don't try to parse an FPImm
4971   // for these:
4972   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
4973   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
4974   bool isVmovf = TyOp.isToken() &&
4975                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64");
4976   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
4977   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
4978                                          Mnemonic.getToken() == "fconsts");
4979   if (!(isVmovf || isFconst))
4980     return MatchOperand_NoMatch;
4981
4982   Parser.Lex(); // Eat '#' or '$'.
4983
4984   // Handle negation, as that still comes through as a separate token.
4985   bool isNegative = false;
4986   if (Parser.getTok().is(AsmToken::Minus)) {
4987     isNegative = true;
4988     Parser.Lex();
4989   }
4990   const AsmToken &Tok = Parser.getTok();
4991   SMLoc Loc = Tok.getLoc();
4992   if (Tok.is(AsmToken::Real) && isVmovf) {
4993     APFloat RealVal(APFloat::IEEEsingle, Tok.getString());
4994     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
4995     // If we had a '-' in front, toggle the sign bit.
4996     IntVal ^= (uint64_t)isNegative << 31;
4997     Parser.Lex(); // Eat the token.
4998     Operands.push_back(ARMOperand::CreateImm(
4999           MCConstantExpr::create(IntVal, getContext()),
5000           S, Parser.getTok().getLoc()));
5001     return MatchOperand_Success;
5002   }
5003   // Also handle plain integers. Instructions which allow floating point
5004   // immediates also allow a raw encoded 8-bit value.
5005   if (Tok.is(AsmToken::Integer) && isFconst) {
5006     int64_t Val = Tok.getIntVal();
5007     Parser.Lex(); // Eat the token.
5008     if (Val > 255 || Val < 0) {
5009       Error(Loc, "encoded floating point value out of range");
5010       return MatchOperand_ParseFail;
5011     }
5012     float RealVal = ARM_AM::getFPImmFloat(Val);
5013     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5014
5015     Operands.push_back(ARMOperand::CreateImm(
5016         MCConstantExpr::create(Val, getContext()), S,
5017         Parser.getTok().getLoc()));
5018     return MatchOperand_Success;
5019   }
5020
5021   Error(Loc, "invalid floating point immediate");
5022   return MatchOperand_ParseFail;
5023 }
5024
5025 /// Parse a arm instruction operand.  For now this parses the operand regardless
5026 /// of the mnemonic.
5027 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5028   MCAsmParser &Parser = getParser();
5029   SMLoc S, E;
5030
5031   // Check if the current operand has a custom associated parser, if so, try to
5032   // custom parse the operand, or fallback to the general approach.
5033   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5034   if (ResTy == MatchOperand_Success)
5035     return false;
5036   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5037   // there was a match, but an error occurred, in which case, just return that
5038   // the operand parsing failed.
5039   if (ResTy == MatchOperand_ParseFail)
5040     return true;
5041
5042   switch (getLexer().getKind()) {
5043   default:
5044     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5045     return true;
5046   case AsmToken::Identifier: {
5047     // If we've seen a branch mnemonic, the next operand must be a label.  This
5048     // is true even if the label is a register name.  So "br r1" means branch to
5049     // label "r1".
5050     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5051     if (!ExpectLabel) {
5052       if (!tryParseRegisterWithWriteBack(Operands))
5053         return false;
5054       int Res = tryParseShiftRegister(Operands);
5055       if (Res == 0) // success
5056         return false;
5057       else if (Res == -1) // irrecoverable error
5058         return true;
5059       // If this is VMRS, check for the apsr_nzcv operand.
5060       if (Mnemonic == "vmrs" &&
5061           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5062         S = Parser.getTok().getLoc();
5063         Parser.Lex();
5064         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5065         return false;
5066       }
5067     }
5068
5069     // Fall though for the Identifier case that is not a register or a
5070     // special name.
5071   }
5072   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5073   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5074   case AsmToken::String:  // quoted label names.
5075   case AsmToken::Dot: {   // . as a branch target
5076     // This was not a register so parse other operands that start with an
5077     // identifier (like labels) as expressions and create them as immediates.
5078     const MCExpr *IdVal;
5079     S = Parser.getTok().getLoc();
5080     if (getParser().parseExpression(IdVal))
5081       return true;
5082     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5083     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5084     return false;
5085   }
5086   case AsmToken::LBrac:
5087     return parseMemory(Operands);
5088   case AsmToken::LCurly:
5089     return parseRegisterList(Operands);
5090   case AsmToken::Dollar:
5091   case AsmToken::Hash: {
5092     // #42 -> immediate.
5093     S = Parser.getTok().getLoc();
5094     Parser.Lex();
5095
5096     if (Parser.getTok().isNot(AsmToken::Colon)) {
5097       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5098       const MCExpr *ImmVal;
5099       if (getParser().parseExpression(ImmVal))
5100         return true;
5101       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5102       if (CE) {
5103         int32_t Val = CE->getValue();
5104         if (isNegative && Val == 0)
5105           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5106       }
5107       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5108       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5109
5110       // There can be a trailing '!' on operands that we want as a separate
5111       // '!' Token operand. Handle that here. For example, the compatibility
5112       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5113       if (Parser.getTok().is(AsmToken::Exclaim)) {
5114         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5115                                                    Parser.getTok().getLoc()));
5116         Parser.Lex(); // Eat exclaim token
5117       }
5118       return false;
5119     }
5120     // w/ a ':' after the '#', it's just like a plain ':'.
5121     // FALLTHROUGH
5122   }
5123   case AsmToken::Colon: {
5124     // ":lower16:" and ":upper16:" expression prefixes
5125     // FIXME: Check it's an expression prefix,
5126     // e.g. (FOO - :lower16:BAR) isn't legal.
5127     ARMMCExpr::VariantKind RefKind;
5128     if (parsePrefix(RefKind))
5129       return true;
5130
5131     const MCExpr *SubExprVal;
5132     if (getParser().parseExpression(SubExprVal))
5133       return true;
5134
5135     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5136                                               getContext());
5137     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5138     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5139     return false;
5140   }
5141   case AsmToken::Equal: {
5142     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5143       return Error(Parser.getTok().getLoc(), "unexpected token in operand");
5144
5145     Parser.Lex(); // Eat '='
5146     const MCExpr *SubExprVal;
5147     if (getParser().parseExpression(SubExprVal))
5148       return true;
5149     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5150
5151     const MCExpr *CPLoc = getTargetStreamer().addConstantPoolEntry(SubExprVal);
5152     Operands.push_back(ARMOperand::CreateImm(CPLoc, S, E));
5153     return false;
5154   }
5155   }
5156 }
5157
5158 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5159 //  :lower16: and :upper16:.
5160 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5161   MCAsmParser &Parser = getParser();
5162   RefKind = ARMMCExpr::VK_ARM_None;
5163
5164   // consume an optional '#' (GNU compatibility)
5165   if (getLexer().is(AsmToken::Hash))
5166     Parser.Lex();
5167
5168   // :lower16: and :upper16: modifiers
5169   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5170   Parser.Lex(); // Eat ':'
5171
5172   if (getLexer().isNot(AsmToken::Identifier)) {
5173     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5174     return true;
5175   }
5176
5177   enum {
5178     COFF = (1 << MCObjectFileInfo::IsCOFF),
5179     ELF = (1 << MCObjectFileInfo::IsELF),
5180     MACHO = (1 << MCObjectFileInfo::IsMachO)
5181   };
5182   static const struct PrefixEntry {
5183     const char *Spelling;
5184     ARMMCExpr::VariantKind VariantKind;
5185     uint8_t SupportedFormats;
5186   } PrefixEntries[] = {
5187     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5188     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5189   };
5190
5191   StringRef IDVal = Parser.getTok().getIdentifier();
5192
5193   const auto &Prefix =
5194       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5195                    [&IDVal](const PrefixEntry &PE) {
5196                       return PE.Spelling == IDVal;
5197                    });
5198   if (Prefix == std::end(PrefixEntries)) {
5199     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5200     return true;
5201   }
5202
5203   uint8_t CurrentFormat;
5204   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5205   case MCObjectFileInfo::IsMachO:
5206     CurrentFormat = MACHO;
5207     break;
5208   case MCObjectFileInfo::IsELF:
5209     CurrentFormat = ELF;
5210     break;
5211   case MCObjectFileInfo::IsCOFF:
5212     CurrentFormat = COFF;
5213     break;
5214   }
5215
5216   if (~Prefix->SupportedFormats & CurrentFormat) {
5217     Error(Parser.getTok().getLoc(),
5218           "cannot represent relocation in the current file format");
5219     return true;
5220   }
5221
5222   RefKind = Prefix->VariantKind;
5223   Parser.Lex();
5224
5225   if (getLexer().isNot(AsmToken::Colon)) {
5226     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5227     return true;
5228   }
5229   Parser.Lex(); // Eat the last ':'
5230
5231   return false;
5232 }
5233
5234 /// \brief Given a mnemonic, split out possible predication code and carry
5235 /// setting letters to form a canonical mnemonic and flags.
5236 //
5237 // FIXME: Would be nice to autogen this.
5238 // FIXME: This is a bit of a maze of special cases.
5239 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5240                                       unsigned &PredicationCode,
5241                                       bool &CarrySetting,
5242                                       unsigned &ProcessorIMod,
5243                                       StringRef &ITMask) {
5244   PredicationCode = ARMCC::AL;
5245   CarrySetting = false;
5246   ProcessorIMod = 0;
5247
5248   // Ignore some mnemonics we know aren't predicated forms.
5249   //
5250   // FIXME: Would be nice to autogen this.
5251   if ((Mnemonic == "movs" && isThumb()) ||
5252       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5253       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5254       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5255       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5256       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5257       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5258       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5259       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5260       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5261       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5262       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5263       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5264       Mnemonic.startswith("vsel"))
5265     return Mnemonic;
5266
5267   // First, split out any predication code. Ignore mnemonics we know aren't
5268   // predicated but do have a carry-set and so weren't caught above.
5269   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5270       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5271       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5272       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5273     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5274       .Case("eq", ARMCC::EQ)
5275       .Case("ne", ARMCC::NE)
5276       .Case("hs", ARMCC::HS)
5277       .Case("cs", ARMCC::HS)
5278       .Case("lo", ARMCC::LO)
5279       .Case("cc", ARMCC::LO)
5280       .Case("mi", ARMCC::MI)
5281       .Case("pl", ARMCC::PL)
5282       .Case("vs", ARMCC::VS)
5283       .Case("vc", ARMCC::VC)
5284       .Case("hi", ARMCC::HI)
5285       .Case("ls", ARMCC::LS)
5286       .Case("ge", ARMCC::GE)
5287       .Case("lt", ARMCC::LT)
5288       .Case("gt", ARMCC::GT)
5289       .Case("le", ARMCC::LE)
5290       .Case("al", ARMCC::AL)
5291       .Default(~0U);
5292     if (CC != ~0U) {
5293       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5294       PredicationCode = CC;
5295     }
5296   }
5297
5298   // Next, determine if we have a carry setting bit. We explicitly ignore all
5299   // the instructions we know end in 's'.
5300   if (Mnemonic.endswith("s") &&
5301       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5302         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5303         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5304         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5305         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5306         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5307         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5308         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5309         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5310         (Mnemonic == "movs" && isThumb()))) {
5311     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5312     CarrySetting = true;
5313   }
5314
5315   // The "cps" instruction can have a interrupt mode operand which is glued into
5316   // the mnemonic. Check if this is the case, split it and parse the imod op
5317   if (Mnemonic.startswith("cps")) {
5318     // Split out any imod code.
5319     unsigned IMod =
5320       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5321       .Case("ie", ARM_PROC::IE)
5322       .Case("id", ARM_PROC::ID)
5323       .Default(~0U);
5324     if (IMod != ~0U) {
5325       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5326       ProcessorIMod = IMod;
5327     }
5328   }
5329
5330   // The "it" instruction has the condition mask on the end of the mnemonic.
5331   if (Mnemonic.startswith("it")) {
5332     ITMask = Mnemonic.slice(2, Mnemonic.size());
5333     Mnemonic = Mnemonic.slice(0, 2);
5334   }
5335
5336   return Mnemonic;
5337 }
5338
5339 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5340 /// inclusion of carry set or predication code operands.
5341 //
5342 // FIXME: It would be nice to autogen this.
5343 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5344                                          bool &CanAcceptCarrySet,
5345                                          bool &CanAcceptPredicationCode) {
5346   CanAcceptCarrySet =
5347       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5348       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5349       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5350       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5351       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5352       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5353       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5354       (!isThumb() &&
5355        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5356         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5357
5358   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5359       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5360       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5361       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5362       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5363       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5364       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5365       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5366       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5367       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5368       (FullInst.startswith("vmull") && FullInst.endswith(".p64"))) {
5369     // These mnemonics are never predicable
5370     CanAcceptPredicationCode = false;
5371   } else if (!isThumb()) {
5372     // Some instructions are only predicable in Thumb mode
5373     CanAcceptPredicationCode =
5374         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5375         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5376         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5377         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5378         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5379         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5380         !Mnemonic.startswith("srs");
5381   } else if (isThumbOne()) {
5382     if (hasV6MOps())
5383       CanAcceptPredicationCode = Mnemonic != "movs";
5384     else
5385       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5386   } else
5387     CanAcceptPredicationCode = true;
5388 }
5389
5390 // \brief Some Thumb instructions have two operand forms that are not
5391 // available as three operand, convert to two operand form if possible.
5392 //
5393 // FIXME: We would really like to be able to tablegen'erate this.
5394 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5395                                                  bool CarrySetting,
5396                                                  OperandVector &Operands) {
5397   if (Operands.size() != 6)
5398     return;
5399
5400   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5401         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5402   if (!Op3.isReg() || !Op4.isReg())
5403     return;
5404
5405   auto Op3Reg = Op3.getReg();
5406   auto Op4Reg = Op4.getReg();
5407
5408   // For most Thumb2 cases we just generate the 3 operand form and reduce
5409   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5410   // won't accept SP or PC so we do the transformation here taking care
5411   // with immediate range in the 'add sp, sp #imm' case.
5412   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5413   if (isThumbTwo()) {
5414     if (Mnemonic != "add")
5415       return;
5416     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5417                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5418     if (!TryTransform) {
5419       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5420                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5421                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5422                        Op5.isImm() && !Op5.isImm0_508s4());
5423     }
5424     if (!TryTransform)
5425       return;
5426   } else if (!isThumbOne())
5427     return;
5428
5429   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5430         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5431         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5432         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5433     return;
5434
5435   // If first 2 operands of a 3 operand instruction are the same
5436   // then transform to 2 operand version of the same instruction
5437   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5438   bool Transform = Op3Reg == Op4Reg;
5439
5440   // For communtative operations, we might be able to transform if we swap
5441   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5442   // as tADDrsp.
5443   const ARMOperand *LastOp = &Op5;
5444   bool Swap = false;
5445   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5446       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5447        Mnemonic == "and" || Mnemonic == "eor" ||
5448        Mnemonic == "adc" || Mnemonic == "orr")) {
5449     Swap = true;
5450     LastOp = &Op4;
5451     Transform = true;
5452   }
5453
5454   // If both registers are the same then remove one of them from
5455   // the operand list, with certain exceptions.
5456   if (Transform) {
5457     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5458     // 2 operand forms don't exist.
5459     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5460         LastOp->isReg())
5461       Transform = false;
5462
5463     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5464     // 3-bits because the ARMARM says not to.
5465     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5466       Transform = false;
5467   }
5468
5469   if (Transform) {
5470     if (Swap)
5471       std::swap(Op4, Op5);
5472     Operands.erase(Operands.begin() + 3);
5473   }
5474 }
5475
5476 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5477                                           OperandVector &Operands) {
5478   // FIXME: This is all horribly hacky. We really need a better way to deal
5479   // with optional operands like this in the matcher table.
5480
5481   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5482   // another does not. Specifically, the MOVW instruction does not. So we
5483   // special case it here and remove the defaulted (non-setting) cc_out
5484   // operand if that's the instruction we're trying to match.
5485   //
5486   // We do this as post-processing of the explicit operands rather than just
5487   // conditionally adding the cc_out in the first place because we need
5488   // to check the type of the parsed immediate operand.
5489   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5490       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5491       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5492       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5493     return true;
5494
5495   // Register-register 'add' for thumb does not have a cc_out operand
5496   // when there are only two register operands.
5497   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5498       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5499       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5500       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5501     return true;
5502   // Register-register 'add' for thumb does not have a cc_out operand
5503   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5504   // have to check the immediate range here since Thumb2 has a variant
5505   // that can handle a different range and has a cc_out operand.
5506   if (((isThumb() && Mnemonic == "add") ||
5507        (isThumbTwo() && Mnemonic == "sub")) &&
5508       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5509       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5510       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5511       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5512       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5513        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5514     return true;
5515   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5516   // imm0_4095 variant. That's the least-preferred variant when
5517   // selecting via the generic "add" mnemonic, so to know that we
5518   // should remove the cc_out operand, we have to explicitly check that
5519   // it's not one of the other variants. Ugh.
5520   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5521       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5522       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5523       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5524     // Nest conditions rather than one big 'if' statement for readability.
5525     //
5526     // If both registers are low, we're in an IT block, and the immediate is
5527     // in range, we should use encoding T1 instead, which has a cc_out.
5528     if (inITBlock() &&
5529         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5530         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5531         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5532       return false;
5533     // Check against T3. If the second register is the PC, this is an
5534     // alternate form of ADR, which uses encoding T4, so check for that too.
5535     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5536         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5537       return false;
5538
5539     // Otherwise, we use encoding T4, which does not have a cc_out
5540     // operand.
5541     return true;
5542   }
5543
5544   // The thumb2 multiply instruction doesn't have a CCOut register, so
5545   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5546   // use the 16-bit encoding or not.
5547   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5548       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5549       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5550       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5551       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5552       // If the registers aren't low regs, the destination reg isn't the
5553       // same as one of the source regs, or the cc_out operand is zero
5554       // outside of an IT block, we have to use the 32-bit encoding, so
5555       // remove the cc_out operand.
5556       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5557        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5558        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5559        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5560                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5561                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5562                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5563     return true;
5564
5565   // Also check the 'mul' syntax variant that doesn't specify an explicit
5566   // destination register.
5567   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5568       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5569       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5570       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5571       // If the registers aren't low regs  or the cc_out operand is zero
5572       // outside of an IT block, we have to use the 32-bit encoding, so
5573       // remove the cc_out operand.
5574       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5575        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5576        !inITBlock()))
5577     return true;
5578
5579
5580
5581   // Register-register 'add/sub' for thumb does not have a cc_out operand
5582   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5583   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5584   // right, this will result in better diagnostics (which operand is off)
5585   // anyway.
5586   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5587       (Operands.size() == 5 || Operands.size() == 6) &&
5588       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5589       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5590       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5591       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5592        (Operands.size() == 6 &&
5593         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5594     return true;
5595
5596   return false;
5597 }
5598
5599 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5600                                               OperandVector &Operands) {
5601   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5602   unsigned RegIdx = 3;
5603   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5604       static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32") {
5605     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5606         static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32")
5607       RegIdx = 4;
5608
5609     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5610         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5611              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5612          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5613              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5614       return true;
5615   }
5616   return false;
5617 }
5618
5619 static bool isDataTypeToken(StringRef Tok) {
5620   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5621     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5622     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5623     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5624     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5625     Tok == ".f" || Tok == ".d";
5626 }
5627
5628 // FIXME: This bit should probably be handled via an explicit match class
5629 // in the .td files that matches the suffix instead of having it be
5630 // a literal string token the way it is now.
5631 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5632   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5633 }
5634 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5635                                  unsigned VariantID);
5636
5637 static bool RequiresVFPRegListValidation(StringRef Inst,
5638                                          bool &AcceptSinglePrecisionOnly,
5639                                          bool &AcceptDoublePrecisionOnly) {
5640   if (Inst.size() < 7)
5641     return false;
5642
5643   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5644     StringRef AddressingMode = Inst.substr(4, 2);
5645     if (AddressingMode == "ia" || AddressingMode == "db" ||
5646         AddressingMode == "ea" || AddressingMode == "fd") {
5647       AcceptSinglePrecisionOnly = Inst[6] == 's';
5648       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5649       return true;
5650     }
5651   }
5652
5653   return false;
5654 }
5655
5656 /// Parse an arm instruction mnemonic followed by its operands.
5657 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5658                                     SMLoc NameLoc, OperandVector &Operands) {
5659   MCAsmParser &Parser = getParser();
5660   // FIXME: Can this be done via tablegen in some fashion?
5661   bool RequireVFPRegisterListCheck;
5662   bool AcceptSinglePrecisionOnly;
5663   bool AcceptDoublePrecisionOnly;
5664   RequireVFPRegisterListCheck =
5665     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5666                                  AcceptDoublePrecisionOnly);
5667
5668   // Apply mnemonic aliases before doing anything else, as the destination
5669   // mnemonic may include suffices and we want to handle them normally.
5670   // The generic tblgen'erated code does this later, at the start of
5671   // MatchInstructionImpl(), but that's too late for aliases that include
5672   // any sort of suffix.
5673   uint64_t AvailableFeatures = getAvailableFeatures();
5674   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5675   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5676
5677   // First check for the ARM-specific .req directive.
5678   if (Parser.getTok().is(AsmToken::Identifier) &&
5679       Parser.getTok().getIdentifier() == ".req") {
5680     parseDirectiveReq(Name, NameLoc);
5681     // We always return 'error' for this, as we're done with this
5682     // statement and don't need to match the 'instruction."
5683     return true;
5684   }
5685
5686   // Create the leading tokens for the mnemonic, split by '.' characters.
5687   size_t Start = 0, Next = Name.find('.');
5688   StringRef Mnemonic = Name.slice(Start, Next);
5689
5690   // Split out the predication code and carry setting flag from the mnemonic.
5691   unsigned PredicationCode;
5692   unsigned ProcessorIMod;
5693   bool CarrySetting;
5694   StringRef ITMask;
5695   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5696                            ProcessorIMod, ITMask);
5697
5698   // In Thumb1, only the branch (B) instruction can be predicated.
5699   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5700     Parser.eatToEndOfStatement();
5701     return Error(NameLoc, "conditional execution not supported in Thumb1");
5702   }
5703
5704   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5705
5706   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5707   // is the mask as it will be for the IT encoding if the conditional
5708   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5709   // where the conditional bit0 is zero, the instruction post-processing
5710   // will adjust the mask accordingly.
5711   if (Mnemonic == "it") {
5712     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5713     if (ITMask.size() > 3) {
5714       Parser.eatToEndOfStatement();
5715       return Error(Loc, "too many conditions on IT instruction");
5716     }
5717     unsigned Mask = 8;
5718     for (unsigned i = ITMask.size(); i != 0; --i) {
5719       char pos = ITMask[i - 1];
5720       if (pos != 't' && pos != 'e') {
5721         Parser.eatToEndOfStatement();
5722         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5723       }
5724       Mask >>= 1;
5725       if (ITMask[i - 1] == 't')
5726         Mask |= 8;
5727     }
5728     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5729   }
5730
5731   // FIXME: This is all a pretty gross hack. We should automatically handle
5732   // optional operands like this via tblgen.
5733
5734   // Next, add the CCOut and ConditionCode operands, if needed.
5735   //
5736   // For mnemonics which can ever incorporate a carry setting bit or predication
5737   // code, our matching model involves us always generating CCOut and
5738   // ConditionCode operands to match the mnemonic "as written" and then we let
5739   // the matcher deal with finding the right instruction or generating an
5740   // appropriate error.
5741   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5742   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5743
5744   // If we had a carry-set on an instruction that can't do that, issue an
5745   // error.
5746   if (!CanAcceptCarrySet && CarrySetting) {
5747     Parser.eatToEndOfStatement();
5748     return Error(NameLoc, "instruction '" + Mnemonic +
5749                  "' can not set flags, but 's' suffix specified");
5750   }
5751   // If we had a predication code on an instruction that can't do that, issue an
5752   // error.
5753   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5754     Parser.eatToEndOfStatement();
5755     return Error(NameLoc, "instruction '" + Mnemonic +
5756                  "' is not predicable, but condition code specified");
5757   }
5758
5759   // Add the carry setting operand, if necessary.
5760   if (CanAcceptCarrySet) {
5761     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5762     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5763                                                Loc));
5764   }
5765
5766   // Add the predication code operand, if necessary.
5767   if (CanAcceptPredicationCode) {
5768     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5769                                       CarrySetting);
5770     Operands.push_back(ARMOperand::CreateCondCode(
5771                          ARMCC::CondCodes(PredicationCode), Loc));
5772   }
5773
5774   // Add the processor imod operand, if necessary.
5775   if (ProcessorIMod) {
5776     Operands.push_back(ARMOperand::CreateImm(
5777           MCConstantExpr::create(ProcessorIMod, getContext()),
5778                                  NameLoc, NameLoc));
5779   } else if (Mnemonic == "cps" && isMClass()) {
5780     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5781   }
5782
5783   // Add the remaining tokens in the mnemonic.
5784   while (Next != StringRef::npos) {
5785     Start = Next;
5786     Next = Name.find('.', Start + 1);
5787     StringRef ExtraToken = Name.slice(Start, Next);
5788
5789     // Some NEON instructions have an optional datatype suffix that is
5790     // completely ignored. Check for that.
5791     if (isDataTypeToken(ExtraToken) &&
5792         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5793       continue;
5794
5795     // For for ARM mode generate an error if the .n qualifier is used.
5796     if (ExtraToken == ".n" && !isThumb()) {
5797       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5798       Parser.eatToEndOfStatement();
5799       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5800                    "arm mode");
5801     }
5802
5803     // The .n qualifier is always discarded as that is what the tables
5804     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5805     // so discard it to avoid errors that can be caused by the matcher.
5806     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5807       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5808       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5809     }
5810   }
5811
5812   // Read the remaining operands.
5813   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5814     // Read the first operand.
5815     if (parseOperand(Operands, Mnemonic)) {
5816       Parser.eatToEndOfStatement();
5817       return true;
5818     }
5819
5820     while (getLexer().is(AsmToken::Comma)) {
5821       Parser.Lex();  // Eat the comma.
5822
5823       // Parse and remember the operand.
5824       if (parseOperand(Operands, Mnemonic)) {
5825         Parser.eatToEndOfStatement();
5826         return true;
5827       }
5828     }
5829   }
5830
5831   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5832     SMLoc Loc = getLexer().getLoc();
5833     Parser.eatToEndOfStatement();
5834     return Error(Loc, "unexpected token in argument list");
5835   }
5836
5837   Parser.Lex(); // Consume the EndOfStatement
5838
5839   if (RequireVFPRegisterListCheck) {
5840     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5841     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5842       return Error(Op.getStartLoc(),
5843                    "VFP/Neon single precision register expected");
5844     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5845       return Error(Op.getStartLoc(),
5846                    "VFP/Neon double precision register expected");
5847   }
5848
5849   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
5850
5851   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5852   // do and don't have a cc_out optional-def operand. With some spot-checks
5853   // of the operand list, we can figure out which variant we're trying to
5854   // parse and adjust accordingly before actually matching. We shouldn't ever
5855   // try to remove a cc_out operand that was explicitly set on the
5856   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5857   // table driven matcher doesn't fit well with the ARM instruction set.
5858   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
5859     Operands.erase(Operands.begin() + 1);
5860
5861   // Some instructions have the same mnemonic, but don't always
5862   // have a predicate. Distinguish them here and delete the
5863   // predicate if needed.
5864   if (shouldOmitPredicateOperand(Mnemonic, Operands))
5865     Operands.erase(Operands.begin() + 1);
5866
5867   // ARM mode 'blx' need special handling, as the register operand version
5868   // is predicable, but the label operand version is not. So, we can't rely
5869   // on the Mnemonic based checking to correctly figure out when to put
5870   // a k_CondCode operand in the list. If we're trying to match the label
5871   // version, remove the k_CondCode operand here.
5872   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
5873       static_cast<ARMOperand &>(*Operands[2]).isImm())
5874     Operands.erase(Operands.begin() + 1);
5875
5876   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
5877   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
5878   // a single GPRPair reg operand is used in the .td file to replace the two
5879   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
5880   // expressed as a GPRPair, so we have to manually merge them.
5881   // FIXME: We would really like to be able to tablegen'erate this.
5882   if (!isThumb() && Operands.size() > 4 &&
5883       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
5884        Mnemonic == "stlexd")) {
5885     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
5886     unsigned Idx = isLoad ? 2 : 3;
5887     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
5888     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
5889
5890     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
5891     // Adjust only if Op1 and Op2 are GPRs.
5892     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
5893         MRC.contains(Op2.getReg())) {
5894       unsigned Reg1 = Op1.getReg();
5895       unsigned Reg2 = Op2.getReg();
5896       unsigned Rt = MRI->getEncodingValue(Reg1);
5897       unsigned Rt2 = MRI->getEncodingValue(Reg2);
5898
5899       // Rt2 must be Rt + 1 and Rt must be even.
5900       if (Rt + 1 != Rt2 || (Rt & 1)) {
5901         Error(Op2.getStartLoc(), isLoad
5902                                      ? "destination operands must be sequential"
5903                                      : "source operands must be sequential");
5904         return true;
5905       }
5906       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
5907           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
5908       Operands[Idx] =
5909           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
5910       Operands.erase(Operands.begin() + Idx + 1);
5911     }
5912   }
5913
5914   // GNU Assembler extension (compatibility)
5915   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
5916     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5917     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5918     if (Op3.isMem()) {
5919       assert(Op2.isReg() && "expected register argument");
5920
5921       unsigned SuperReg = MRI->getMatchingSuperReg(
5922           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
5923
5924       assert(SuperReg && "expected register pair");
5925
5926       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
5927
5928       Operands.insert(
5929           Operands.begin() + 3,
5930           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
5931     }
5932   }
5933
5934   // FIXME: As said above, this is all a pretty gross hack.  This instruction
5935   // does not fit with other "subs" and tblgen.
5936   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
5937   // so the Mnemonic is the original name "subs" and delete the predicate
5938   // operand so it will match the table entry.
5939   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
5940       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5941       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
5942       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5943       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
5944       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5945     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
5946     Operands.erase(Operands.begin() + 1);
5947   }
5948   return false;
5949 }
5950
5951 // Validate context-sensitive operand constraints.
5952
5953 // return 'true' if register list contains non-low GPR registers,
5954 // 'false' otherwise. If Reg is in the register list or is HiReg, set
5955 // 'containsReg' to true.
5956 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
5957                                  unsigned Reg, unsigned HiReg,
5958                                  bool &containsReg) {
5959   containsReg = false;
5960   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
5961     unsigned OpReg = Inst.getOperand(i).getReg();
5962     if (OpReg == Reg)
5963       containsReg = true;
5964     // Anything other than a low register isn't legal here.
5965     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
5966       return true;
5967   }
5968   return false;
5969 }
5970
5971 // Check if the specified regisgter is in the register list of the inst,
5972 // starting at the indicated operand number.
5973 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
5974   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
5975     unsigned OpReg = Inst.getOperand(i).getReg();
5976     if (OpReg == Reg)
5977       return true;
5978   }
5979   return false;
5980 }
5981
5982 // Return true if instruction has the interesting property of being
5983 // allowed in IT blocks, but not being predicable.
5984 static bool instIsBreakpoint(const MCInst &Inst) {
5985     return Inst.getOpcode() == ARM::tBKPT ||
5986            Inst.getOpcode() == ARM::BKPT ||
5987            Inst.getOpcode() == ARM::tHLT ||
5988            Inst.getOpcode() == ARM::HLT;
5989
5990 }
5991
5992 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
5993                                        const OperandVector &Operands,
5994                                        unsigned ListNo, bool IsARPop) {
5995   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
5996   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
5997
5998   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
5999   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6000   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6001
6002   if (!IsARPop && ListContainsSP)
6003     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6004                  "SP may not be in the register list");
6005   else if (ListContainsPC && ListContainsLR)
6006     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6007                  "PC and LR may not be in the register list simultaneously");
6008   else if (inITBlock() && !lastInITBlock() && ListContainsPC)
6009     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6010                  "instruction must be outside of IT block or the last "
6011                  "instruction in an IT block");
6012   return false;
6013 }
6014
6015 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6016                                        const OperandVector &Operands,
6017                                        unsigned ListNo) {
6018   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6019   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6020
6021   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6022   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6023
6024   if (ListContainsSP && ListContainsPC)
6025     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6026                  "SP and PC may not be in the register list");
6027   else if (ListContainsSP)
6028     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6029                  "SP may not be in the register list");
6030   else if (ListContainsPC)
6031     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6032                  "PC may not be in the register list");
6033   return false;
6034 }
6035
6036 // FIXME: We would really like to be able to tablegen'erate this.
6037 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6038                                        const OperandVector &Operands) {
6039   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6040   SMLoc Loc = Operands[0]->getStartLoc();
6041
6042   // Check the IT block state first.
6043   // NOTE: BKPT and HLT instructions have the interesting property of being
6044   // allowed in IT blocks, but not being predicable. They just always execute.
6045   if (inITBlock() && !instIsBreakpoint(Inst)) {
6046     unsigned Bit = 1;
6047     if (ITState.FirstCond)
6048       ITState.FirstCond = false;
6049     else
6050       Bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
6051     // The instruction must be predicable.
6052     if (!MCID.isPredicable())
6053       return Error(Loc, "instructions in IT block must be predicable");
6054     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6055     unsigned ITCond = Bit ? ITState.Cond :
6056       ARMCC::getOppositeCondition(ITState.Cond);
6057     if (Cond != ITCond) {
6058       // Find the condition code Operand to get its SMLoc information.
6059       SMLoc CondLoc;
6060       for (unsigned I = 1; I < Operands.size(); ++I)
6061         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6062           CondLoc = Operands[I]->getStartLoc();
6063       return Error(CondLoc, "incorrect condition in IT block; got '" +
6064                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6065                    "', but expected '" +
6066                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
6067     }
6068   // Check for non-'al' condition codes outside of the IT block.
6069   } else if (isThumbTwo() && MCID.isPredicable() &&
6070              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6071              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6072              Inst.getOpcode() != ARM::t2Bcc)
6073     return Error(Loc, "predicated instructions must be in IT block");
6074
6075   const unsigned Opcode = Inst.getOpcode();
6076   switch (Opcode) {
6077   case ARM::LDRD:
6078   case ARM::LDRD_PRE:
6079   case ARM::LDRD_POST: {
6080     const unsigned RtReg = Inst.getOperand(0).getReg();
6081
6082     // Rt can't be R14.
6083     if (RtReg == ARM::LR)
6084       return Error(Operands[3]->getStartLoc(),
6085                    "Rt can't be R14");
6086
6087     const unsigned Rt = MRI->getEncodingValue(RtReg);
6088     // Rt must be even-numbered.
6089     if ((Rt & 1) == 1)
6090       return Error(Operands[3]->getStartLoc(),
6091                    "Rt must be even-numbered");
6092
6093     // Rt2 must be Rt + 1.
6094     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6095     if (Rt2 != Rt + 1)
6096       return Error(Operands[3]->getStartLoc(),
6097                    "destination operands must be sequential");
6098
6099     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6100       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6101       // For addressing modes with writeback, the base register needs to be
6102       // different from the destination registers.
6103       if (Rn == Rt || Rn == Rt2)
6104         return Error(Operands[3]->getStartLoc(),
6105                      "base register needs to be different from destination "
6106                      "registers");
6107     }
6108
6109     return false;
6110   }
6111   case ARM::t2LDRDi8:
6112   case ARM::t2LDRD_PRE:
6113   case ARM::t2LDRD_POST: {
6114     // Rt2 must be different from Rt.
6115     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6116     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6117     if (Rt2 == Rt)
6118       return Error(Operands[3]->getStartLoc(),
6119                    "destination operands can't be identical");
6120     return false;
6121   }
6122   case ARM::t2BXJ: {
6123     const unsigned RmReg = Inst.getOperand(0).getReg();
6124     // Rm = SP is no longer unpredictable in v8-A
6125     if (RmReg == ARM::SP && !hasV8Ops())
6126       return Error(Operands[2]->getStartLoc(),
6127                    "r13 (SP) is an unpredictable operand to BXJ");
6128     return false;
6129   }
6130   case ARM::STRD: {
6131     // Rt2 must be Rt + 1.
6132     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6133     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6134     if (Rt2 != Rt + 1)
6135       return Error(Operands[3]->getStartLoc(),
6136                    "source operands must be sequential");
6137     return false;
6138   }
6139   case ARM::STRD_PRE:
6140   case ARM::STRD_POST: {
6141     // Rt2 must be Rt + 1.
6142     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6143     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6144     if (Rt2 != Rt + 1)
6145       return Error(Operands[3]->getStartLoc(),
6146                    "source operands must be sequential");
6147     return false;
6148   }
6149   case ARM::STR_PRE_IMM:
6150   case ARM::STR_PRE_REG:
6151   case ARM::STR_POST_IMM:
6152   case ARM::STR_POST_REG:
6153   case ARM::STRH_PRE:
6154   case ARM::STRH_POST:
6155   case ARM::STRB_PRE_IMM:
6156   case ARM::STRB_PRE_REG:
6157   case ARM::STRB_POST_IMM:
6158   case ARM::STRB_POST_REG: {
6159     // Rt must be different from Rn.
6160     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6161     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6162
6163     if (Rt == Rn)
6164       return Error(Operands[3]->getStartLoc(),
6165                    "source register and base register can't be identical");
6166     return false;
6167   }
6168   case ARM::LDR_PRE_IMM:
6169   case ARM::LDR_PRE_REG:
6170   case ARM::LDR_POST_IMM:
6171   case ARM::LDR_POST_REG:
6172   case ARM::LDRH_PRE:
6173   case ARM::LDRH_POST:
6174   case ARM::LDRSH_PRE:
6175   case ARM::LDRSH_POST:
6176   case ARM::LDRB_PRE_IMM:
6177   case ARM::LDRB_PRE_REG:
6178   case ARM::LDRB_POST_IMM:
6179   case ARM::LDRB_POST_REG:
6180   case ARM::LDRSB_PRE:
6181   case ARM::LDRSB_POST: {
6182     // Rt must be different from Rn.
6183     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6184     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6185
6186     if (Rt == Rn)
6187       return Error(Operands[3]->getStartLoc(),
6188                    "destination register and base register can't be identical");
6189     return false;
6190   }
6191   case ARM::SBFX:
6192   case ARM::UBFX: {
6193     // Width must be in range [1, 32-lsb].
6194     unsigned LSB = Inst.getOperand(2).getImm();
6195     unsigned Widthm1 = Inst.getOperand(3).getImm();
6196     if (Widthm1 >= 32 - LSB)
6197       return Error(Operands[5]->getStartLoc(),
6198                    "bitfield width must be in range [1,32-lsb]");
6199     return false;
6200   }
6201   // Notionally handles ARM::tLDMIA_UPD too.
6202   case ARM::tLDMIA: {
6203     // If we're parsing Thumb2, the .w variant is available and handles
6204     // most cases that are normally illegal for a Thumb1 LDM instruction.
6205     // We'll make the transformation in processInstruction() if necessary.
6206     //
6207     // Thumb LDM instructions are writeback iff the base register is not
6208     // in the register list.
6209     unsigned Rn = Inst.getOperand(0).getReg();
6210     bool HasWritebackToken =
6211         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6212          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6213     bool ListContainsBase;
6214     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6215       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6216                    "registers must be in range r0-r7");
6217     // If we should have writeback, then there should be a '!' token.
6218     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6219       return Error(Operands[2]->getStartLoc(),
6220                    "writeback operator '!' expected");
6221     // If we should not have writeback, there must not be a '!'. This is
6222     // true even for the 32-bit wide encodings.
6223     if (ListContainsBase && HasWritebackToken)
6224       return Error(Operands[3]->getStartLoc(),
6225                    "writeback operator '!' not allowed when base register "
6226                    "in register list");
6227
6228     if (validatetLDMRegList(Inst, Operands, 3))
6229       return true;
6230     break;
6231   }
6232   case ARM::LDMIA_UPD:
6233   case ARM::LDMDB_UPD:
6234   case ARM::LDMIB_UPD:
6235   case ARM::LDMDA_UPD:
6236     // ARM variants loading and updating the same register are only officially
6237     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6238     if (!hasV7Ops())
6239       break;
6240     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6241       return Error(Operands.back()->getStartLoc(),
6242                    "writeback register not allowed in register list");
6243     break;
6244   case ARM::t2LDMIA:
6245   case ARM::t2LDMDB:
6246     if (validatetLDMRegList(Inst, Operands, 3))
6247       return true;
6248     break;
6249   case ARM::t2STMIA:
6250   case ARM::t2STMDB:
6251     if (validatetSTMRegList(Inst, Operands, 3))
6252       return true;
6253     break;
6254   case ARM::t2LDMIA_UPD:
6255   case ARM::t2LDMDB_UPD:
6256   case ARM::t2STMIA_UPD:
6257   case ARM::t2STMDB_UPD: {
6258     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6259       return Error(Operands.back()->getStartLoc(),
6260                    "writeback register not allowed in register list");
6261
6262     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6263       if (validatetLDMRegList(Inst, Operands, 3))
6264         return true;
6265     } else {
6266       if (validatetSTMRegList(Inst, Operands, 3))
6267         return true;
6268     }
6269     break;
6270   }
6271   case ARM::sysLDMIA_UPD:
6272   case ARM::sysLDMDA_UPD:
6273   case ARM::sysLDMDB_UPD:
6274   case ARM::sysLDMIB_UPD:
6275     if (!listContainsReg(Inst, 3, ARM::PC))
6276       return Error(Operands[4]->getStartLoc(),
6277                    "writeback register only allowed on system LDM "
6278                    "if PC in register-list");
6279     break;
6280   case ARM::sysSTMIA_UPD:
6281   case ARM::sysSTMDA_UPD:
6282   case ARM::sysSTMDB_UPD:
6283   case ARM::sysSTMIB_UPD:
6284     return Error(Operands[2]->getStartLoc(),
6285                  "system STM cannot have writeback register");
6286   case ARM::tMUL: {
6287     // The second source operand must be the same register as the destination
6288     // operand.
6289     //
6290     // In this case, we must directly check the parsed operands because the
6291     // cvtThumbMultiply() function is written in such a way that it guarantees
6292     // this first statement is always true for the new Inst.  Essentially, the
6293     // destination is unconditionally copied into the second source operand
6294     // without checking to see if it matches what we actually parsed.
6295     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6296                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6297         (((ARMOperand &)*Operands[3]).getReg() !=
6298          ((ARMOperand &)*Operands[4]).getReg())) {
6299       return Error(Operands[3]->getStartLoc(),
6300                    "destination register must match source register");
6301     }
6302     break;
6303   }
6304   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6305   // so only issue a diagnostic for thumb1. The instructions will be
6306   // switched to the t2 encodings in processInstruction() if necessary.
6307   case ARM::tPOP: {
6308     bool ListContainsBase;
6309     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6310         !isThumbTwo())
6311       return Error(Operands[2]->getStartLoc(),
6312                    "registers must be in range r0-r7 or pc");
6313     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6314       return true;
6315     break;
6316   }
6317   case ARM::tPUSH: {
6318     bool ListContainsBase;
6319     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6320         !isThumbTwo())
6321       return Error(Operands[2]->getStartLoc(),
6322                    "registers must be in range r0-r7 or lr");
6323     if (validatetSTMRegList(Inst, Operands, 2))
6324       return true;
6325     break;
6326   }
6327   case ARM::tSTMIA_UPD: {
6328     bool ListContainsBase, InvalidLowList;
6329     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6330                                           0, ListContainsBase);
6331     if (InvalidLowList && !isThumbTwo())
6332       return Error(Operands[4]->getStartLoc(),
6333                    "registers must be in range r0-r7");
6334
6335     // This would be converted to a 32-bit stm, but that's not valid if the
6336     // writeback register is in the list.
6337     if (InvalidLowList && ListContainsBase)
6338       return Error(Operands[4]->getStartLoc(),
6339                    "writeback operator '!' not allowed when base register "
6340                    "in register list");
6341
6342     if (validatetSTMRegList(Inst, Operands, 4))
6343       return true;
6344     break;
6345   }
6346   case ARM::tADDrSP: {
6347     // If the non-SP source operand and the destination operand are not the
6348     // same, we need thumb2 (for the wide encoding), or we have an error.
6349     if (!isThumbTwo() &&
6350         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6351       return Error(Operands[4]->getStartLoc(),
6352                    "source register must be the same as destination");
6353     }
6354     break;
6355   }
6356   // Final range checking for Thumb unconditional branch instructions.
6357   case ARM::tB:
6358     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6359       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6360     break;
6361   case ARM::t2B: {
6362     int op = (Operands[2]->isImm()) ? 2 : 3;
6363     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6364       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6365     break;
6366   }
6367   // Final range checking for Thumb conditional branch instructions.
6368   case ARM::tBcc:
6369     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6370       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6371     break;
6372   case ARM::t2Bcc: {
6373     int Op = (Operands[2]->isImm()) ? 2 : 3;
6374     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6375       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6376     break;
6377   }
6378   case ARM::MOVi16:
6379   case ARM::t2MOVi16:
6380   case ARM::t2MOVTi16:
6381     {
6382     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6383     // especially when we turn it into a movw and the expression <symbol> does
6384     // not have a :lower16: or :upper16 as part of the expression.  We don't
6385     // want the behavior of silently truncating, which can be unexpected and
6386     // lead to bugs that are difficult to find since this is an easy mistake
6387     // to make.
6388     int i = (Operands[3]->isImm()) ? 3 : 4;
6389     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6390     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6391     if (CE) break;
6392     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6393     if (!E) break;
6394     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6395     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6396                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6397       return Error(
6398           Op.getStartLoc(),
6399           "immediate expression for mov requires :lower16: or :upper16");
6400     break;
6401   }
6402   }
6403
6404   return false;
6405 }
6406
6407 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6408   switch(Opc) {
6409   default: llvm_unreachable("unexpected opcode!");
6410   // VST1LN
6411   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6412   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6413   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6414   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6415   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6416   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6417   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6418   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6419   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6420
6421   // VST2LN
6422   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6423   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6424   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6425   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6426   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6427
6428   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6429   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6430   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6431   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6432   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6433
6434   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6435   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6436   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6437   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6438   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6439
6440   // VST3LN
6441   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6442   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6443   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6444   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6445   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6446   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6447   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6448   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6449   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6450   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6451   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6452   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6453   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6454   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6455   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6456
6457   // VST3
6458   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6459   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6460   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6461   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6462   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6463   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6464   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6465   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6466   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6467   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6468   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6469   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6470   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6471   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6472   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6473   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6474   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6475   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6476
6477   // VST4LN
6478   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6479   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6480   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6481   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6482   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6483   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6484   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6485   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6486   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6487   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6488   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6489   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6490   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6491   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6492   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6493
6494   // VST4
6495   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6496   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6497   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6498   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6499   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6500   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6501   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6502   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6503   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6504   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6505   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6506   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6507   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6508   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6509   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6510   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6511   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6512   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6513   }
6514 }
6515
6516 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6517   switch(Opc) {
6518   default: llvm_unreachable("unexpected opcode!");
6519   // VLD1LN
6520   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6521   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6522   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6523   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6524   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6525   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6526   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6527   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6528   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6529
6530   // VLD2LN
6531   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6532   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6533   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6534   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6535   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6536   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6537   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6538   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6539   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6540   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6541   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6542   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6543   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6544   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6545   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6546
6547   // VLD3DUP
6548   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6549   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6550   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6551   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6552   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6553   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6554   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6555   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6556   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6557   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6558   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6559   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6560   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6561   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6562   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6563   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6564   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6565   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6566
6567   // VLD3LN
6568   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6569   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6570   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6571   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6572   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6573   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6574   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6575   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6576   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6577   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6578   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6579   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6580   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6581   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6582   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6583
6584   // VLD3
6585   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6586   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6587   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6588   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6589   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6590   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6591   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6592   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6593   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6594   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6595   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6596   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6597   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6598   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6599   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6600   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6601   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6602   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6603
6604   // VLD4LN
6605   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6606   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6607   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6608   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6609   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6610   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6611   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6612   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6613   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6614   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6615   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6616   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6617   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6618   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6619   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6620
6621   // VLD4DUP
6622   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6623   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6624   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6625   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6626   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6627   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6628   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6629   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6630   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6631   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6632   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6633   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6634   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6635   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6636   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6637   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6638   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6639   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6640
6641   // VLD4
6642   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6643   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6644   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6645   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6646   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6647   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6648   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6649   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6650   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6651   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6652   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6653   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6654   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6655   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6656   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6657   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6658   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6659   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6660   }
6661 }
6662
6663 bool ARMAsmParser::processInstruction(MCInst &Inst,
6664                                       const OperandVector &Operands,
6665                                       MCStreamer &Out) {
6666   switch (Inst.getOpcode()) {
6667   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6668   case ARM::LDRT_POST:
6669   case ARM::LDRBT_POST: {
6670     const unsigned Opcode =
6671       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6672                                            : ARM::LDRBT_POST_IMM;
6673     MCInst TmpInst;
6674     TmpInst.setOpcode(Opcode);
6675     TmpInst.addOperand(Inst.getOperand(0));
6676     TmpInst.addOperand(Inst.getOperand(1));
6677     TmpInst.addOperand(Inst.getOperand(1));
6678     TmpInst.addOperand(MCOperand::createReg(0));
6679     TmpInst.addOperand(MCOperand::createImm(0));
6680     TmpInst.addOperand(Inst.getOperand(2));
6681     TmpInst.addOperand(Inst.getOperand(3));
6682     Inst = TmpInst;
6683     return true;
6684   }
6685   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6686   case ARM::STRT_POST:
6687   case ARM::STRBT_POST: {
6688     const unsigned Opcode =
6689       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6690                                            : ARM::STRBT_POST_IMM;
6691     MCInst TmpInst;
6692     TmpInst.setOpcode(Opcode);
6693     TmpInst.addOperand(Inst.getOperand(1));
6694     TmpInst.addOperand(Inst.getOperand(0));
6695     TmpInst.addOperand(Inst.getOperand(1));
6696     TmpInst.addOperand(MCOperand::createReg(0));
6697     TmpInst.addOperand(MCOperand::createImm(0));
6698     TmpInst.addOperand(Inst.getOperand(2));
6699     TmpInst.addOperand(Inst.getOperand(3));
6700     Inst = TmpInst;
6701     return true;
6702   }
6703   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6704   case ARM::ADDri: {
6705     if (Inst.getOperand(1).getReg() != ARM::PC ||
6706         Inst.getOperand(5).getReg() != 0 ||
6707         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6708       return false;
6709     MCInst TmpInst;
6710     TmpInst.setOpcode(ARM::ADR);
6711     TmpInst.addOperand(Inst.getOperand(0));
6712     if (Inst.getOperand(2).isImm()) {
6713       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6714       // before passing it to the ADR instruction.
6715       unsigned Enc = Inst.getOperand(2).getImm();
6716       TmpInst.addOperand(MCOperand::createImm(
6717         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6718     } else {
6719       // Turn PC-relative expression into absolute expression.
6720       // Reading PC provides the start of the current instruction + 8 and
6721       // the transform to adr is biased by that.
6722       MCSymbol *Dot = getContext().createTempSymbol();
6723       Out.EmitLabel(Dot);
6724       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6725       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6726                                                      MCSymbolRefExpr::VK_None,
6727                                                      getContext());
6728       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6729       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6730                                                      getContext());
6731       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6732                                                         getContext());
6733       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6734     }
6735     TmpInst.addOperand(Inst.getOperand(3));
6736     TmpInst.addOperand(Inst.getOperand(4));
6737     Inst = TmpInst;
6738     return true;
6739   }
6740   // Aliases for alternate PC+imm syntax of LDR instructions.
6741   case ARM::t2LDRpcrel:
6742     // Select the narrow version if the immediate will fit.
6743     if (Inst.getOperand(1).getImm() > 0 &&
6744         Inst.getOperand(1).getImm() <= 0xff &&
6745         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6746           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
6747       Inst.setOpcode(ARM::tLDRpci);
6748     else
6749       Inst.setOpcode(ARM::t2LDRpci);
6750     return true;
6751   case ARM::t2LDRBpcrel:
6752     Inst.setOpcode(ARM::t2LDRBpci);
6753     return true;
6754   case ARM::t2LDRHpcrel:
6755     Inst.setOpcode(ARM::t2LDRHpci);
6756     return true;
6757   case ARM::t2LDRSBpcrel:
6758     Inst.setOpcode(ARM::t2LDRSBpci);
6759     return true;
6760   case ARM::t2LDRSHpcrel:
6761     Inst.setOpcode(ARM::t2LDRSHpci);
6762     return true;
6763   // Handle NEON VST complex aliases.
6764   case ARM::VST1LNdWB_register_Asm_8:
6765   case ARM::VST1LNdWB_register_Asm_16:
6766   case ARM::VST1LNdWB_register_Asm_32: {
6767     MCInst TmpInst;
6768     // Shuffle the operands around so the lane index operand is in the
6769     // right place.
6770     unsigned Spacing;
6771     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6772     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6773     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6774     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6775     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6776     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6777     TmpInst.addOperand(Inst.getOperand(1)); // lane
6778     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6779     TmpInst.addOperand(Inst.getOperand(6));
6780     Inst = TmpInst;
6781     return true;
6782   }
6783
6784   case ARM::VST2LNdWB_register_Asm_8:
6785   case ARM::VST2LNdWB_register_Asm_16:
6786   case ARM::VST2LNdWB_register_Asm_32:
6787   case ARM::VST2LNqWB_register_Asm_16:
6788   case ARM::VST2LNqWB_register_Asm_32: {
6789     MCInst TmpInst;
6790     // Shuffle the operands around so the lane index operand is in the
6791     // right place.
6792     unsigned Spacing;
6793     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6794     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6795     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6796     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6797     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6798     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6799     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6800                                             Spacing));
6801     TmpInst.addOperand(Inst.getOperand(1)); // lane
6802     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6803     TmpInst.addOperand(Inst.getOperand(6));
6804     Inst = TmpInst;
6805     return true;
6806   }
6807
6808   case ARM::VST3LNdWB_register_Asm_8:
6809   case ARM::VST3LNdWB_register_Asm_16:
6810   case ARM::VST3LNdWB_register_Asm_32:
6811   case ARM::VST3LNqWB_register_Asm_16:
6812   case ARM::VST3LNqWB_register_Asm_32: {
6813     MCInst TmpInst;
6814     // Shuffle the operands around so the lane index operand is in the
6815     // right place.
6816     unsigned Spacing;
6817     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6818     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6819     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6820     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6821     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6822     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6823     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6824                                             Spacing));
6825     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6826                                             Spacing * 2));
6827     TmpInst.addOperand(Inst.getOperand(1)); // lane
6828     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6829     TmpInst.addOperand(Inst.getOperand(6));
6830     Inst = TmpInst;
6831     return true;
6832   }
6833
6834   case ARM::VST4LNdWB_register_Asm_8:
6835   case ARM::VST4LNdWB_register_Asm_16:
6836   case ARM::VST4LNdWB_register_Asm_32:
6837   case ARM::VST4LNqWB_register_Asm_16:
6838   case ARM::VST4LNqWB_register_Asm_32: {
6839     MCInst TmpInst;
6840     // Shuffle the operands around so the lane index operand is in the
6841     // right place.
6842     unsigned Spacing;
6843     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6844     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6845     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6846     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6847     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6848     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6849     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6850                                             Spacing));
6851     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6852                                             Spacing * 2));
6853     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6854                                             Spacing * 3));
6855     TmpInst.addOperand(Inst.getOperand(1)); // lane
6856     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6857     TmpInst.addOperand(Inst.getOperand(6));
6858     Inst = TmpInst;
6859     return true;
6860   }
6861
6862   case ARM::VST1LNdWB_fixed_Asm_8:
6863   case ARM::VST1LNdWB_fixed_Asm_16:
6864   case ARM::VST1LNdWB_fixed_Asm_32: {
6865     MCInst TmpInst;
6866     // Shuffle the operands around so the lane index operand is in the
6867     // right place.
6868     unsigned Spacing;
6869     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6870     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6871     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6872     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6873     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6874     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6875     TmpInst.addOperand(Inst.getOperand(1)); // lane
6876     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6877     TmpInst.addOperand(Inst.getOperand(5));
6878     Inst = TmpInst;
6879     return true;
6880   }
6881
6882   case ARM::VST2LNdWB_fixed_Asm_8:
6883   case ARM::VST2LNdWB_fixed_Asm_16:
6884   case ARM::VST2LNdWB_fixed_Asm_32:
6885   case ARM::VST2LNqWB_fixed_Asm_16:
6886   case ARM::VST2LNqWB_fixed_Asm_32: {
6887     MCInst TmpInst;
6888     // Shuffle the operands around so the lane index operand is in the
6889     // right place.
6890     unsigned Spacing;
6891     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6892     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6893     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6894     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6895     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6896     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6897     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6898                                             Spacing));
6899     TmpInst.addOperand(Inst.getOperand(1)); // lane
6900     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6901     TmpInst.addOperand(Inst.getOperand(5));
6902     Inst = TmpInst;
6903     return true;
6904   }
6905
6906   case ARM::VST3LNdWB_fixed_Asm_8:
6907   case ARM::VST3LNdWB_fixed_Asm_16:
6908   case ARM::VST3LNdWB_fixed_Asm_32:
6909   case ARM::VST3LNqWB_fixed_Asm_16:
6910   case ARM::VST3LNqWB_fixed_Asm_32: {
6911     MCInst TmpInst;
6912     // Shuffle the operands around so the lane index operand is in the
6913     // right place.
6914     unsigned Spacing;
6915     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6916     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6917     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6918     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6919     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6920     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6921     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6922                                             Spacing));
6923     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6924                                             Spacing * 2));
6925     TmpInst.addOperand(Inst.getOperand(1)); // lane
6926     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6927     TmpInst.addOperand(Inst.getOperand(5));
6928     Inst = TmpInst;
6929     return true;
6930   }
6931
6932   case ARM::VST4LNdWB_fixed_Asm_8:
6933   case ARM::VST4LNdWB_fixed_Asm_16:
6934   case ARM::VST4LNdWB_fixed_Asm_32:
6935   case ARM::VST4LNqWB_fixed_Asm_16:
6936   case ARM::VST4LNqWB_fixed_Asm_32: {
6937     MCInst TmpInst;
6938     // Shuffle the operands around so the lane index operand is in the
6939     // right place.
6940     unsigned Spacing;
6941     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6942     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6943     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6944     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6945     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6946     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6947     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6948                                             Spacing));
6949     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6950                                             Spacing * 2));
6951     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6952                                             Spacing * 3));
6953     TmpInst.addOperand(Inst.getOperand(1)); // lane
6954     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6955     TmpInst.addOperand(Inst.getOperand(5));
6956     Inst = TmpInst;
6957     return true;
6958   }
6959
6960   case ARM::VST1LNdAsm_8:
6961   case ARM::VST1LNdAsm_16:
6962   case ARM::VST1LNdAsm_32: {
6963     MCInst TmpInst;
6964     // Shuffle the operands around so the lane index operand is in the
6965     // right place.
6966     unsigned Spacing;
6967     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6968     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6969     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6970     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6971     TmpInst.addOperand(Inst.getOperand(1)); // lane
6972     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6973     TmpInst.addOperand(Inst.getOperand(5));
6974     Inst = TmpInst;
6975     return true;
6976   }
6977
6978   case ARM::VST2LNdAsm_8:
6979   case ARM::VST2LNdAsm_16:
6980   case ARM::VST2LNdAsm_32:
6981   case ARM::VST2LNqAsm_16:
6982   case ARM::VST2LNqAsm_32: {
6983     MCInst TmpInst;
6984     // Shuffle the operands around so the lane index operand is in the
6985     // right place.
6986     unsigned Spacing;
6987     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6988     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6989     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6990     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6991     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6992                                             Spacing));
6993     TmpInst.addOperand(Inst.getOperand(1)); // lane
6994     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6995     TmpInst.addOperand(Inst.getOperand(5));
6996     Inst = TmpInst;
6997     return true;
6998   }
6999
7000   case ARM::VST3LNdAsm_8:
7001   case ARM::VST3LNdAsm_16:
7002   case ARM::VST3LNdAsm_32:
7003   case ARM::VST3LNqAsm_16:
7004   case ARM::VST3LNqAsm_32: {
7005     MCInst TmpInst;
7006     // Shuffle the operands around so the lane index operand is in the
7007     // right place.
7008     unsigned Spacing;
7009     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7010     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7011     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7012     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7013     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7014                                             Spacing));
7015     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7016                                             Spacing * 2));
7017     TmpInst.addOperand(Inst.getOperand(1)); // lane
7018     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7019     TmpInst.addOperand(Inst.getOperand(5));
7020     Inst = TmpInst;
7021     return true;
7022   }
7023
7024   case ARM::VST4LNdAsm_8:
7025   case ARM::VST4LNdAsm_16:
7026   case ARM::VST4LNdAsm_32:
7027   case ARM::VST4LNqAsm_16:
7028   case ARM::VST4LNqAsm_32: {
7029     MCInst TmpInst;
7030     // Shuffle the operands around so the lane index operand is in the
7031     // right place.
7032     unsigned Spacing;
7033     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7034     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7035     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7036     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7037     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7038                                             Spacing));
7039     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7040                                             Spacing * 2));
7041     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7042                                             Spacing * 3));
7043     TmpInst.addOperand(Inst.getOperand(1)); // lane
7044     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7045     TmpInst.addOperand(Inst.getOperand(5));
7046     Inst = TmpInst;
7047     return true;
7048   }
7049
7050   // Handle NEON VLD complex aliases.
7051   case ARM::VLD1LNdWB_register_Asm_8:
7052   case ARM::VLD1LNdWB_register_Asm_16:
7053   case ARM::VLD1LNdWB_register_Asm_32: {
7054     MCInst TmpInst;
7055     // Shuffle the operands around so the lane index operand is in the
7056     // right place.
7057     unsigned Spacing;
7058     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7059     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7060     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7061     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7062     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7063     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7064     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7065     TmpInst.addOperand(Inst.getOperand(1)); // lane
7066     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7067     TmpInst.addOperand(Inst.getOperand(6));
7068     Inst = TmpInst;
7069     return true;
7070   }
7071
7072   case ARM::VLD2LNdWB_register_Asm_8:
7073   case ARM::VLD2LNdWB_register_Asm_16:
7074   case ARM::VLD2LNdWB_register_Asm_32:
7075   case ARM::VLD2LNqWB_register_Asm_16:
7076   case ARM::VLD2LNqWB_register_Asm_32: {
7077     MCInst TmpInst;
7078     // Shuffle the operands around so the lane index operand is in the
7079     // right place.
7080     unsigned Spacing;
7081     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7082     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7083     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7084                                             Spacing));
7085     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7086     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7087     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7088     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7089     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7090     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7091                                             Spacing));
7092     TmpInst.addOperand(Inst.getOperand(1)); // lane
7093     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7094     TmpInst.addOperand(Inst.getOperand(6));
7095     Inst = TmpInst;
7096     return true;
7097   }
7098
7099   case ARM::VLD3LNdWB_register_Asm_8:
7100   case ARM::VLD3LNdWB_register_Asm_16:
7101   case ARM::VLD3LNdWB_register_Asm_32:
7102   case ARM::VLD3LNqWB_register_Asm_16:
7103   case ARM::VLD3LNqWB_register_Asm_32: {
7104     MCInst TmpInst;
7105     // Shuffle the operands around so the lane index operand is in the
7106     // right place.
7107     unsigned Spacing;
7108     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7109     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7110     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7111                                             Spacing));
7112     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7113                                             Spacing * 2));
7114     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7115     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7116     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7117     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7118     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7119     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7120                                             Spacing));
7121     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7122                                             Spacing * 2));
7123     TmpInst.addOperand(Inst.getOperand(1)); // lane
7124     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7125     TmpInst.addOperand(Inst.getOperand(6));
7126     Inst = TmpInst;
7127     return true;
7128   }
7129
7130   case ARM::VLD4LNdWB_register_Asm_8:
7131   case ARM::VLD4LNdWB_register_Asm_16:
7132   case ARM::VLD4LNdWB_register_Asm_32:
7133   case ARM::VLD4LNqWB_register_Asm_16:
7134   case ARM::VLD4LNqWB_register_Asm_32: {
7135     MCInst TmpInst;
7136     // Shuffle the operands around so the lane index operand is in the
7137     // right place.
7138     unsigned Spacing;
7139     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7140     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7141     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7142                                             Spacing));
7143     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7144                                             Spacing * 2));
7145     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7146                                             Spacing * 3));
7147     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7148     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7149     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7150     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7151     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7152     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7153                                             Spacing));
7154     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7155                                             Spacing * 2));
7156     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7157                                             Spacing * 3));
7158     TmpInst.addOperand(Inst.getOperand(1)); // lane
7159     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7160     TmpInst.addOperand(Inst.getOperand(6));
7161     Inst = TmpInst;
7162     return true;
7163   }
7164
7165   case ARM::VLD1LNdWB_fixed_Asm_8:
7166   case ARM::VLD1LNdWB_fixed_Asm_16:
7167   case ARM::VLD1LNdWB_fixed_Asm_32: {
7168     MCInst TmpInst;
7169     // Shuffle the operands around so the lane index operand is in the
7170     // right place.
7171     unsigned Spacing;
7172     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7173     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7174     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7175     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7176     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7177     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7178     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7179     TmpInst.addOperand(Inst.getOperand(1)); // lane
7180     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7181     TmpInst.addOperand(Inst.getOperand(5));
7182     Inst = TmpInst;
7183     return true;
7184   }
7185
7186   case ARM::VLD2LNdWB_fixed_Asm_8:
7187   case ARM::VLD2LNdWB_fixed_Asm_16:
7188   case ARM::VLD2LNdWB_fixed_Asm_32:
7189   case ARM::VLD2LNqWB_fixed_Asm_16:
7190   case ARM::VLD2LNqWB_fixed_Asm_32: {
7191     MCInst TmpInst;
7192     // Shuffle the operands around so the lane index operand is in the
7193     // right place.
7194     unsigned Spacing;
7195     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7196     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7197     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7198                                             Spacing));
7199     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7200     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7201     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7202     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7203     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7204     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7205                                             Spacing));
7206     TmpInst.addOperand(Inst.getOperand(1)); // lane
7207     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7208     TmpInst.addOperand(Inst.getOperand(5));
7209     Inst = TmpInst;
7210     return true;
7211   }
7212
7213   case ARM::VLD3LNdWB_fixed_Asm_8:
7214   case ARM::VLD3LNdWB_fixed_Asm_16:
7215   case ARM::VLD3LNdWB_fixed_Asm_32:
7216   case ARM::VLD3LNqWB_fixed_Asm_16:
7217   case ARM::VLD3LNqWB_fixed_Asm_32: {
7218     MCInst TmpInst;
7219     // Shuffle the operands around so the lane index operand is in the
7220     // right place.
7221     unsigned Spacing;
7222     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7223     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7224     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7225                                             Spacing));
7226     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7227                                             Spacing * 2));
7228     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7229     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7230     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7231     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7232     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7233     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7234                                             Spacing));
7235     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7236                                             Spacing * 2));
7237     TmpInst.addOperand(Inst.getOperand(1)); // lane
7238     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7239     TmpInst.addOperand(Inst.getOperand(5));
7240     Inst = TmpInst;
7241     return true;
7242   }
7243
7244   case ARM::VLD4LNdWB_fixed_Asm_8:
7245   case ARM::VLD4LNdWB_fixed_Asm_16:
7246   case ARM::VLD4LNdWB_fixed_Asm_32:
7247   case ARM::VLD4LNqWB_fixed_Asm_16:
7248   case ARM::VLD4LNqWB_fixed_Asm_32: {
7249     MCInst TmpInst;
7250     // Shuffle the operands around so the lane index operand is in the
7251     // right place.
7252     unsigned Spacing;
7253     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7254     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7255     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7256                                             Spacing));
7257     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7258                                             Spacing * 2));
7259     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7260                                             Spacing * 3));
7261     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7262     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7263     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7264     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7265     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7266     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7267                                             Spacing));
7268     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7269                                             Spacing * 2));
7270     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7271                                             Spacing * 3));
7272     TmpInst.addOperand(Inst.getOperand(1)); // lane
7273     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7274     TmpInst.addOperand(Inst.getOperand(5));
7275     Inst = TmpInst;
7276     return true;
7277   }
7278
7279   case ARM::VLD1LNdAsm_8:
7280   case ARM::VLD1LNdAsm_16:
7281   case ARM::VLD1LNdAsm_32: {
7282     MCInst TmpInst;
7283     // Shuffle the operands around so the lane index operand is in the
7284     // right place.
7285     unsigned Spacing;
7286     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7287     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7288     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7289     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7290     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7291     TmpInst.addOperand(Inst.getOperand(1)); // lane
7292     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7293     TmpInst.addOperand(Inst.getOperand(5));
7294     Inst = TmpInst;
7295     return true;
7296   }
7297
7298   case ARM::VLD2LNdAsm_8:
7299   case ARM::VLD2LNdAsm_16:
7300   case ARM::VLD2LNdAsm_32:
7301   case ARM::VLD2LNqAsm_16:
7302   case ARM::VLD2LNqAsm_32: {
7303     MCInst TmpInst;
7304     // Shuffle the operands around so the lane index operand is in the
7305     // right place.
7306     unsigned Spacing;
7307     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7308     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7309     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7310                                             Spacing));
7311     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7312     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7313     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7314     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7315                                             Spacing));
7316     TmpInst.addOperand(Inst.getOperand(1)); // lane
7317     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7318     TmpInst.addOperand(Inst.getOperand(5));
7319     Inst = TmpInst;
7320     return true;
7321   }
7322
7323   case ARM::VLD3LNdAsm_8:
7324   case ARM::VLD3LNdAsm_16:
7325   case ARM::VLD3LNdAsm_32:
7326   case ARM::VLD3LNqAsm_16:
7327   case ARM::VLD3LNqAsm_32: {
7328     MCInst TmpInst;
7329     // Shuffle the operands around so the lane index operand is in the
7330     // right place.
7331     unsigned Spacing;
7332     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7333     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7334     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7335                                             Spacing));
7336     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7337                                             Spacing * 2));
7338     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7339     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7340     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7341     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7342                                             Spacing));
7343     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7344                                             Spacing * 2));
7345     TmpInst.addOperand(Inst.getOperand(1)); // lane
7346     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7347     TmpInst.addOperand(Inst.getOperand(5));
7348     Inst = TmpInst;
7349     return true;
7350   }
7351
7352   case ARM::VLD4LNdAsm_8:
7353   case ARM::VLD4LNdAsm_16:
7354   case ARM::VLD4LNdAsm_32:
7355   case ARM::VLD4LNqAsm_16:
7356   case ARM::VLD4LNqAsm_32: {
7357     MCInst TmpInst;
7358     // Shuffle the operands around so the lane index operand is in the
7359     // right place.
7360     unsigned Spacing;
7361     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7362     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7363     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7364                                             Spacing));
7365     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7366                                             Spacing * 2));
7367     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7368                                             Spacing * 3));
7369     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7370     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7371     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7372     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7373                                             Spacing));
7374     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7375                                             Spacing * 2));
7376     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7377                                             Spacing * 3));
7378     TmpInst.addOperand(Inst.getOperand(1)); // lane
7379     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7380     TmpInst.addOperand(Inst.getOperand(5));
7381     Inst = TmpInst;
7382     return true;
7383   }
7384
7385   // VLD3DUP single 3-element structure to all lanes instructions.
7386   case ARM::VLD3DUPdAsm_8:
7387   case ARM::VLD3DUPdAsm_16:
7388   case ARM::VLD3DUPdAsm_32:
7389   case ARM::VLD3DUPqAsm_8:
7390   case ARM::VLD3DUPqAsm_16:
7391   case ARM::VLD3DUPqAsm_32: {
7392     MCInst TmpInst;
7393     unsigned Spacing;
7394     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7395     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7396     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7397                                             Spacing));
7398     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7399                                             Spacing * 2));
7400     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7401     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7402     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7403     TmpInst.addOperand(Inst.getOperand(4));
7404     Inst = TmpInst;
7405     return true;
7406   }
7407
7408   case ARM::VLD3DUPdWB_fixed_Asm_8:
7409   case ARM::VLD3DUPdWB_fixed_Asm_16:
7410   case ARM::VLD3DUPdWB_fixed_Asm_32:
7411   case ARM::VLD3DUPqWB_fixed_Asm_8:
7412   case ARM::VLD3DUPqWB_fixed_Asm_16:
7413   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7414     MCInst TmpInst;
7415     unsigned Spacing;
7416     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7417     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7418     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7419                                             Spacing));
7420     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7421                                             Spacing * 2));
7422     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7423     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7424     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7425     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7426     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7427     TmpInst.addOperand(Inst.getOperand(4));
7428     Inst = TmpInst;
7429     return true;
7430   }
7431
7432   case ARM::VLD3DUPdWB_register_Asm_8:
7433   case ARM::VLD3DUPdWB_register_Asm_16:
7434   case ARM::VLD3DUPdWB_register_Asm_32:
7435   case ARM::VLD3DUPqWB_register_Asm_8:
7436   case ARM::VLD3DUPqWB_register_Asm_16:
7437   case ARM::VLD3DUPqWB_register_Asm_32: {
7438     MCInst TmpInst;
7439     unsigned Spacing;
7440     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7441     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7442     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7443                                             Spacing));
7444     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7445                                             Spacing * 2));
7446     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7447     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7448     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7449     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7450     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7451     TmpInst.addOperand(Inst.getOperand(5));
7452     Inst = TmpInst;
7453     return true;
7454   }
7455
7456   // VLD3 multiple 3-element structure instructions.
7457   case ARM::VLD3dAsm_8:
7458   case ARM::VLD3dAsm_16:
7459   case ARM::VLD3dAsm_32:
7460   case ARM::VLD3qAsm_8:
7461   case ARM::VLD3qAsm_16:
7462   case ARM::VLD3qAsm_32: {
7463     MCInst TmpInst;
7464     unsigned Spacing;
7465     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7466     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7467     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7468                                             Spacing));
7469     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7470                                             Spacing * 2));
7471     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7472     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7473     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7474     TmpInst.addOperand(Inst.getOperand(4));
7475     Inst = TmpInst;
7476     return true;
7477   }
7478
7479   case ARM::VLD3dWB_fixed_Asm_8:
7480   case ARM::VLD3dWB_fixed_Asm_16:
7481   case ARM::VLD3dWB_fixed_Asm_32:
7482   case ARM::VLD3qWB_fixed_Asm_8:
7483   case ARM::VLD3qWB_fixed_Asm_16:
7484   case ARM::VLD3qWB_fixed_Asm_32: {
7485     MCInst TmpInst;
7486     unsigned Spacing;
7487     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7488     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7489     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7490                                             Spacing));
7491     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7492                                             Spacing * 2));
7493     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7494     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7495     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7496     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7497     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7498     TmpInst.addOperand(Inst.getOperand(4));
7499     Inst = TmpInst;
7500     return true;
7501   }
7502
7503   case ARM::VLD3dWB_register_Asm_8:
7504   case ARM::VLD3dWB_register_Asm_16:
7505   case ARM::VLD3dWB_register_Asm_32:
7506   case ARM::VLD3qWB_register_Asm_8:
7507   case ARM::VLD3qWB_register_Asm_16:
7508   case ARM::VLD3qWB_register_Asm_32: {
7509     MCInst TmpInst;
7510     unsigned Spacing;
7511     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7512     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7513     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7514                                             Spacing));
7515     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7516                                             Spacing * 2));
7517     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7518     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7519     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7520     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7521     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7522     TmpInst.addOperand(Inst.getOperand(5));
7523     Inst = TmpInst;
7524     return true;
7525   }
7526
7527   // VLD4DUP single 3-element structure to all lanes instructions.
7528   case ARM::VLD4DUPdAsm_8:
7529   case ARM::VLD4DUPdAsm_16:
7530   case ARM::VLD4DUPdAsm_32:
7531   case ARM::VLD4DUPqAsm_8:
7532   case ARM::VLD4DUPqAsm_16:
7533   case ARM::VLD4DUPqAsm_32: {
7534     MCInst TmpInst;
7535     unsigned Spacing;
7536     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7537     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7538     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7539                                             Spacing));
7540     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7541                                             Spacing * 2));
7542     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7543                                             Spacing * 3));
7544     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7545     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7546     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7547     TmpInst.addOperand(Inst.getOperand(4));
7548     Inst = TmpInst;
7549     return true;
7550   }
7551
7552   case ARM::VLD4DUPdWB_fixed_Asm_8:
7553   case ARM::VLD4DUPdWB_fixed_Asm_16:
7554   case ARM::VLD4DUPdWB_fixed_Asm_32:
7555   case ARM::VLD4DUPqWB_fixed_Asm_8:
7556   case ARM::VLD4DUPqWB_fixed_Asm_16:
7557   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7558     MCInst TmpInst;
7559     unsigned Spacing;
7560     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7561     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7562     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7563                                             Spacing));
7564     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7565                                             Spacing * 2));
7566     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7567                                             Spacing * 3));
7568     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7569     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7570     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7571     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7572     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7573     TmpInst.addOperand(Inst.getOperand(4));
7574     Inst = TmpInst;
7575     return true;
7576   }
7577
7578   case ARM::VLD4DUPdWB_register_Asm_8:
7579   case ARM::VLD4DUPdWB_register_Asm_16:
7580   case ARM::VLD4DUPdWB_register_Asm_32:
7581   case ARM::VLD4DUPqWB_register_Asm_8:
7582   case ARM::VLD4DUPqWB_register_Asm_16:
7583   case ARM::VLD4DUPqWB_register_Asm_32: {
7584     MCInst TmpInst;
7585     unsigned Spacing;
7586     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7587     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7588     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7589                                             Spacing));
7590     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7591                                             Spacing * 2));
7592     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7593                                             Spacing * 3));
7594     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7595     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7596     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7597     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7598     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7599     TmpInst.addOperand(Inst.getOperand(5));
7600     Inst = TmpInst;
7601     return true;
7602   }
7603
7604   // VLD4 multiple 4-element structure instructions.
7605   case ARM::VLD4dAsm_8:
7606   case ARM::VLD4dAsm_16:
7607   case ARM::VLD4dAsm_32:
7608   case ARM::VLD4qAsm_8:
7609   case ARM::VLD4qAsm_16:
7610   case ARM::VLD4qAsm_32: {
7611     MCInst TmpInst;
7612     unsigned Spacing;
7613     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7614     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7615     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7616                                             Spacing));
7617     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7618                                             Spacing * 2));
7619     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7620                                             Spacing * 3));
7621     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7622     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7623     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7624     TmpInst.addOperand(Inst.getOperand(4));
7625     Inst = TmpInst;
7626     return true;
7627   }
7628
7629   case ARM::VLD4dWB_fixed_Asm_8:
7630   case ARM::VLD4dWB_fixed_Asm_16:
7631   case ARM::VLD4dWB_fixed_Asm_32:
7632   case ARM::VLD4qWB_fixed_Asm_8:
7633   case ARM::VLD4qWB_fixed_Asm_16:
7634   case ARM::VLD4qWB_fixed_Asm_32: {
7635     MCInst TmpInst;
7636     unsigned Spacing;
7637     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7638     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7639     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7640                                             Spacing));
7641     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7642                                             Spacing * 2));
7643     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7644                                             Spacing * 3));
7645     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7646     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7647     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7648     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7649     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7650     TmpInst.addOperand(Inst.getOperand(4));
7651     Inst = TmpInst;
7652     return true;
7653   }
7654
7655   case ARM::VLD4dWB_register_Asm_8:
7656   case ARM::VLD4dWB_register_Asm_16:
7657   case ARM::VLD4dWB_register_Asm_32:
7658   case ARM::VLD4qWB_register_Asm_8:
7659   case ARM::VLD4qWB_register_Asm_16:
7660   case ARM::VLD4qWB_register_Asm_32: {
7661     MCInst TmpInst;
7662     unsigned Spacing;
7663     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7664     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7665     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7666                                             Spacing));
7667     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7668                                             Spacing * 2));
7669     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7670                                             Spacing * 3));
7671     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7672     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7673     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7674     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7675     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7676     TmpInst.addOperand(Inst.getOperand(5));
7677     Inst = TmpInst;
7678     return true;
7679   }
7680
7681   // VST3 multiple 3-element structure instructions.
7682   case ARM::VST3dAsm_8:
7683   case ARM::VST3dAsm_16:
7684   case ARM::VST3dAsm_32:
7685   case ARM::VST3qAsm_8:
7686   case ARM::VST3qAsm_16:
7687   case ARM::VST3qAsm_32: {
7688     MCInst TmpInst;
7689     unsigned Spacing;
7690     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7691     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7692     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7693     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7694     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7695                                             Spacing));
7696     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7697                                             Spacing * 2));
7698     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7699     TmpInst.addOperand(Inst.getOperand(4));
7700     Inst = TmpInst;
7701     return true;
7702   }
7703
7704   case ARM::VST3dWB_fixed_Asm_8:
7705   case ARM::VST3dWB_fixed_Asm_16:
7706   case ARM::VST3dWB_fixed_Asm_32:
7707   case ARM::VST3qWB_fixed_Asm_8:
7708   case ARM::VST3qWB_fixed_Asm_16:
7709   case ARM::VST3qWB_fixed_Asm_32: {
7710     MCInst TmpInst;
7711     unsigned Spacing;
7712     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7713     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7714     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7715     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7716     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7717     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7718     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7719                                             Spacing));
7720     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7721                                             Spacing * 2));
7722     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7723     TmpInst.addOperand(Inst.getOperand(4));
7724     Inst = TmpInst;
7725     return true;
7726   }
7727
7728   case ARM::VST3dWB_register_Asm_8:
7729   case ARM::VST3dWB_register_Asm_16:
7730   case ARM::VST3dWB_register_Asm_32:
7731   case ARM::VST3qWB_register_Asm_8:
7732   case ARM::VST3qWB_register_Asm_16:
7733   case ARM::VST3qWB_register_Asm_32: {
7734     MCInst TmpInst;
7735     unsigned Spacing;
7736     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7737     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7738     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7739     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7740     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7741     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7742     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7743                                             Spacing));
7744     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7745                                             Spacing * 2));
7746     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7747     TmpInst.addOperand(Inst.getOperand(5));
7748     Inst = TmpInst;
7749     return true;
7750   }
7751
7752   // VST4 multiple 3-element structure instructions.
7753   case ARM::VST4dAsm_8:
7754   case ARM::VST4dAsm_16:
7755   case ARM::VST4dAsm_32:
7756   case ARM::VST4qAsm_8:
7757   case ARM::VST4qAsm_16:
7758   case ARM::VST4qAsm_32: {
7759     MCInst TmpInst;
7760     unsigned Spacing;
7761     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7762     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7763     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7764     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7765     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7766                                             Spacing));
7767     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7768                                             Spacing * 2));
7769     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7770                                             Spacing * 3));
7771     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7772     TmpInst.addOperand(Inst.getOperand(4));
7773     Inst = TmpInst;
7774     return true;
7775   }
7776
7777   case ARM::VST4dWB_fixed_Asm_8:
7778   case ARM::VST4dWB_fixed_Asm_16:
7779   case ARM::VST4dWB_fixed_Asm_32:
7780   case ARM::VST4qWB_fixed_Asm_8:
7781   case ARM::VST4qWB_fixed_Asm_16:
7782   case ARM::VST4qWB_fixed_Asm_32: {
7783     MCInst TmpInst;
7784     unsigned Spacing;
7785     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7786     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7787     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7788     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7789     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7790     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7791     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7792                                             Spacing));
7793     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7794                                             Spacing * 2));
7795     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7796                                             Spacing * 3));
7797     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7798     TmpInst.addOperand(Inst.getOperand(4));
7799     Inst = TmpInst;
7800     return true;
7801   }
7802
7803   case ARM::VST4dWB_register_Asm_8:
7804   case ARM::VST4dWB_register_Asm_16:
7805   case ARM::VST4dWB_register_Asm_32:
7806   case ARM::VST4qWB_register_Asm_8:
7807   case ARM::VST4qWB_register_Asm_16:
7808   case ARM::VST4qWB_register_Asm_32: {
7809     MCInst TmpInst;
7810     unsigned Spacing;
7811     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7812     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7813     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7814     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7815     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7816     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7817     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7818                                             Spacing));
7819     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7820                                             Spacing * 2));
7821     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7822                                             Spacing * 3));
7823     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7824     TmpInst.addOperand(Inst.getOperand(5));
7825     Inst = TmpInst;
7826     return true;
7827   }
7828
7829   // Handle encoding choice for the shift-immediate instructions.
7830   case ARM::t2LSLri:
7831   case ARM::t2LSRri:
7832   case ARM::t2ASRri: {
7833     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7834         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7835         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
7836         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7837           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
7838       unsigned NewOpc;
7839       switch (Inst.getOpcode()) {
7840       default: llvm_unreachable("unexpected opcode");
7841       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
7842       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
7843       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
7844       }
7845       // The Thumb1 operands aren't in the same order. Awesome, eh?
7846       MCInst TmpInst;
7847       TmpInst.setOpcode(NewOpc);
7848       TmpInst.addOperand(Inst.getOperand(0));
7849       TmpInst.addOperand(Inst.getOperand(5));
7850       TmpInst.addOperand(Inst.getOperand(1));
7851       TmpInst.addOperand(Inst.getOperand(2));
7852       TmpInst.addOperand(Inst.getOperand(3));
7853       TmpInst.addOperand(Inst.getOperand(4));
7854       Inst = TmpInst;
7855       return true;
7856     }
7857     return false;
7858   }
7859
7860   // Handle the Thumb2 mode MOV complex aliases.
7861   case ARM::t2MOVsr:
7862   case ARM::t2MOVSsr: {
7863     // Which instruction to expand to depends on the CCOut operand and
7864     // whether we're in an IT block if the register operands are low
7865     // registers.
7866     bool isNarrow = false;
7867     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7868         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7869         isARMLowRegister(Inst.getOperand(2).getReg()) &&
7870         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7871         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
7872       isNarrow = true;
7873     MCInst TmpInst;
7874     unsigned newOpc;
7875     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
7876     default: llvm_unreachable("unexpected opcode!");
7877     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
7878     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
7879     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
7880     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
7881     }
7882     TmpInst.setOpcode(newOpc);
7883     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7884     if (isNarrow)
7885       TmpInst.addOperand(MCOperand::createReg(
7886           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7887     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7888     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7889     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7890     TmpInst.addOperand(Inst.getOperand(5));
7891     if (!isNarrow)
7892       TmpInst.addOperand(MCOperand::createReg(
7893           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7894     Inst = TmpInst;
7895     return true;
7896   }
7897   case ARM::t2MOVsi:
7898   case ARM::t2MOVSsi: {
7899     // Which instruction to expand to depends on the CCOut operand and
7900     // whether we're in an IT block if the register operands are low
7901     // registers.
7902     bool isNarrow = false;
7903     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7904         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7905         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
7906       isNarrow = true;
7907     MCInst TmpInst;
7908     unsigned newOpc;
7909     switch(ARM_AM::getSORegShOp(Inst.getOperand(2).getImm())) {
7910     default: llvm_unreachable("unexpected opcode!");
7911     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
7912     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
7913     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
7914     case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
7915     case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
7916     }
7917     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
7918     if (Amount == 32) Amount = 0;
7919     TmpInst.setOpcode(newOpc);
7920     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7921     if (isNarrow)
7922       TmpInst.addOperand(MCOperand::createReg(
7923           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7924     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7925     if (newOpc != ARM::t2RRX)
7926       TmpInst.addOperand(MCOperand::createImm(Amount));
7927     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7928     TmpInst.addOperand(Inst.getOperand(4));
7929     if (!isNarrow)
7930       TmpInst.addOperand(MCOperand::createReg(
7931           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7932     Inst = TmpInst;
7933     return true;
7934   }
7935   // Handle the ARM mode MOV complex aliases.
7936   case ARM::ASRr:
7937   case ARM::LSRr:
7938   case ARM::LSLr:
7939   case ARM::RORr: {
7940     ARM_AM::ShiftOpc ShiftTy;
7941     switch(Inst.getOpcode()) {
7942     default: llvm_unreachable("unexpected opcode!");
7943     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
7944     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
7945     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
7946     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
7947     }
7948     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
7949     MCInst TmpInst;
7950     TmpInst.setOpcode(ARM::MOVsr);
7951     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7952     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7953     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7954     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7955     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7956     TmpInst.addOperand(Inst.getOperand(4));
7957     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7958     Inst = TmpInst;
7959     return true;
7960   }
7961   case ARM::ASRi:
7962   case ARM::LSRi:
7963   case ARM::LSLi:
7964   case ARM::RORi: {
7965     ARM_AM::ShiftOpc ShiftTy;
7966     switch(Inst.getOpcode()) {
7967     default: llvm_unreachable("unexpected opcode!");
7968     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
7969     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
7970     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
7971     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
7972     }
7973     // A shift by zero is a plain MOVr, not a MOVsi.
7974     unsigned Amt = Inst.getOperand(2).getImm();
7975     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
7976     // A shift by 32 should be encoded as 0 when permitted
7977     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
7978       Amt = 0;
7979     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
7980     MCInst TmpInst;
7981     TmpInst.setOpcode(Opc);
7982     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7983     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7984     if (Opc == ARM::MOVsi)
7985       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7986     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7987     TmpInst.addOperand(Inst.getOperand(4));
7988     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7989     Inst = TmpInst;
7990     return true;
7991   }
7992   case ARM::RRXi: {
7993     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
7994     MCInst TmpInst;
7995     TmpInst.setOpcode(ARM::MOVsi);
7996     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7997     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7998     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7999     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8000     TmpInst.addOperand(Inst.getOperand(3));
8001     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8002     Inst = TmpInst;
8003     return true;
8004   }
8005   case ARM::t2LDMIA_UPD: {
8006     // If this is a load of a single register, then we should use
8007     // a post-indexed LDR instruction instead, per the ARM ARM.
8008     if (Inst.getNumOperands() != 5)
8009       return false;
8010     MCInst TmpInst;
8011     TmpInst.setOpcode(ARM::t2LDR_POST);
8012     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8013     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8014     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8015     TmpInst.addOperand(MCOperand::createImm(4));
8016     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8017     TmpInst.addOperand(Inst.getOperand(3));
8018     Inst = TmpInst;
8019     return true;
8020   }
8021   case ARM::t2STMDB_UPD: {
8022     // If this is a store of a single register, then we should use
8023     // a pre-indexed STR instruction instead, per the ARM ARM.
8024     if (Inst.getNumOperands() != 5)
8025       return false;
8026     MCInst TmpInst;
8027     TmpInst.setOpcode(ARM::t2STR_PRE);
8028     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8029     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8030     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8031     TmpInst.addOperand(MCOperand::createImm(-4));
8032     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8033     TmpInst.addOperand(Inst.getOperand(3));
8034     Inst = TmpInst;
8035     return true;
8036   }
8037   case ARM::LDMIA_UPD:
8038     // If this is a load of a single register via a 'pop', then we should use
8039     // a post-indexed LDR instruction instead, per the ARM ARM.
8040     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8041         Inst.getNumOperands() == 5) {
8042       MCInst TmpInst;
8043       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8044       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8045       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8046       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8047       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8048       TmpInst.addOperand(MCOperand::createImm(4));
8049       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8050       TmpInst.addOperand(Inst.getOperand(3));
8051       Inst = TmpInst;
8052       return true;
8053     }
8054     break;
8055   case ARM::STMDB_UPD:
8056     // If this is a store of a single register via a 'push', then we should use
8057     // a pre-indexed STR instruction instead, per the ARM ARM.
8058     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8059         Inst.getNumOperands() == 5) {
8060       MCInst TmpInst;
8061       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8062       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8063       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8064       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8065       TmpInst.addOperand(MCOperand::createImm(-4));
8066       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8067       TmpInst.addOperand(Inst.getOperand(3));
8068       Inst = TmpInst;
8069     }
8070     break;
8071   case ARM::t2ADDri12:
8072     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8073     // mnemonic was used (not "addw"), encoding T3 is preferred.
8074     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8075         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8076       break;
8077     Inst.setOpcode(ARM::t2ADDri);
8078     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8079     break;
8080   case ARM::t2SUBri12:
8081     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8082     // mnemonic was used (not "subw"), encoding T3 is preferred.
8083     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8084         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8085       break;
8086     Inst.setOpcode(ARM::t2SUBri);
8087     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8088     break;
8089   case ARM::tADDi8:
8090     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8091     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8092     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8093     // to encoding T1 if <Rd> is omitted."
8094     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8095       Inst.setOpcode(ARM::tADDi3);
8096       return true;
8097     }
8098     break;
8099   case ARM::tSUBi8:
8100     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8101     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8102     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8103     // to encoding T1 if <Rd> is omitted."
8104     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8105       Inst.setOpcode(ARM::tSUBi3);
8106       return true;
8107     }
8108     break;
8109   case ARM::t2ADDri:
8110   case ARM::t2SUBri: {
8111     // If the destination and first source operand are the same, and
8112     // the flags are compatible with the current IT status, use encoding T2
8113     // instead of T3. For compatibility with the system 'as'. Make sure the
8114     // wide encoding wasn't explicit.
8115     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8116         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8117         (unsigned)Inst.getOperand(2).getImm() > 255 ||
8118         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
8119          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
8120         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8121          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8122       break;
8123     MCInst TmpInst;
8124     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8125                       ARM::tADDi8 : ARM::tSUBi8);
8126     TmpInst.addOperand(Inst.getOperand(0));
8127     TmpInst.addOperand(Inst.getOperand(5));
8128     TmpInst.addOperand(Inst.getOperand(0));
8129     TmpInst.addOperand(Inst.getOperand(2));
8130     TmpInst.addOperand(Inst.getOperand(3));
8131     TmpInst.addOperand(Inst.getOperand(4));
8132     Inst = TmpInst;
8133     return true;
8134   }
8135   case ARM::t2ADDrr: {
8136     // If the destination and first source operand are the same, and
8137     // there's no setting of the flags, use encoding T2 instead of T3.
8138     // Note that this is only for ADD, not SUB. This mirrors the system
8139     // 'as' behaviour.  Also take advantage of ADD being commutative.
8140     // Make sure the wide encoding wasn't explicit.
8141     bool Swap = false;
8142     auto DestReg = Inst.getOperand(0).getReg();
8143     bool Transform = DestReg == Inst.getOperand(1).getReg();
8144     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8145       Transform = true;
8146       Swap = true;
8147     }
8148     if (!Transform ||
8149         Inst.getOperand(5).getReg() != 0 ||
8150         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8151          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8152       break;
8153     MCInst TmpInst;
8154     TmpInst.setOpcode(ARM::tADDhirr);
8155     TmpInst.addOperand(Inst.getOperand(0));
8156     TmpInst.addOperand(Inst.getOperand(0));
8157     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8158     TmpInst.addOperand(Inst.getOperand(3));
8159     TmpInst.addOperand(Inst.getOperand(4));
8160     Inst = TmpInst;
8161     return true;
8162   }
8163   case ARM::tADDrSP: {
8164     // If the non-SP source operand and the destination operand are not the
8165     // same, we need to use the 32-bit encoding if it's available.
8166     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8167       Inst.setOpcode(ARM::t2ADDrr);
8168       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8169       return true;
8170     }
8171     break;
8172   }
8173   case ARM::tB:
8174     // A Thumb conditional branch outside of an IT block is a tBcc.
8175     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8176       Inst.setOpcode(ARM::tBcc);
8177       return true;
8178     }
8179     break;
8180   case ARM::t2B:
8181     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8182     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8183       Inst.setOpcode(ARM::t2Bcc);
8184       return true;
8185     }
8186     break;
8187   case ARM::t2Bcc:
8188     // If the conditional is AL or we're in an IT block, we really want t2B.
8189     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8190       Inst.setOpcode(ARM::t2B);
8191       return true;
8192     }
8193     break;
8194   case ARM::tBcc:
8195     // If the conditional is AL, we really want tB.
8196     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8197       Inst.setOpcode(ARM::tB);
8198       return true;
8199     }
8200     break;
8201   case ARM::tLDMIA: {
8202     // If the register list contains any high registers, or if the writeback
8203     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8204     // instead if we're in Thumb2. Otherwise, this should have generated
8205     // an error in validateInstruction().
8206     unsigned Rn = Inst.getOperand(0).getReg();
8207     bool hasWritebackToken =
8208         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8209          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8210     bool listContainsBase;
8211     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8212         (!listContainsBase && !hasWritebackToken) ||
8213         (listContainsBase && hasWritebackToken)) {
8214       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8215       assert (isThumbTwo());
8216       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8217       // If we're switching to the updating version, we need to insert
8218       // the writeback tied operand.
8219       if (hasWritebackToken)
8220         Inst.insert(Inst.begin(),
8221                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8222       return true;
8223     }
8224     break;
8225   }
8226   case ARM::tSTMIA_UPD: {
8227     // If the register list contains any high registers, we need to use
8228     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8229     // should have generated an error in validateInstruction().
8230     unsigned Rn = Inst.getOperand(0).getReg();
8231     bool listContainsBase;
8232     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8233       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8234       assert (isThumbTwo());
8235       Inst.setOpcode(ARM::t2STMIA_UPD);
8236       return true;
8237     }
8238     break;
8239   }
8240   case ARM::tPOP: {
8241     bool listContainsBase;
8242     // If the register list contains any high registers, we need to use
8243     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8244     // should have generated an error in validateInstruction().
8245     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8246       return false;
8247     assert (isThumbTwo());
8248     Inst.setOpcode(ARM::t2LDMIA_UPD);
8249     // Add the base register and writeback operands.
8250     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8251     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8252     return true;
8253   }
8254   case ARM::tPUSH: {
8255     bool listContainsBase;
8256     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8257       return false;
8258     assert (isThumbTwo());
8259     Inst.setOpcode(ARM::t2STMDB_UPD);
8260     // Add the base register and writeback operands.
8261     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8262     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8263     return true;
8264   }
8265   case ARM::t2MOVi: {
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         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8270         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8271           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8272          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8273         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8274          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8275       // The operands aren't in the same order for tMOVi8...
8276       MCInst TmpInst;
8277       TmpInst.setOpcode(ARM::tMOVi8);
8278       TmpInst.addOperand(Inst.getOperand(0));
8279       TmpInst.addOperand(Inst.getOperand(4));
8280       TmpInst.addOperand(Inst.getOperand(1));
8281       TmpInst.addOperand(Inst.getOperand(2));
8282       TmpInst.addOperand(Inst.getOperand(3));
8283       Inst = TmpInst;
8284       return true;
8285     }
8286     break;
8287   }
8288   case ARM::t2MOVr: {
8289     // If we can use the 16-bit encoding and the user didn't explicitly
8290     // request the 32-bit variant, transform it here.
8291     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8292         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8293         Inst.getOperand(2).getImm() == ARMCC::AL &&
8294         Inst.getOperand(4).getReg() == ARM::CPSR &&
8295         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8296          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8297       // The operands aren't the same for tMOV[S]r... (no cc_out)
8298       MCInst TmpInst;
8299       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8300       TmpInst.addOperand(Inst.getOperand(0));
8301       TmpInst.addOperand(Inst.getOperand(1));
8302       TmpInst.addOperand(Inst.getOperand(2));
8303       TmpInst.addOperand(Inst.getOperand(3));
8304       Inst = TmpInst;
8305       return true;
8306     }
8307     break;
8308   }
8309   case ARM::t2SXTH:
8310   case ARM::t2SXTB:
8311   case ARM::t2UXTH:
8312   case ARM::t2UXTB: {
8313     // If we can use the 16-bit encoding and the user didn't explicitly
8314     // request the 32-bit variant, transform it here.
8315     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8316         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8317         Inst.getOperand(2).getImm() == 0 &&
8318         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8319          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8320       unsigned NewOpc;
8321       switch (Inst.getOpcode()) {
8322       default: llvm_unreachable("Illegal opcode!");
8323       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8324       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8325       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8326       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8327       }
8328       // The operands aren't the same for thumb1 (no rotate operand).
8329       MCInst TmpInst;
8330       TmpInst.setOpcode(NewOpc);
8331       TmpInst.addOperand(Inst.getOperand(0));
8332       TmpInst.addOperand(Inst.getOperand(1));
8333       TmpInst.addOperand(Inst.getOperand(3));
8334       TmpInst.addOperand(Inst.getOperand(4));
8335       Inst = TmpInst;
8336       return true;
8337     }
8338     break;
8339   }
8340   case ARM::MOVsi: {
8341     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8342     // rrx shifts and asr/lsr of #32 is encoded as 0
8343     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr) 
8344       return false;
8345     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8346       // Shifting by zero is accepted as a vanilla 'MOVr'
8347       MCInst TmpInst;
8348       TmpInst.setOpcode(ARM::MOVr);
8349       TmpInst.addOperand(Inst.getOperand(0));
8350       TmpInst.addOperand(Inst.getOperand(1));
8351       TmpInst.addOperand(Inst.getOperand(3));
8352       TmpInst.addOperand(Inst.getOperand(4));
8353       TmpInst.addOperand(Inst.getOperand(5));
8354       Inst = TmpInst;
8355       return true;
8356     }
8357     return false;
8358   }
8359   case ARM::ANDrsi:
8360   case ARM::ORRrsi:
8361   case ARM::EORrsi:
8362   case ARM::BICrsi:
8363   case ARM::SUBrsi:
8364   case ARM::ADDrsi: {
8365     unsigned newOpc;
8366     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8367     if (SOpc == ARM_AM::rrx) return false;
8368     switch (Inst.getOpcode()) {
8369     default: llvm_unreachable("unexpected opcode!");
8370     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8371     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8372     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8373     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8374     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8375     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8376     }
8377     // If the shift is by zero, use the non-shifted instruction definition.
8378     // The exception is for right shifts, where 0 == 32
8379     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8380         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8381       MCInst TmpInst;
8382       TmpInst.setOpcode(newOpc);
8383       TmpInst.addOperand(Inst.getOperand(0));
8384       TmpInst.addOperand(Inst.getOperand(1));
8385       TmpInst.addOperand(Inst.getOperand(2));
8386       TmpInst.addOperand(Inst.getOperand(4));
8387       TmpInst.addOperand(Inst.getOperand(5));
8388       TmpInst.addOperand(Inst.getOperand(6));
8389       Inst = TmpInst;
8390       return true;
8391     }
8392     return false;
8393   }
8394   case ARM::ITasm:
8395   case ARM::t2IT: {
8396     // The mask bits for all but the first condition are represented as
8397     // the low bit of the condition code value implies 't'. We currently
8398     // always have 1 implies 't', so XOR toggle the bits if the low bit
8399     // of the condition code is zero. 
8400     MCOperand &MO = Inst.getOperand(1);
8401     unsigned Mask = MO.getImm();
8402     unsigned OrigMask = Mask;
8403     unsigned TZ = countTrailingZeros(Mask);
8404     if ((Inst.getOperand(0).getImm() & 1) == 0) {
8405       assert(Mask && TZ <= 3 && "illegal IT mask value!");
8406       Mask ^= (0xE << TZ) & 0xF;
8407     }
8408     MO.setImm(Mask);
8409
8410     // Set up the IT block state according to the IT instruction we just
8411     // matched.
8412     assert(!inITBlock() && "nested IT blocks?!");
8413     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8414     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
8415     ITState.CurPosition = 0;
8416     ITState.FirstCond = true;
8417     break;
8418   }
8419   case ARM::t2LSLrr:
8420   case ARM::t2LSRrr:
8421   case ARM::t2ASRrr:
8422   case ARM::t2SBCrr:
8423   case ARM::t2RORrr:
8424   case ARM::t2BICrr:
8425   {
8426     // Assemblers should use the narrow encodings of these instructions when permissible.
8427     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8428          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8429         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8430         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8431          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8432         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8433          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8434              ".w"))) {
8435       unsigned NewOpc;
8436       switch (Inst.getOpcode()) {
8437         default: llvm_unreachable("unexpected opcode");
8438         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8439         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8440         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8441         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8442         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8443         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8444       }
8445       MCInst TmpInst;
8446       TmpInst.setOpcode(NewOpc);
8447       TmpInst.addOperand(Inst.getOperand(0));
8448       TmpInst.addOperand(Inst.getOperand(5));
8449       TmpInst.addOperand(Inst.getOperand(1));
8450       TmpInst.addOperand(Inst.getOperand(2));
8451       TmpInst.addOperand(Inst.getOperand(3));
8452       TmpInst.addOperand(Inst.getOperand(4));
8453       Inst = TmpInst;
8454       return true;
8455     }
8456     return false;
8457   }
8458   case ARM::t2ANDrr:
8459   case ARM::t2EORrr:
8460   case ARM::t2ADCrr:
8461   case ARM::t2ORRrr:
8462   {
8463     // Assemblers should use the narrow encodings of these instructions when permissible.
8464     // These instructions are special in that they are commutable, so shorter encodings
8465     // are available more often.
8466     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8467          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8468         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8469          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8470         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8471          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8472         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8473          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8474              ".w"))) {
8475       unsigned NewOpc;
8476       switch (Inst.getOpcode()) {
8477         default: llvm_unreachable("unexpected opcode");
8478         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8479         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8480         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8481         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8482       }
8483       MCInst TmpInst;
8484       TmpInst.setOpcode(NewOpc);
8485       TmpInst.addOperand(Inst.getOperand(0));
8486       TmpInst.addOperand(Inst.getOperand(5));
8487       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8488         TmpInst.addOperand(Inst.getOperand(1));
8489         TmpInst.addOperand(Inst.getOperand(2));
8490       } else {
8491         TmpInst.addOperand(Inst.getOperand(2));
8492         TmpInst.addOperand(Inst.getOperand(1));
8493       }
8494       TmpInst.addOperand(Inst.getOperand(3));
8495       TmpInst.addOperand(Inst.getOperand(4));
8496       Inst = TmpInst;
8497       return true;
8498     }
8499     return false;
8500   }
8501   }
8502   return false;
8503 }
8504
8505 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8506   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8507   // suffix depending on whether they're in an IT block or not.
8508   unsigned Opc = Inst.getOpcode();
8509   const MCInstrDesc &MCID = MII.get(Opc);
8510   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8511     assert(MCID.hasOptionalDef() &&
8512            "optionally flag setting instruction missing optional def operand");
8513     assert(MCID.NumOperands == Inst.getNumOperands() &&
8514            "operand count mismatch!");
8515     // Find the optional-def operand (cc_out).
8516     unsigned OpNo;
8517     for (OpNo = 0;
8518          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8519          ++OpNo)
8520       ;
8521     // If we're parsing Thumb1, reject it completely.
8522     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8523       return Match_MnemonicFail;
8524     // If we're parsing Thumb2, which form is legal depends on whether we're
8525     // in an IT block.
8526     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8527         !inITBlock())
8528       return Match_RequiresITBlock;
8529     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8530         inITBlock())
8531       return Match_RequiresNotITBlock;
8532   } else if (isThumbOne()) {
8533     // Some high-register supporting Thumb1 encodings only allow both registers
8534     // to be from r0-r7 when in Thumb2.
8535     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8536         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8537         isARMLowRegister(Inst.getOperand(2).getReg()))
8538       return Match_RequiresThumb2;
8539     // Others only require ARMv6 or later.
8540     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8541              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8542              isARMLowRegister(Inst.getOperand(1).getReg()))
8543       return Match_RequiresV6;
8544   }
8545
8546   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8547     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8548       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8549       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8550         return Match_RequiresV8;
8551       else if (Inst.getOperand(I).getReg() == ARM::PC)
8552         return Match_InvalidOperand;
8553     }
8554
8555   return Match_Success;
8556 }
8557
8558 namespace llvm {
8559 template <> inline bool IsCPSRDead<MCInst>(MCInst *Instr) {
8560   return true; // In an assembly source, no need to second-guess
8561 }
8562 }
8563
8564 static const char *getSubtargetFeatureName(uint64_t Val);
8565 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8566                                            OperandVector &Operands,
8567                                            MCStreamer &Out, uint64_t &ErrorInfo,
8568                                            bool MatchingInlineAsm) {
8569   MCInst Inst;
8570   unsigned MatchResult;
8571
8572   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
8573                                      MatchingInlineAsm);
8574   switch (MatchResult) {
8575   case Match_Success:
8576     // Context sensitive operand constraints aren't handled by the matcher,
8577     // so check them here.
8578     if (validateInstruction(Inst, Operands)) {
8579       // Still progress the IT block, otherwise one wrong condition causes
8580       // nasty cascading errors.
8581       forwardITPosition();
8582       return true;
8583     }
8584
8585     { // processInstruction() updates inITBlock state, we need to save it away
8586       bool wasInITBlock = inITBlock();
8587
8588       // Some instructions need post-processing to, for example, tweak which
8589       // encoding is selected. Loop on it while changes happen so the
8590       // individual transformations can chain off each other. E.g.,
8591       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
8592       while (processInstruction(Inst, Operands, Out))
8593         ;
8594
8595       // Only after the instruction is fully processed, we can validate it
8596       if (wasInITBlock && hasV8Ops() && isThumb() &&
8597           !isV8EligibleForIT(&Inst)) {
8598         Warning(IDLoc, "deprecated instruction in IT block");
8599       }
8600     }
8601
8602     // Only move forward at the very end so that everything in validate
8603     // and process gets a consistent answer about whether we're in an IT
8604     // block.
8605     forwardITPosition();
8606
8607     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
8608     // doesn't actually encode.
8609     if (Inst.getOpcode() == ARM::ITasm)
8610       return false;
8611
8612     Inst.setLoc(IDLoc);
8613     Out.EmitInstruction(Inst, getSTI());
8614     return false;
8615   case Match_MissingFeature: {
8616     assert(ErrorInfo && "Unknown missing feature!");
8617     // Special case the error message for the very common case where only
8618     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
8619     std::string Msg = "instruction requires:";
8620     uint64_t Mask = 1;
8621     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
8622       if (ErrorInfo & Mask) {
8623         Msg += " ";
8624         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
8625       }
8626       Mask <<= 1;
8627     }
8628     return Error(IDLoc, Msg);
8629   }
8630   case Match_InvalidOperand: {
8631     SMLoc ErrorLoc = IDLoc;
8632     if (ErrorInfo != ~0ULL) {
8633       if (ErrorInfo >= Operands.size())
8634         return Error(IDLoc, "too few operands for instruction");
8635
8636       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8637       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8638     }
8639
8640     return Error(ErrorLoc, "invalid operand for instruction");
8641   }
8642   case Match_MnemonicFail:
8643     return Error(IDLoc, "invalid instruction",
8644                  ((ARMOperand &)*Operands[0]).getLocRange());
8645   case Match_RequiresNotITBlock:
8646     return Error(IDLoc, "flag setting instruction only valid outside IT block");
8647   case Match_RequiresITBlock:
8648     return Error(IDLoc, "instruction only valid inside IT block");
8649   case Match_RequiresV6:
8650     return Error(IDLoc, "instruction variant requires ARMv6 or later");
8651   case Match_RequiresThumb2:
8652     return Error(IDLoc, "instruction variant requires Thumb2");
8653   case Match_RequiresV8:
8654     return Error(IDLoc, "instruction variant requires ARMv8 or later");
8655   case Match_ImmRange0_15: {
8656     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8657     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8658     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
8659   }
8660   case Match_ImmRange0_239: {
8661     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8662     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8663     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
8664   }
8665   case Match_AlignedMemoryRequiresNone:
8666   case Match_DupAlignedMemoryRequiresNone:
8667   case Match_AlignedMemoryRequires16:
8668   case Match_DupAlignedMemoryRequires16:
8669   case Match_AlignedMemoryRequires32:
8670   case Match_DupAlignedMemoryRequires32:
8671   case Match_AlignedMemoryRequires64:
8672   case Match_DupAlignedMemoryRequires64:
8673   case Match_AlignedMemoryRequires64or128:
8674   case Match_DupAlignedMemoryRequires64or128:
8675   case Match_AlignedMemoryRequires64or128or256:
8676   {
8677     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
8678     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8679     switch (MatchResult) {
8680       default:
8681         llvm_unreachable("Missing Match_Aligned type");
8682       case Match_AlignedMemoryRequiresNone:
8683       case Match_DupAlignedMemoryRequiresNone:
8684         return Error(ErrorLoc, "alignment must be omitted");
8685       case Match_AlignedMemoryRequires16:
8686       case Match_DupAlignedMemoryRequires16:
8687         return Error(ErrorLoc, "alignment must be 16 or omitted");
8688       case Match_AlignedMemoryRequires32:
8689       case Match_DupAlignedMemoryRequires32:
8690         return Error(ErrorLoc, "alignment must be 32 or omitted");
8691       case Match_AlignedMemoryRequires64:
8692       case Match_DupAlignedMemoryRequires64:
8693         return Error(ErrorLoc, "alignment must be 64 or omitted");
8694       case Match_AlignedMemoryRequires64or128:
8695       case Match_DupAlignedMemoryRequires64or128:
8696         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
8697       case Match_AlignedMemoryRequires64or128or256:
8698         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
8699     }
8700   }
8701   }
8702
8703   llvm_unreachable("Implement any new match types added!");
8704 }
8705
8706 /// parseDirective parses the arm specific directives
8707 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
8708   const MCObjectFileInfo::Environment Format =
8709     getContext().getObjectFileInfo()->getObjectFileType();
8710   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8711   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
8712
8713   StringRef IDVal = DirectiveID.getIdentifier();
8714   if (IDVal == ".word")
8715     return parseLiteralValues(4, DirectiveID.getLoc());
8716   else if (IDVal == ".short" || IDVal == ".hword")
8717     return parseLiteralValues(2, DirectiveID.getLoc());
8718   else if (IDVal == ".thumb")
8719     return parseDirectiveThumb(DirectiveID.getLoc());
8720   else if (IDVal == ".arm")
8721     return parseDirectiveARM(DirectiveID.getLoc());
8722   else if (IDVal == ".thumb_func")
8723     return parseDirectiveThumbFunc(DirectiveID.getLoc());
8724   else if (IDVal == ".code")
8725     return parseDirectiveCode(DirectiveID.getLoc());
8726   else if (IDVal == ".syntax")
8727     return parseDirectiveSyntax(DirectiveID.getLoc());
8728   else if (IDVal == ".unreq")
8729     return parseDirectiveUnreq(DirectiveID.getLoc());
8730   else if (IDVal == ".fnend")
8731     return parseDirectiveFnEnd(DirectiveID.getLoc());
8732   else if (IDVal == ".cantunwind")
8733     return parseDirectiveCantUnwind(DirectiveID.getLoc());
8734   else if (IDVal == ".personality")
8735     return parseDirectivePersonality(DirectiveID.getLoc());
8736   else if (IDVal == ".handlerdata")
8737     return parseDirectiveHandlerData(DirectiveID.getLoc());
8738   else if (IDVal == ".setfp")
8739     return parseDirectiveSetFP(DirectiveID.getLoc());
8740   else if (IDVal == ".pad")
8741     return parseDirectivePad(DirectiveID.getLoc());
8742   else if (IDVal == ".save")
8743     return parseDirectiveRegSave(DirectiveID.getLoc(), false);
8744   else if (IDVal == ".vsave")
8745     return parseDirectiveRegSave(DirectiveID.getLoc(), true);
8746   else if (IDVal == ".ltorg" || IDVal == ".pool")
8747     return parseDirectiveLtorg(DirectiveID.getLoc());
8748   else if (IDVal == ".even")
8749     return parseDirectiveEven(DirectiveID.getLoc());
8750   else if (IDVal == ".personalityindex")
8751     return parseDirectivePersonalityIndex(DirectiveID.getLoc());
8752   else if (IDVal == ".unwind_raw")
8753     return parseDirectiveUnwindRaw(DirectiveID.getLoc());
8754   else if (IDVal == ".movsp")
8755     return parseDirectiveMovSP(DirectiveID.getLoc());
8756   else if (IDVal == ".arch_extension")
8757     return parseDirectiveArchExtension(DirectiveID.getLoc());
8758   else if (IDVal == ".align")
8759     return parseDirectiveAlign(DirectiveID.getLoc());
8760   else if (IDVal == ".thumb_set")
8761     return parseDirectiveThumbSet(DirectiveID.getLoc());
8762
8763   if (!IsMachO && !IsCOFF) {
8764     if (IDVal == ".arch")
8765       return parseDirectiveArch(DirectiveID.getLoc());
8766     else if (IDVal == ".cpu")
8767       return parseDirectiveCPU(DirectiveID.getLoc());
8768     else if (IDVal == ".eabi_attribute")
8769       return parseDirectiveEabiAttr(DirectiveID.getLoc());
8770     else if (IDVal == ".fpu")
8771       return parseDirectiveFPU(DirectiveID.getLoc());
8772     else if (IDVal == ".fnstart")
8773       return parseDirectiveFnStart(DirectiveID.getLoc());
8774     else if (IDVal == ".inst")
8775       return parseDirectiveInst(DirectiveID.getLoc());
8776     else if (IDVal == ".inst.n")
8777       return parseDirectiveInst(DirectiveID.getLoc(), 'n');
8778     else if (IDVal == ".inst.w")
8779       return parseDirectiveInst(DirectiveID.getLoc(), 'w');
8780     else if (IDVal == ".object_arch")
8781       return parseDirectiveObjectArch(DirectiveID.getLoc());
8782     else if (IDVal == ".tlsdescseq")
8783       return parseDirectiveTLSDescSeq(DirectiveID.getLoc());
8784   }
8785
8786   return true;
8787 }
8788
8789 /// parseLiteralValues
8790 ///  ::= .hword expression [, expression]*
8791 ///  ::= .short expression [, expression]*
8792 ///  ::= .word expression [, expression]*
8793 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
8794   MCAsmParser &Parser = getParser();
8795   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8796     for (;;) {
8797       const MCExpr *Value;
8798       if (getParser().parseExpression(Value)) {
8799         Parser.eatToEndOfStatement();
8800         return false;
8801       }
8802
8803       getParser().getStreamer().EmitValue(Value, Size);
8804
8805       if (getLexer().is(AsmToken::EndOfStatement))
8806         break;
8807
8808       // FIXME: Improve diagnostic.
8809       if (getLexer().isNot(AsmToken::Comma)) {
8810         Error(L, "unexpected token in directive");
8811         return false;
8812       }
8813       Parser.Lex();
8814     }
8815   }
8816
8817   Parser.Lex();
8818   return false;
8819 }
8820
8821 /// parseDirectiveThumb
8822 ///  ::= .thumb
8823 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
8824   MCAsmParser &Parser = getParser();
8825   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8826     Error(L, "unexpected token in directive");
8827     return false;
8828   }
8829   Parser.Lex();
8830
8831   if (!hasThumb()) {
8832     Error(L, "target does not support Thumb mode");
8833     return false;
8834   }
8835
8836   if (!isThumb())
8837     SwitchMode();
8838
8839   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8840   return false;
8841 }
8842
8843 /// parseDirectiveARM
8844 ///  ::= .arm
8845 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
8846   MCAsmParser &Parser = getParser();
8847   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8848     Error(L, "unexpected token in directive");
8849     return false;
8850   }
8851   Parser.Lex();
8852
8853   if (!hasARM()) {
8854     Error(L, "target does not support ARM mode");
8855     return false;
8856   }
8857
8858   if (isThumb())
8859     SwitchMode();
8860
8861   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8862   return false;
8863 }
8864
8865 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
8866   if (NextSymbolIsThumb) {
8867     getParser().getStreamer().EmitThumbFunc(Symbol);
8868     NextSymbolIsThumb = false;
8869   }
8870 }
8871
8872 /// parseDirectiveThumbFunc
8873 ///  ::= .thumbfunc symbol_name
8874 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
8875   MCAsmParser &Parser = getParser();
8876   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
8877   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8878
8879   // Darwin asm has (optionally) function name after .thumb_func direction
8880   // ELF doesn't
8881   if (IsMachO) {
8882     const AsmToken &Tok = Parser.getTok();
8883     if (Tok.isNot(AsmToken::EndOfStatement)) {
8884       if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String)) {
8885         Error(L, "unexpected token in .thumb_func directive");
8886         return false;
8887       }
8888
8889       MCSymbol *Func =
8890           getParser().getContext().getOrCreateSymbol(Tok.getIdentifier());
8891       getParser().getStreamer().EmitThumbFunc(Func);
8892       Parser.Lex(); // Consume the identifier token.
8893       return false;
8894     }
8895   }
8896
8897   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8898     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8899     Parser.eatToEndOfStatement();
8900     return false;
8901   }
8902
8903   NextSymbolIsThumb = true;
8904   return false;
8905 }
8906
8907 /// parseDirectiveSyntax
8908 ///  ::= .syntax unified | divided
8909 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
8910   MCAsmParser &Parser = getParser();
8911   const AsmToken &Tok = Parser.getTok();
8912   if (Tok.isNot(AsmToken::Identifier)) {
8913     Error(L, "unexpected token in .syntax directive");
8914     return false;
8915   }
8916
8917   StringRef Mode = Tok.getString();
8918   if (Mode == "unified" || Mode == "UNIFIED") {
8919     Parser.Lex();
8920   } else if (Mode == "divided" || Mode == "DIVIDED") {
8921     Error(L, "'.syntax divided' arm asssembly not supported");
8922     return false;
8923   } else {
8924     Error(L, "unrecognized syntax mode in .syntax directive");
8925     return false;
8926   }
8927
8928   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8929     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8930     return false;
8931   }
8932   Parser.Lex();
8933
8934   // TODO tell the MC streamer the mode
8935   // getParser().getStreamer().Emit???();
8936   return false;
8937 }
8938
8939 /// parseDirectiveCode
8940 ///  ::= .code 16 | 32
8941 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
8942   MCAsmParser &Parser = getParser();
8943   const AsmToken &Tok = Parser.getTok();
8944   if (Tok.isNot(AsmToken::Integer)) {
8945     Error(L, "unexpected token in .code directive");
8946     return false;
8947   }
8948   int64_t Val = Parser.getTok().getIntVal();
8949   if (Val != 16 && Val != 32) {
8950     Error(L, "invalid operand to .code directive");
8951     return false;
8952   }
8953   Parser.Lex();
8954
8955   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8956     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8957     return false;
8958   }
8959   Parser.Lex();
8960
8961   if (Val == 16) {
8962     if (!hasThumb()) {
8963       Error(L, "target does not support Thumb mode");
8964       return false;
8965     }
8966
8967     if (!isThumb())
8968       SwitchMode();
8969     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8970   } else {
8971     if (!hasARM()) {
8972       Error(L, "target does not support ARM mode");
8973       return false;
8974     }
8975
8976     if (isThumb())
8977       SwitchMode();
8978     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8979   }
8980
8981   return false;
8982 }
8983
8984 /// parseDirectiveReq
8985 ///  ::= name .req registername
8986 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
8987   MCAsmParser &Parser = getParser();
8988   Parser.Lex(); // Eat the '.req' token.
8989   unsigned Reg;
8990   SMLoc SRegLoc, ERegLoc;
8991   if (ParseRegister(Reg, SRegLoc, ERegLoc)) {
8992     Parser.eatToEndOfStatement();
8993     Error(SRegLoc, "register name expected");
8994     return false;
8995   }
8996
8997   // Shouldn't be anything else.
8998   if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
8999     Parser.eatToEndOfStatement();
9000     Error(Parser.getTok().getLoc(), "unexpected input in .req directive.");
9001     return false;
9002   }
9003
9004   Parser.Lex(); // Consume the EndOfStatement
9005
9006   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg) {
9007     Error(SRegLoc, "redefinition of '" + Name + "' does not match original.");
9008     return false;
9009   }
9010
9011   return false;
9012 }
9013
9014 /// parseDirectiveUneq
9015 ///  ::= .unreq registername
9016 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9017   MCAsmParser &Parser = getParser();
9018   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9019     Parser.eatToEndOfStatement();
9020     Error(L, "unexpected input in .unreq directive.");
9021     return false;
9022   }
9023   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9024   Parser.Lex(); // Eat the identifier.
9025   return false;
9026 }
9027
9028 /// parseDirectiveArch
9029 ///  ::= .arch token
9030 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9031   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9032
9033   unsigned ID = ARM::parseArch(Arch);
9034
9035   if (ID == ARM::AK_INVALID) {
9036     Error(L, "Unknown arch name");
9037     return false;
9038   }
9039
9040   Triple T;
9041   STI.setDefaultFeatures(T.getARMCPUForArch(Arch));
9042   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9043
9044   getTargetStreamer().emitArch(ID);
9045   return false;
9046 }
9047
9048 /// parseDirectiveEabiAttr
9049 ///  ::= .eabi_attribute int, int [, "str"]
9050 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9051 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9052   MCAsmParser &Parser = getParser();
9053   int64_t Tag;
9054   SMLoc TagLoc;
9055   TagLoc = Parser.getTok().getLoc();
9056   if (Parser.getTok().is(AsmToken::Identifier)) {
9057     StringRef Name = Parser.getTok().getIdentifier();
9058     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9059     if (Tag == -1) {
9060       Error(TagLoc, "attribute name not recognised: " + Name);
9061       Parser.eatToEndOfStatement();
9062       return false;
9063     }
9064     Parser.Lex();
9065   } else {
9066     const MCExpr *AttrExpr;
9067
9068     TagLoc = Parser.getTok().getLoc();
9069     if (Parser.parseExpression(AttrExpr)) {
9070       Parser.eatToEndOfStatement();
9071       return false;
9072     }
9073
9074     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9075     if (!CE) {
9076       Error(TagLoc, "expected numeric constant");
9077       Parser.eatToEndOfStatement();
9078       return false;
9079     }
9080
9081     Tag = CE->getValue();
9082   }
9083
9084   if (Parser.getTok().isNot(AsmToken::Comma)) {
9085     Error(Parser.getTok().getLoc(), "comma expected");
9086     Parser.eatToEndOfStatement();
9087     return false;
9088   }
9089   Parser.Lex(); // skip comma
9090
9091   StringRef StringValue = "";
9092   bool IsStringValue = false;
9093
9094   int64_t IntegerValue = 0;
9095   bool IsIntegerValue = false;
9096
9097   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9098     IsStringValue = true;
9099   else if (Tag == ARMBuildAttrs::compatibility) {
9100     IsStringValue = true;
9101     IsIntegerValue = true;
9102   } else if (Tag < 32 || Tag % 2 == 0)
9103     IsIntegerValue = true;
9104   else if (Tag % 2 == 1)
9105     IsStringValue = true;
9106   else
9107     llvm_unreachable("invalid tag type");
9108
9109   if (IsIntegerValue) {
9110     const MCExpr *ValueExpr;
9111     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9112     if (Parser.parseExpression(ValueExpr)) {
9113       Parser.eatToEndOfStatement();
9114       return false;
9115     }
9116
9117     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9118     if (!CE) {
9119       Error(ValueExprLoc, "expected numeric constant");
9120       Parser.eatToEndOfStatement();
9121       return false;
9122     }
9123
9124     IntegerValue = CE->getValue();
9125   }
9126
9127   if (Tag == ARMBuildAttrs::compatibility) {
9128     if (Parser.getTok().isNot(AsmToken::Comma))
9129       IsStringValue = false;
9130     if (Parser.getTok().isNot(AsmToken::Comma)) {
9131       Error(Parser.getTok().getLoc(), "comma expected");
9132       Parser.eatToEndOfStatement();
9133       return false;
9134     } else {
9135        Parser.Lex();
9136     }
9137   }
9138
9139   if (IsStringValue) {
9140     if (Parser.getTok().isNot(AsmToken::String)) {
9141       Error(Parser.getTok().getLoc(), "bad string constant");
9142       Parser.eatToEndOfStatement();
9143       return false;
9144     }
9145
9146     StringValue = Parser.getTok().getStringContents();
9147     Parser.Lex();
9148   }
9149
9150   if (IsIntegerValue && IsStringValue) {
9151     assert(Tag == ARMBuildAttrs::compatibility);
9152     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9153   } else if (IsIntegerValue)
9154     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9155   else if (IsStringValue)
9156     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9157   return false;
9158 }
9159
9160 /// parseDirectiveCPU
9161 ///  ::= .cpu str
9162 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9163   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9164   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9165
9166   // FIXME: This is using table-gen data, but should be moved to
9167   // ARMTargetParser once that is table-gen'd.
9168   if (!getSTI().isCPUStringValid(CPU)) {
9169     Error(L, "Unknown CPU name");
9170     return false;
9171   }
9172
9173   STI.setDefaultFeatures(CPU);
9174   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9175
9176   return false;
9177 }
9178 /// parseDirectiveFPU
9179 ///  ::= .fpu str
9180 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9181   SMLoc FPUNameLoc = getTok().getLoc();
9182   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9183
9184   unsigned ID = ARM::parseFPU(FPU);
9185   std::vector<const char *> Features;
9186   if (!ARM::getFPUFeatures(ID, Features)) {
9187     Error(FPUNameLoc, "Unknown FPU name");
9188     return false;
9189   }
9190
9191   for (auto Feature : Features)
9192     STI.ApplyFeatureFlag(Feature);
9193   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9194
9195   getTargetStreamer().emitFPU(ID);
9196   return false;
9197 }
9198
9199 /// parseDirectiveFnStart
9200 ///  ::= .fnstart
9201 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9202   if (UC.hasFnStart()) {
9203     Error(L, ".fnstart starts before the end of previous one");
9204     UC.emitFnStartLocNotes();
9205     return false;
9206   }
9207
9208   // Reset the unwind directives parser state
9209   UC.reset();
9210
9211   getTargetStreamer().emitFnStart();
9212
9213   UC.recordFnStart(L);
9214   return false;
9215 }
9216
9217 /// parseDirectiveFnEnd
9218 ///  ::= .fnend
9219 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9220   // Check the ordering of unwind directives
9221   if (!UC.hasFnStart()) {
9222     Error(L, ".fnstart must precede .fnend directive");
9223     return false;
9224   }
9225
9226   // Reset the unwind directives parser state
9227   getTargetStreamer().emitFnEnd();
9228
9229   UC.reset();
9230   return false;
9231 }
9232
9233 /// parseDirectiveCantUnwind
9234 ///  ::= .cantunwind
9235 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9236   UC.recordCantUnwind(L);
9237
9238   // Check the ordering of unwind directives
9239   if (!UC.hasFnStart()) {
9240     Error(L, ".fnstart must precede .cantunwind directive");
9241     return false;
9242   }
9243   if (UC.hasHandlerData()) {
9244     Error(L, ".cantunwind can't be used with .handlerdata directive");
9245     UC.emitHandlerDataLocNotes();
9246     return false;
9247   }
9248   if (UC.hasPersonality()) {
9249     Error(L, ".cantunwind can't be used with .personality directive");
9250     UC.emitPersonalityLocNotes();
9251     return false;
9252   }
9253
9254   getTargetStreamer().emitCantUnwind();
9255   return false;
9256 }
9257
9258 /// parseDirectivePersonality
9259 ///  ::= .personality name
9260 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9261   MCAsmParser &Parser = getParser();
9262   bool HasExistingPersonality = UC.hasPersonality();
9263
9264   UC.recordPersonality(L);
9265
9266   // Check the ordering of unwind directives
9267   if (!UC.hasFnStart()) {
9268     Error(L, ".fnstart must precede .personality directive");
9269     return false;
9270   }
9271   if (UC.cantUnwind()) {
9272     Error(L, ".personality can't be used with .cantunwind directive");
9273     UC.emitCantUnwindLocNotes();
9274     return false;
9275   }
9276   if (UC.hasHandlerData()) {
9277     Error(L, ".personality must precede .handlerdata directive");
9278     UC.emitHandlerDataLocNotes();
9279     return false;
9280   }
9281   if (HasExistingPersonality) {
9282     Parser.eatToEndOfStatement();
9283     Error(L, "multiple personality directives");
9284     UC.emitPersonalityLocNotes();
9285     return false;
9286   }
9287
9288   // Parse the name of the personality routine
9289   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9290     Parser.eatToEndOfStatement();
9291     Error(L, "unexpected input in .personality directive.");
9292     return false;
9293   }
9294   StringRef Name(Parser.getTok().getIdentifier());
9295   Parser.Lex();
9296
9297   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9298   getTargetStreamer().emitPersonality(PR);
9299   return false;
9300 }
9301
9302 /// parseDirectiveHandlerData
9303 ///  ::= .handlerdata
9304 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9305   UC.recordHandlerData(L);
9306
9307   // Check the ordering of unwind directives
9308   if (!UC.hasFnStart()) {
9309     Error(L, ".fnstart must precede .personality directive");
9310     return false;
9311   }
9312   if (UC.cantUnwind()) {
9313     Error(L, ".handlerdata can't be used with .cantunwind directive");
9314     UC.emitCantUnwindLocNotes();
9315     return false;
9316   }
9317
9318   getTargetStreamer().emitHandlerData();
9319   return false;
9320 }
9321
9322 /// parseDirectiveSetFP
9323 ///  ::= .setfp fpreg, spreg [, offset]
9324 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9325   MCAsmParser &Parser = getParser();
9326   // Check the ordering of unwind directives
9327   if (!UC.hasFnStart()) {
9328     Error(L, ".fnstart must precede .setfp directive");
9329     return false;
9330   }
9331   if (UC.hasHandlerData()) {
9332     Error(L, ".setfp must precede .handlerdata directive");
9333     return false;
9334   }
9335
9336   // Parse fpreg
9337   SMLoc FPRegLoc = Parser.getTok().getLoc();
9338   int FPReg = tryParseRegister();
9339   if (FPReg == -1) {
9340     Error(FPRegLoc, "frame pointer register expected");
9341     return false;
9342   }
9343
9344   // Consume comma
9345   if (Parser.getTok().isNot(AsmToken::Comma)) {
9346     Error(Parser.getTok().getLoc(), "comma expected");
9347     return false;
9348   }
9349   Parser.Lex(); // skip comma
9350
9351   // Parse spreg
9352   SMLoc SPRegLoc = Parser.getTok().getLoc();
9353   int SPReg = tryParseRegister();
9354   if (SPReg == -1) {
9355     Error(SPRegLoc, "stack pointer register expected");
9356     return false;
9357   }
9358
9359   if (SPReg != ARM::SP && SPReg != UC.getFPReg()) {
9360     Error(SPRegLoc, "register should be either $sp or the latest fp register");
9361     return false;
9362   }
9363
9364   // Update the frame pointer register
9365   UC.saveFPReg(FPReg);
9366
9367   // Parse offset
9368   int64_t Offset = 0;
9369   if (Parser.getTok().is(AsmToken::Comma)) {
9370     Parser.Lex(); // skip comma
9371
9372     if (Parser.getTok().isNot(AsmToken::Hash) &&
9373         Parser.getTok().isNot(AsmToken::Dollar)) {
9374       Error(Parser.getTok().getLoc(), "'#' expected");
9375       return false;
9376     }
9377     Parser.Lex(); // skip hash token.
9378
9379     const MCExpr *OffsetExpr;
9380     SMLoc ExLoc = Parser.getTok().getLoc();
9381     SMLoc EndLoc;
9382     if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9383       Error(ExLoc, "malformed setfp offset");
9384       return false;
9385     }
9386     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9387     if (!CE) {
9388       Error(ExLoc, "setfp offset must be an immediate");
9389       return false;
9390     }
9391
9392     Offset = CE->getValue();
9393   }
9394
9395   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9396                                 static_cast<unsigned>(SPReg), Offset);
9397   return false;
9398 }
9399
9400 /// parseDirective
9401 ///  ::= .pad offset
9402 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9403   MCAsmParser &Parser = getParser();
9404   // Check the ordering of unwind directives
9405   if (!UC.hasFnStart()) {
9406     Error(L, ".fnstart must precede .pad directive");
9407     return false;
9408   }
9409   if (UC.hasHandlerData()) {
9410     Error(L, ".pad must precede .handlerdata directive");
9411     return false;
9412   }
9413
9414   // Parse the offset
9415   if (Parser.getTok().isNot(AsmToken::Hash) &&
9416       Parser.getTok().isNot(AsmToken::Dollar)) {
9417     Error(Parser.getTok().getLoc(), "'#' expected");
9418     return false;
9419   }
9420   Parser.Lex(); // skip hash token.
9421
9422   const MCExpr *OffsetExpr;
9423   SMLoc ExLoc = Parser.getTok().getLoc();
9424   SMLoc EndLoc;
9425   if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9426     Error(ExLoc, "malformed pad offset");
9427     return false;
9428   }
9429   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9430   if (!CE) {
9431     Error(ExLoc, "pad offset must be an immediate");
9432     return false;
9433   }
9434
9435   getTargetStreamer().emitPad(CE->getValue());
9436   return false;
9437 }
9438
9439 /// parseDirectiveRegSave
9440 ///  ::= .save  { registers }
9441 ///  ::= .vsave { registers }
9442 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9443   // Check the ordering of unwind directives
9444   if (!UC.hasFnStart()) {
9445     Error(L, ".fnstart must precede .save or .vsave directives");
9446     return false;
9447   }
9448   if (UC.hasHandlerData()) {
9449     Error(L, ".save or .vsave must precede .handlerdata directive");
9450     return false;
9451   }
9452
9453   // RAII object to make sure parsed operands are deleted.
9454   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9455
9456   // Parse the register list
9457   if (parseRegisterList(Operands))
9458     return false;
9459   ARMOperand &Op = (ARMOperand &)*Operands[0];
9460   if (!IsVector && !Op.isRegList()) {
9461     Error(L, ".save expects GPR registers");
9462     return false;
9463   }
9464   if (IsVector && !Op.isDPRRegList()) {
9465     Error(L, ".vsave expects DPR registers");
9466     return false;
9467   }
9468
9469   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9470   return false;
9471 }
9472
9473 /// parseDirectiveInst
9474 ///  ::= .inst opcode [, ...]
9475 ///  ::= .inst.n opcode [, ...]
9476 ///  ::= .inst.w opcode [, ...]
9477 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9478   MCAsmParser &Parser = getParser();
9479   int Width;
9480
9481   if (isThumb()) {
9482     switch (Suffix) {
9483     case 'n':
9484       Width = 2;
9485       break;
9486     case 'w':
9487       Width = 4;
9488       break;
9489     default:
9490       Parser.eatToEndOfStatement();
9491       Error(Loc, "cannot determine Thumb instruction size, "
9492                  "use inst.n/inst.w instead");
9493       return false;
9494     }
9495   } else {
9496     if (Suffix) {
9497       Parser.eatToEndOfStatement();
9498       Error(Loc, "width suffixes are invalid in ARM mode");
9499       return false;
9500     }
9501     Width = 4;
9502   }
9503
9504   if (getLexer().is(AsmToken::EndOfStatement)) {
9505     Parser.eatToEndOfStatement();
9506     Error(Loc, "expected expression following directive");
9507     return false;
9508   }
9509
9510   for (;;) {
9511     const MCExpr *Expr;
9512
9513     if (getParser().parseExpression(Expr)) {
9514       Error(Loc, "expected expression");
9515       return false;
9516     }
9517
9518     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9519     if (!Value) {
9520       Error(Loc, "expected constant expression");
9521       return false;
9522     }
9523
9524     switch (Width) {
9525     case 2:
9526       if (Value->getValue() > 0xffff) {
9527         Error(Loc, "inst.n operand is too big, use inst.w instead");
9528         return false;
9529       }
9530       break;
9531     case 4:
9532       if (Value->getValue() > 0xffffffff) {
9533         Error(Loc,
9534               StringRef(Suffix ? "inst.w" : "inst") + " operand is too big");
9535         return false;
9536       }
9537       break;
9538     default:
9539       llvm_unreachable("only supported widths are 2 and 4");
9540     }
9541
9542     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9543
9544     if (getLexer().is(AsmToken::EndOfStatement))
9545       break;
9546
9547     if (getLexer().isNot(AsmToken::Comma)) {
9548       Error(Loc, "unexpected token in directive");
9549       return false;
9550     }
9551
9552     Parser.Lex();
9553   }
9554
9555   Parser.Lex();
9556   return false;
9557 }
9558
9559 /// parseDirectiveLtorg
9560 ///  ::= .ltorg | .pool
9561 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9562   getTargetStreamer().emitCurrentConstantPool();
9563   return false;
9564 }
9565
9566 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9567   const MCSection *Section = getStreamer().getCurrentSection().first;
9568
9569   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9570     TokError("unexpected token in directive");
9571     return false;
9572   }
9573
9574   if (!Section) {
9575     getStreamer().InitSections(false);
9576     Section = getStreamer().getCurrentSection().first;
9577   }
9578
9579   assert(Section && "must have section to emit alignment");
9580   if (Section->UseCodeAlign())
9581     getStreamer().EmitCodeAlignment(2);
9582   else
9583     getStreamer().EmitValueToAlignment(2);
9584
9585   return false;
9586 }
9587
9588 /// parseDirectivePersonalityIndex
9589 ///   ::= .personalityindex index
9590 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9591   MCAsmParser &Parser = getParser();
9592   bool HasExistingPersonality = UC.hasPersonality();
9593
9594   UC.recordPersonalityIndex(L);
9595
9596   if (!UC.hasFnStart()) {
9597     Parser.eatToEndOfStatement();
9598     Error(L, ".fnstart must precede .personalityindex directive");
9599     return false;
9600   }
9601   if (UC.cantUnwind()) {
9602     Parser.eatToEndOfStatement();
9603     Error(L, ".personalityindex cannot be used with .cantunwind");
9604     UC.emitCantUnwindLocNotes();
9605     return false;
9606   }
9607   if (UC.hasHandlerData()) {
9608     Parser.eatToEndOfStatement();
9609     Error(L, ".personalityindex must precede .handlerdata directive");
9610     UC.emitHandlerDataLocNotes();
9611     return false;
9612   }
9613   if (HasExistingPersonality) {
9614     Parser.eatToEndOfStatement();
9615     Error(L, "multiple personality directives");
9616     UC.emitPersonalityLocNotes();
9617     return false;
9618   }
9619
9620   const MCExpr *IndexExpression;
9621   SMLoc IndexLoc = Parser.getTok().getLoc();
9622   if (Parser.parseExpression(IndexExpression)) {
9623     Parser.eatToEndOfStatement();
9624     return false;
9625   }
9626
9627   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9628   if (!CE) {
9629     Parser.eatToEndOfStatement();
9630     Error(IndexLoc, "index must be a constant number");
9631     return false;
9632   }
9633   if (CE->getValue() < 0 ||
9634       CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX) {
9635     Parser.eatToEndOfStatement();
9636     Error(IndexLoc, "personality routine index should be in range [0-3]");
9637     return false;
9638   }
9639
9640   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9641   return false;
9642 }
9643
9644 /// parseDirectiveUnwindRaw
9645 ///   ::= .unwind_raw offset, opcode [, opcode...]
9646 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9647   MCAsmParser &Parser = getParser();
9648   if (!UC.hasFnStart()) {
9649     Parser.eatToEndOfStatement();
9650     Error(L, ".fnstart must precede .unwind_raw directives");
9651     return false;
9652   }
9653
9654   int64_t StackOffset;
9655
9656   const MCExpr *OffsetExpr;
9657   SMLoc OffsetLoc = getLexer().getLoc();
9658   if (getLexer().is(AsmToken::EndOfStatement) ||
9659       getParser().parseExpression(OffsetExpr)) {
9660     Error(OffsetLoc, "expected expression");
9661     Parser.eatToEndOfStatement();
9662     return false;
9663   }
9664
9665   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9666   if (!CE) {
9667     Error(OffsetLoc, "offset must be a constant");
9668     Parser.eatToEndOfStatement();
9669     return false;
9670   }
9671
9672   StackOffset = CE->getValue();
9673
9674   if (getLexer().isNot(AsmToken::Comma)) {
9675     Error(getLexer().getLoc(), "expected comma");
9676     Parser.eatToEndOfStatement();
9677     return false;
9678   }
9679   Parser.Lex();
9680
9681   SmallVector<uint8_t, 16> Opcodes;
9682   for (;;) {
9683     const MCExpr *OE;
9684
9685     SMLoc OpcodeLoc = getLexer().getLoc();
9686     if (getLexer().is(AsmToken::EndOfStatement) || Parser.parseExpression(OE)) {
9687       Error(OpcodeLoc, "expected opcode expression");
9688       Parser.eatToEndOfStatement();
9689       return false;
9690     }
9691
9692     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9693     if (!OC) {
9694       Error(OpcodeLoc, "opcode value must be a constant");
9695       Parser.eatToEndOfStatement();
9696       return false;
9697     }
9698
9699     const int64_t Opcode = OC->getValue();
9700     if (Opcode & ~0xff) {
9701       Error(OpcodeLoc, "invalid opcode");
9702       Parser.eatToEndOfStatement();
9703       return false;
9704     }
9705
9706     Opcodes.push_back(uint8_t(Opcode));
9707
9708     if (getLexer().is(AsmToken::EndOfStatement))
9709       break;
9710
9711     if (getLexer().isNot(AsmToken::Comma)) {
9712       Error(getLexer().getLoc(), "unexpected token in directive");
9713       Parser.eatToEndOfStatement();
9714       return false;
9715     }
9716
9717     Parser.Lex();
9718   }
9719
9720   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9721
9722   Parser.Lex();
9723   return false;
9724 }
9725
9726 /// parseDirectiveTLSDescSeq
9727 ///   ::= .tlsdescseq tls-variable
9728 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9729   MCAsmParser &Parser = getParser();
9730
9731   if (getLexer().isNot(AsmToken::Identifier)) {
9732     TokError("expected variable after '.tlsdescseq' directive");
9733     Parser.eatToEndOfStatement();
9734     return false;
9735   }
9736
9737   const MCSymbolRefExpr *SRE =
9738     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
9739                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9740   Lex();
9741
9742   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9743     Error(Parser.getTok().getLoc(), "unexpected token");
9744     Parser.eatToEndOfStatement();
9745     return false;
9746   }
9747
9748   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9749   return false;
9750 }
9751
9752 /// parseDirectiveMovSP
9753 ///  ::= .movsp reg [, #offset]
9754 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
9755   MCAsmParser &Parser = getParser();
9756   if (!UC.hasFnStart()) {
9757     Parser.eatToEndOfStatement();
9758     Error(L, ".fnstart must precede .movsp directives");
9759     return false;
9760   }
9761   if (UC.getFPReg() != ARM::SP) {
9762     Parser.eatToEndOfStatement();
9763     Error(L, "unexpected .movsp directive");
9764     return false;
9765   }
9766
9767   SMLoc SPRegLoc = Parser.getTok().getLoc();
9768   int SPReg = tryParseRegister();
9769   if (SPReg == -1) {
9770     Parser.eatToEndOfStatement();
9771     Error(SPRegLoc, "register expected");
9772     return false;
9773   }
9774
9775   if (SPReg == ARM::SP || SPReg == ARM::PC) {
9776     Parser.eatToEndOfStatement();
9777     Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
9778     return false;
9779   }
9780
9781   int64_t Offset = 0;
9782   if (Parser.getTok().is(AsmToken::Comma)) {
9783     Parser.Lex();
9784
9785     if (Parser.getTok().isNot(AsmToken::Hash)) {
9786       Error(Parser.getTok().getLoc(), "expected #constant");
9787       Parser.eatToEndOfStatement();
9788       return false;
9789     }
9790     Parser.Lex();
9791
9792     const MCExpr *OffsetExpr;
9793     SMLoc OffsetLoc = Parser.getTok().getLoc();
9794     if (Parser.parseExpression(OffsetExpr)) {
9795       Parser.eatToEndOfStatement();
9796       Error(OffsetLoc, "malformed offset expression");
9797       return false;
9798     }
9799
9800     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9801     if (!CE) {
9802       Parser.eatToEndOfStatement();
9803       Error(OffsetLoc, "offset must be an immediate constant");
9804       return false;
9805     }
9806
9807     Offset = CE->getValue();
9808   }
9809
9810   getTargetStreamer().emitMovSP(SPReg, Offset);
9811   UC.saveFPReg(SPReg);
9812
9813   return false;
9814 }
9815
9816 /// parseDirectiveObjectArch
9817 ///   ::= .object_arch name
9818 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
9819   MCAsmParser &Parser = getParser();
9820   if (getLexer().isNot(AsmToken::Identifier)) {
9821     Error(getLexer().getLoc(), "unexpected token");
9822     Parser.eatToEndOfStatement();
9823     return false;
9824   }
9825
9826   StringRef Arch = Parser.getTok().getString();
9827   SMLoc ArchLoc = Parser.getTok().getLoc();
9828   getLexer().Lex();
9829
9830   unsigned ID = ARM::parseArch(Arch);
9831
9832   if (ID == ARM::AK_INVALID) {
9833     Error(ArchLoc, "unknown architecture '" + Arch + "'");
9834     Parser.eatToEndOfStatement();
9835     return false;
9836   }
9837
9838   getTargetStreamer().emitObjectArch(ID);
9839
9840   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9841     Error(getLexer().getLoc(), "unexpected token");
9842     Parser.eatToEndOfStatement();
9843   }
9844
9845   return false;
9846 }
9847
9848 /// parseDirectiveAlign
9849 ///   ::= .align
9850 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
9851   // NOTE: if this is not the end of the statement, fall back to the target
9852   // agnostic handling for this directive which will correctly handle this.
9853   if (getLexer().isNot(AsmToken::EndOfStatement))
9854     return true;
9855
9856   // '.align' is target specifically handled to mean 2**2 byte alignment.
9857   if (getStreamer().getCurrentSection().first->UseCodeAlign())
9858     getStreamer().EmitCodeAlignment(4, 0);
9859   else
9860     getStreamer().EmitValueToAlignment(4, 0, 1, 0);
9861
9862   return false;
9863 }
9864
9865 /// parseDirectiveThumbSet
9866 ///  ::= .thumb_set name, value
9867 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
9868   MCAsmParser &Parser = getParser();
9869
9870   StringRef Name;
9871   if (Parser.parseIdentifier(Name)) {
9872     TokError("expected identifier after '.thumb_set'");
9873     Parser.eatToEndOfStatement();
9874     return false;
9875   }
9876
9877   if (getLexer().isNot(AsmToken::Comma)) {
9878     TokError("expected comma after name '" + Name + "'");
9879     Parser.eatToEndOfStatement();
9880     return false;
9881   }
9882   Lex();
9883
9884   MCSymbol *Sym;
9885   const MCExpr *Value;
9886   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
9887                                                Parser, Sym, Value))
9888     return true;
9889
9890   getTargetStreamer().emitThumbSet(Sym, Value);
9891   return false;
9892 }
9893
9894 /// Force static initialization.
9895 extern "C" void LLVMInitializeARMAsmParser() {
9896   RegisterMCAsmParser<ARMAsmParser> X(TheARMLETarget);
9897   RegisterMCAsmParser<ARMAsmParser> Y(TheARMBETarget);
9898   RegisterMCAsmParser<ARMAsmParser> A(TheThumbLETarget);
9899   RegisterMCAsmParser<ARMAsmParser> B(TheThumbBETarget);
9900 }
9901
9902 #define GET_REGISTER_MATCHER
9903 #define GET_SUBTARGET_FEATURE_NAME
9904 #define GET_MATCHER_IMPLEMENTATION
9905 #include "ARMGenAsmMatcher.inc"
9906
9907 // FIXME: This structure should be moved inside ARMTargetParser
9908 // when we start to table-generate them, and we can use the ARM
9909 // flags below, that were generated by table-gen.
9910 static const struct {
9911   const unsigned Kind;
9912   const unsigned ArchCheck;
9913   const FeatureBitset Features;
9914 } Extensions[] = {
9915   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
9916   { ARM::AEK_CRYPTO,  Feature_HasV8,
9917     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
9918   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
9919   { (ARM::AEK_HWDIV | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
9920     {ARM::FeatureHWDiv, ARM::FeatureHWDivARM} },
9921   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
9922   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
9923   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
9924   // FIXME: Only available in A-class, isel not predicated
9925   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
9926   // FIXME: Unsupported extensions.
9927   { ARM::AEK_OS, Feature_None, {} },
9928   { ARM::AEK_IWMMXT, Feature_None, {} },
9929   { ARM::AEK_IWMMXT2, Feature_None, {} },
9930   { ARM::AEK_MAVERICK, Feature_None, {} },
9931   { ARM::AEK_XSCALE, Feature_None, {} },
9932 };
9933
9934 /// parseDirectiveArchExtension
9935 ///   ::= .arch_extension [no]feature
9936 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
9937   MCAsmParser &Parser = getParser();
9938
9939   if (getLexer().isNot(AsmToken::Identifier)) {
9940     Error(getLexer().getLoc(), "unexpected token");
9941     Parser.eatToEndOfStatement();
9942     return false;
9943   }
9944
9945   StringRef Name = Parser.getTok().getString();
9946   SMLoc ExtLoc = Parser.getTok().getLoc();
9947   getLexer().Lex();
9948
9949   bool EnableFeature = true;
9950   if (Name.startswith_lower("no")) {
9951     EnableFeature = false;
9952     Name = Name.substr(2);
9953   }
9954   unsigned FeatureKind = ARM::parseArchExt(Name);
9955   if (FeatureKind == ARM::AEK_INVALID)
9956     Error(ExtLoc, "unknown architectural extension: " + Name);
9957
9958   for (const auto &Extension : Extensions) {
9959     if (Extension.Kind != FeatureKind)
9960       continue;
9961
9962     if (Extension.Features.none())
9963       report_fatal_error("unsupported architectural extension: " + Name);
9964
9965     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck) {
9966       Error(ExtLoc, "architectural extension '" + Name + "' is not "
9967             "allowed for the current base architecture");
9968       return false;
9969     }
9970
9971     FeatureBitset ToggleFeatures = EnableFeature
9972       ? (~STI.getFeatureBits() & Extension.Features)
9973       : ( STI.getFeatureBits() & Extension.Features);
9974
9975     uint64_t Features =
9976         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
9977     setAvailableFeatures(Features);
9978     return false;
9979   }
9980
9981   Error(ExtLoc, "unknown architectural extension: " + Name);
9982   Parser.eatToEndOfStatement();
9983   return false;
9984 }
9985
9986 // Define this matcher function after the auto-generated include so we
9987 // have the match class enum definitions.
9988 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
9989                                                   unsigned Kind) {
9990   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
9991   // If the kind is a token for a literal immediate, check if our asm
9992   // operand matches. This is for InstAliases which have a fixed-value
9993   // immediate in the syntax.
9994   switch (Kind) {
9995   default: break;
9996   case MCK__35_0:
9997     if (Op.isImm())
9998       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
9999         if (CE->getValue() == 0)
10000           return Match_Success;
10001     break;
10002   case MCK_ModImm:
10003     if (Op.isImm()) {
10004       const MCExpr *SOExpr = Op.getImm();
10005       int64_t Value;
10006       if (!SOExpr->evaluateAsAbsolute(Value))
10007         return Match_Success;
10008       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
10009              "expression value must be representable in 32 bits");
10010     }
10011     break;
10012   case MCK_rGPR:
10013     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10014       return Match_Success;
10015     break;
10016   case MCK_GPRPair:
10017     if (Op.isReg() &&
10018         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10019       return Match_Success;
10020     break;
10021   }
10022   return Match_InvalidOperand;
10023 }