2d291bf8652cbcd5128a05d32364b5610016aef1
[oota-llvm.git] / lib / Target / ARM / AsmParser / ARMAsmParser.cpp
1 //===-- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "ARMFeatures.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMMCExpr.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDisassembler.h"
23 #include "llvm/MC/MCELFStreamer.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCObjectFileInfo.h"
29 #include "llvm/MC/MCParser/MCAsmLexer.h"
30 #include "llvm/MC/MCParser/MCAsmParser.h"
31 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
32 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
33 #include "llvm/MC/MCRegisterInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSubtargetInfo.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/MC/MCTargetAsmParser.h"
39 #include "llvm/Support/ARMBuildAttributes.h"
40 #include "llvm/Support/ARMEHABI.h"
41 #include "llvm/Support/TargetParser.h"
42 #include "llvm/Support/COFF.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/raw_ostream.h"
49
50 using namespace llvm;
51
52 namespace {
53
54 class ARMOperand;
55
56 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
57
58 class UnwindContext {
59   MCAsmParser &Parser;
60
61   typedef SmallVector<SMLoc, 4> Locs;
62
63   Locs FnStartLocs;
64   Locs CantUnwindLocs;
65   Locs PersonalityLocs;
66   Locs PersonalityIndexLocs;
67   Locs HandlerDataLocs;
68   int FPReg;
69
70 public:
71   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
72
73   bool hasFnStart() const { return !FnStartLocs.empty(); }
74   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
75   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
76   bool hasPersonality() const {
77     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
78   }
79
80   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
81   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
82   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
83   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
84   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
85
86   void saveFPReg(int Reg) { FPReg = Reg; }
87   int getFPReg() const { return FPReg; }
88
89   void emitFnStartLocNotes() const {
90     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
91          FI != FE; ++FI)
92       Parser.Note(*FI, ".fnstart was specified here");
93   }
94   void emitCantUnwindLocNotes() const {
95     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
96                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
97       Parser.Note(*UI, ".cantunwind was specified here");
98   }
99   void emitHandlerDataLocNotes() const {
100     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
101                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
102       Parser.Note(*HI, ".handlerdata was specified here");
103   }
104   void emitPersonalityLocNotes() const {
105     for (Locs::const_iterator PI = PersonalityLocs.begin(),
106                               PE = PersonalityLocs.end(),
107                               PII = PersonalityIndexLocs.begin(),
108                               PIE = PersonalityIndexLocs.end();
109          PI != PE || PII != PIE;) {
110       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
111         Parser.Note(*PI++, ".personality was specified here");
112       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
113         Parser.Note(*PII++, ".personalityindex was specified here");
114       else
115         llvm_unreachable(".personality and .personalityindex cannot be "
116                          "at the same location");
117     }
118   }
119
120   void reset() {
121     FnStartLocs = Locs();
122     CantUnwindLocs = Locs();
123     PersonalityLocs = Locs();
124     HandlerDataLocs = Locs();
125     PersonalityIndexLocs = Locs();
126     FPReg = ARM::SP;
127   }
128 };
129
130 class ARMAsmParser : public MCTargetAsmParser {
131   MCSubtargetInfo &STI;
132   const MCInstrInfo &MII;
133   const MCRegisterInfo *MRI;
134   UnwindContext UC;
135
136   ARMTargetStreamer &getTargetStreamer() {
137     assert(getParser().getStreamer().getTargetStreamer() &&
138            "do not have a target streamer");
139     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
140     return static_cast<ARMTargetStreamer &>(TS);
141   }
142
143   // Map of register aliases registers via the .req directive.
144   StringMap<unsigned> RegisterReqs;
145
146   bool NextSymbolIsThumb;
147
148   struct {
149     ARMCC::CondCodes Cond;    // Condition for IT block.
150     unsigned Mask:4;          // Condition mask for instructions.
151                               // Starting at first 1 (from lsb).
152                               //   '1'  condition as indicated in IT.
153                               //   '0'  inverse of condition (else).
154                               // Count of instructions in IT block is
155                               // 4 - trailingzeroes(mask)
156
157     bool FirstCond;           // Explicit flag for when we're parsing the
158                               // First instruction in the IT block. It's
159                               // implied in the mask, so needs special
160                               // handling.
161
162     unsigned CurPosition;     // Current position in parsing of IT
163                               // block. In range [0,3]. Initialized
164                               // according to count of instructions in block.
165                               // ~0U if no active IT block.
166   } ITState;
167   bool inITBlock() { return ITState.CurPosition != ~0U; }
168   bool lastInITBlock() {
169     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
170   }
171   void forwardITPosition() {
172     if (!inITBlock()) return;
173     // Move to the next instruction in the IT block, if there is one. If not,
174     // mark the block as done.
175     unsigned TZ = countTrailingZeros(ITState.Mask);
176     if (++ITState.CurPosition == 5 - TZ)
177       ITState.CurPosition = ~0U; // Done with the IT block after this.
178   }
179
180   void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None) {
181     return getParser().Note(L, Msg, Ranges);
182   }
183   bool Warning(SMLoc L, const Twine &Msg,
184                ArrayRef<SMRange> Ranges = None) {
185     return getParser().Warning(L, Msg, Ranges);
186   }
187   bool Error(SMLoc L, const Twine &Msg,
188              ArrayRef<SMRange> Ranges = None) {
189     return getParser().Error(L, Msg, Ranges);
190   }
191
192   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
193                            unsigned ListNo, bool IsARPop = false);
194   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
195                            unsigned ListNo);
196
197   int tryParseRegister();
198   bool tryParseRegisterWithWriteBack(OperandVector &);
199   int tryParseShiftRegister(OperandVector &);
200   bool parseRegisterList(OperandVector &);
201   bool parseMemory(OperandVector &);
202   bool parseOperand(OperandVector &, StringRef Mnemonic);
203   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
204   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
205                               unsigned &ShiftAmount);
206   bool parseLiteralValues(unsigned Size, SMLoc L);
207   bool parseDirectiveThumb(SMLoc L);
208   bool parseDirectiveARM(SMLoc L);
209   bool parseDirectiveThumbFunc(SMLoc L);
210   bool parseDirectiveCode(SMLoc L);
211   bool parseDirectiveSyntax(SMLoc L);
212   bool parseDirectiveReq(StringRef Name, SMLoc L);
213   bool parseDirectiveUnreq(SMLoc L);
214   bool parseDirectiveArch(SMLoc L);
215   bool parseDirectiveEabiAttr(SMLoc L);
216   bool parseDirectiveCPU(SMLoc L);
217   bool parseDirectiveFPU(SMLoc L);
218   bool parseDirectiveFnStart(SMLoc L);
219   bool parseDirectiveFnEnd(SMLoc L);
220   bool parseDirectiveCantUnwind(SMLoc L);
221   bool parseDirectivePersonality(SMLoc L);
222   bool parseDirectiveHandlerData(SMLoc L);
223   bool parseDirectiveSetFP(SMLoc L);
224   bool parseDirectivePad(SMLoc L);
225   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
226   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
227   bool parseDirectiveLtorg(SMLoc L);
228   bool parseDirectiveEven(SMLoc L);
229   bool parseDirectivePersonalityIndex(SMLoc L);
230   bool parseDirectiveUnwindRaw(SMLoc L);
231   bool parseDirectiveTLSDescSeq(SMLoc L);
232   bool parseDirectiveMovSP(SMLoc L);
233   bool parseDirectiveObjectArch(SMLoc L);
234   bool parseDirectiveArchExtension(SMLoc L);
235   bool parseDirectiveAlign(SMLoc L);
236   bool parseDirectiveThumbSet(SMLoc L);
237
238   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
239                           bool &CarrySetting, unsigned &ProcessorIMod,
240                           StringRef &ITMask);
241   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
242                              bool &CanAcceptCarrySet,
243                              bool &CanAcceptPredicationCode);
244
245   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
246                                      OperandVector &Operands);
247   bool isThumb() const {
248     // FIXME: Can tablegen auto-generate this?
249     return STI.getFeatureBits()[ARM::ModeThumb];
250   }
251   bool isThumbOne() const {
252     return isThumb() && !STI.getFeatureBits()[ARM::FeatureThumb2];
253   }
254   bool isThumbTwo() const {
255     return isThumb() && STI.getFeatureBits()[ARM::FeatureThumb2];
256   }
257   bool hasThumb() const {
258     return STI.getFeatureBits()[ARM::HasV4TOps];
259   }
260   bool hasV6Ops() const {
261     return STI.getFeatureBits()[ARM::HasV6Ops];
262   }
263   bool hasV6MOps() const {
264     return STI.getFeatureBits()[ARM::HasV6MOps];
265   }
266   bool hasV7Ops() const {
267     return STI.getFeatureBits()[ARM::HasV7Ops];
268   }
269   bool hasV8Ops() const {
270     return STI.getFeatureBits()[ARM::HasV8Ops];
271   }
272   bool hasARM() const {
273     return !STI.getFeatureBits()[ARM::FeatureNoARM];
274   }
275   bool hasThumb2DSP() const {
276     return STI.getFeatureBits()[ARM::FeatureDSPThumb2];
277   }
278   bool hasD16() const {
279     return STI.getFeatureBits()[ARM::FeatureD16];
280   }
281   bool hasV8_1aOps() const {
282     return STI.getFeatureBits()[ARM::HasV8_1aOps];
283   }
284
285   void SwitchMode() {
286     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
287     setAvailableFeatures(FB);
288   }
289   bool isMClass() const {
290     return STI.getFeatureBits()[ARM::FeatureMClass];
291   }
292
293   /// @name Auto-generated Match Functions
294   /// {
295
296 #define GET_ASSEMBLER_HEADER
297 #include "ARMGenAsmMatcher.inc"
298
299   /// }
300
301   OperandMatchResultTy parseITCondCode(OperandVector &);
302   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
303   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
304   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
305   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
306   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
307   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
308   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
309   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
310   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
311                                    int High);
312   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
313     return parsePKHImm(O, "lsl", 0, 31);
314   }
315   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
316     return parsePKHImm(O, "asr", 1, 32);
317   }
318   OperandMatchResultTy parseSetEndImm(OperandVector &);
319   OperandMatchResultTy parseShifterImm(OperandVector &);
320   OperandMatchResultTy parseRotImm(OperandVector &);
321   OperandMatchResultTy parseModImm(OperandVector &);
322   OperandMatchResultTy parseBitfield(OperandVector &);
323   OperandMatchResultTy parsePostIdxReg(OperandVector &);
324   OperandMatchResultTy parseAM3Offset(OperandVector &);
325   OperandMatchResultTy parseFPImm(OperandVector &);
326   OperandMatchResultTy parseVectorList(OperandVector &);
327   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
328                                        SMLoc &EndLoc);
329
330   // Asm Match Converter Methods
331   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
332   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
333
334   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
335   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
336   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
337   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
338
339 public:
340   enum ARMMatchResultTy {
341     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
342     Match_RequiresNotITBlock,
343     Match_RequiresV6,
344     Match_RequiresThumb2,
345 #define GET_OPERAND_DIAGNOSTIC_TYPES
346 #include "ARMGenAsmMatcher.inc"
347
348   };
349
350   ARMAsmParser(MCSubtargetInfo &STI, MCAsmParser &Parser,
351                const MCInstrInfo &MII, const MCTargetOptions &Options)
352       : MCTargetAsmParser(Options), STI(STI), MII(MII), UC(Parser) {
353     MCAsmParserExtension::Initialize(Parser);
354
355     // Cache the MCRegisterInfo.
356     MRI = getContext().getRegisterInfo();
357
358     // Initialize the set of available features.
359     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
360
361     // Not in an ITBlock to start with.
362     ITState.CurPosition = ~0U;
363
364     NextSymbolIsThumb = false;
365   }
366
367   // Implementation of the MCTargetAsmParser interface:
368   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
369   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
370                         SMLoc NameLoc, OperandVector &Operands) override;
371   bool ParseDirective(AsmToken DirectiveID) override;
372
373   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
374                                       unsigned Kind) override;
375   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
376
377   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
378                                OperandVector &Operands, MCStreamer &Out,
379                                uint64_t &ErrorInfo,
380                                bool MatchingInlineAsm) override;
381   void onLabelParsed(MCSymbol *Symbol) override;
382 };
383 } // end anonymous namespace
384
385 namespace {
386
387 /// ARMOperand - Instances of this class represent a parsed ARM machine
388 /// operand.
389 class ARMOperand : public MCParsedAsmOperand {
390   enum KindTy {
391     k_CondCode,
392     k_CCOut,
393     k_ITCondMask,
394     k_CoprocNum,
395     k_CoprocReg,
396     k_CoprocOption,
397     k_Immediate,
398     k_MemBarrierOpt,
399     k_InstSyncBarrierOpt,
400     k_Memory,
401     k_PostIndexRegister,
402     k_MSRMask,
403     k_BankedReg,
404     k_ProcIFlags,
405     k_VectorIndex,
406     k_Register,
407     k_RegisterList,
408     k_DPRRegisterList,
409     k_SPRRegisterList,
410     k_VectorList,
411     k_VectorListAllLanes,
412     k_VectorListIndexed,
413     k_ShiftedRegister,
414     k_ShiftedImmediate,
415     k_ShifterImmediate,
416     k_RotateImmediate,
417     k_ModifiedImmediate,
418     k_BitfieldDescriptor,
419     k_Token
420   } Kind;
421
422   SMLoc StartLoc, EndLoc, AlignmentLoc;
423   SmallVector<unsigned, 8> Registers;
424
425   struct CCOp {
426     ARMCC::CondCodes Val;
427   };
428
429   struct CopOp {
430     unsigned Val;
431   };
432
433   struct CoprocOptionOp {
434     unsigned Val;
435   };
436
437   struct ITMaskOp {
438     unsigned Mask:4;
439   };
440
441   struct MBOptOp {
442     ARM_MB::MemBOpt Val;
443   };
444
445   struct ISBOptOp {
446     ARM_ISB::InstSyncBOpt Val;
447   };
448
449   struct IFlagsOp {
450     ARM_PROC::IFlags Val;
451   };
452
453   struct MMaskOp {
454     unsigned Val;
455   };
456
457   struct BankedRegOp {
458     unsigned Val;
459   };
460
461   struct TokOp {
462     const char *Data;
463     unsigned Length;
464   };
465
466   struct RegOp {
467     unsigned RegNum;
468   };
469
470   // A vector register list is a sequential list of 1 to 4 registers.
471   struct VectorListOp {
472     unsigned RegNum;
473     unsigned Count;
474     unsigned LaneIndex;
475     bool isDoubleSpaced;
476   };
477
478   struct VectorIndexOp {
479     unsigned Val;
480   };
481
482   struct ImmOp {
483     const MCExpr *Val;
484   };
485
486   /// Combined record for all forms of ARM address expressions.
487   struct MemoryOp {
488     unsigned BaseRegNum;
489     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
490     // was specified.
491     const MCConstantExpr *OffsetImm;  // Offset immediate value
492     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
493     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
494     unsigned ShiftImm;        // shift for OffsetReg.
495     unsigned Alignment;       // 0 = no alignment specified
496     // n = alignment in bytes (2, 4, 8, 16, or 32)
497     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
498   };
499
500   struct PostIdxRegOp {
501     unsigned RegNum;
502     bool isAdd;
503     ARM_AM::ShiftOpc ShiftTy;
504     unsigned ShiftImm;
505   };
506
507   struct ShifterImmOp {
508     bool isASR;
509     unsigned Imm;
510   };
511
512   struct RegShiftedRegOp {
513     ARM_AM::ShiftOpc ShiftTy;
514     unsigned SrcReg;
515     unsigned ShiftReg;
516     unsigned ShiftImm;
517   };
518
519   struct RegShiftedImmOp {
520     ARM_AM::ShiftOpc ShiftTy;
521     unsigned SrcReg;
522     unsigned ShiftImm;
523   };
524
525   struct RotImmOp {
526     unsigned Imm;
527   };
528
529   struct ModImmOp {
530     unsigned Bits;
531     unsigned Rot;
532   };
533
534   struct BitfieldOp {
535     unsigned LSB;
536     unsigned Width;
537   };
538
539   union {
540     struct CCOp CC;
541     struct CopOp Cop;
542     struct CoprocOptionOp CoprocOption;
543     struct MBOptOp MBOpt;
544     struct ISBOptOp ISBOpt;
545     struct ITMaskOp ITMask;
546     struct IFlagsOp IFlags;
547     struct MMaskOp MMask;
548     struct BankedRegOp BankedReg;
549     struct TokOp Tok;
550     struct RegOp Reg;
551     struct VectorListOp VectorList;
552     struct VectorIndexOp VectorIndex;
553     struct ImmOp Imm;
554     struct MemoryOp Memory;
555     struct PostIdxRegOp PostIdxReg;
556     struct ShifterImmOp ShifterImm;
557     struct RegShiftedRegOp RegShiftedReg;
558     struct RegShiftedImmOp RegShiftedImm;
559     struct RotImmOp RotImm;
560     struct ModImmOp ModImm;
561     struct BitfieldOp Bitfield;
562   };
563
564 public:
565   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
566
567   /// getStartLoc - Get the location of the first token of this operand.
568   SMLoc getStartLoc() const override { return StartLoc; }
569   /// getEndLoc - Get the location of the last token of this operand.
570   SMLoc getEndLoc() const override { return EndLoc; }
571   /// getLocRange - Get the range between the first and last token of this
572   /// operand.
573   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
574
575   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
576   SMLoc getAlignmentLoc() const {
577     assert(Kind == k_Memory && "Invalid access!");
578     return AlignmentLoc;
579   }
580
581   ARMCC::CondCodes getCondCode() const {
582     assert(Kind == k_CondCode && "Invalid access!");
583     return CC.Val;
584   }
585
586   unsigned getCoproc() const {
587     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
588     return Cop.Val;
589   }
590
591   StringRef getToken() const {
592     assert(Kind == k_Token && "Invalid access!");
593     return StringRef(Tok.Data, Tok.Length);
594   }
595
596   unsigned getReg() const override {
597     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
598     return Reg.RegNum;
599   }
600
601   const SmallVectorImpl<unsigned> &getRegList() const {
602     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
603             Kind == k_SPRRegisterList) && "Invalid access!");
604     return Registers;
605   }
606
607   const MCExpr *getImm() const {
608     assert(isImm() && "Invalid access!");
609     return Imm.Val;
610   }
611
612   unsigned getVectorIndex() const {
613     assert(Kind == k_VectorIndex && "Invalid access!");
614     return VectorIndex.Val;
615   }
616
617   ARM_MB::MemBOpt getMemBarrierOpt() const {
618     assert(Kind == k_MemBarrierOpt && "Invalid access!");
619     return MBOpt.Val;
620   }
621
622   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
623     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
624     return ISBOpt.Val;
625   }
626
627   ARM_PROC::IFlags getProcIFlags() const {
628     assert(Kind == k_ProcIFlags && "Invalid access!");
629     return IFlags.Val;
630   }
631
632   unsigned getMSRMask() const {
633     assert(Kind == k_MSRMask && "Invalid access!");
634     return MMask.Val;
635   }
636
637   unsigned getBankedReg() const {
638     assert(Kind == k_BankedReg && "Invalid access!");
639     return BankedReg.Val;
640   }
641
642   bool isCoprocNum() const { return Kind == k_CoprocNum; }
643   bool isCoprocReg() const { return Kind == k_CoprocReg; }
644   bool isCoprocOption() const { return Kind == k_CoprocOption; }
645   bool isCondCode() const { return Kind == k_CondCode; }
646   bool isCCOut() const { return Kind == k_CCOut; }
647   bool isITMask() const { return Kind == k_ITCondMask; }
648   bool isITCondCode() const { return Kind == k_CondCode; }
649   bool isImm() const override { return Kind == k_Immediate; }
650   // checks whether this operand is an unsigned offset which fits is a field
651   // of specified width and scaled by a specific number of bits
652   template<unsigned width, unsigned scale>
653   bool isUnsignedOffset() const {
654     if (!isImm()) return false;
655     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
656     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
657       int64_t Val = CE->getValue();
658       int64_t Align = 1LL << scale;
659       int64_t Max = Align * ((1LL << width) - 1);
660       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
661     }
662     return false;
663   }
664   // checks whether this operand is an signed offset which fits is a field
665   // of specified width and scaled by a specific number of bits
666   template<unsigned width, unsigned scale>
667   bool isSignedOffset() const {
668     if (!isImm()) return false;
669     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
670     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
671       int64_t Val = CE->getValue();
672       int64_t Align = 1LL << scale;
673       int64_t Max = Align * ((1LL << (width-1)) - 1);
674       int64_t Min = -Align * (1LL << (width-1));
675       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
676     }
677     return false;
678   }
679
680   // checks whether this operand is a memory operand computed as an offset
681   // applied to PC. the offset may have 8 bits of magnitude and is represented
682   // with two bits of shift. textually it may be either [pc, #imm], #imm or 
683   // relocable expression...
684   bool isThumbMemPC() const {
685     int64_t Val = 0;
686     if (isImm()) {
687       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
688       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
689       if (!CE) return false;
690       Val = CE->getValue();
691     }
692     else if (isMem()) {
693       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
694       if(Memory.BaseRegNum != ARM::PC) return false;
695       Val = Memory.OffsetImm->getValue();
696     }
697     else return false;
698     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
699   }
700   bool isFPImm() const {
701     if (!isImm()) return false;
702     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
703     if (!CE) return false;
704     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
705     return Val != -1;
706   }
707   bool isFBits16() const {
708     if (!isImm()) return false;
709     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
710     if (!CE) return false;
711     int64_t Value = CE->getValue();
712     return Value >= 0 && Value <= 16;
713   }
714   bool isFBits32() const {
715     if (!isImm()) return false;
716     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
717     if (!CE) return false;
718     int64_t Value = CE->getValue();
719     return Value >= 1 && Value <= 32;
720   }
721   bool isImm8s4() const {
722     if (!isImm()) return false;
723     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
724     if (!CE) return false;
725     int64_t Value = CE->getValue();
726     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
727   }
728   bool isImm0_1020s4() const {
729     if (!isImm()) return false;
730     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
731     if (!CE) return false;
732     int64_t Value = CE->getValue();
733     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
734   }
735   bool isImm0_508s4() const {
736     if (!isImm()) return false;
737     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
738     if (!CE) return false;
739     int64_t Value = CE->getValue();
740     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
741   }
742   bool isImm0_508s4Neg() const {
743     if (!isImm()) return false;
744     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
745     if (!CE) return false;
746     int64_t Value = -CE->getValue();
747     // explicitly exclude zero. we want that to use the normal 0_508 version.
748     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
749   }
750   bool isImm0_239() const {
751     if (!isImm()) return false;
752     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
753     if (!CE) return false;
754     int64_t Value = CE->getValue();
755     return Value >= 0 && Value < 240;
756   }
757   bool isImm0_255() const {
758     if (!isImm()) return false;
759     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
760     if (!CE) return false;
761     int64_t Value = CE->getValue();
762     return Value >= 0 && Value < 256;
763   }
764   bool isImm0_4095() const {
765     if (!isImm()) return false;
766     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
767     if (!CE) return false;
768     int64_t Value = CE->getValue();
769     return Value >= 0 && Value < 4096;
770   }
771   bool isImm0_4095Neg() const {
772     if (!isImm()) return false;
773     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
774     if (!CE) return false;
775     int64_t Value = -CE->getValue();
776     return Value > 0 && Value < 4096;
777   }
778   bool isImm0_1() const {
779     if (!isImm()) return false;
780     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
781     if (!CE) return false;
782     int64_t Value = CE->getValue();
783     return Value >= 0 && Value < 2;
784   }
785   bool isImm0_3() const {
786     if (!isImm()) return false;
787     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
788     if (!CE) return false;
789     int64_t Value = CE->getValue();
790     return Value >= 0 && Value < 4;
791   }
792   bool isImm0_7() const {
793     if (!isImm()) return false;
794     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
795     if (!CE) return false;
796     int64_t Value = CE->getValue();
797     return Value >= 0 && Value < 8;
798   }
799   bool isImm0_15() const {
800     if (!isImm()) return false;
801     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
802     if (!CE) return false;
803     int64_t Value = CE->getValue();
804     return Value >= 0 && Value < 16;
805   }
806   bool isImm0_31() const {
807     if (!isImm()) return false;
808     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
809     if (!CE) return false;
810     int64_t Value = CE->getValue();
811     return Value >= 0 && Value < 32;
812   }
813   bool isImm0_63() const {
814     if (!isImm()) return false;
815     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
816     if (!CE) return false;
817     int64_t Value = CE->getValue();
818     return Value >= 0 && Value < 64;
819   }
820   bool isImm8() const {
821     if (!isImm()) return false;
822     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
823     if (!CE) return false;
824     int64_t Value = CE->getValue();
825     return Value == 8;
826   }
827   bool isImm16() const {
828     if (!isImm()) return false;
829     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
830     if (!CE) return false;
831     int64_t Value = CE->getValue();
832     return Value == 16;
833   }
834   bool isImm32() const {
835     if (!isImm()) return false;
836     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
837     if (!CE) return false;
838     int64_t Value = CE->getValue();
839     return Value == 32;
840   }
841   bool isShrImm8() const {
842     if (!isImm()) return false;
843     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
844     if (!CE) return false;
845     int64_t Value = CE->getValue();
846     return Value > 0 && Value <= 8;
847   }
848   bool isShrImm16() const {
849     if (!isImm()) return false;
850     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
851     if (!CE) return false;
852     int64_t Value = CE->getValue();
853     return Value > 0 && Value <= 16;
854   }
855   bool isShrImm32() const {
856     if (!isImm()) return false;
857     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
858     if (!CE) return false;
859     int64_t Value = CE->getValue();
860     return Value > 0 && Value <= 32;
861   }
862   bool isShrImm64() const {
863     if (!isImm()) return false;
864     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
865     if (!CE) return false;
866     int64_t Value = CE->getValue();
867     return Value > 0 && Value <= 64;
868   }
869   bool isImm1_7() const {
870     if (!isImm()) return false;
871     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
872     if (!CE) return false;
873     int64_t Value = CE->getValue();
874     return Value > 0 && Value < 8;
875   }
876   bool isImm1_15() const {
877     if (!isImm()) return false;
878     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
879     if (!CE) return false;
880     int64_t Value = CE->getValue();
881     return Value > 0 && Value < 16;
882   }
883   bool isImm1_31() const {
884     if (!isImm()) return false;
885     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
886     if (!CE) return false;
887     int64_t Value = CE->getValue();
888     return Value > 0 && Value < 32;
889   }
890   bool isImm1_16() const {
891     if (!isImm()) return false;
892     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
893     if (!CE) return false;
894     int64_t Value = CE->getValue();
895     return Value > 0 && Value < 17;
896   }
897   bool isImm1_32() const {
898     if (!isImm()) return false;
899     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
900     if (!CE) return false;
901     int64_t Value = CE->getValue();
902     return Value > 0 && Value < 33;
903   }
904   bool isImm0_32() const {
905     if (!isImm()) return false;
906     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
907     if (!CE) return false;
908     int64_t Value = CE->getValue();
909     return Value >= 0 && Value < 33;
910   }
911   bool isImm0_65535() const {
912     if (!isImm()) return false;
913     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
914     if (!CE) return false;
915     int64_t Value = CE->getValue();
916     return Value >= 0 && Value < 65536;
917   }
918   bool isImm256_65535Expr() const {
919     if (!isImm()) return false;
920     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
921     // If it's not a constant expression, it'll generate a fixup and be
922     // handled later.
923     if (!CE) return true;
924     int64_t Value = CE->getValue();
925     return Value >= 256 && Value < 65536;
926   }
927   bool isImm0_65535Expr() const {
928     if (!isImm()) return false;
929     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
930     // If it's not a constant expression, it'll generate a fixup and be
931     // handled later.
932     if (!CE) return true;
933     int64_t Value = CE->getValue();
934     return Value >= 0 && Value < 65536;
935   }
936   bool isImm24bit() const {
937     if (!isImm()) return false;
938     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
939     if (!CE) return false;
940     int64_t Value = CE->getValue();
941     return Value >= 0 && Value <= 0xffffff;
942   }
943   bool isImmThumbSR() const {
944     if (!isImm()) return false;
945     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
946     if (!CE) return false;
947     int64_t Value = CE->getValue();
948     return Value > 0 && Value < 33;
949   }
950   bool isPKHLSLImm() const {
951     if (!isImm()) return false;
952     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
953     if (!CE) return false;
954     int64_t Value = CE->getValue();
955     return Value >= 0 && Value < 32;
956   }
957   bool isPKHASRImm() const {
958     if (!isImm()) return false;
959     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
960     if (!CE) return false;
961     int64_t Value = CE->getValue();
962     return Value > 0 && Value <= 32;
963   }
964   bool isAdrLabel() const {
965     // If we have an immediate that's not a constant, treat it as a label
966     // reference needing a fixup.
967     if (isImm() && !isa<MCConstantExpr>(getImm()))
968       return true;
969
970     // If it is a constant, it must fit into a modified immediate encoding.
971     if (!isImm()) return false;
972     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
973     if (!CE) return false;
974     int64_t Value = CE->getValue();
975     return (ARM_AM::getSOImmVal(Value) != -1 ||
976             ARM_AM::getSOImmVal(-Value) != -1);
977   }
978   bool isT2SOImm() const {
979     if (!isImm()) return false;
980     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
981     if (!CE) return false;
982     int64_t Value = CE->getValue();
983     return ARM_AM::getT2SOImmVal(Value) != -1;
984   }
985   bool isT2SOImmNot() const {
986     if (!isImm()) return false;
987     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
988     if (!CE) return false;
989     int64_t Value = CE->getValue();
990     return ARM_AM::getT2SOImmVal(Value) == -1 &&
991       ARM_AM::getT2SOImmVal(~Value) != -1;
992   }
993   bool isT2SOImmNeg() const {
994     if (!isImm()) return false;
995     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
996     if (!CE) return false;
997     int64_t Value = CE->getValue();
998     // Only use this when not representable as a plain so_imm.
999     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1000       ARM_AM::getT2SOImmVal(-Value) != -1;
1001   }
1002   bool isSetEndImm() const {
1003     if (!isImm()) return false;
1004     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1005     if (!CE) return false;
1006     int64_t Value = CE->getValue();
1007     return Value == 1 || Value == 0;
1008   }
1009   bool isReg() const override { return Kind == k_Register; }
1010   bool isRegList() const { return Kind == k_RegisterList; }
1011   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1012   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1013   bool isToken() const override { return Kind == k_Token; }
1014   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1015   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1016   bool isMem() const override { return Kind == k_Memory; }
1017   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1018   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1019   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1020   bool isRotImm() const { return Kind == k_RotateImmediate; }
1021   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1022   bool isModImmNot() const {
1023     if (!isImm()) return false;
1024     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1025     if (!CE) return false;
1026     int64_t Value = CE->getValue();
1027     return ARM_AM::getSOImmVal(~Value) != -1;
1028   }
1029   bool isModImmNeg() const {
1030     if (!isImm()) return false;
1031     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1032     if (!CE) return false;
1033     int64_t Value = CE->getValue();
1034     return ARM_AM::getSOImmVal(Value) == -1 &&
1035       ARM_AM::getSOImmVal(-Value) != -1;
1036   }
1037   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1038   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1039   bool isPostIdxReg() const {
1040     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1041   }
1042   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1043     if (!isMem())
1044       return false;
1045     // No offset of any kind.
1046     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1047      (alignOK || Memory.Alignment == Alignment);
1048   }
1049   bool isMemPCRelImm12() const {
1050     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1051       return false;
1052     // Base register must be PC.
1053     if (Memory.BaseRegNum != ARM::PC)
1054       return false;
1055     // Immediate offset in range [-4095, 4095].
1056     if (!Memory.OffsetImm) return true;
1057     int64_t Val = Memory.OffsetImm->getValue();
1058     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1059   }
1060   bool isAlignedMemory() const {
1061     return isMemNoOffset(true);
1062   }
1063   bool isAlignedMemoryNone() const {
1064     return isMemNoOffset(false, 0);
1065   }
1066   bool isDupAlignedMemoryNone() const {
1067     return isMemNoOffset(false, 0);
1068   }
1069   bool isAlignedMemory16() const {
1070     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1071       return true;
1072     return isMemNoOffset(false, 0);
1073   }
1074   bool isDupAlignedMemory16() const {
1075     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1076       return true;
1077     return isMemNoOffset(false, 0);
1078   }
1079   bool isAlignedMemory32() const {
1080     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1081       return true;
1082     return isMemNoOffset(false, 0);
1083   }
1084   bool isDupAlignedMemory32() const {
1085     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1086       return true;
1087     return isMemNoOffset(false, 0);
1088   }
1089   bool isAlignedMemory64() const {
1090     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1091       return true;
1092     return isMemNoOffset(false, 0);
1093   }
1094   bool isDupAlignedMemory64() const {
1095     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1096       return true;
1097     return isMemNoOffset(false, 0);
1098   }
1099   bool isAlignedMemory64or128() const {
1100     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1101       return true;
1102     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1103       return true;
1104     return isMemNoOffset(false, 0);
1105   }
1106   bool isDupAlignedMemory64or128() const {
1107     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1108       return true;
1109     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1110       return true;
1111     return isMemNoOffset(false, 0);
1112   }
1113   bool isAlignedMemory64or128or256() const {
1114     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1115       return true;
1116     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1117       return true;
1118     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1119       return true;
1120     return isMemNoOffset(false, 0);
1121   }
1122   bool isAddrMode2() const {
1123     if (!isMem() || Memory.Alignment != 0) return false;
1124     // Check for register offset.
1125     if (Memory.OffsetRegNum) return true;
1126     // Immediate offset in range [-4095, 4095].
1127     if (!Memory.OffsetImm) return true;
1128     int64_t Val = Memory.OffsetImm->getValue();
1129     return Val > -4096 && Val < 4096;
1130   }
1131   bool isAM2OffsetImm() const {
1132     if (!isImm()) return false;
1133     // Immediate offset in range [-4095, 4095].
1134     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1135     if (!CE) return false;
1136     int64_t Val = CE->getValue();
1137     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1138   }
1139   bool isAddrMode3() const {
1140     // If we have an immediate that's not a constant, treat it as a label
1141     // reference needing a fixup. If it is a constant, it's something else
1142     // and we reject it.
1143     if (isImm() && !isa<MCConstantExpr>(getImm()))
1144       return true;
1145     if (!isMem() || Memory.Alignment != 0) return false;
1146     // No shifts are legal for AM3.
1147     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1148     // Check for register offset.
1149     if (Memory.OffsetRegNum) return true;
1150     // Immediate offset in range [-255, 255].
1151     if (!Memory.OffsetImm) return true;
1152     int64_t Val = Memory.OffsetImm->getValue();
1153     // The #-0 offset is encoded as INT32_MIN, and we have to check 
1154     // for this too.
1155     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1156   }
1157   bool isAM3Offset() const {
1158     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1159       return false;
1160     if (Kind == k_PostIndexRegister)
1161       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1162     // Immediate offset in range [-255, 255].
1163     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1164     if (!CE) return false;
1165     int64_t Val = CE->getValue();
1166     // Special case, #-0 is INT32_MIN.
1167     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1168   }
1169   bool isAddrMode5() const {
1170     // If we have an immediate that's not a constant, treat it as a label
1171     // reference needing a fixup. If it is a constant, it's something else
1172     // and we reject it.
1173     if (isImm() && !isa<MCConstantExpr>(getImm()))
1174       return true;
1175     if (!isMem() || Memory.Alignment != 0) return false;
1176     // Check for register offset.
1177     if (Memory.OffsetRegNum) return false;
1178     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1179     if (!Memory.OffsetImm) return true;
1180     int64_t Val = Memory.OffsetImm->getValue();
1181     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1182       Val == INT32_MIN;
1183   }
1184   bool isMemTBB() const {
1185     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1186         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1187       return false;
1188     return true;
1189   }
1190   bool isMemTBH() const {
1191     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1192         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1193         Memory.Alignment != 0 )
1194       return false;
1195     return true;
1196   }
1197   bool isMemRegOffset() const {
1198     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1199       return false;
1200     return true;
1201   }
1202   bool isT2MemRegOffset() const {
1203     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1204         Memory.Alignment != 0)
1205       return false;
1206     // Only lsl #{0, 1, 2, 3} allowed.
1207     if (Memory.ShiftType == ARM_AM::no_shift)
1208       return true;
1209     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1210       return false;
1211     return true;
1212   }
1213   bool isMemThumbRR() const {
1214     // Thumb reg+reg addressing is simple. Just two registers, a base and
1215     // an offset. No shifts, negations or any other complicating factors.
1216     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1217         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1218       return false;
1219     return isARMLowRegister(Memory.BaseRegNum) &&
1220       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1221   }
1222   bool isMemThumbRIs4() const {
1223     if (!isMem() || Memory.OffsetRegNum != 0 ||
1224         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1225       return false;
1226     // Immediate offset, multiple of 4 in range [0, 124].
1227     if (!Memory.OffsetImm) return true;
1228     int64_t Val = Memory.OffsetImm->getValue();
1229     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1230   }
1231   bool isMemThumbRIs2() const {
1232     if (!isMem() || Memory.OffsetRegNum != 0 ||
1233         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1234       return false;
1235     // Immediate offset, multiple of 4 in range [0, 62].
1236     if (!Memory.OffsetImm) return true;
1237     int64_t Val = Memory.OffsetImm->getValue();
1238     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1239   }
1240   bool isMemThumbRIs1() const {
1241     if (!isMem() || Memory.OffsetRegNum != 0 ||
1242         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1243       return false;
1244     // Immediate offset in range [0, 31].
1245     if (!Memory.OffsetImm) return true;
1246     int64_t Val = Memory.OffsetImm->getValue();
1247     return Val >= 0 && Val <= 31;
1248   }
1249   bool isMemThumbSPI() const {
1250     if (!isMem() || Memory.OffsetRegNum != 0 ||
1251         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1252       return false;
1253     // Immediate offset, multiple of 4 in range [0, 1020].
1254     if (!Memory.OffsetImm) return true;
1255     int64_t Val = Memory.OffsetImm->getValue();
1256     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1257   }
1258   bool isMemImm8s4Offset() const {
1259     // If we have an immediate that's not a constant, treat it as a label
1260     // reference needing a fixup. If it is a constant, it's something else
1261     // and we reject it.
1262     if (isImm() && !isa<MCConstantExpr>(getImm()))
1263       return true;
1264     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1265       return false;
1266     // Immediate offset a multiple of 4 in range [-1020, 1020].
1267     if (!Memory.OffsetImm) return true;
1268     int64_t Val = Memory.OffsetImm->getValue();
1269     // Special case, #-0 is INT32_MIN.
1270     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1271   }
1272   bool isMemImm0_1020s4Offset() const {
1273     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1274       return false;
1275     // Immediate offset a multiple of 4 in range [0, 1020].
1276     if (!Memory.OffsetImm) return true;
1277     int64_t Val = Memory.OffsetImm->getValue();
1278     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1279   }
1280   bool isMemImm8Offset() const {
1281     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1282       return false;
1283     // Base reg of PC isn't allowed for these encodings.
1284     if (Memory.BaseRegNum == ARM::PC) return false;
1285     // Immediate offset in range [-255, 255].
1286     if (!Memory.OffsetImm) return true;
1287     int64_t Val = Memory.OffsetImm->getValue();
1288     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1289   }
1290   bool isMemPosImm8Offset() const {
1291     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1292       return false;
1293     // Immediate offset in range [0, 255].
1294     if (!Memory.OffsetImm) return true;
1295     int64_t Val = Memory.OffsetImm->getValue();
1296     return Val >= 0 && Val < 256;
1297   }
1298   bool isMemNegImm8Offset() const {
1299     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1300       return false;
1301     // Base reg of PC isn't allowed for these encodings.
1302     if (Memory.BaseRegNum == ARM::PC) return false;
1303     // Immediate offset in range [-255, -1].
1304     if (!Memory.OffsetImm) return false;
1305     int64_t Val = Memory.OffsetImm->getValue();
1306     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1307   }
1308   bool isMemUImm12Offset() const {
1309     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1310       return false;
1311     // Immediate offset in range [0, 4095].
1312     if (!Memory.OffsetImm) return true;
1313     int64_t Val = Memory.OffsetImm->getValue();
1314     return (Val >= 0 && Val < 4096);
1315   }
1316   bool isMemImm12Offset() const {
1317     // If we have an immediate that's not a constant, treat it as a label
1318     // reference needing a fixup. If it is a constant, it's something else
1319     // and we reject it.
1320     if (isImm() && !isa<MCConstantExpr>(getImm()))
1321       return true;
1322
1323     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1324       return false;
1325     // Immediate offset in range [-4095, 4095].
1326     if (!Memory.OffsetImm) return true;
1327     int64_t Val = Memory.OffsetImm->getValue();
1328     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1329   }
1330   bool isPostIdxImm8() const {
1331     if (!isImm()) return false;
1332     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1333     if (!CE) return false;
1334     int64_t Val = CE->getValue();
1335     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1336   }
1337   bool isPostIdxImm8s4() const {
1338     if (!isImm()) return false;
1339     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1340     if (!CE) return false;
1341     int64_t Val = CE->getValue();
1342     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1343       (Val == INT32_MIN);
1344   }
1345
1346   bool isMSRMask() const { return Kind == k_MSRMask; }
1347   bool isBankedReg() const { return Kind == k_BankedReg; }
1348   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1349
1350   // NEON operands.
1351   bool isSingleSpacedVectorList() const {
1352     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1353   }
1354   bool isDoubleSpacedVectorList() const {
1355     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1356   }
1357   bool isVecListOneD() const {
1358     if (!isSingleSpacedVectorList()) return false;
1359     return VectorList.Count == 1;
1360   }
1361
1362   bool isVecListDPair() const {
1363     if (!isSingleSpacedVectorList()) return false;
1364     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1365               .contains(VectorList.RegNum));
1366   }
1367
1368   bool isVecListThreeD() const {
1369     if (!isSingleSpacedVectorList()) return false;
1370     return VectorList.Count == 3;
1371   }
1372
1373   bool isVecListFourD() const {
1374     if (!isSingleSpacedVectorList()) return false;
1375     return VectorList.Count == 4;
1376   }
1377
1378   bool isVecListDPairSpaced() const {
1379     if (Kind != k_VectorList) return false;
1380     if (isSingleSpacedVectorList()) return false;
1381     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1382               .contains(VectorList.RegNum));
1383   }
1384
1385   bool isVecListThreeQ() const {
1386     if (!isDoubleSpacedVectorList()) return false;
1387     return VectorList.Count == 3;
1388   }
1389
1390   bool isVecListFourQ() const {
1391     if (!isDoubleSpacedVectorList()) return false;
1392     return VectorList.Count == 4;
1393   }
1394
1395   bool isSingleSpacedVectorAllLanes() const {
1396     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1397   }
1398   bool isDoubleSpacedVectorAllLanes() const {
1399     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1400   }
1401   bool isVecListOneDAllLanes() const {
1402     if (!isSingleSpacedVectorAllLanes()) return false;
1403     return VectorList.Count == 1;
1404   }
1405
1406   bool isVecListDPairAllLanes() const {
1407     if (!isSingleSpacedVectorAllLanes()) return false;
1408     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1409               .contains(VectorList.RegNum));
1410   }
1411
1412   bool isVecListDPairSpacedAllLanes() const {
1413     if (!isDoubleSpacedVectorAllLanes()) return false;
1414     return VectorList.Count == 2;
1415   }
1416
1417   bool isVecListThreeDAllLanes() const {
1418     if (!isSingleSpacedVectorAllLanes()) return false;
1419     return VectorList.Count == 3;
1420   }
1421
1422   bool isVecListThreeQAllLanes() const {
1423     if (!isDoubleSpacedVectorAllLanes()) return false;
1424     return VectorList.Count == 3;
1425   }
1426
1427   bool isVecListFourDAllLanes() const {
1428     if (!isSingleSpacedVectorAllLanes()) return false;
1429     return VectorList.Count == 4;
1430   }
1431
1432   bool isVecListFourQAllLanes() const {
1433     if (!isDoubleSpacedVectorAllLanes()) return false;
1434     return VectorList.Count == 4;
1435   }
1436
1437   bool isSingleSpacedVectorIndexed() const {
1438     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1439   }
1440   bool isDoubleSpacedVectorIndexed() const {
1441     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1442   }
1443   bool isVecListOneDByteIndexed() const {
1444     if (!isSingleSpacedVectorIndexed()) return false;
1445     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1446   }
1447
1448   bool isVecListOneDHWordIndexed() const {
1449     if (!isSingleSpacedVectorIndexed()) return false;
1450     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1451   }
1452
1453   bool isVecListOneDWordIndexed() const {
1454     if (!isSingleSpacedVectorIndexed()) return false;
1455     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1456   }
1457
1458   bool isVecListTwoDByteIndexed() const {
1459     if (!isSingleSpacedVectorIndexed()) return false;
1460     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1461   }
1462
1463   bool isVecListTwoDHWordIndexed() const {
1464     if (!isSingleSpacedVectorIndexed()) return false;
1465     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1466   }
1467
1468   bool isVecListTwoQWordIndexed() const {
1469     if (!isDoubleSpacedVectorIndexed()) return false;
1470     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1471   }
1472
1473   bool isVecListTwoQHWordIndexed() const {
1474     if (!isDoubleSpacedVectorIndexed()) return false;
1475     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1476   }
1477
1478   bool isVecListTwoDWordIndexed() const {
1479     if (!isSingleSpacedVectorIndexed()) return false;
1480     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1481   }
1482
1483   bool isVecListThreeDByteIndexed() const {
1484     if (!isSingleSpacedVectorIndexed()) return false;
1485     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1486   }
1487
1488   bool isVecListThreeDHWordIndexed() const {
1489     if (!isSingleSpacedVectorIndexed()) return false;
1490     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1491   }
1492
1493   bool isVecListThreeQWordIndexed() const {
1494     if (!isDoubleSpacedVectorIndexed()) return false;
1495     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1496   }
1497
1498   bool isVecListThreeQHWordIndexed() const {
1499     if (!isDoubleSpacedVectorIndexed()) return false;
1500     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1501   }
1502
1503   bool isVecListThreeDWordIndexed() const {
1504     if (!isSingleSpacedVectorIndexed()) return false;
1505     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1506   }
1507
1508   bool isVecListFourDByteIndexed() const {
1509     if (!isSingleSpacedVectorIndexed()) return false;
1510     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1511   }
1512
1513   bool isVecListFourDHWordIndexed() const {
1514     if (!isSingleSpacedVectorIndexed()) return false;
1515     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1516   }
1517
1518   bool isVecListFourQWordIndexed() const {
1519     if (!isDoubleSpacedVectorIndexed()) return false;
1520     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1521   }
1522
1523   bool isVecListFourQHWordIndexed() const {
1524     if (!isDoubleSpacedVectorIndexed()) return false;
1525     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1526   }
1527
1528   bool isVecListFourDWordIndexed() const {
1529     if (!isSingleSpacedVectorIndexed()) return false;
1530     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1531   }
1532
1533   bool isVectorIndex8() const {
1534     if (Kind != k_VectorIndex) return false;
1535     return VectorIndex.Val < 8;
1536   }
1537   bool isVectorIndex16() const {
1538     if (Kind != k_VectorIndex) return false;
1539     return VectorIndex.Val < 4;
1540   }
1541   bool isVectorIndex32() const {
1542     if (Kind != k_VectorIndex) return false;
1543     return VectorIndex.Val < 2;
1544   }
1545
1546   bool isNEONi8splat() const {
1547     if (!isImm()) return false;
1548     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1549     // Must be a constant.
1550     if (!CE) return false;
1551     int64_t Value = CE->getValue();
1552     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1553     // value.
1554     return Value >= 0 && Value < 256;
1555   }
1556
1557   bool isNEONi16splat() const {
1558     if (isNEONByteReplicate(2))
1559       return false; // Leave that for bytes replication and forbid by default.
1560     if (!isImm())
1561       return false;
1562     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1563     // Must be a constant.
1564     if (!CE) return false;
1565     unsigned Value = CE->getValue();
1566     return ARM_AM::isNEONi16splat(Value);
1567   }
1568
1569   bool isNEONi16splatNot() const {
1570     if (!isImm())
1571       return false;
1572     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1573     // Must be a constant.
1574     if (!CE) return false;
1575     unsigned Value = CE->getValue();
1576     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1577   }
1578
1579   bool isNEONi32splat() const {
1580     if (isNEONByteReplicate(4))
1581       return false; // Leave that for bytes replication and forbid by default.
1582     if (!isImm())
1583       return false;
1584     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1585     // Must be a constant.
1586     if (!CE) return false;
1587     unsigned Value = CE->getValue();
1588     return ARM_AM::isNEONi32splat(Value);
1589   }
1590
1591   bool isNEONi32splatNot() const {
1592     if (!isImm())
1593       return false;
1594     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1595     // Must be a constant.
1596     if (!CE) return false;
1597     unsigned Value = CE->getValue();
1598     return ARM_AM::isNEONi32splat(~Value);
1599   }
1600
1601   bool isNEONByteReplicate(unsigned NumBytes) const {
1602     if (!isImm())
1603       return false;
1604     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1605     // Must be a constant.
1606     if (!CE)
1607       return false;
1608     int64_t Value = CE->getValue();
1609     if (!Value)
1610       return false; // Don't bother with zero.
1611
1612     unsigned char B = Value & 0xff;
1613     for (unsigned i = 1; i < NumBytes; ++i) {
1614       Value >>= 8;
1615       if ((Value & 0xff) != B)
1616         return false;
1617     }
1618     return true;
1619   }
1620   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1621   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1622   bool isNEONi32vmov() const {
1623     if (isNEONByteReplicate(4))
1624       return false; // Let it to be classified as byte-replicate case.
1625     if (!isImm())
1626       return false;
1627     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1628     // Must be a constant.
1629     if (!CE)
1630       return false;
1631     int64_t Value = CE->getValue();
1632     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1633     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1634     // FIXME: This is probably wrong and a copy and paste from previous example
1635     return (Value >= 0 && Value < 256) ||
1636       (Value >= 0x0100 && Value <= 0xff00) ||
1637       (Value >= 0x010000 && Value <= 0xff0000) ||
1638       (Value >= 0x01000000 && Value <= 0xff000000) ||
1639       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1640       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1641   }
1642   bool isNEONi32vmovNeg() const {
1643     if (!isImm()) return false;
1644     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1645     // Must be a constant.
1646     if (!CE) return false;
1647     int64_t Value = ~CE->getValue();
1648     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1649     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1650     // FIXME: This is probably wrong and a copy and paste from previous example
1651     return (Value >= 0 && Value < 256) ||
1652       (Value >= 0x0100 && Value <= 0xff00) ||
1653       (Value >= 0x010000 && Value <= 0xff0000) ||
1654       (Value >= 0x01000000 && Value <= 0xff000000) ||
1655       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1656       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1657   }
1658
1659   bool isNEONi64splat() const {
1660     if (!isImm()) return false;
1661     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1662     // Must be a constant.
1663     if (!CE) return false;
1664     uint64_t Value = CE->getValue();
1665     // i64 value with each byte being either 0 or 0xff.
1666     for (unsigned i = 0; i < 8; ++i)
1667       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1668     return true;
1669   }
1670
1671   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1672     // Add as immediates when possible.  Null MCExpr = 0.
1673     if (!Expr)
1674       Inst.addOperand(MCOperand::createImm(0));
1675     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1676       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1677     else
1678       Inst.addOperand(MCOperand::createExpr(Expr));
1679   }
1680
1681   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1682     assert(N == 2 && "Invalid number of operands!");
1683     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1684     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1685     Inst.addOperand(MCOperand::createReg(RegNum));
1686   }
1687
1688   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1689     assert(N == 1 && "Invalid number of operands!");
1690     Inst.addOperand(MCOperand::createImm(getCoproc()));
1691   }
1692
1693   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1694     assert(N == 1 && "Invalid number of operands!");
1695     Inst.addOperand(MCOperand::createImm(getCoproc()));
1696   }
1697
1698   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1699     assert(N == 1 && "Invalid number of operands!");
1700     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1701   }
1702
1703   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1704     assert(N == 1 && "Invalid number of operands!");
1705     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1706   }
1707
1708   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1709     assert(N == 1 && "Invalid number of operands!");
1710     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1711   }
1712
1713   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1714     assert(N == 1 && "Invalid number of operands!");
1715     Inst.addOperand(MCOperand::createReg(getReg()));
1716   }
1717
1718   void addRegOperands(MCInst &Inst, unsigned N) const {
1719     assert(N == 1 && "Invalid number of operands!");
1720     Inst.addOperand(MCOperand::createReg(getReg()));
1721   }
1722
1723   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1724     assert(N == 3 && "Invalid number of operands!");
1725     assert(isRegShiftedReg() &&
1726            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1727     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1728     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1729     Inst.addOperand(MCOperand::createImm(
1730       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1731   }
1732
1733   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1734     assert(N == 2 && "Invalid number of operands!");
1735     assert(isRegShiftedImm() &&
1736            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1737     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1738     // Shift of #32 is encoded as 0 where permitted
1739     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1740     Inst.addOperand(MCOperand::createImm(
1741       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1742   }
1743
1744   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1745     assert(N == 1 && "Invalid number of operands!");
1746     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1747                                          ShifterImm.Imm));
1748   }
1749
1750   void addRegListOperands(MCInst &Inst, unsigned N) const {
1751     assert(N == 1 && "Invalid number of operands!");
1752     const SmallVectorImpl<unsigned> &RegList = getRegList();
1753     for (SmallVectorImpl<unsigned>::const_iterator
1754            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1755       Inst.addOperand(MCOperand::createReg(*I));
1756   }
1757
1758   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1759     addRegListOperands(Inst, N);
1760   }
1761
1762   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1763     addRegListOperands(Inst, N);
1764   }
1765
1766   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1767     assert(N == 1 && "Invalid number of operands!");
1768     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1769     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1770   }
1771
1772   void addModImmOperands(MCInst &Inst, unsigned N) const {
1773     assert(N == 1 && "Invalid number of operands!");
1774
1775     // Support for fixups (MCFixup)
1776     if (isImm())
1777       return addImmOperands(Inst, N);
1778
1779     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
1780   }
1781
1782   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1783     assert(N == 1 && "Invalid number of operands!");
1784     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1785     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1786     Inst.addOperand(MCOperand::createImm(Enc));
1787   }
1788
1789   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1790     assert(N == 1 && "Invalid number of operands!");
1791     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1792     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1793     Inst.addOperand(MCOperand::createImm(Enc));
1794   }
1795
1796   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1797     assert(N == 1 && "Invalid number of operands!");
1798     // Munge the lsb/width into a bitfield mask.
1799     unsigned lsb = Bitfield.LSB;
1800     unsigned width = Bitfield.Width;
1801     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1802     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1803                       (32 - (lsb + width)));
1804     Inst.addOperand(MCOperand::createImm(Mask));
1805   }
1806
1807   void addImmOperands(MCInst &Inst, unsigned N) const {
1808     assert(N == 1 && "Invalid number of operands!");
1809     addExpr(Inst, getImm());
1810   }
1811
1812   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1813     assert(N == 1 && "Invalid number of operands!");
1814     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1815     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
1816   }
1817
1818   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1819     assert(N == 1 && "Invalid number of operands!");
1820     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1821     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
1822   }
1823
1824   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1825     assert(N == 1 && "Invalid number of operands!");
1826     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1827     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1828     Inst.addOperand(MCOperand::createImm(Val));
1829   }
1830
1831   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1832     assert(N == 1 && "Invalid number of operands!");
1833     // FIXME: We really want to scale the value here, but the LDRD/STRD
1834     // instruction don't encode operands that way yet.
1835     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1836     Inst.addOperand(MCOperand::createImm(CE->getValue()));
1837   }
1838
1839   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1840     assert(N == 1 && "Invalid number of operands!");
1841     // The immediate is scaled by four in the encoding and is stored
1842     // in the MCInst as such. Lop off the low two bits here.
1843     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1844     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1845   }
1846
1847   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1848     assert(N == 1 && "Invalid number of operands!");
1849     // The immediate is scaled by four in the encoding and is stored
1850     // in the MCInst as such. Lop off the low two bits here.
1851     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1852     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
1853   }
1854
1855   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1856     assert(N == 1 && "Invalid number of operands!");
1857     // The immediate is scaled by four in the encoding and is stored
1858     // in the MCInst as such. Lop off the low two bits here.
1859     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1860     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1861   }
1862
1863   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1864     assert(N == 1 && "Invalid number of operands!");
1865     // The constant encodes as the immediate-1, and we store in the instruction
1866     // the bits as encoded, so subtract off one here.
1867     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1868     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1869   }
1870
1871   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1872     assert(N == 1 && "Invalid number of operands!");
1873     // The constant encodes as the immediate-1, and we store in the instruction
1874     // the bits as encoded, so subtract off one here.
1875     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1876     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1877   }
1878
1879   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1880     assert(N == 1 && "Invalid number of operands!");
1881     // The constant encodes as the immediate, except for 32, which encodes as
1882     // zero.
1883     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1884     unsigned Imm = CE->getValue();
1885     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
1886   }
1887
1888   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1889     assert(N == 1 && "Invalid number of operands!");
1890     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1891     // the instruction as well.
1892     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1893     int Val = CE->getValue();
1894     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
1895   }
1896
1897   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
1898     assert(N == 1 && "Invalid number of operands!");
1899     // The operand is actually a t2_so_imm, but we have its bitwise
1900     // negation in the assembly source, so twiddle it here.
1901     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1902     Inst.addOperand(MCOperand::createImm(~CE->getValue()));
1903   }
1904
1905   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
1906     assert(N == 1 && "Invalid number of operands!");
1907     // The operand is actually a t2_so_imm, but we have its
1908     // negation in the assembly source, so twiddle it here.
1909     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1910     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1911   }
1912
1913   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
1914     assert(N == 1 && "Invalid number of operands!");
1915     // The operand is actually an imm0_4095, but we have its
1916     // negation in the assembly source, so twiddle it here.
1917     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1918     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1919   }
1920
1921   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
1922     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
1923       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
1924       return;
1925     }
1926
1927     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1928     assert(SR && "Unknown value type!");
1929     Inst.addOperand(MCOperand::createExpr(SR));
1930   }
1931
1932   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
1933     assert(N == 1 && "Invalid number of operands!");
1934     if (isImm()) {
1935       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1936       if (CE) {
1937         Inst.addOperand(MCOperand::createImm(CE->getValue()));
1938         return;
1939       }
1940
1941       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1942       assert(SR && "Unknown value type!");
1943       Inst.addOperand(MCOperand::createExpr(SR));
1944       return;
1945     }
1946
1947     assert(isMem()  && "Unknown value type!");
1948     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
1949     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
1950   }
1951
1952   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
1953     assert(N == 1 && "Invalid number of operands!");
1954     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
1955   }
1956
1957   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
1958     assert(N == 1 && "Invalid number of operands!");
1959     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
1960   }
1961
1962   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
1963     assert(N == 1 && "Invalid number of operands!");
1964     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
1965   }
1966
1967   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
1968     assert(N == 1 && "Invalid number of operands!");
1969     int32_t Imm = Memory.OffsetImm->getValue();
1970     Inst.addOperand(MCOperand::createImm(Imm));
1971   }
1972
1973   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
1974     assert(N == 1 && "Invalid number of operands!");
1975     assert(isImm() && "Not an immediate!");
1976
1977     // If we have an immediate that's not a constant, treat it as a label
1978     // reference needing a fixup. 
1979     if (!isa<MCConstantExpr>(getImm())) {
1980       Inst.addOperand(MCOperand::createExpr(getImm()));
1981       return;
1982     }
1983
1984     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1985     int Val = CE->getValue();
1986     Inst.addOperand(MCOperand::createImm(Val));
1987   }
1988
1989   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
1990     assert(N == 2 && "Invalid number of operands!");
1991     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
1992     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
1993   }
1994
1995   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
1996     addAlignedMemoryOperands(Inst, N);
1997   }
1998
1999   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2000     addAlignedMemoryOperands(Inst, N);
2001   }
2002
2003   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2004     addAlignedMemoryOperands(Inst, N);
2005   }
2006
2007   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2008     addAlignedMemoryOperands(Inst, N);
2009   }
2010
2011   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2012     addAlignedMemoryOperands(Inst, N);
2013   }
2014
2015   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2016     addAlignedMemoryOperands(Inst, N);
2017   }
2018
2019   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2020     addAlignedMemoryOperands(Inst, N);
2021   }
2022
2023   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2024     addAlignedMemoryOperands(Inst, N);
2025   }
2026
2027   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2028     addAlignedMemoryOperands(Inst, N);
2029   }
2030
2031   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2032     addAlignedMemoryOperands(Inst, N);
2033   }
2034
2035   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2036     addAlignedMemoryOperands(Inst, N);
2037   }
2038
2039   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2040     assert(N == 3 && "Invalid number of operands!");
2041     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2042     if (!Memory.OffsetRegNum) {
2043       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2044       // Special case for #-0
2045       if (Val == INT32_MIN) Val = 0;
2046       if (Val < 0) Val = -Val;
2047       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2048     } else {
2049       // For register offset, we encode the shift type and negation flag
2050       // here.
2051       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2052                               Memory.ShiftImm, Memory.ShiftType);
2053     }
2054     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2055     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2056     Inst.addOperand(MCOperand::createImm(Val));
2057   }
2058
2059   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2060     assert(N == 2 && "Invalid number of operands!");
2061     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2062     assert(CE && "non-constant AM2OffsetImm operand!");
2063     int32_t Val = CE->getValue();
2064     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2065     // Special case for #-0
2066     if (Val == INT32_MIN) Val = 0;
2067     if (Val < 0) Val = -Val;
2068     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2069     Inst.addOperand(MCOperand::createReg(0));
2070     Inst.addOperand(MCOperand::createImm(Val));
2071   }
2072
2073   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2074     assert(N == 3 && "Invalid number of operands!");
2075     // If we have an immediate that's not a constant, treat it as a label
2076     // reference needing a fixup. If it is a constant, it's something else
2077     // and we reject it.
2078     if (isImm()) {
2079       Inst.addOperand(MCOperand::createExpr(getImm()));
2080       Inst.addOperand(MCOperand::createReg(0));
2081       Inst.addOperand(MCOperand::createImm(0));
2082       return;
2083     }
2084
2085     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2086     if (!Memory.OffsetRegNum) {
2087       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2088       // Special case for #-0
2089       if (Val == INT32_MIN) Val = 0;
2090       if (Val < 0) Val = -Val;
2091       Val = ARM_AM::getAM3Opc(AddSub, Val);
2092     } else {
2093       // For register offset, we encode the shift type and negation flag
2094       // here.
2095       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2096     }
2097     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2098     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2099     Inst.addOperand(MCOperand::createImm(Val));
2100   }
2101
2102   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2103     assert(N == 2 && "Invalid number of operands!");
2104     if (Kind == k_PostIndexRegister) {
2105       int32_t Val =
2106         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2107       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2108       Inst.addOperand(MCOperand::createImm(Val));
2109       return;
2110     }
2111
2112     // Constant offset.
2113     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2114     int32_t Val = CE->getValue();
2115     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2116     // Special case for #-0
2117     if (Val == INT32_MIN) Val = 0;
2118     if (Val < 0) Val = -Val;
2119     Val = ARM_AM::getAM3Opc(AddSub, Val);
2120     Inst.addOperand(MCOperand::createReg(0));
2121     Inst.addOperand(MCOperand::createImm(Val));
2122   }
2123
2124   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2125     assert(N == 2 && "Invalid number of operands!");
2126     // If we have an immediate that's not a constant, treat it as a label
2127     // reference needing a fixup. If it is a constant, it's something else
2128     // and we reject it.
2129     if (isImm()) {
2130       Inst.addOperand(MCOperand::createExpr(getImm()));
2131       Inst.addOperand(MCOperand::createImm(0));
2132       return;
2133     }
2134
2135     // The lower two bits are always zero and as such are not encoded.
2136     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2137     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2138     // Special case for #-0
2139     if (Val == INT32_MIN) Val = 0;
2140     if (Val < 0) Val = -Val;
2141     Val = ARM_AM::getAM5Opc(AddSub, Val);
2142     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2143     Inst.addOperand(MCOperand::createImm(Val));
2144   }
2145
2146   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2147     assert(N == 2 && "Invalid number of operands!");
2148     // If we have an immediate that's not a constant, treat it as a label
2149     // reference needing a fixup. If it is a constant, it's something else
2150     // and we reject it.
2151     if (isImm()) {
2152       Inst.addOperand(MCOperand::createExpr(getImm()));
2153       Inst.addOperand(MCOperand::createImm(0));
2154       return;
2155     }
2156
2157     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2158     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2159     Inst.addOperand(MCOperand::createImm(Val));
2160   }
2161
2162   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2163     assert(N == 2 && "Invalid number of operands!");
2164     // The lower two bits are always zero and as such are not encoded.
2165     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2166     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2167     Inst.addOperand(MCOperand::createImm(Val));
2168   }
2169
2170   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2171     assert(N == 2 && "Invalid number of operands!");
2172     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2173     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2174     Inst.addOperand(MCOperand::createImm(Val));
2175   }
2176
2177   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2178     addMemImm8OffsetOperands(Inst, N);
2179   }
2180
2181   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2182     addMemImm8OffsetOperands(Inst, N);
2183   }
2184
2185   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2186     assert(N == 2 && "Invalid number of operands!");
2187     // If this is an immediate, it's a label reference.
2188     if (isImm()) {
2189       addExpr(Inst, getImm());
2190       Inst.addOperand(MCOperand::createImm(0));
2191       return;
2192     }
2193
2194     // Otherwise, it's a normal memory reg+offset.
2195     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2196     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2197     Inst.addOperand(MCOperand::createImm(Val));
2198   }
2199
2200   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2201     assert(N == 2 && "Invalid number of operands!");
2202     // If this is an immediate, it's a label reference.
2203     if (isImm()) {
2204       addExpr(Inst, getImm());
2205       Inst.addOperand(MCOperand::createImm(0));
2206       return;
2207     }
2208
2209     // Otherwise, it's a normal memory reg+offset.
2210     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2211     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2212     Inst.addOperand(MCOperand::createImm(Val));
2213   }
2214
2215   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2216     assert(N == 2 && "Invalid number of operands!");
2217     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2218     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2219   }
2220
2221   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2222     assert(N == 2 && "Invalid number of operands!");
2223     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2224     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2225   }
2226
2227   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2228     assert(N == 3 && "Invalid number of operands!");
2229     unsigned Val =
2230       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2231                         Memory.ShiftImm, Memory.ShiftType);
2232     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2233     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2234     Inst.addOperand(MCOperand::createImm(Val));
2235   }
2236
2237   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2238     assert(N == 3 && "Invalid number of operands!");
2239     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2240     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2241     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2242   }
2243
2244   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2245     assert(N == 2 && "Invalid number of operands!");
2246     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2247     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2248   }
2249
2250   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2251     assert(N == 2 && "Invalid number of operands!");
2252     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2253     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2254     Inst.addOperand(MCOperand::createImm(Val));
2255   }
2256
2257   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2258     assert(N == 2 && "Invalid number of operands!");
2259     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2260     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2261     Inst.addOperand(MCOperand::createImm(Val));
2262   }
2263
2264   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2265     assert(N == 2 && "Invalid number of operands!");
2266     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2267     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2268     Inst.addOperand(MCOperand::createImm(Val));
2269   }
2270
2271   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2272     assert(N == 2 && "Invalid number of operands!");
2273     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2274     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2275     Inst.addOperand(MCOperand::createImm(Val));
2276   }
2277
2278   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2279     assert(N == 1 && "Invalid number of operands!");
2280     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2281     assert(CE && "non-constant post-idx-imm8 operand!");
2282     int Imm = CE->getValue();
2283     bool isAdd = Imm >= 0;
2284     if (Imm == INT32_MIN) Imm = 0;
2285     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2286     Inst.addOperand(MCOperand::createImm(Imm));
2287   }
2288
2289   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2290     assert(N == 1 && "Invalid number of operands!");
2291     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2292     assert(CE && "non-constant post-idx-imm8s4 operand!");
2293     int Imm = CE->getValue();
2294     bool isAdd = Imm >= 0;
2295     if (Imm == INT32_MIN) Imm = 0;
2296     // Immediate is scaled by 4.
2297     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2298     Inst.addOperand(MCOperand::createImm(Imm));
2299   }
2300
2301   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2302     assert(N == 2 && "Invalid number of operands!");
2303     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2304     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2305   }
2306
2307   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2308     assert(N == 2 && "Invalid number of operands!");
2309     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2310     // The sign, shift type, and shift amount are encoded in a single operand
2311     // using the AM2 encoding helpers.
2312     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2313     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2314                                      PostIdxReg.ShiftTy);
2315     Inst.addOperand(MCOperand::createImm(Imm));
2316   }
2317
2318   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2319     assert(N == 1 && "Invalid number of operands!");
2320     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2321   }
2322
2323   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2324     assert(N == 1 && "Invalid number of operands!");
2325     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2326   }
2327
2328   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2329     assert(N == 1 && "Invalid number of operands!");
2330     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2331   }
2332
2333   void addVecListOperands(MCInst &Inst, unsigned N) const {
2334     assert(N == 1 && "Invalid number of operands!");
2335     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2336   }
2337
2338   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2339     assert(N == 2 && "Invalid number of operands!");
2340     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2341     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2342   }
2343
2344   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2345     assert(N == 1 && "Invalid number of operands!");
2346     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2347   }
2348
2349   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2350     assert(N == 1 && "Invalid number of operands!");
2351     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2352   }
2353
2354   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2355     assert(N == 1 && "Invalid number of operands!");
2356     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2357   }
2358
2359   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2360     assert(N == 1 && "Invalid number of operands!");
2361     // The immediate encodes the type of constant as well as the value.
2362     // Mask in that this is an i8 splat.
2363     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2364     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2365   }
2366
2367   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2368     assert(N == 1 && "Invalid number of operands!");
2369     // The immediate encodes the type of constant as well as the value.
2370     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2371     unsigned Value = CE->getValue();
2372     Value = ARM_AM::encodeNEONi16splat(Value);
2373     Inst.addOperand(MCOperand::createImm(Value));
2374   }
2375
2376   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2377     assert(N == 1 && "Invalid number of operands!");
2378     // The immediate encodes the type of constant as well as the value.
2379     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2380     unsigned Value = CE->getValue();
2381     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2382     Inst.addOperand(MCOperand::createImm(Value));
2383   }
2384
2385   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2386     assert(N == 1 && "Invalid number of operands!");
2387     // The immediate encodes the type of constant as well as the value.
2388     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2389     unsigned Value = CE->getValue();
2390     Value = ARM_AM::encodeNEONi32splat(Value);
2391     Inst.addOperand(MCOperand::createImm(Value));
2392   }
2393
2394   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2395     assert(N == 1 && "Invalid number of operands!");
2396     // The immediate encodes the type of constant as well as the value.
2397     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2398     unsigned Value = CE->getValue();
2399     Value = ARM_AM::encodeNEONi32splat(~Value);
2400     Inst.addOperand(MCOperand::createImm(Value));
2401   }
2402
2403   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2404     assert(N == 1 && "Invalid number of operands!");
2405     // The immediate encodes the type of constant as well as the value.
2406     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2407     unsigned Value = CE->getValue();
2408     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2409             Inst.getOpcode() == ARM::VMOVv16i8) &&
2410            "All vmvn instructions that wants to replicate non-zero byte "
2411            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2412     unsigned B = ((~Value) & 0xff);
2413     B |= 0xe00; // cmode = 0b1110
2414     Inst.addOperand(MCOperand::createImm(B));
2415   }
2416   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2417     assert(N == 1 && "Invalid number of operands!");
2418     // The immediate encodes the type of constant as well as the value.
2419     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2420     unsigned Value = CE->getValue();
2421     if (Value >= 256 && Value <= 0xffff)
2422       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2423     else if (Value > 0xffff && Value <= 0xffffff)
2424       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2425     else if (Value > 0xffffff)
2426       Value = (Value >> 24) | 0x600;
2427     Inst.addOperand(MCOperand::createImm(Value));
2428   }
2429
2430   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2431     assert(N == 1 && "Invalid number of operands!");
2432     // The immediate encodes the type of constant as well as the value.
2433     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2434     unsigned Value = CE->getValue();
2435     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2436             Inst.getOpcode() == ARM::VMOVv16i8) &&
2437            "All instructions that wants to replicate non-zero byte "
2438            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2439     unsigned B = Value & 0xff;
2440     B |= 0xe00; // cmode = 0b1110
2441     Inst.addOperand(MCOperand::createImm(B));
2442   }
2443   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2444     assert(N == 1 && "Invalid number of operands!");
2445     // The immediate encodes the type of constant as well as the value.
2446     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2447     unsigned Value = ~CE->getValue();
2448     if (Value >= 256 && Value <= 0xffff)
2449       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2450     else if (Value > 0xffff && Value <= 0xffffff)
2451       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2452     else if (Value > 0xffffff)
2453       Value = (Value >> 24) | 0x600;
2454     Inst.addOperand(MCOperand::createImm(Value));
2455   }
2456
2457   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2458     assert(N == 1 && "Invalid number of operands!");
2459     // The immediate encodes the type of constant as well as the value.
2460     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2461     uint64_t Value = CE->getValue();
2462     unsigned Imm = 0;
2463     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2464       Imm |= (Value & 1) << i;
2465     }
2466     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2467   }
2468
2469   void print(raw_ostream &OS) const override;
2470
2471   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2472     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2473     Op->ITMask.Mask = Mask;
2474     Op->StartLoc = S;
2475     Op->EndLoc = S;
2476     return Op;
2477   }
2478
2479   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2480                                                     SMLoc S) {
2481     auto Op = make_unique<ARMOperand>(k_CondCode);
2482     Op->CC.Val = CC;
2483     Op->StartLoc = S;
2484     Op->EndLoc = S;
2485     return Op;
2486   }
2487
2488   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2489     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2490     Op->Cop.Val = CopVal;
2491     Op->StartLoc = S;
2492     Op->EndLoc = S;
2493     return Op;
2494   }
2495
2496   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2497     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2498     Op->Cop.Val = CopVal;
2499     Op->StartLoc = S;
2500     Op->EndLoc = S;
2501     return Op;
2502   }
2503
2504   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2505                                                         SMLoc E) {
2506     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2507     Op->Cop.Val = Val;
2508     Op->StartLoc = S;
2509     Op->EndLoc = E;
2510     return Op;
2511   }
2512
2513   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2514     auto Op = make_unique<ARMOperand>(k_CCOut);
2515     Op->Reg.RegNum = RegNum;
2516     Op->StartLoc = S;
2517     Op->EndLoc = S;
2518     return Op;
2519   }
2520
2521   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2522     auto Op = make_unique<ARMOperand>(k_Token);
2523     Op->Tok.Data = Str.data();
2524     Op->Tok.Length = Str.size();
2525     Op->StartLoc = S;
2526     Op->EndLoc = S;
2527     return Op;
2528   }
2529
2530   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2531                                                SMLoc E) {
2532     auto Op = make_unique<ARMOperand>(k_Register);
2533     Op->Reg.RegNum = RegNum;
2534     Op->StartLoc = S;
2535     Op->EndLoc = E;
2536     return Op;
2537   }
2538
2539   static std::unique_ptr<ARMOperand>
2540   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2541                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2542                         SMLoc E) {
2543     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2544     Op->RegShiftedReg.ShiftTy = ShTy;
2545     Op->RegShiftedReg.SrcReg = SrcReg;
2546     Op->RegShiftedReg.ShiftReg = ShiftReg;
2547     Op->RegShiftedReg.ShiftImm = ShiftImm;
2548     Op->StartLoc = S;
2549     Op->EndLoc = E;
2550     return Op;
2551   }
2552
2553   static std::unique_ptr<ARMOperand>
2554   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2555                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2556     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2557     Op->RegShiftedImm.ShiftTy = ShTy;
2558     Op->RegShiftedImm.SrcReg = SrcReg;
2559     Op->RegShiftedImm.ShiftImm = ShiftImm;
2560     Op->StartLoc = S;
2561     Op->EndLoc = E;
2562     return Op;
2563   }
2564
2565   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2566                                                       SMLoc S, SMLoc E) {
2567     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2568     Op->ShifterImm.isASR = isASR;
2569     Op->ShifterImm.Imm = Imm;
2570     Op->StartLoc = S;
2571     Op->EndLoc = E;
2572     return Op;
2573   }
2574
2575   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2576                                                   SMLoc E) {
2577     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2578     Op->RotImm.Imm = Imm;
2579     Op->StartLoc = S;
2580     Op->EndLoc = E;
2581     return Op;
2582   }
2583
2584   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2585                                                   SMLoc S, SMLoc E) {
2586     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2587     Op->ModImm.Bits = Bits;
2588     Op->ModImm.Rot = Rot;
2589     Op->StartLoc = S;
2590     Op->EndLoc = E;
2591     return Op;
2592   }
2593
2594   static std::unique_ptr<ARMOperand>
2595   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2596     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2597     Op->Bitfield.LSB = LSB;
2598     Op->Bitfield.Width = Width;
2599     Op->StartLoc = S;
2600     Op->EndLoc = E;
2601     return Op;
2602   }
2603
2604   static std::unique_ptr<ARMOperand>
2605   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2606                 SMLoc StartLoc, SMLoc EndLoc) {
2607     assert (Regs.size() > 0 && "RegList contains no registers?");
2608     KindTy Kind = k_RegisterList;
2609
2610     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2611       Kind = k_DPRRegisterList;
2612     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2613              contains(Regs.front().second))
2614       Kind = k_SPRRegisterList;
2615
2616     // Sort based on the register encoding values.
2617     array_pod_sort(Regs.begin(), Regs.end());
2618
2619     auto Op = make_unique<ARMOperand>(Kind);
2620     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2621            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2622       Op->Registers.push_back(I->second);
2623     Op->StartLoc = StartLoc;
2624     Op->EndLoc = EndLoc;
2625     return Op;
2626   }
2627
2628   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2629                                                       unsigned Count,
2630                                                       bool isDoubleSpaced,
2631                                                       SMLoc S, SMLoc E) {
2632     auto Op = make_unique<ARMOperand>(k_VectorList);
2633     Op->VectorList.RegNum = RegNum;
2634     Op->VectorList.Count = Count;
2635     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2636     Op->StartLoc = S;
2637     Op->EndLoc = E;
2638     return Op;
2639   }
2640
2641   static std::unique_ptr<ARMOperand>
2642   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2643                            SMLoc S, SMLoc E) {
2644     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2645     Op->VectorList.RegNum = RegNum;
2646     Op->VectorList.Count = Count;
2647     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2648     Op->StartLoc = S;
2649     Op->EndLoc = E;
2650     return Op;
2651   }
2652
2653   static std::unique_ptr<ARMOperand>
2654   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2655                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2656     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2657     Op->VectorList.RegNum = RegNum;
2658     Op->VectorList.Count = Count;
2659     Op->VectorList.LaneIndex = Index;
2660     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2661     Op->StartLoc = S;
2662     Op->EndLoc = E;
2663     return Op;
2664   }
2665
2666   static std::unique_ptr<ARMOperand>
2667   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2668     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2669     Op->VectorIndex.Val = Idx;
2670     Op->StartLoc = S;
2671     Op->EndLoc = E;
2672     return Op;
2673   }
2674
2675   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2676                                                SMLoc E) {
2677     auto Op = make_unique<ARMOperand>(k_Immediate);
2678     Op->Imm.Val = Val;
2679     Op->StartLoc = S;
2680     Op->EndLoc = E;
2681     return Op;
2682   }
2683
2684   static std::unique_ptr<ARMOperand>
2685   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2686             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2687             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2688             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2689     auto Op = make_unique<ARMOperand>(k_Memory);
2690     Op->Memory.BaseRegNum = BaseRegNum;
2691     Op->Memory.OffsetImm = OffsetImm;
2692     Op->Memory.OffsetRegNum = OffsetRegNum;
2693     Op->Memory.ShiftType = ShiftType;
2694     Op->Memory.ShiftImm = ShiftImm;
2695     Op->Memory.Alignment = Alignment;
2696     Op->Memory.isNegative = isNegative;
2697     Op->StartLoc = S;
2698     Op->EndLoc = E;
2699     Op->AlignmentLoc = AlignmentLoc;
2700     return Op;
2701   }
2702
2703   static std::unique_ptr<ARMOperand>
2704   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2705                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2706     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2707     Op->PostIdxReg.RegNum = RegNum;
2708     Op->PostIdxReg.isAdd = isAdd;
2709     Op->PostIdxReg.ShiftTy = ShiftTy;
2710     Op->PostIdxReg.ShiftImm = ShiftImm;
2711     Op->StartLoc = S;
2712     Op->EndLoc = E;
2713     return Op;
2714   }
2715
2716   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2717                                                          SMLoc S) {
2718     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2719     Op->MBOpt.Val = Opt;
2720     Op->StartLoc = S;
2721     Op->EndLoc = S;
2722     return Op;
2723   }
2724
2725   static std::unique_ptr<ARMOperand>
2726   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2727     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2728     Op->ISBOpt.Val = Opt;
2729     Op->StartLoc = S;
2730     Op->EndLoc = S;
2731     return Op;
2732   }
2733
2734   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2735                                                       SMLoc S) {
2736     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2737     Op->IFlags.Val = IFlags;
2738     Op->StartLoc = S;
2739     Op->EndLoc = S;
2740     return Op;
2741   }
2742
2743   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2744     auto Op = make_unique<ARMOperand>(k_MSRMask);
2745     Op->MMask.Val = MMask;
2746     Op->StartLoc = S;
2747     Op->EndLoc = S;
2748     return Op;
2749   }
2750
2751   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2752     auto Op = make_unique<ARMOperand>(k_BankedReg);
2753     Op->BankedReg.Val = Reg;
2754     Op->StartLoc = S;
2755     Op->EndLoc = S;
2756     return Op;
2757   }
2758 };
2759
2760 } // end anonymous namespace.
2761
2762 void ARMOperand::print(raw_ostream &OS) const {
2763   switch (Kind) {
2764   case k_CondCode:
2765     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2766     break;
2767   case k_CCOut:
2768     OS << "<ccout " << getReg() << ">";
2769     break;
2770   case k_ITCondMask: {
2771     static const char *const MaskStr[] = {
2772       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2773       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2774     };
2775     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2776     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2777     break;
2778   }
2779   case k_CoprocNum:
2780     OS << "<coprocessor number: " << getCoproc() << ">";
2781     break;
2782   case k_CoprocReg:
2783     OS << "<coprocessor register: " << getCoproc() << ">";
2784     break;
2785   case k_CoprocOption:
2786     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2787     break;
2788   case k_MSRMask:
2789     OS << "<mask: " << getMSRMask() << ">";
2790     break;
2791   case k_BankedReg:
2792     OS << "<banked reg: " << getBankedReg() << ">";
2793     break;
2794   case k_Immediate:
2795     OS << *getImm();
2796     break;
2797   case k_MemBarrierOpt:
2798     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2799     break;
2800   case k_InstSyncBarrierOpt:
2801     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2802     break;
2803   case k_Memory:
2804     OS << "<memory "
2805        << " base:" << Memory.BaseRegNum;
2806     OS << ">";
2807     break;
2808   case k_PostIndexRegister:
2809     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2810        << PostIdxReg.RegNum;
2811     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2812       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2813          << PostIdxReg.ShiftImm;
2814     OS << ">";
2815     break;
2816   case k_ProcIFlags: {
2817     OS << "<ARM_PROC::";
2818     unsigned IFlags = getProcIFlags();
2819     for (int i=2; i >= 0; --i)
2820       if (IFlags & (1 << i))
2821         OS << ARM_PROC::IFlagsToString(1 << i);
2822     OS << ">";
2823     break;
2824   }
2825   case k_Register:
2826     OS << "<register " << getReg() << ">";
2827     break;
2828   case k_ShifterImmediate:
2829     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2830        << " #" << ShifterImm.Imm << ">";
2831     break;
2832   case k_ShiftedRegister:
2833     OS << "<so_reg_reg "
2834        << RegShiftedReg.SrcReg << " "
2835        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2836        << " " << RegShiftedReg.ShiftReg << ">";
2837     break;
2838   case k_ShiftedImmediate:
2839     OS << "<so_reg_imm "
2840        << RegShiftedImm.SrcReg << " "
2841        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2842        << " #" << RegShiftedImm.ShiftImm << ">";
2843     break;
2844   case k_RotateImmediate:
2845     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2846     break;
2847   case k_ModifiedImmediate:
2848     OS << "<mod_imm #" << ModImm.Bits << ", #"
2849        <<  ModImm.Rot << ")>";
2850     break;
2851   case k_BitfieldDescriptor:
2852     OS << "<bitfield " << "lsb: " << Bitfield.LSB
2853        << ", width: " << Bitfield.Width << ">";
2854     break;
2855   case k_RegisterList:
2856   case k_DPRRegisterList:
2857   case k_SPRRegisterList: {
2858     OS << "<register_list ";
2859
2860     const SmallVectorImpl<unsigned> &RegList = getRegList();
2861     for (SmallVectorImpl<unsigned>::const_iterator
2862            I = RegList.begin(), E = RegList.end(); I != E; ) {
2863       OS << *I;
2864       if (++I < E) OS << ", ";
2865     }
2866
2867     OS << ">";
2868     break;
2869   }
2870   case k_VectorList:
2871     OS << "<vector_list " << VectorList.Count << " * "
2872        << VectorList.RegNum << ">";
2873     break;
2874   case k_VectorListAllLanes:
2875     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
2876        << VectorList.RegNum << ">";
2877     break;
2878   case k_VectorListIndexed:
2879     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
2880        << VectorList.Count << " * " << VectorList.RegNum << ">";
2881     break;
2882   case k_Token:
2883     OS << "'" << getToken() << "'";
2884     break;
2885   case k_VectorIndex:
2886     OS << "<vectorindex " << getVectorIndex() << ">";
2887     break;
2888   }
2889 }
2890
2891 /// @name Auto-generated Match Functions
2892 /// {
2893
2894 static unsigned MatchRegisterName(StringRef Name);
2895
2896 /// }
2897
2898 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
2899                                  SMLoc &StartLoc, SMLoc &EndLoc) {
2900   const AsmToken &Tok = getParser().getTok();
2901   StartLoc = Tok.getLoc();
2902   EndLoc = Tok.getEndLoc();
2903   RegNo = tryParseRegister();
2904
2905   return (RegNo == (unsigned)-1);
2906 }
2907
2908 /// Try to parse a register name.  The token must be an Identifier when called,
2909 /// and if it is a register name the token is eaten and the register number is
2910 /// returned.  Otherwise return -1.
2911 ///
2912 int ARMAsmParser::tryParseRegister() {
2913   MCAsmParser &Parser = getParser();
2914   const AsmToken &Tok = Parser.getTok();
2915   if (Tok.isNot(AsmToken::Identifier)) return -1;
2916
2917   std::string lowerCase = Tok.getString().lower();
2918   unsigned RegNum = MatchRegisterName(lowerCase);
2919   if (!RegNum) {
2920     RegNum = StringSwitch<unsigned>(lowerCase)
2921       .Case("r13", ARM::SP)
2922       .Case("r14", ARM::LR)
2923       .Case("r15", ARM::PC)
2924       .Case("ip", ARM::R12)
2925       // Additional register name aliases for 'gas' compatibility.
2926       .Case("a1", ARM::R0)
2927       .Case("a2", ARM::R1)
2928       .Case("a3", ARM::R2)
2929       .Case("a4", ARM::R3)
2930       .Case("v1", ARM::R4)
2931       .Case("v2", ARM::R5)
2932       .Case("v3", ARM::R6)
2933       .Case("v4", ARM::R7)
2934       .Case("v5", ARM::R8)
2935       .Case("v6", ARM::R9)
2936       .Case("v7", ARM::R10)
2937       .Case("v8", ARM::R11)
2938       .Case("sb", ARM::R9)
2939       .Case("sl", ARM::R10)
2940       .Case("fp", ARM::R11)
2941       .Default(0);
2942   }
2943   if (!RegNum) {
2944     // Check for aliases registered via .req. Canonicalize to lower case.
2945     // That's more consistent since register names are case insensitive, and
2946     // it's how the original entry was passed in from MC/MCParser/AsmParser.
2947     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
2948     // If no match, return failure.
2949     if (Entry == RegisterReqs.end())
2950       return -1;
2951     Parser.Lex(); // Eat identifier token.
2952     return Entry->getValue();
2953   }
2954
2955   // Some FPUs only have 16 D registers, so D16-D31 are invalid
2956   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
2957     return -1;
2958
2959   Parser.Lex(); // Eat identifier token.
2960
2961   return RegNum;
2962 }
2963
2964 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
2965 // If a recoverable error occurs, return 1. If an irrecoverable error
2966 // occurs, return -1. An irrecoverable error is one where tokens have been
2967 // consumed in the process of trying to parse the shifter (i.e., when it is
2968 // indeed a shifter operand, but malformed).
2969 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
2970   MCAsmParser &Parser = getParser();
2971   SMLoc S = Parser.getTok().getLoc();
2972   const AsmToken &Tok = Parser.getTok();
2973   if (Tok.isNot(AsmToken::Identifier))
2974     return -1; 
2975
2976   std::string lowerCase = Tok.getString().lower();
2977   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
2978       .Case("asl", ARM_AM::lsl)
2979       .Case("lsl", ARM_AM::lsl)
2980       .Case("lsr", ARM_AM::lsr)
2981       .Case("asr", ARM_AM::asr)
2982       .Case("ror", ARM_AM::ror)
2983       .Case("rrx", ARM_AM::rrx)
2984       .Default(ARM_AM::no_shift);
2985
2986   if (ShiftTy == ARM_AM::no_shift)
2987     return 1;
2988
2989   Parser.Lex(); // Eat the operator.
2990
2991   // The source register for the shift has already been added to the
2992   // operand list, so we need to pop it off and combine it into the shifted
2993   // register operand instead.
2994   std::unique_ptr<ARMOperand> PrevOp(
2995       (ARMOperand *)Operands.pop_back_val().release());
2996   if (!PrevOp->isReg())
2997     return Error(PrevOp->getStartLoc(), "shift must be of a register");
2998   int SrcReg = PrevOp->getReg();
2999
3000   SMLoc EndLoc;
3001   int64_t Imm = 0;
3002   int ShiftReg = 0;
3003   if (ShiftTy == ARM_AM::rrx) {
3004     // RRX Doesn't have an explicit shift amount. The encoder expects
3005     // the shift register to be the same as the source register. Seems odd,
3006     // but OK.
3007     ShiftReg = SrcReg;
3008   } else {
3009     // Figure out if this is shifted by a constant or a register (for non-RRX).
3010     if (Parser.getTok().is(AsmToken::Hash) ||
3011         Parser.getTok().is(AsmToken::Dollar)) {
3012       Parser.Lex(); // Eat hash.
3013       SMLoc ImmLoc = Parser.getTok().getLoc();
3014       const MCExpr *ShiftExpr = nullptr;
3015       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3016         Error(ImmLoc, "invalid immediate shift value");
3017         return -1;
3018       }
3019       // The expression must be evaluatable as an immediate.
3020       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3021       if (!CE) {
3022         Error(ImmLoc, "invalid immediate shift value");
3023         return -1;
3024       }
3025       // Range check the immediate.
3026       // lsl, ror: 0 <= imm <= 31
3027       // lsr, asr: 0 <= imm <= 32
3028       Imm = CE->getValue();
3029       if (Imm < 0 ||
3030           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3031           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3032         Error(ImmLoc, "immediate shift value out of range");
3033         return -1;
3034       }
3035       // shift by zero is a nop. Always send it through as lsl.
3036       // ('as' compatibility)
3037       if (Imm == 0)
3038         ShiftTy = ARM_AM::lsl;
3039     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3040       SMLoc L = Parser.getTok().getLoc();
3041       EndLoc = Parser.getTok().getEndLoc();
3042       ShiftReg = tryParseRegister();
3043       if (ShiftReg == -1) {
3044         Error(L, "expected immediate or register in shift operand");
3045         return -1;
3046       }
3047     } else {
3048       Error(Parser.getTok().getLoc(),
3049             "expected immediate or register in shift operand");
3050       return -1;
3051     }
3052   }
3053
3054   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3055     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3056                                                          ShiftReg, Imm,
3057                                                          S, EndLoc));
3058   else
3059     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3060                                                           S, EndLoc));
3061
3062   return 0;
3063 }
3064
3065
3066 /// Try to parse a register name.  The token must be an Identifier when called.
3067 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3068 /// if there is a "writeback". 'true' if it's not a register.
3069 ///
3070 /// TODO this is likely to change to allow different register types and or to
3071 /// parse for a specific register type.
3072 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3073   MCAsmParser &Parser = getParser();
3074   const AsmToken &RegTok = Parser.getTok();
3075   int RegNo = tryParseRegister();
3076   if (RegNo == -1)
3077     return true;
3078
3079   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3080                                            RegTok.getEndLoc()));
3081
3082   const AsmToken &ExclaimTok = Parser.getTok();
3083   if (ExclaimTok.is(AsmToken::Exclaim)) {
3084     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3085                                                ExclaimTok.getLoc()));
3086     Parser.Lex(); // Eat exclaim token
3087     return false;
3088   }
3089
3090   // Also check for an index operand. This is only legal for vector registers,
3091   // but that'll get caught OK in operand matching, so we don't need to
3092   // explicitly filter everything else out here.
3093   if (Parser.getTok().is(AsmToken::LBrac)) {
3094     SMLoc SIdx = Parser.getTok().getLoc();
3095     Parser.Lex(); // Eat left bracket token.
3096
3097     const MCExpr *ImmVal;
3098     if (getParser().parseExpression(ImmVal))
3099       return true;
3100     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3101     if (!MCE)
3102       return TokError("immediate value expected for vector index");
3103
3104     if (Parser.getTok().isNot(AsmToken::RBrac))
3105       return Error(Parser.getTok().getLoc(), "']' expected");
3106
3107     SMLoc E = Parser.getTok().getEndLoc();
3108     Parser.Lex(); // Eat right bracket token.
3109
3110     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3111                                                      SIdx, E,
3112                                                      getContext()));
3113   }
3114
3115   return false;
3116 }
3117
3118 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3119 /// instruction with a symbolic operand name.
3120 /// We accept "crN" syntax for GAS compatibility.
3121 /// <operand-name> ::= <prefix><number>
3122 /// If CoprocOp is 'c', then:
3123 ///   <prefix> ::= c | cr
3124 /// If CoprocOp is 'p', then :
3125 ///   <prefix> ::= p
3126 /// <number> ::= integer in range [0, 15]
3127 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3128   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3129   // but efficient.
3130   if (Name.size() < 2 || Name[0] != CoprocOp)
3131     return -1;
3132   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3133
3134   switch (Name.size()) {
3135   default: return -1;
3136   case 1:
3137     switch (Name[0]) {
3138     default:  return -1;
3139     case '0': return 0;
3140     case '1': return 1;
3141     case '2': return 2;
3142     case '3': return 3;
3143     case '4': return 4;
3144     case '5': return 5;
3145     case '6': return 6;
3146     case '7': return 7;
3147     case '8': return 8;
3148     case '9': return 9;
3149     }
3150   case 2:
3151     if (Name[0] != '1')
3152       return -1;
3153     switch (Name[1]) {
3154     default:  return -1;
3155     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3156     // However, old cores (v5/v6) did use them in that way.
3157     case '0': return 10;
3158     case '1': return 11;
3159     case '2': return 12;
3160     case '3': return 13;
3161     case '4': return 14;
3162     case '5': return 15;
3163     }
3164   }
3165 }
3166
3167 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3168 ARMAsmParser::OperandMatchResultTy
3169 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3170   MCAsmParser &Parser = getParser();
3171   SMLoc S = Parser.getTok().getLoc();
3172   const AsmToken &Tok = Parser.getTok();
3173   if (!Tok.is(AsmToken::Identifier))
3174     return MatchOperand_NoMatch;
3175   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3176     .Case("eq", ARMCC::EQ)
3177     .Case("ne", ARMCC::NE)
3178     .Case("hs", ARMCC::HS)
3179     .Case("cs", ARMCC::HS)
3180     .Case("lo", ARMCC::LO)
3181     .Case("cc", ARMCC::LO)
3182     .Case("mi", ARMCC::MI)
3183     .Case("pl", ARMCC::PL)
3184     .Case("vs", ARMCC::VS)
3185     .Case("vc", ARMCC::VC)
3186     .Case("hi", ARMCC::HI)
3187     .Case("ls", ARMCC::LS)
3188     .Case("ge", ARMCC::GE)
3189     .Case("lt", ARMCC::LT)
3190     .Case("gt", ARMCC::GT)
3191     .Case("le", ARMCC::LE)
3192     .Case("al", ARMCC::AL)
3193     .Default(~0U);
3194   if (CC == ~0U)
3195     return MatchOperand_NoMatch;
3196   Parser.Lex(); // Eat the token.
3197
3198   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3199
3200   return MatchOperand_Success;
3201 }
3202
3203 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3204 /// token must be an Identifier when called, and if it is a coprocessor
3205 /// number, the token is eaten and the operand is added to the operand list.
3206 ARMAsmParser::OperandMatchResultTy
3207 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3208   MCAsmParser &Parser = getParser();
3209   SMLoc S = Parser.getTok().getLoc();
3210   const AsmToken &Tok = Parser.getTok();
3211   if (Tok.isNot(AsmToken::Identifier))
3212     return MatchOperand_NoMatch;
3213
3214   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3215   if (Num == -1)
3216     return MatchOperand_NoMatch;
3217   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3218   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3219     return MatchOperand_NoMatch;
3220
3221   Parser.Lex(); // Eat identifier token.
3222   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3223   return MatchOperand_Success;
3224 }
3225
3226 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3227 /// token must be an Identifier when called, and if it is a coprocessor
3228 /// number, the token is eaten and the operand is added to the operand list.
3229 ARMAsmParser::OperandMatchResultTy
3230 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3231   MCAsmParser &Parser = getParser();
3232   SMLoc S = Parser.getTok().getLoc();
3233   const AsmToken &Tok = Parser.getTok();
3234   if (Tok.isNot(AsmToken::Identifier))
3235     return MatchOperand_NoMatch;
3236
3237   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3238   if (Reg == -1)
3239     return MatchOperand_NoMatch;
3240
3241   Parser.Lex(); // Eat identifier token.
3242   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3243   return MatchOperand_Success;
3244 }
3245
3246 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3247 /// coproc_option : '{' imm0_255 '}'
3248 ARMAsmParser::OperandMatchResultTy
3249 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3250   MCAsmParser &Parser = getParser();
3251   SMLoc S = Parser.getTok().getLoc();
3252
3253   // If this isn't a '{', this isn't a coprocessor immediate operand.
3254   if (Parser.getTok().isNot(AsmToken::LCurly))
3255     return MatchOperand_NoMatch;
3256   Parser.Lex(); // Eat the '{'
3257
3258   const MCExpr *Expr;
3259   SMLoc Loc = Parser.getTok().getLoc();
3260   if (getParser().parseExpression(Expr)) {
3261     Error(Loc, "illegal expression");
3262     return MatchOperand_ParseFail;
3263   }
3264   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3265   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3266     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3267     return MatchOperand_ParseFail;
3268   }
3269   int Val = CE->getValue();
3270
3271   // Check for and consume the closing '}'
3272   if (Parser.getTok().isNot(AsmToken::RCurly))
3273     return MatchOperand_ParseFail;
3274   SMLoc E = Parser.getTok().getEndLoc();
3275   Parser.Lex(); // Eat the '}'
3276
3277   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3278   return MatchOperand_Success;
3279 }
3280
3281 // For register list parsing, we need to map from raw GPR register numbering
3282 // to the enumeration values. The enumeration values aren't sorted by
3283 // register number due to our using "sp", "lr" and "pc" as canonical names.
3284 static unsigned getNextRegister(unsigned Reg) {
3285   // If this is a GPR, we need to do it manually, otherwise we can rely
3286   // on the sort ordering of the enumeration since the other reg-classes
3287   // are sane.
3288   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3289     return Reg + 1;
3290   switch(Reg) {
3291   default: llvm_unreachable("Invalid GPR number!");
3292   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3293   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3294   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3295   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3296   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3297   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3298   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3299   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3300   }
3301 }
3302
3303 // Return the low-subreg of a given Q register.
3304 static unsigned getDRegFromQReg(unsigned QReg) {
3305   switch (QReg) {
3306   default: llvm_unreachable("expected a Q register!");
3307   case ARM::Q0:  return ARM::D0;
3308   case ARM::Q1:  return ARM::D2;
3309   case ARM::Q2:  return ARM::D4;
3310   case ARM::Q3:  return ARM::D6;
3311   case ARM::Q4:  return ARM::D8;
3312   case ARM::Q5:  return ARM::D10;
3313   case ARM::Q6:  return ARM::D12;
3314   case ARM::Q7:  return ARM::D14;
3315   case ARM::Q8:  return ARM::D16;
3316   case ARM::Q9:  return ARM::D18;
3317   case ARM::Q10: return ARM::D20;
3318   case ARM::Q11: return ARM::D22;
3319   case ARM::Q12: return ARM::D24;
3320   case ARM::Q13: return ARM::D26;
3321   case ARM::Q14: return ARM::D28;
3322   case ARM::Q15: return ARM::D30;
3323   }
3324 }
3325
3326 /// Parse a register list.
3327 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3328   MCAsmParser &Parser = getParser();
3329   assert(Parser.getTok().is(AsmToken::LCurly) &&
3330          "Token is not a Left Curly Brace");
3331   SMLoc S = Parser.getTok().getLoc();
3332   Parser.Lex(); // Eat '{' token.
3333   SMLoc RegLoc = Parser.getTok().getLoc();
3334
3335   // Check the first register in the list to see what register class
3336   // this is a list of.
3337   int Reg = tryParseRegister();
3338   if (Reg == -1)
3339     return Error(RegLoc, "register expected");
3340
3341   // The reglist instructions have at most 16 registers, so reserve
3342   // space for that many.
3343   int EReg = 0;
3344   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3345
3346   // Allow Q regs and just interpret them as the two D sub-registers.
3347   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3348     Reg = getDRegFromQReg(Reg);
3349     EReg = MRI->getEncodingValue(Reg);
3350     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3351     ++Reg;
3352   }
3353   const MCRegisterClass *RC;
3354   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3355     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3356   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3357     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3358   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3359     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3360   else
3361     return Error(RegLoc, "invalid register in register list");
3362
3363   // Store the register.
3364   EReg = MRI->getEncodingValue(Reg);
3365   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3366
3367   // This starts immediately after the first register token in the list,
3368   // so we can see either a comma or a minus (range separator) as a legal
3369   // next token.
3370   while (Parser.getTok().is(AsmToken::Comma) ||
3371          Parser.getTok().is(AsmToken::Minus)) {
3372     if (Parser.getTok().is(AsmToken::Minus)) {
3373       Parser.Lex(); // Eat the minus.
3374       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3375       int EndReg = tryParseRegister();
3376       if (EndReg == -1)
3377         return Error(AfterMinusLoc, "register expected");
3378       // Allow Q regs and just interpret them as the two D sub-registers.
3379       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3380         EndReg = getDRegFromQReg(EndReg) + 1;
3381       // If the register is the same as the start reg, there's nothing
3382       // more to do.
3383       if (Reg == EndReg)
3384         continue;
3385       // The register must be in the same register class as the first.
3386       if (!RC->contains(EndReg))
3387         return Error(AfterMinusLoc, "invalid register in register list");
3388       // Ranges must go from low to high.
3389       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3390         return Error(AfterMinusLoc, "bad range in register list");
3391
3392       // Add all the registers in the range to the register list.
3393       while (Reg != EndReg) {
3394         Reg = getNextRegister(Reg);
3395         EReg = MRI->getEncodingValue(Reg);
3396         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3397       }
3398       continue;
3399     }
3400     Parser.Lex(); // Eat the comma.
3401     RegLoc = Parser.getTok().getLoc();
3402     int OldReg = Reg;
3403     const AsmToken RegTok = Parser.getTok();
3404     Reg = tryParseRegister();
3405     if (Reg == -1)
3406       return Error(RegLoc, "register expected");
3407     // Allow Q regs and just interpret them as the two D sub-registers.
3408     bool isQReg = false;
3409     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3410       Reg = getDRegFromQReg(Reg);
3411       isQReg = true;
3412     }
3413     // The register must be in the same register class as the first.
3414     if (!RC->contains(Reg))
3415       return Error(RegLoc, "invalid register in register list");
3416     // List must be monotonically increasing.
3417     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3418       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3419         Warning(RegLoc, "register list not in ascending order");
3420       else
3421         return Error(RegLoc, "register list not in ascending order");
3422     }
3423     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3424       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3425               ") in register list");
3426       continue;
3427     }
3428     // VFP register lists must also be contiguous.
3429     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3430         Reg != OldReg + 1)
3431       return Error(RegLoc, "non-contiguous register range");
3432     EReg = MRI->getEncodingValue(Reg);
3433     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3434     if (isQReg) {
3435       EReg = MRI->getEncodingValue(++Reg);
3436       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3437     }
3438   }
3439
3440   if (Parser.getTok().isNot(AsmToken::RCurly))
3441     return Error(Parser.getTok().getLoc(), "'}' expected");
3442   SMLoc E = Parser.getTok().getEndLoc();
3443   Parser.Lex(); // Eat '}' token.
3444
3445   // Push the register list operand.
3446   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3447
3448   // The ARM system instruction variants for LDM/STM have a '^' token here.
3449   if (Parser.getTok().is(AsmToken::Caret)) {
3450     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3451     Parser.Lex(); // Eat '^' token.
3452   }
3453
3454   return false;
3455 }
3456
3457 // Helper function to parse the lane index for vector lists.
3458 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3459 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3460   MCAsmParser &Parser = getParser();
3461   Index = 0; // Always return a defined index value.
3462   if (Parser.getTok().is(AsmToken::LBrac)) {
3463     Parser.Lex(); // Eat the '['.
3464     if (Parser.getTok().is(AsmToken::RBrac)) {
3465       // "Dn[]" is the 'all lanes' syntax.
3466       LaneKind = AllLanes;
3467       EndLoc = Parser.getTok().getEndLoc();
3468       Parser.Lex(); // Eat the ']'.
3469       return MatchOperand_Success;
3470     }
3471
3472     // There's an optional '#' token here. Normally there wouldn't be, but
3473     // inline assemble puts one in, and it's friendly to accept that.
3474     if (Parser.getTok().is(AsmToken::Hash))
3475       Parser.Lex(); // Eat '#' or '$'.
3476
3477     const MCExpr *LaneIndex;
3478     SMLoc Loc = Parser.getTok().getLoc();
3479     if (getParser().parseExpression(LaneIndex)) {
3480       Error(Loc, "illegal expression");
3481       return MatchOperand_ParseFail;
3482     }
3483     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3484     if (!CE) {
3485       Error(Loc, "lane index must be empty or an integer");
3486       return MatchOperand_ParseFail;
3487     }
3488     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3489       Error(Parser.getTok().getLoc(), "']' expected");
3490       return MatchOperand_ParseFail;
3491     }
3492     EndLoc = Parser.getTok().getEndLoc();
3493     Parser.Lex(); // Eat the ']'.
3494     int64_t Val = CE->getValue();
3495
3496     // FIXME: Make this range check context sensitive for .8, .16, .32.
3497     if (Val < 0 || Val > 7) {
3498       Error(Parser.getTok().getLoc(), "lane index out of range");
3499       return MatchOperand_ParseFail;
3500     }
3501     Index = Val;
3502     LaneKind = IndexedLane;
3503     return MatchOperand_Success;
3504   }
3505   LaneKind = NoLanes;
3506   return MatchOperand_Success;
3507 }
3508
3509 // parse a vector register list
3510 ARMAsmParser::OperandMatchResultTy
3511 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3512   MCAsmParser &Parser = getParser();
3513   VectorLaneTy LaneKind;
3514   unsigned LaneIndex;
3515   SMLoc S = Parser.getTok().getLoc();
3516   // As an extension (to match gas), support a plain D register or Q register
3517   // (without encosing curly braces) as a single or double entry list,
3518   // respectively.
3519   if (Parser.getTok().is(AsmToken::Identifier)) {
3520     SMLoc E = Parser.getTok().getEndLoc();
3521     int Reg = tryParseRegister();
3522     if (Reg == -1)
3523       return MatchOperand_NoMatch;
3524     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3525       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3526       if (Res != MatchOperand_Success)
3527         return Res;
3528       switch (LaneKind) {
3529       case NoLanes:
3530         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3531         break;
3532       case AllLanes:
3533         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3534                                                                 S, E));
3535         break;
3536       case IndexedLane:
3537         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3538                                                                LaneIndex,
3539                                                                false, S, E));
3540         break;
3541       }
3542       return MatchOperand_Success;
3543     }
3544     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3545       Reg = getDRegFromQReg(Reg);
3546       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3547       if (Res != MatchOperand_Success)
3548         return Res;
3549       switch (LaneKind) {
3550       case NoLanes:
3551         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3552                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3553         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3554         break;
3555       case AllLanes:
3556         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3557                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3558         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3559                                                                 S, E));
3560         break;
3561       case IndexedLane:
3562         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3563                                                                LaneIndex,
3564                                                                false, S, E));
3565         break;
3566       }
3567       return MatchOperand_Success;
3568     }
3569     Error(S, "vector register expected");
3570     return MatchOperand_ParseFail;
3571   }
3572
3573   if (Parser.getTok().isNot(AsmToken::LCurly))
3574     return MatchOperand_NoMatch;
3575
3576   Parser.Lex(); // Eat '{' token.
3577   SMLoc RegLoc = Parser.getTok().getLoc();
3578
3579   int Reg = tryParseRegister();
3580   if (Reg == -1) {
3581     Error(RegLoc, "register expected");
3582     return MatchOperand_ParseFail;
3583   }
3584   unsigned Count = 1;
3585   int Spacing = 0;
3586   unsigned FirstReg = Reg;
3587   // The list is of D registers, but we also allow Q regs and just interpret
3588   // them as the two D sub-registers.
3589   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3590     FirstReg = Reg = getDRegFromQReg(Reg);
3591     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3592                  // it's ambiguous with four-register single spaced.
3593     ++Reg;
3594     ++Count;
3595   }
3596
3597   SMLoc E;
3598   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3599     return MatchOperand_ParseFail;
3600
3601   while (Parser.getTok().is(AsmToken::Comma) ||
3602          Parser.getTok().is(AsmToken::Minus)) {
3603     if (Parser.getTok().is(AsmToken::Minus)) {
3604       if (!Spacing)
3605         Spacing = 1; // Register range implies a single spaced list.
3606       else if (Spacing == 2) {
3607         Error(Parser.getTok().getLoc(),
3608               "sequential registers in double spaced list");
3609         return MatchOperand_ParseFail;
3610       }
3611       Parser.Lex(); // Eat the minus.
3612       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3613       int EndReg = tryParseRegister();
3614       if (EndReg == -1) {
3615         Error(AfterMinusLoc, "register expected");
3616         return MatchOperand_ParseFail;
3617       }
3618       // Allow Q regs and just interpret them as the two D sub-registers.
3619       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3620         EndReg = getDRegFromQReg(EndReg) + 1;
3621       // If the register is the same as the start reg, there's nothing
3622       // more to do.
3623       if (Reg == EndReg)
3624         continue;
3625       // The register must be in the same register class as the first.
3626       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3627         Error(AfterMinusLoc, "invalid register in register list");
3628         return MatchOperand_ParseFail;
3629       }
3630       // Ranges must go from low to high.
3631       if (Reg > EndReg) {
3632         Error(AfterMinusLoc, "bad range in register list");
3633         return MatchOperand_ParseFail;
3634       }
3635       // Parse the lane specifier if present.
3636       VectorLaneTy NextLaneKind;
3637       unsigned NextLaneIndex;
3638       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3639           MatchOperand_Success)
3640         return MatchOperand_ParseFail;
3641       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3642         Error(AfterMinusLoc, "mismatched lane index in register list");
3643         return MatchOperand_ParseFail;
3644       }
3645
3646       // Add all the registers in the range to the register list.
3647       Count += EndReg - Reg;
3648       Reg = EndReg;
3649       continue;
3650     }
3651     Parser.Lex(); // Eat the comma.
3652     RegLoc = Parser.getTok().getLoc();
3653     int OldReg = Reg;
3654     Reg = tryParseRegister();
3655     if (Reg == -1) {
3656       Error(RegLoc, "register expected");
3657       return MatchOperand_ParseFail;
3658     }
3659     // vector register lists must be contiguous.
3660     // It's OK to use the enumeration values directly here rather, as the
3661     // VFP register classes have the enum sorted properly.
3662     //
3663     // The list is of D registers, but we also allow Q regs and just interpret
3664     // them as the two D sub-registers.
3665     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3666       if (!Spacing)
3667         Spacing = 1; // Register range implies a single spaced list.
3668       else if (Spacing == 2) {
3669         Error(RegLoc,
3670               "invalid register in double-spaced list (must be 'D' register')");
3671         return MatchOperand_ParseFail;
3672       }
3673       Reg = getDRegFromQReg(Reg);
3674       if (Reg != OldReg + 1) {
3675         Error(RegLoc, "non-contiguous register range");
3676         return MatchOperand_ParseFail;
3677       }
3678       ++Reg;
3679       Count += 2;
3680       // Parse the lane specifier if present.
3681       VectorLaneTy NextLaneKind;
3682       unsigned NextLaneIndex;
3683       SMLoc LaneLoc = Parser.getTok().getLoc();
3684       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3685           MatchOperand_Success)
3686         return MatchOperand_ParseFail;
3687       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3688         Error(LaneLoc, "mismatched lane index in register list");
3689         return MatchOperand_ParseFail;
3690       }
3691       continue;
3692     }
3693     // Normal D register.
3694     // Figure out the register spacing (single or double) of the list if
3695     // we don't know it already.
3696     if (!Spacing)
3697       Spacing = 1 + (Reg == OldReg + 2);
3698
3699     // Just check that it's contiguous and keep going.
3700     if (Reg != OldReg + Spacing) {
3701       Error(RegLoc, "non-contiguous register range");
3702       return MatchOperand_ParseFail;
3703     }
3704     ++Count;
3705     // Parse the lane specifier if present.
3706     VectorLaneTy NextLaneKind;
3707     unsigned NextLaneIndex;
3708     SMLoc EndLoc = Parser.getTok().getLoc();
3709     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3710       return MatchOperand_ParseFail;
3711     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3712       Error(EndLoc, "mismatched lane index in register list");
3713       return MatchOperand_ParseFail;
3714     }
3715   }
3716
3717   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3718     Error(Parser.getTok().getLoc(), "'}' expected");
3719     return MatchOperand_ParseFail;
3720   }
3721   E = Parser.getTok().getEndLoc();
3722   Parser.Lex(); // Eat '}' token.
3723
3724   switch (LaneKind) {
3725   case NoLanes:
3726     // Two-register operands have been converted to the
3727     // composite register classes.
3728     if (Count == 2) {
3729       const MCRegisterClass *RC = (Spacing == 1) ?
3730         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3731         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3732       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3733     }
3734
3735     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3736                                                     (Spacing == 2), S, E));
3737     break;
3738   case AllLanes:
3739     // Two-register operands have been converted to the
3740     // composite register classes.
3741     if (Count == 2) {
3742       const MCRegisterClass *RC = (Spacing == 1) ?
3743         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3744         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3745       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3746     }
3747     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3748                                                             (Spacing == 2),
3749                                                             S, E));
3750     break;
3751   case IndexedLane:
3752     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3753                                                            LaneIndex,
3754                                                            (Spacing == 2),
3755                                                            S, E));
3756     break;
3757   }
3758   return MatchOperand_Success;
3759 }
3760
3761 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3762 ARMAsmParser::OperandMatchResultTy
3763 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3764   MCAsmParser &Parser = getParser();
3765   SMLoc S = Parser.getTok().getLoc();
3766   const AsmToken &Tok = Parser.getTok();
3767   unsigned Opt;
3768
3769   if (Tok.is(AsmToken::Identifier)) {
3770     StringRef OptStr = Tok.getString();
3771
3772     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3773       .Case("sy",    ARM_MB::SY)
3774       .Case("st",    ARM_MB::ST)
3775       .Case("ld",    ARM_MB::LD)
3776       .Case("sh",    ARM_MB::ISH)
3777       .Case("ish",   ARM_MB::ISH)
3778       .Case("shst",  ARM_MB::ISHST)
3779       .Case("ishst", ARM_MB::ISHST)
3780       .Case("ishld", ARM_MB::ISHLD)
3781       .Case("nsh",   ARM_MB::NSH)
3782       .Case("un",    ARM_MB::NSH)
3783       .Case("nshst", ARM_MB::NSHST)
3784       .Case("nshld", ARM_MB::NSHLD)
3785       .Case("unst",  ARM_MB::NSHST)
3786       .Case("osh",   ARM_MB::OSH)
3787       .Case("oshst", ARM_MB::OSHST)
3788       .Case("oshld", ARM_MB::OSHLD)
3789       .Default(~0U);
3790
3791     // ishld, oshld, nshld and ld are only available from ARMv8.
3792     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3793                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3794       Opt = ~0U;
3795
3796     if (Opt == ~0U)
3797       return MatchOperand_NoMatch;
3798
3799     Parser.Lex(); // Eat identifier token.
3800   } else if (Tok.is(AsmToken::Hash) ||
3801              Tok.is(AsmToken::Dollar) ||
3802              Tok.is(AsmToken::Integer)) {
3803     if (Parser.getTok().isNot(AsmToken::Integer))
3804       Parser.Lex(); // Eat '#' or '$'.
3805     SMLoc Loc = Parser.getTok().getLoc();
3806
3807     const MCExpr *MemBarrierID;
3808     if (getParser().parseExpression(MemBarrierID)) {
3809       Error(Loc, "illegal expression");
3810       return MatchOperand_ParseFail;
3811     }
3812
3813     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3814     if (!CE) {
3815       Error(Loc, "constant expression expected");
3816       return MatchOperand_ParseFail;
3817     }
3818
3819     int Val = CE->getValue();
3820     if (Val & ~0xf) {
3821       Error(Loc, "immediate value out of range");
3822       return MatchOperand_ParseFail;
3823     }
3824
3825     Opt = ARM_MB::RESERVED_0 + Val;
3826   } else
3827     return MatchOperand_ParseFail;
3828
3829   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3830   return MatchOperand_Success;
3831 }
3832
3833 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3834 ARMAsmParser::OperandMatchResultTy
3835 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3836   MCAsmParser &Parser = getParser();
3837   SMLoc S = Parser.getTok().getLoc();
3838   const AsmToken &Tok = Parser.getTok();
3839   unsigned Opt;
3840
3841   if (Tok.is(AsmToken::Identifier)) {
3842     StringRef OptStr = Tok.getString();
3843
3844     if (OptStr.equals_lower("sy"))
3845       Opt = ARM_ISB::SY;
3846     else
3847       return MatchOperand_NoMatch;
3848
3849     Parser.Lex(); // Eat identifier token.
3850   } else if (Tok.is(AsmToken::Hash) ||
3851              Tok.is(AsmToken::Dollar) ||
3852              Tok.is(AsmToken::Integer)) {
3853     if (Parser.getTok().isNot(AsmToken::Integer))
3854       Parser.Lex(); // Eat '#' or '$'.
3855     SMLoc Loc = Parser.getTok().getLoc();
3856
3857     const MCExpr *ISBarrierID;
3858     if (getParser().parseExpression(ISBarrierID)) {
3859       Error(Loc, "illegal expression");
3860       return MatchOperand_ParseFail;
3861     }
3862
3863     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
3864     if (!CE) {
3865       Error(Loc, "constant expression expected");
3866       return MatchOperand_ParseFail;
3867     }
3868
3869     int Val = CE->getValue();
3870     if (Val & ~0xf) {
3871       Error(Loc, "immediate value out of range");
3872       return MatchOperand_ParseFail;
3873     }
3874
3875     Opt = ARM_ISB::RESERVED_0 + Val;
3876   } else
3877     return MatchOperand_ParseFail;
3878
3879   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
3880           (ARM_ISB::InstSyncBOpt)Opt, S));
3881   return MatchOperand_Success;
3882 }
3883
3884
3885 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
3886 ARMAsmParser::OperandMatchResultTy
3887 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
3888   MCAsmParser &Parser = getParser();
3889   SMLoc S = Parser.getTok().getLoc();
3890   const AsmToken &Tok = Parser.getTok();
3891   if (!Tok.is(AsmToken::Identifier)) 
3892     return MatchOperand_NoMatch;
3893   StringRef IFlagsStr = Tok.getString();
3894
3895   // An iflags string of "none" is interpreted to mean that none of the AIF
3896   // bits are set.  Not a terribly useful instruction, but a valid encoding.
3897   unsigned IFlags = 0;
3898   if (IFlagsStr != "none") {
3899         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
3900       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
3901         .Case("a", ARM_PROC::A)
3902         .Case("i", ARM_PROC::I)
3903         .Case("f", ARM_PROC::F)
3904         .Default(~0U);
3905
3906       // If some specific iflag is already set, it means that some letter is
3907       // present more than once, this is not acceptable.
3908       if (Flag == ~0U || (IFlags & Flag))
3909         return MatchOperand_NoMatch;
3910
3911       IFlags |= Flag;
3912     }
3913   }
3914
3915   Parser.Lex(); // Eat identifier token.
3916   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
3917   return MatchOperand_Success;
3918 }
3919
3920 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
3921 ARMAsmParser::OperandMatchResultTy
3922 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
3923   MCAsmParser &Parser = getParser();
3924   SMLoc S = Parser.getTok().getLoc();
3925   const AsmToken &Tok = Parser.getTok();
3926   if (!Tok.is(AsmToken::Identifier))
3927     return MatchOperand_NoMatch;
3928   StringRef Mask = Tok.getString();
3929
3930   if (isMClass()) {
3931     // See ARMv6-M 10.1.1
3932     std::string Name = Mask.lower();
3933     unsigned FlagsVal = StringSwitch<unsigned>(Name)
3934       // Note: in the documentation:
3935       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
3936       //  for MSR APSR_nzcvq.
3937       // but we do make it an alias here.  This is so to get the "mask encoding"
3938       // bits correct on MSR APSR writes.
3939       //
3940       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
3941       // should really only be allowed when writing a special register.  Note
3942       // they get dropped in the MRS instruction reading a special register as
3943       // the SYSm field is only 8 bits.
3944       .Case("apsr", 0x800)
3945       .Case("apsr_nzcvq", 0x800)
3946       .Case("apsr_g", 0x400)
3947       .Case("apsr_nzcvqg", 0xc00)
3948       .Case("iapsr", 0x801)
3949       .Case("iapsr_nzcvq", 0x801)
3950       .Case("iapsr_g", 0x401)
3951       .Case("iapsr_nzcvqg", 0xc01)
3952       .Case("eapsr", 0x802)
3953       .Case("eapsr_nzcvq", 0x802)
3954       .Case("eapsr_g", 0x402)
3955       .Case("eapsr_nzcvqg", 0xc02)
3956       .Case("xpsr", 0x803)
3957       .Case("xpsr_nzcvq", 0x803)
3958       .Case("xpsr_g", 0x403)
3959       .Case("xpsr_nzcvqg", 0xc03)
3960       .Case("ipsr", 0x805)
3961       .Case("epsr", 0x806)
3962       .Case("iepsr", 0x807)
3963       .Case("msp", 0x808)
3964       .Case("psp", 0x809)
3965       .Case("primask", 0x810)
3966       .Case("basepri", 0x811)
3967       .Case("basepri_max", 0x812)
3968       .Case("faultmask", 0x813)
3969       .Case("control", 0x814)
3970       .Default(~0U);
3971
3972     if (FlagsVal == ~0U)
3973       return MatchOperand_NoMatch;
3974
3975     if (!hasThumb2DSP() && (FlagsVal & 0x400))
3976       // The _g and _nzcvqg versions are only valid if the DSP extension is
3977       // available.
3978       return MatchOperand_NoMatch;
3979
3980     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
3981       // basepri, basepri_max and faultmask only valid for V7m.
3982       return MatchOperand_NoMatch;
3983
3984     Parser.Lex(); // Eat identifier token.
3985     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
3986     return MatchOperand_Success;
3987   }
3988
3989   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
3990   size_t Start = 0, Next = Mask.find('_');
3991   StringRef Flags = "";
3992   std::string SpecReg = Mask.slice(Start, Next).lower();
3993   if (Next != StringRef::npos)
3994     Flags = Mask.slice(Next+1, Mask.size());
3995
3996   // FlagsVal contains the complete mask:
3997   // 3-0: Mask
3998   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
3999   unsigned FlagsVal = 0;
4000
4001   if (SpecReg == "apsr") {
4002     FlagsVal = StringSwitch<unsigned>(Flags)
4003     .Case("nzcvq",  0x8) // same as CPSR_f
4004     .Case("g",      0x4) // same as CPSR_s
4005     .Case("nzcvqg", 0xc) // same as CPSR_fs
4006     .Default(~0U);
4007
4008     if (FlagsVal == ~0U) {
4009       if (!Flags.empty())
4010         return MatchOperand_NoMatch;
4011       else
4012         FlagsVal = 8; // No flag
4013     }
4014   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4015     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4016     if (Flags == "all" || Flags == "")
4017       Flags = "fc";
4018     for (int i = 0, e = Flags.size(); i != e; ++i) {
4019       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4020       .Case("c", 1)
4021       .Case("x", 2)
4022       .Case("s", 4)
4023       .Case("f", 8)
4024       .Default(~0U);
4025
4026       // If some specific flag is already set, it means that some letter is
4027       // present more than once, this is not acceptable.
4028       if (FlagsVal == ~0U || (FlagsVal & Flag))
4029         return MatchOperand_NoMatch;
4030       FlagsVal |= Flag;
4031     }
4032   } else // No match for special register.
4033     return MatchOperand_NoMatch;
4034
4035   // Special register without flags is NOT equivalent to "fc" flags.
4036   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4037   // two lines would enable gas compatibility at the expense of breaking
4038   // round-tripping.
4039   //
4040   // if (!FlagsVal)
4041   //  FlagsVal = 0x9;
4042
4043   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4044   if (SpecReg == "spsr")
4045     FlagsVal |= 16;
4046
4047   Parser.Lex(); // Eat identifier token.
4048   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4049   return MatchOperand_Success;
4050 }
4051
4052 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4053 /// use in the MRS/MSR instructions added to support virtualization.
4054 ARMAsmParser::OperandMatchResultTy
4055 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4056   MCAsmParser &Parser = getParser();
4057   SMLoc S = Parser.getTok().getLoc();
4058   const AsmToken &Tok = Parser.getTok();
4059   if (!Tok.is(AsmToken::Identifier))
4060     return MatchOperand_NoMatch;
4061   StringRef RegName = Tok.getString();
4062
4063   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4064   // and bit 5 is R.
4065   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4066                           .Case("r8_usr", 0x00)
4067                           .Case("r9_usr", 0x01)
4068                           .Case("r10_usr", 0x02)
4069                           .Case("r11_usr", 0x03)
4070                           .Case("r12_usr", 0x04)
4071                           .Case("sp_usr", 0x05)
4072                           .Case("lr_usr", 0x06)
4073                           .Case("r8_fiq", 0x08)
4074                           .Case("r9_fiq", 0x09)
4075                           .Case("r10_fiq", 0x0a)
4076                           .Case("r11_fiq", 0x0b)
4077                           .Case("r12_fiq", 0x0c)
4078                           .Case("sp_fiq", 0x0d)
4079                           .Case("lr_fiq", 0x0e)
4080                           .Case("lr_irq", 0x10)
4081                           .Case("sp_irq", 0x11)
4082                           .Case("lr_svc", 0x12)
4083                           .Case("sp_svc", 0x13)
4084                           .Case("lr_abt", 0x14)
4085                           .Case("sp_abt", 0x15)
4086                           .Case("lr_und", 0x16)
4087                           .Case("sp_und", 0x17)
4088                           .Case("lr_mon", 0x1c)
4089                           .Case("sp_mon", 0x1d)
4090                           .Case("elr_hyp", 0x1e)
4091                           .Case("sp_hyp", 0x1f)
4092                           .Case("spsr_fiq", 0x2e)
4093                           .Case("spsr_irq", 0x30)
4094                           .Case("spsr_svc", 0x32)
4095                           .Case("spsr_abt", 0x34)
4096                           .Case("spsr_und", 0x36)
4097                           .Case("spsr_mon", 0x3c)
4098                           .Case("spsr_hyp", 0x3e)
4099                           .Default(~0U);
4100
4101   if (Encoding == ~0U)
4102     return MatchOperand_NoMatch;
4103
4104   Parser.Lex(); // Eat identifier token.
4105   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4106   return MatchOperand_Success;
4107 }
4108
4109 ARMAsmParser::OperandMatchResultTy
4110 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4111                           int High) {
4112   MCAsmParser &Parser = getParser();
4113   const AsmToken &Tok = Parser.getTok();
4114   if (Tok.isNot(AsmToken::Identifier)) {
4115     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4116     return MatchOperand_ParseFail;
4117   }
4118   StringRef ShiftName = Tok.getString();
4119   std::string LowerOp = Op.lower();
4120   std::string UpperOp = Op.upper();
4121   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4122     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4123     return MatchOperand_ParseFail;
4124   }
4125   Parser.Lex(); // Eat shift type token.
4126
4127   // There must be a '#' and a shift amount.
4128   if (Parser.getTok().isNot(AsmToken::Hash) &&
4129       Parser.getTok().isNot(AsmToken::Dollar)) {
4130     Error(Parser.getTok().getLoc(), "'#' expected");
4131     return MatchOperand_ParseFail;
4132   }
4133   Parser.Lex(); // Eat hash token.
4134
4135   const MCExpr *ShiftAmount;
4136   SMLoc Loc = Parser.getTok().getLoc();
4137   SMLoc EndLoc;
4138   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4139     Error(Loc, "illegal expression");
4140     return MatchOperand_ParseFail;
4141   }
4142   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4143   if (!CE) {
4144     Error(Loc, "constant expression expected");
4145     return MatchOperand_ParseFail;
4146   }
4147   int Val = CE->getValue();
4148   if (Val < Low || Val > High) {
4149     Error(Loc, "immediate value out of range");
4150     return MatchOperand_ParseFail;
4151   }
4152
4153   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4154
4155   return MatchOperand_Success;
4156 }
4157
4158 ARMAsmParser::OperandMatchResultTy
4159 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4160   MCAsmParser &Parser = getParser();
4161   const AsmToken &Tok = Parser.getTok();
4162   SMLoc S = Tok.getLoc();
4163   if (Tok.isNot(AsmToken::Identifier)) {
4164     Error(S, "'be' or 'le' operand expected");
4165     return MatchOperand_ParseFail;
4166   }
4167   int Val = StringSwitch<int>(Tok.getString().lower())
4168     .Case("be", 1)
4169     .Case("le", 0)
4170     .Default(-1);
4171   Parser.Lex(); // Eat the token.
4172
4173   if (Val == -1) {
4174     Error(S, "'be' or 'le' operand expected");
4175     return MatchOperand_ParseFail;
4176   }
4177   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4178                                                                   getContext()),
4179                                            S, Tok.getEndLoc()));
4180   return MatchOperand_Success;
4181 }
4182
4183 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4184 /// instructions. Legal values are:
4185 ///     lsl #n  'n' in [0,31]
4186 ///     asr #n  'n' in [1,32]
4187 ///             n == 32 encoded as n == 0.
4188 ARMAsmParser::OperandMatchResultTy
4189 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4190   MCAsmParser &Parser = getParser();
4191   const AsmToken &Tok = Parser.getTok();
4192   SMLoc S = Tok.getLoc();
4193   if (Tok.isNot(AsmToken::Identifier)) {
4194     Error(S, "shift operator 'asr' or 'lsl' expected");
4195     return MatchOperand_ParseFail;
4196   }
4197   StringRef ShiftName = Tok.getString();
4198   bool isASR;
4199   if (ShiftName == "lsl" || ShiftName == "LSL")
4200     isASR = false;
4201   else if (ShiftName == "asr" || ShiftName == "ASR")
4202     isASR = true;
4203   else {
4204     Error(S, "shift operator 'asr' or 'lsl' expected");
4205     return MatchOperand_ParseFail;
4206   }
4207   Parser.Lex(); // Eat the operator.
4208
4209   // A '#' and a shift amount.
4210   if (Parser.getTok().isNot(AsmToken::Hash) &&
4211       Parser.getTok().isNot(AsmToken::Dollar)) {
4212     Error(Parser.getTok().getLoc(), "'#' expected");
4213     return MatchOperand_ParseFail;
4214   }
4215   Parser.Lex(); // Eat hash token.
4216   SMLoc ExLoc = Parser.getTok().getLoc();
4217
4218   const MCExpr *ShiftAmount;
4219   SMLoc EndLoc;
4220   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4221     Error(ExLoc, "malformed shift expression");
4222     return MatchOperand_ParseFail;
4223   }
4224   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4225   if (!CE) {
4226     Error(ExLoc, "shift amount must be an immediate");
4227     return MatchOperand_ParseFail;
4228   }
4229
4230   int64_t Val = CE->getValue();
4231   if (isASR) {
4232     // Shift amount must be in [1,32]
4233     if (Val < 1 || Val > 32) {
4234       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4235       return MatchOperand_ParseFail;
4236     }
4237     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4238     if (isThumb() && Val == 32) {
4239       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4240       return MatchOperand_ParseFail;
4241     }
4242     if (Val == 32) Val = 0;
4243   } else {
4244     // Shift amount must be in [1,32]
4245     if (Val < 0 || Val > 31) {
4246       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4247       return MatchOperand_ParseFail;
4248     }
4249   }
4250
4251   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4252
4253   return MatchOperand_Success;
4254 }
4255
4256 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4257 /// of instructions. Legal values are:
4258 ///     ror #n  'n' in {0, 8, 16, 24}
4259 ARMAsmParser::OperandMatchResultTy
4260 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4261   MCAsmParser &Parser = getParser();
4262   const AsmToken &Tok = Parser.getTok();
4263   SMLoc S = Tok.getLoc();
4264   if (Tok.isNot(AsmToken::Identifier))
4265     return MatchOperand_NoMatch;
4266   StringRef ShiftName = Tok.getString();
4267   if (ShiftName != "ror" && ShiftName != "ROR")
4268     return MatchOperand_NoMatch;
4269   Parser.Lex(); // Eat the operator.
4270
4271   // A '#' and a rotate amount.
4272   if (Parser.getTok().isNot(AsmToken::Hash) &&
4273       Parser.getTok().isNot(AsmToken::Dollar)) {
4274     Error(Parser.getTok().getLoc(), "'#' expected");
4275     return MatchOperand_ParseFail;
4276   }
4277   Parser.Lex(); // Eat hash token.
4278   SMLoc ExLoc = Parser.getTok().getLoc();
4279
4280   const MCExpr *ShiftAmount;
4281   SMLoc EndLoc;
4282   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4283     Error(ExLoc, "malformed rotate expression");
4284     return MatchOperand_ParseFail;
4285   }
4286   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4287   if (!CE) {
4288     Error(ExLoc, "rotate amount must be an immediate");
4289     return MatchOperand_ParseFail;
4290   }
4291
4292   int64_t Val = CE->getValue();
4293   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4294   // normally, zero is represented in asm by omitting the rotate operand
4295   // entirely.
4296   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4297     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4298     return MatchOperand_ParseFail;
4299   }
4300
4301   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4302
4303   return MatchOperand_Success;
4304 }
4305
4306 ARMAsmParser::OperandMatchResultTy
4307 ARMAsmParser::parseModImm(OperandVector &Operands) {
4308   MCAsmParser &Parser = getParser();
4309   MCAsmLexer &Lexer = getLexer();
4310   int64_t Imm1, Imm2;
4311
4312   SMLoc S = Parser.getTok().getLoc();
4313
4314   // 1) A mod_imm operand can appear in the place of a register name:
4315   //   add r0, #mod_imm
4316   //   add r0, r0, #mod_imm
4317   // to correctly handle the latter, we bail out as soon as we see an
4318   // identifier.
4319   //
4320   // 2) Similarly, we do not want to parse into complex operands:
4321   //   mov r0, #mod_imm
4322   //   mov r0, :lower16:(_foo)
4323   if (Parser.getTok().is(AsmToken::Identifier) ||
4324       Parser.getTok().is(AsmToken::Colon))
4325     return MatchOperand_NoMatch;
4326
4327   // Hash (dollar) is optional as per the ARMARM
4328   if (Parser.getTok().is(AsmToken::Hash) ||
4329       Parser.getTok().is(AsmToken::Dollar)) {
4330     // Avoid parsing into complex operands (#:)
4331     if (Lexer.peekTok().is(AsmToken::Colon))
4332       return MatchOperand_NoMatch;
4333
4334     // Eat the hash (dollar)
4335     Parser.Lex();
4336   }
4337
4338   SMLoc Sx1, Ex1;
4339   Sx1 = Parser.getTok().getLoc();
4340   const MCExpr *Imm1Exp;
4341   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4342     Error(Sx1, "malformed expression");
4343     return MatchOperand_ParseFail;
4344   }
4345
4346   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4347
4348   if (CE) {
4349     // Immediate must fit within 32-bits
4350     Imm1 = CE->getValue();
4351     int Enc = ARM_AM::getSOImmVal(Imm1);
4352     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4353       // We have a match!
4354       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4355                                                   (Enc & 0xF00) >> 7,
4356                                                   Sx1, Ex1));
4357       return MatchOperand_Success;
4358     }
4359
4360     // We have parsed an immediate which is not for us, fallback to a plain
4361     // immediate. This can happen for instruction aliases. For an example,
4362     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4363     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4364     // instruction with a mod_imm operand. The alias is defined such that the
4365     // parser method is shared, that's why we have to do this here.
4366     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4367       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4368       return MatchOperand_Success;
4369     }
4370   } else {
4371     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4372     // MCFixup). Fallback to a plain immediate.
4373     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4374     return MatchOperand_Success;
4375   }
4376
4377   // From this point onward, we expect the input to be a (#bits, #rot) pair
4378   if (Parser.getTok().isNot(AsmToken::Comma)) {
4379     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4380     return MatchOperand_ParseFail;
4381   }
4382
4383   if (Imm1 & ~0xFF) {
4384     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4385     return MatchOperand_ParseFail;
4386   }
4387
4388   // Eat the comma
4389   Parser.Lex();
4390
4391   // Repeat for #rot
4392   SMLoc Sx2, Ex2;
4393   Sx2 = Parser.getTok().getLoc();
4394
4395   // Eat the optional hash (dollar)
4396   if (Parser.getTok().is(AsmToken::Hash) ||
4397       Parser.getTok().is(AsmToken::Dollar))
4398     Parser.Lex();
4399
4400   const MCExpr *Imm2Exp;
4401   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4402     Error(Sx2, "malformed expression");
4403     return MatchOperand_ParseFail;
4404   }
4405
4406   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4407
4408   if (CE) {
4409     Imm2 = CE->getValue();
4410     if (!(Imm2 & ~0x1E)) {
4411       // We have a match!
4412       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4413       return MatchOperand_Success;
4414     }
4415     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4416     return MatchOperand_ParseFail;
4417   } else {
4418     Error(Sx2, "constant expression expected");
4419     return MatchOperand_ParseFail;
4420   }
4421 }
4422
4423 ARMAsmParser::OperandMatchResultTy
4424 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4425   MCAsmParser &Parser = getParser();
4426   SMLoc S = Parser.getTok().getLoc();
4427   // The bitfield descriptor is really two operands, the LSB and the width.
4428   if (Parser.getTok().isNot(AsmToken::Hash) &&
4429       Parser.getTok().isNot(AsmToken::Dollar)) {
4430     Error(Parser.getTok().getLoc(), "'#' expected");
4431     return MatchOperand_ParseFail;
4432   }
4433   Parser.Lex(); // Eat hash token.
4434
4435   const MCExpr *LSBExpr;
4436   SMLoc E = Parser.getTok().getLoc();
4437   if (getParser().parseExpression(LSBExpr)) {
4438     Error(E, "malformed immediate expression");
4439     return MatchOperand_ParseFail;
4440   }
4441   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4442   if (!CE) {
4443     Error(E, "'lsb' operand must be an immediate");
4444     return MatchOperand_ParseFail;
4445   }
4446
4447   int64_t LSB = CE->getValue();
4448   // The LSB must be in the range [0,31]
4449   if (LSB < 0 || LSB > 31) {
4450     Error(E, "'lsb' operand must be in the range [0,31]");
4451     return MatchOperand_ParseFail;
4452   }
4453   E = Parser.getTok().getLoc();
4454
4455   // Expect another immediate operand.
4456   if (Parser.getTok().isNot(AsmToken::Comma)) {
4457     Error(Parser.getTok().getLoc(), "too few operands");
4458     return MatchOperand_ParseFail;
4459   }
4460   Parser.Lex(); // Eat hash token.
4461   if (Parser.getTok().isNot(AsmToken::Hash) &&
4462       Parser.getTok().isNot(AsmToken::Dollar)) {
4463     Error(Parser.getTok().getLoc(), "'#' expected");
4464     return MatchOperand_ParseFail;
4465   }
4466   Parser.Lex(); // Eat hash token.
4467
4468   const MCExpr *WidthExpr;
4469   SMLoc EndLoc;
4470   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4471     Error(E, "malformed immediate expression");
4472     return MatchOperand_ParseFail;
4473   }
4474   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4475   if (!CE) {
4476     Error(E, "'width' operand must be an immediate");
4477     return MatchOperand_ParseFail;
4478   }
4479
4480   int64_t Width = CE->getValue();
4481   // The LSB must be in the range [1,32-lsb]
4482   if (Width < 1 || Width > 32 - LSB) {
4483     Error(E, "'width' operand must be in the range [1,32-lsb]");
4484     return MatchOperand_ParseFail;
4485   }
4486
4487   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4488
4489   return MatchOperand_Success;
4490 }
4491
4492 ARMAsmParser::OperandMatchResultTy
4493 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4494   // Check for a post-index addressing register operand. Specifically:
4495   // postidx_reg := '+' register {, shift}
4496   //              | '-' register {, shift}
4497   //              | register {, shift}
4498
4499   // This method must return MatchOperand_NoMatch without consuming any tokens
4500   // in the case where there is no match, as other alternatives take other
4501   // parse methods.
4502   MCAsmParser &Parser = getParser();
4503   AsmToken Tok = Parser.getTok();
4504   SMLoc S = Tok.getLoc();
4505   bool haveEaten = false;
4506   bool isAdd = true;
4507   if (Tok.is(AsmToken::Plus)) {
4508     Parser.Lex(); // Eat the '+' token.
4509     haveEaten = true;
4510   } else if (Tok.is(AsmToken::Minus)) {
4511     Parser.Lex(); // Eat the '-' token.
4512     isAdd = false;
4513     haveEaten = true;
4514   }
4515
4516   SMLoc E = Parser.getTok().getEndLoc();
4517   int Reg = tryParseRegister();
4518   if (Reg == -1) {
4519     if (!haveEaten)
4520       return MatchOperand_NoMatch;
4521     Error(Parser.getTok().getLoc(), "register expected");
4522     return MatchOperand_ParseFail;
4523   }
4524
4525   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4526   unsigned ShiftImm = 0;
4527   if (Parser.getTok().is(AsmToken::Comma)) {
4528     Parser.Lex(); // Eat the ','.
4529     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4530       return MatchOperand_ParseFail;
4531
4532     // FIXME: Only approximates end...may include intervening whitespace.
4533     E = Parser.getTok().getLoc();
4534   }
4535
4536   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4537                                                   ShiftImm, S, E));
4538
4539   return MatchOperand_Success;
4540 }
4541
4542 ARMAsmParser::OperandMatchResultTy
4543 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4544   // Check for a post-index addressing register operand. Specifically:
4545   // am3offset := '+' register
4546   //              | '-' register
4547   //              | register
4548   //              | # imm
4549   //              | # + imm
4550   //              | # - imm
4551
4552   // This method must return MatchOperand_NoMatch without consuming any tokens
4553   // in the case where there is no match, as other alternatives take other
4554   // parse methods.
4555   MCAsmParser &Parser = getParser();
4556   AsmToken Tok = Parser.getTok();
4557   SMLoc S = Tok.getLoc();
4558
4559   // Do immediates first, as we always parse those if we have a '#'.
4560   if (Parser.getTok().is(AsmToken::Hash) ||
4561       Parser.getTok().is(AsmToken::Dollar)) {
4562     Parser.Lex(); // Eat '#' or '$'.
4563     // Explicitly look for a '-', as we need to encode negative zero
4564     // differently.
4565     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4566     const MCExpr *Offset;
4567     SMLoc E;
4568     if (getParser().parseExpression(Offset, E))
4569       return MatchOperand_ParseFail;
4570     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4571     if (!CE) {
4572       Error(S, "constant expression expected");
4573       return MatchOperand_ParseFail;
4574     }
4575     // Negative zero is encoded as the flag value INT32_MIN.
4576     int32_t Val = CE->getValue();
4577     if (isNegative && Val == 0)
4578       Val = INT32_MIN;
4579
4580     Operands.push_back(
4581       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4582
4583     return MatchOperand_Success;
4584   }
4585
4586
4587   bool haveEaten = false;
4588   bool isAdd = true;
4589   if (Tok.is(AsmToken::Plus)) {
4590     Parser.Lex(); // Eat the '+' token.
4591     haveEaten = true;
4592   } else if (Tok.is(AsmToken::Minus)) {
4593     Parser.Lex(); // Eat the '-' token.
4594     isAdd = false;
4595     haveEaten = true;
4596   }
4597
4598   Tok = Parser.getTok();
4599   int Reg = tryParseRegister();
4600   if (Reg == -1) {
4601     if (!haveEaten)
4602       return MatchOperand_NoMatch;
4603     Error(Tok.getLoc(), "register expected");
4604     return MatchOperand_ParseFail;
4605   }
4606
4607   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4608                                                   0, S, Tok.getEndLoc()));
4609
4610   return MatchOperand_Success;
4611 }
4612
4613 /// Convert parsed operands to MCInst.  Needed here because this instruction
4614 /// only has two register operands, but multiplication is commutative so
4615 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4616 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4617                                     const OperandVector &Operands) {
4618   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4619   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4620   // If we have a three-operand form, make sure to set Rn to be the operand
4621   // that isn't the same as Rd.
4622   unsigned RegOp = 4;
4623   if (Operands.size() == 6 &&
4624       ((ARMOperand &)*Operands[4]).getReg() ==
4625           ((ARMOperand &)*Operands[3]).getReg())
4626     RegOp = 5;
4627   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4628   Inst.addOperand(Inst.getOperand(0));
4629   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4630 }
4631
4632 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4633                                     const OperandVector &Operands) {
4634   int CondOp = -1, ImmOp = -1;
4635   switch(Inst.getOpcode()) {
4636     case ARM::tB:
4637     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4638
4639     case ARM::t2B:
4640     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4641
4642     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4643   }
4644   // first decide whether or not the branch should be conditional
4645   // by looking at it's location relative to an IT block
4646   if(inITBlock()) {
4647     // inside an IT block we cannot have any conditional branches. any 
4648     // such instructions needs to be converted to unconditional form
4649     switch(Inst.getOpcode()) {
4650       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4651       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4652     }
4653   } else {
4654     // outside IT blocks we can only have unconditional branches with AL
4655     // condition code or conditional branches with non-AL condition code
4656     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4657     switch(Inst.getOpcode()) {
4658       case ARM::tB:
4659       case ARM::tBcc: 
4660         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc); 
4661         break;
4662       case ARM::t2B:
4663       case ARM::t2Bcc: 
4664         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4665         break;
4666     }
4667   }
4668
4669   // now decide on encoding size based on branch target range
4670   switch(Inst.getOpcode()) {
4671     // classify tB as either t2B or t1B based on range of immediate operand
4672     case ARM::tB: {
4673       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4674       if (!op.isSignedOffset<11, 1>() && isThumbTwo())
4675         Inst.setOpcode(ARM::t2B);
4676       break;
4677     }
4678     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4679     case ARM::tBcc: {
4680       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4681       if (!op.isSignedOffset<8, 1>() && isThumbTwo())
4682         Inst.setOpcode(ARM::t2Bcc);
4683       break;
4684     }
4685   }
4686   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4687   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4688 }
4689
4690 /// Parse an ARM memory expression, return false if successful else return true
4691 /// or an error.  The first token must be a '[' when called.
4692 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4693   MCAsmParser &Parser = getParser();
4694   SMLoc S, E;
4695   assert(Parser.getTok().is(AsmToken::LBrac) &&
4696          "Token is not a Left Bracket");
4697   S = Parser.getTok().getLoc();
4698   Parser.Lex(); // Eat left bracket token.
4699
4700   const AsmToken &BaseRegTok = Parser.getTok();
4701   int BaseRegNum = tryParseRegister();
4702   if (BaseRegNum == -1)
4703     return Error(BaseRegTok.getLoc(), "register expected");
4704
4705   // The next token must either be a comma, a colon or a closing bracket.
4706   const AsmToken &Tok = Parser.getTok();
4707   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4708       !Tok.is(AsmToken::RBrac))
4709     return Error(Tok.getLoc(), "malformed memory operand");
4710
4711   if (Tok.is(AsmToken::RBrac)) {
4712     E = Tok.getEndLoc();
4713     Parser.Lex(); // Eat right bracket token.
4714
4715     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4716                                              ARM_AM::no_shift, 0, 0, false,
4717                                              S, E));
4718
4719     // If there's a pre-indexing writeback marker, '!', just add it as a token
4720     // operand. It's rather odd, but syntactically valid.
4721     if (Parser.getTok().is(AsmToken::Exclaim)) {
4722       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4723       Parser.Lex(); // Eat the '!'.
4724     }
4725
4726     return false;
4727   }
4728
4729   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4730          "Lost colon or comma in memory operand?!");
4731   if (Tok.is(AsmToken::Comma)) {
4732     Parser.Lex(); // Eat the comma.
4733   }
4734
4735   // If we have a ':', it's an alignment specifier.
4736   if (Parser.getTok().is(AsmToken::Colon)) {
4737     Parser.Lex(); // Eat the ':'.
4738     E = Parser.getTok().getLoc();
4739     SMLoc AlignmentLoc = Tok.getLoc();
4740
4741     const MCExpr *Expr;
4742     if (getParser().parseExpression(Expr))
4743      return true;
4744
4745     // The expression has to be a constant. Memory references with relocations
4746     // don't come through here, as they use the <label> forms of the relevant
4747     // instructions.
4748     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4749     if (!CE)
4750       return Error (E, "constant expression expected");
4751
4752     unsigned Align = 0;
4753     switch (CE->getValue()) {
4754     default:
4755       return Error(E,
4756                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4757     case 16:  Align = 2; break;
4758     case 32:  Align = 4; break;
4759     case 64:  Align = 8; break;
4760     case 128: Align = 16; break;
4761     case 256: Align = 32; break;
4762     }
4763
4764     // Now we should have the closing ']'
4765     if (Parser.getTok().isNot(AsmToken::RBrac))
4766       return Error(Parser.getTok().getLoc(), "']' expected");
4767     E = Parser.getTok().getEndLoc();
4768     Parser.Lex(); // Eat right bracket token.
4769
4770     // Don't worry about range checking the value here. That's handled by
4771     // the is*() predicates.
4772     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4773                                              ARM_AM::no_shift, 0, Align,
4774                                              false, S, E, AlignmentLoc));
4775
4776     // If there's a pre-indexing writeback marker, '!', just add it as a token
4777     // operand.
4778     if (Parser.getTok().is(AsmToken::Exclaim)) {
4779       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4780       Parser.Lex(); // Eat the '!'.
4781     }
4782
4783     return false;
4784   }
4785
4786   // If we have a '#', it's an immediate offset, else assume it's a register
4787   // offset. Be friendly and also accept a plain integer (without a leading
4788   // hash) for gas compatibility.
4789   if (Parser.getTok().is(AsmToken::Hash) ||
4790       Parser.getTok().is(AsmToken::Dollar) ||
4791       Parser.getTok().is(AsmToken::Integer)) {
4792     if (Parser.getTok().isNot(AsmToken::Integer))
4793       Parser.Lex(); // Eat '#' or '$'.
4794     E = Parser.getTok().getLoc();
4795
4796     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4797     const MCExpr *Offset;
4798     if (getParser().parseExpression(Offset))
4799      return true;
4800
4801     // The expression has to be a constant. Memory references with relocations
4802     // don't come through here, as they use the <label> forms of the relevant
4803     // instructions.
4804     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4805     if (!CE)
4806       return Error (E, "constant expression expected");
4807
4808     // If the constant was #-0, represent it as INT32_MIN.
4809     int32_t Val = CE->getValue();
4810     if (isNegative && Val == 0)
4811       CE = MCConstantExpr::create(INT32_MIN, getContext());
4812
4813     // Now we should have the closing ']'
4814     if (Parser.getTok().isNot(AsmToken::RBrac))
4815       return Error(Parser.getTok().getLoc(), "']' expected");
4816     E = Parser.getTok().getEndLoc();
4817     Parser.Lex(); // Eat right bracket token.
4818
4819     // Don't worry about range checking the value here. That's handled by
4820     // the is*() predicates.
4821     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4822                                              ARM_AM::no_shift, 0, 0,
4823                                              false, S, E));
4824
4825     // If there's a pre-indexing writeback marker, '!', just add it as a token
4826     // operand.
4827     if (Parser.getTok().is(AsmToken::Exclaim)) {
4828       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4829       Parser.Lex(); // Eat the '!'.
4830     }
4831
4832     return false;
4833   }
4834
4835   // The register offset is optionally preceded by a '+' or '-'
4836   bool isNegative = false;
4837   if (Parser.getTok().is(AsmToken::Minus)) {
4838     isNegative = true;
4839     Parser.Lex(); // Eat the '-'.
4840   } else if (Parser.getTok().is(AsmToken::Plus)) {
4841     // Nothing to do.
4842     Parser.Lex(); // Eat the '+'.
4843   }
4844
4845   E = Parser.getTok().getLoc();
4846   int OffsetRegNum = tryParseRegister();
4847   if (OffsetRegNum == -1)
4848     return Error(E, "register expected");
4849
4850   // If there's a shift operator, handle it.
4851   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4852   unsigned ShiftImm = 0;
4853   if (Parser.getTok().is(AsmToken::Comma)) {
4854     Parser.Lex(); // Eat the ','.
4855     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4856       return true;
4857   }
4858
4859   // Now we should have the closing ']'
4860   if (Parser.getTok().isNot(AsmToken::RBrac))
4861     return Error(Parser.getTok().getLoc(), "']' expected");
4862   E = Parser.getTok().getEndLoc();
4863   Parser.Lex(); // Eat right bracket token.
4864
4865   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
4866                                            ShiftType, ShiftImm, 0, isNegative,
4867                                            S, E));
4868
4869   // If there's a pre-indexing writeback marker, '!', just add it as a token
4870   // operand.
4871   if (Parser.getTok().is(AsmToken::Exclaim)) {
4872     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4873     Parser.Lex(); // Eat the '!'.
4874   }
4875
4876   return false;
4877 }
4878
4879 /// parseMemRegOffsetShift - one of these two:
4880 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4881 ///   rrx
4882 /// return true if it parses a shift otherwise it returns false.
4883 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4884                                           unsigned &Amount) {
4885   MCAsmParser &Parser = getParser();
4886   SMLoc Loc = Parser.getTok().getLoc();
4887   const AsmToken &Tok = Parser.getTok();
4888   if (Tok.isNot(AsmToken::Identifier))
4889     return true;
4890   StringRef ShiftName = Tok.getString();
4891   if (ShiftName == "lsl" || ShiftName == "LSL" ||
4892       ShiftName == "asl" || ShiftName == "ASL")
4893     St = ARM_AM::lsl;
4894   else if (ShiftName == "lsr" || ShiftName == "LSR")
4895     St = ARM_AM::lsr;
4896   else if (ShiftName == "asr" || ShiftName == "ASR")
4897     St = ARM_AM::asr;
4898   else if (ShiftName == "ror" || ShiftName == "ROR")
4899     St = ARM_AM::ror;
4900   else if (ShiftName == "rrx" || ShiftName == "RRX")
4901     St = ARM_AM::rrx;
4902   else
4903     return Error(Loc, "illegal shift operator");
4904   Parser.Lex(); // Eat shift type token.
4905
4906   // rrx stands alone.
4907   Amount = 0;
4908   if (St != ARM_AM::rrx) {
4909     Loc = Parser.getTok().getLoc();
4910     // A '#' and a shift amount.
4911     const AsmToken &HashTok = Parser.getTok();
4912     if (HashTok.isNot(AsmToken::Hash) &&
4913         HashTok.isNot(AsmToken::Dollar))
4914       return Error(HashTok.getLoc(), "'#' expected");
4915     Parser.Lex(); // Eat hash token.
4916
4917     const MCExpr *Expr;
4918     if (getParser().parseExpression(Expr))
4919       return true;
4920     // Range check the immediate.
4921     // lsl, ror: 0 <= imm <= 31
4922     // lsr, asr: 0 <= imm <= 32
4923     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4924     if (!CE)
4925       return Error(Loc, "shift amount must be an immediate");
4926     int64_t Imm = CE->getValue();
4927     if (Imm < 0 ||
4928         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
4929         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
4930       return Error(Loc, "immediate shift value out of range");
4931     // If <ShiftTy> #0, turn it into a no_shift.
4932     if (Imm == 0)
4933       St = ARM_AM::lsl;
4934     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
4935     if (Imm == 32)
4936       Imm = 0;
4937     Amount = Imm;
4938   }
4939
4940   return false;
4941 }
4942
4943 /// parseFPImm - A floating point immediate expression operand.
4944 ARMAsmParser::OperandMatchResultTy
4945 ARMAsmParser::parseFPImm(OperandVector &Operands) {
4946   MCAsmParser &Parser = getParser();
4947   // Anything that can accept a floating point constant as an operand
4948   // needs to go through here, as the regular parseExpression is
4949   // integer only.
4950   //
4951   // This routine still creates a generic Immediate operand, containing
4952   // a bitcast of the 64-bit floating point value. The various operands
4953   // that accept floats can check whether the value is valid for them
4954   // via the standard is*() predicates.
4955
4956   SMLoc S = Parser.getTok().getLoc();
4957
4958   if (Parser.getTok().isNot(AsmToken::Hash) &&
4959       Parser.getTok().isNot(AsmToken::Dollar))
4960     return MatchOperand_NoMatch;
4961
4962   // Disambiguate the VMOV forms that can accept an FP immediate.
4963   // vmov.f32 <sreg>, #imm
4964   // vmov.f64 <dreg>, #imm
4965   // vmov.f32 <dreg>, #imm  @ vector f32x2
4966   // vmov.f32 <qreg>, #imm  @ vector f32x4
4967   //
4968   // There are also the NEON VMOV instructions which expect an
4969   // integer constant. Make sure we don't try to parse an FPImm
4970   // for these:
4971   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
4972   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
4973   bool isVmovf = TyOp.isToken() &&
4974                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64");
4975   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
4976   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
4977                                          Mnemonic.getToken() == "fconsts");
4978   if (!(isVmovf || isFconst))
4979     return MatchOperand_NoMatch;
4980
4981   Parser.Lex(); // Eat '#' or '$'.
4982
4983   // Handle negation, as that still comes through as a separate token.
4984   bool isNegative = false;
4985   if (Parser.getTok().is(AsmToken::Minus)) {
4986     isNegative = true;
4987     Parser.Lex();
4988   }
4989   const AsmToken &Tok = Parser.getTok();
4990   SMLoc Loc = Tok.getLoc();
4991   if (Tok.is(AsmToken::Real) && isVmovf) {
4992     APFloat RealVal(APFloat::IEEEsingle, Tok.getString());
4993     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
4994     // If we had a '-' in front, toggle the sign bit.
4995     IntVal ^= (uint64_t)isNegative << 31;
4996     Parser.Lex(); // Eat the token.
4997     Operands.push_back(ARMOperand::CreateImm(
4998           MCConstantExpr::create(IntVal, getContext()),
4999           S, Parser.getTok().getLoc()));
5000     return MatchOperand_Success;
5001   }
5002   // Also handle plain integers. Instructions which allow floating point
5003   // immediates also allow a raw encoded 8-bit value.
5004   if (Tok.is(AsmToken::Integer) && isFconst) {
5005     int64_t Val = Tok.getIntVal();
5006     Parser.Lex(); // Eat the token.
5007     if (Val > 255 || Val < 0) {
5008       Error(Loc, "encoded floating point value out of range");
5009       return MatchOperand_ParseFail;
5010     }
5011     float RealVal = ARM_AM::getFPImmFloat(Val);
5012     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5013
5014     Operands.push_back(ARMOperand::CreateImm(
5015         MCConstantExpr::create(Val, getContext()), S,
5016         Parser.getTok().getLoc()));
5017     return MatchOperand_Success;
5018   }
5019
5020   Error(Loc, "invalid floating point immediate");
5021   return MatchOperand_ParseFail;
5022 }
5023
5024 /// Parse a arm instruction operand.  For now this parses the operand regardless
5025 /// of the mnemonic.
5026 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5027   MCAsmParser &Parser = getParser();
5028   SMLoc S, E;
5029
5030   // Check if the current operand has a custom associated parser, if so, try to
5031   // custom parse the operand, or fallback to the general approach.
5032   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5033   if (ResTy == MatchOperand_Success)
5034     return false;
5035   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5036   // there was a match, but an error occurred, in which case, just return that
5037   // the operand parsing failed.
5038   if (ResTy == MatchOperand_ParseFail)
5039     return true;
5040
5041   switch (getLexer().getKind()) {
5042   default:
5043     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5044     return true;
5045   case AsmToken::Identifier: {
5046     // If we've seen a branch mnemonic, the next operand must be a label.  This
5047     // is true even if the label is a register name.  So "br r1" means branch to
5048     // label "r1".
5049     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5050     if (!ExpectLabel) {
5051       if (!tryParseRegisterWithWriteBack(Operands))
5052         return false;
5053       int Res = tryParseShiftRegister(Operands);
5054       if (Res == 0) // success
5055         return false;
5056       else if (Res == -1) // irrecoverable error
5057         return true;
5058       // If this is VMRS, check for the apsr_nzcv operand.
5059       if (Mnemonic == "vmrs" &&
5060           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5061         S = Parser.getTok().getLoc();
5062         Parser.Lex();
5063         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5064         return false;
5065       }
5066     }
5067
5068     // Fall though for the Identifier case that is not a register or a
5069     // special name.
5070   }
5071   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5072   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5073   case AsmToken::String:  // quoted label names.
5074   case AsmToken::Dot: {   // . as a branch target
5075     // This was not a register so parse other operands that start with an
5076     // identifier (like labels) as expressions and create them as immediates.
5077     const MCExpr *IdVal;
5078     S = Parser.getTok().getLoc();
5079     if (getParser().parseExpression(IdVal))
5080       return true;
5081     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5082     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5083     return false;
5084   }
5085   case AsmToken::LBrac:
5086     return parseMemory(Operands);
5087   case AsmToken::LCurly:
5088     return parseRegisterList(Operands);
5089   case AsmToken::Dollar:
5090   case AsmToken::Hash: {
5091     // #42 -> immediate.
5092     S = Parser.getTok().getLoc();
5093     Parser.Lex();
5094
5095     if (Parser.getTok().isNot(AsmToken::Colon)) {
5096       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5097       const MCExpr *ImmVal;
5098       if (getParser().parseExpression(ImmVal))
5099         return true;
5100       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5101       if (CE) {
5102         int32_t Val = CE->getValue();
5103         if (isNegative && Val == 0)
5104           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5105       }
5106       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5107       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5108
5109       // There can be a trailing '!' on operands that we want as a separate
5110       // '!' Token operand. Handle that here. For example, the compatibility
5111       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5112       if (Parser.getTok().is(AsmToken::Exclaim)) {
5113         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5114                                                    Parser.getTok().getLoc()));
5115         Parser.Lex(); // Eat exclaim token
5116       }
5117       return false;
5118     }
5119     // w/ a ':' after the '#', it's just like a plain ':'.
5120     // FALLTHROUGH
5121   }
5122   case AsmToken::Colon: {
5123     // ":lower16:" and ":upper16:" expression prefixes
5124     // FIXME: Check it's an expression prefix,
5125     // e.g. (FOO - :lower16:BAR) isn't legal.
5126     ARMMCExpr::VariantKind RefKind;
5127     if (parsePrefix(RefKind))
5128       return true;
5129
5130     const MCExpr *SubExprVal;
5131     if (getParser().parseExpression(SubExprVal))
5132       return true;
5133
5134     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5135                                               getContext());
5136     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5137     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5138     return false;
5139   }
5140   case AsmToken::Equal: {
5141     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5142       return Error(Parser.getTok().getLoc(), "unexpected token in operand");
5143
5144     Parser.Lex(); // Eat '='
5145     const MCExpr *SubExprVal;
5146     if (getParser().parseExpression(SubExprVal))
5147       return true;
5148     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5149
5150     const MCExpr *CPLoc = getTargetStreamer().addConstantPoolEntry(SubExprVal);
5151     Operands.push_back(ARMOperand::CreateImm(CPLoc, S, E));
5152     return false;
5153   }
5154   }
5155 }
5156
5157 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5158 //  :lower16: and :upper16:.
5159 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5160   MCAsmParser &Parser = getParser();
5161   RefKind = ARMMCExpr::VK_ARM_None;
5162
5163   // consume an optional '#' (GNU compatibility)
5164   if (getLexer().is(AsmToken::Hash))
5165     Parser.Lex();
5166
5167   // :lower16: and :upper16: modifiers
5168   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5169   Parser.Lex(); // Eat ':'
5170
5171   if (getLexer().isNot(AsmToken::Identifier)) {
5172     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5173     return true;
5174   }
5175
5176   enum {
5177     COFF = (1 << MCObjectFileInfo::IsCOFF),
5178     ELF = (1 << MCObjectFileInfo::IsELF),
5179     MACHO = (1 << MCObjectFileInfo::IsMachO)
5180   };
5181   static const struct PrefixEntry {
5182     const char *Spelling;
5183     ARMMCExpr::VariantKind VariantKind;
5184     uint8_t SupportedFormats;
5185   } PrefixEntries[] = {
5186     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5187     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5188   };
5189
5190   StringRef IDVal = Parser.getTok().getIdentifier();
5191
5192   const auto &Prefix =
5193       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5194                    [&IDVal](const PrefixEntry &PE) {
5195                       return PE.Spelling == IDVal;
5196                    });
5197   if (Prefix == std::end(PrefixEntries)) {
5198     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5199     return true;
5200   }
5201
5202   uint8_t CurrentFormat;
5203   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5204   case MCObjectFileInfo::IsMachO:
5205     CurrentFormat = MACHO;
5206     break;
5207   case MCObjectFileInfo::IsELF:
5208     CurrentFormat = ELF;
5209     break;
5210   case MCObjectFileInfo::IsCOFF:
5211     CurrentFormat = COFF;
5212     break;
5213   }
5214
5215   if (~Prefix->SupportedFormats & CurrentFormat) {
5216     Error(Parser.getTok().getLoc(),
5217           "cannot represent relocation in the current file format");
5218     return true;
5219   }
5220
5221   RefKind = Prefix->VariantKind;
5222   Parser.Lex();
5223
5224   if (getLexer().isNot(AsmToken::Colon)) {
5225     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5226     return true;
5227   }
5228   Parser.Lex(); // Eat the last ':'
5229
5230   return false;
5231 }
5232
5233 /// \brief Given a mnemonic, split out possible predication code and carry
5234 /// setting letters to form a canonical mnemonic and flags.
5235 //
5236 // FIXME: Would be nice to autogen this.
5237 // FIXME: This is a bit of a maze of special cases.
5238 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5239                                       unsigned &PredicationCode,
5240                                       bool &CarrySetting,
5241                                       unsigned &ProcessorIMod,
5242                                       StringRef &ITMask) {
5243   PredicationCode = ARMCC::AL;
5244   CarrySetting = false;
5245   ProcessorIMod = 0;
5246
5247   // Ignore some mnemonics we know aren't predicated forms.
5248   //
5249   // FIXME: Would be nice to autogen this.
5250   if ((Mnemonic == "movs" && isThumb()) ||
5251       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5252       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5253       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5254       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5255       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5256       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5257       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5258       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5259       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5260       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5261       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5262       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5263       Mnemonic.startswith("vsel"))
5264     return Mnemonic;
5265
5266   // First, split out any predication code. Ignore mnemonics we know aren't
5267   // predicated but do have a carry-set and so weren't caught above.
5268   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5269       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5270       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5271       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5272     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5273       .Case("eq", ARMCC::EQ)
5274       .Case("ne", ARMCC::NE)
5275       .Case("hs", ARMCC::HS)
5276       .Case("cs", ARMCC::HS)
5277       .Case("lo", ARMCC::LO)
5278       .Case("cc", ARMCC::LO)
5279       .Case("mi", ARMCC::MI)
5280       .Case("pl", ARMCC::PL)
5281       .Case("vs", ARMCC::VS)
5282       .Case("vc", ARMCC::VC)
5283       .Case("hi", ARMCC::HI)
5284       .Case("ls", ARMCC::LS)
5285       .Case("ge", ARMCC::GE)
5286       .Case("lt", ARMCC::LT)
5287       .Case("gt", ARMCC::GT)
5288       .Case("le", ARMCC::LE)
5289       .Case("al", ARMCC::AL)
5290       .Default(~0U);
5291     if (CC != ~0U) {
5292       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5293       PredicationCode = CC;
5294     }
5295   }
5296
5297   // Next, determine if we have a carry setting bit. We explicitly ignore all
5298   // the instructions we know end in 's'.
5299   if (Mnemonic.endswith("s") &&
5300       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5301         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5302         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5303         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5304         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5305         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5306         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5307         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5308         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5309         (Mnemonic == "movs" && isThumb()))) {
5310     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5311     CarrySetting = true;
5312   }
5313
5314   // The "cps" instruction can have a interrupt mode operand which is glued into
5315   // the mnemonic. Check if this is the case, split it and parse the imod op
5316   if (Mnemonic.startswith("cps")) {
5317     // Split out any imod code.
5318     unsigned IMod =
5319       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5320       .Case("ie", ARM_PROC::IE)
5321       .Case("id", ARM_PROC::ID)
5322       .Default(~0U);
5323     if (IMod != ~0U) {
5324       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5325       ProcessorIMod = IMod;
5326     }
5327   }
5328
5329   // The "it" instruction has the condition mask on the end of the mnemonic.
5330   if (Mnemonic.startswith("it")) {
5331     ITMask = Mnemonic.slice(2, Mnemonic.size());
5332     Mnemonic = Mnemonic.slice(0, 2);
5333   }
5334
5335   return Mnemonic;
5336 }
5337
5338 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5339 /// inclusion of carry set or predication code operands.
5340 //
5341 // FIXME: It would be nice to autogen this.
5342 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5343                                          bool &CanAcceptCarrySet,
5344                                          bool &CanAcceptPredicationCode) {
5345   CanAcceptCarrySet =
5346       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5347       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5348       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5349       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5350       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5351       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5352       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5353       (!isThumb() &&
5354        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5355         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5356
5357   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5358       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5359       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5360       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5361       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5362       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5363       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5364       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5365       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5366       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5367       (FullInst.startswith("vmull") && FullInst.endswith(".p64"))) {
5368     // These mnemonics are never predicable
5369     CanAcceptPredicationCode = false;
5370   } else if (!isThumb()) {
5371     // Some instructions are only predicable in Thumb mode
5372     CanAcceptPredicationCode =
5373         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5374         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5375         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5376         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5377         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5378         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5379         !Mnemonic.startswith("srs");
5380   } else if (isThumbOne()) {
5381     if (hasV6MOps())
5382       CanAcceptPredicationCode = Mnemonic != "movs";
5383     else
5384       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5385   } else
5386     CanAcceptPredicationCode = true;
5387 }
5388
5389 // \brief Some Thumb instructions have two operand forms that are not
5390 // available as three operand, convert to two operand form if possible.
5391 //
5392 // FIXME: We would really like to be able to tablegen'erate this.
5393 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5394                                                  bool CarrySetting,
5395                                                  OperandVector &Operands) {
5396   if (Operands.size() != 6)
5397     return;
5398
5399   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5400         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5401   if (!Op3.isReg() || !Op4.isReg())
5402     return;
5403
5404   auto Op3Reg = Op3.getReg();
5405   auto Op4Reg = Op4.getReg();
5406
5407   // For most Thumb2 cases we just generate the 3 operand form and reduce
5408   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5409   // won't accept SP or PC so we do the transformation here taking care
5410   // with immediate range in the 'add sp, sp #imm' case.
5411   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5412   if (isThumbTwo()) {
5413     if (Mnemonic != "add")
5414       return;
5415     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5416                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5417     if (!TryTransform) {
5418       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5419                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5420                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5421                        Op5.isImm() && !Op5.isImm0_508s4());
5422     }
5423     if (!TryTransform)
5424       return;
5425   } else if (!isThumbOne())
5426     return;
5427
5428   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5429         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5430         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5431         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5432     return;
5433
5434   // If first 2 operands of a 3 operand instruction are the same
5435   // then transform to 2 operand version of the same instruction
5436   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5437   bool Transform = Op3Reg == Op4Reg;
5438
5439   // For communtative operations, we might be able to transform if we swap
5440   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5441   // as tADDrsp.
5442   const ARMOperand *LastOp = &Op5;
5443   bool Swap = false;
5444   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5445       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5446        Mnemonic == "and" || Mnemonic == "eor" ||
5447        Mnemonic == "adc" || Mnemonic == "orr")) {
5448     Swap = true;
5449     LastOp = &Op4;
5450     Transform = true;
5451   }
5452
5453   // If both registers are the same then remove one of them from
5454   // the operand list, with certain exceptions.
5455   if (Transform) {
5456     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5457     // 2 operand forms don't exist.
5458     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5459         LastOp->isReg())
5460       Transform = false;
5461
5462     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5463     // 3-bits because the ARMARM says not to.
5464     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5465       Transform = false;
5466   }
5467
5468   if (Transform) {
5469     if (Swap)
5470       std::swap(Op4, Op5);
5471     Operands.erase(Operands.begin() + 3);
5472   }
5473 }
5474
5475 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5476                                           OperandVector &Operands) {
5477   // FIXME: This is all horribly hacky. We really need a better way to deal
5478   // with optional operands like this in the matcher table.
5479
5480   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5481   // another does not. Specifically, the MOVW instruction does not. So we
5482   // special case it here and remove the defaulted (non-setting) cc_out
5483   // operand if that's the instruction we're trying to match.
5484   //
5485   // We do this as post-processing of the explicit operands rather than just
5486   // conditionally adding the cc_out in the first place because we need
5487   // to check the type of the parsed immediate operand.
5488   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5489       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5490       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5491       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5492     return true;
5493
5494   // Register-register 'add' for thumb does not have a cc_out operand
5495   // when there are only two register operands.
5496   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5497       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5498       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5499       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5500     return true;
5501   // Register-register 'add' for thumb does not have a cc_out operand
5502   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5503   // have to check the immediate range here since Thumb2 has a variant
5504   // that can handle a different range and has a cc_out operand.
5505   if (((isThumb() && Mnemonic == "add") ||
5506        (isThumbTwo() && Mnemonic == "sub")) &&
5507       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5508       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5509       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5510       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5511       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5512        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5513     return true;
5514   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5515   // imm0_4095 variant. That's the least-preferred variant when
5516   // selecting via the generic "add" mnemonic, so to know that we
5517   // should remove the cc_out operand, we have to explicitly check that
5518   // it's not one of the other variants. Ugh.
5519   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5520       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5521       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5522       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5523     // Nest conditions rather than one big 'if' statement for readability.
5524     //
5525     // If both registers are low, we're in an IT block, and the immediate is
5526     // in range, we should use encoding T1 instead, which has a cc_out.
5527     if (inITBlock() &&
5528         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5529         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5530         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5531       return false;
5532     // Check against T3. If the second register is the PC, this is an
5533     // alternate form of ADR, which uses encoding T4, so check for that too.
5534     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5535         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5536       return false;
5537
5538     // Otherwise, we use encoding T4, which does not have a cc_out
5539     // operand.
5540     return true;
5541   }
5542
5543   // The thumb2 multiply instruction doesn't have a CCOut register, so
5544   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5545   // use the 16-bit encoding or not.
5546   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5547       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5548       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5549       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5550       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5551       // If the registers aren't low regs, the destination reg isn't the
5552       // same as one of the source regs, or the cc_out operand is zero
5553       // outside of an IT block, we have to use the 32-bit encoding, so
5554       // remove the cc_out operand.
5555       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5556        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5557        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5558        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5559                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5560                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5561                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5562     return true;
5563
5564   // Also check the 'mul' syntax variant that doesn't specify an explicit
5565   // destination register.
5566   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5567       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5568       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5569       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5570       // If the registers aren't low regs  or the cc_out operand is zero
5571       // outside of an IT block, we have to use the 32-bit encoding, so
5572       // remove the cc_out operand.
5573       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5574        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5575        !inITBlock()))
5576     return true;
5577
5578
5579
5580   // Register-register 'add/sub' for thumb does not have a cc_out operand
5581   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5582   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5583   // right, this will result in better diagnostics (which operand is off)
5584   // anyway.
5585   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5586       (Operands.size() == 5 || Operands.size() == 6) &&
5587       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5588       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5589       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5590       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5591        (Operands.size() == 6 &&
5592         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5593     return true;
5594
5595   return false;
5596 }
5597
5598 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5599                                               OperandVector &Operands) {
5600   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5601   unsigned RegIdx = 3;
5602   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5603       static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32") {
5604     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5605         static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32")
5606       RegIdx = 4;
5607
5608     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5609         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5610              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5611          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5612              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5613       return true;
5614   }
5615   return false;
5616 }
5617
5618 static bool isDataTypeToken(StringRef Tok) {
5619   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5620     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5621     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5622     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5623     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5624     Tok == ".f" || Tok == ".d";
5625 }
5626
5627 // FIXME: This bit should probably be handled via an explicit match class
5628 // in the .td files that matches the suffix instead of having it be
5629 // a literal string token the way it is now.
5630 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5631   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5632 }
5633 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5634                                  unsigned VariantID);
5635
5636 static bool RequiresVFPRegListValidation(StringRef Inst,
5637                                          bool &AcceptSinglePrecisionOnly,
5638                                          bool &AcceptDoublePrecisionOnly) {
5639   if (Inst.size() < 7)
5640     return false;
5641
5642   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5643     StringRef AddressingMode = Inst.substr(4, 2);
5644     if (AddressingMode == "ia" || AddressingMode == "db" ||
5645         AddressingMode == "ea" || AddressingMode == "fd") {
5646       AcceptSinglePrecisionOnly = Inst[6] == 's';
5647       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5648       return true;
5649     }
5650   }
5651
5652   return false;
5653 }
5654
5655 /// Parse an arm instruction mnemonic followed by its operands.
5656 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5657                                     SMLoc NameLoc, OperandVector &Operands) {
5658   MCAsmParser &Parser = getParser();
5659   // FIXME: Can this be done via tablegen in some fashion?
5660   bool RequireVFPRegisterListCheck;
5661   bool AcceptSinglePrecisionOnly;
5662   bool AcceptDoublePrecisionOnly;
5663   RequireVFPRegisterListCheck =
5664     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5665                                  AcceptDoublePrecisionOnly);
5666
5667   // Apply mnemonic aliases before doing anything else, as the destination
5668   // mnemonic may include suffices and we want to handle them normally.
5669   // The generic tblgen'erated code does this later, at the start of
5670   // MatchInstructionImpl(), but that's too late for aliases that include
5671   // any sort of suffix.
5672   uint64_t AvailableFeatures = getAvailableFeatures();
5673   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5674   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5675
5676   // First check for the ARM-specific .req directive.
5677   if (Parser.getTok().is(AsmToken::Identifier) &&
5678       Parser.getTok().getIdentifier() == ".req") {
5679     parseDirectiveReq(Name, NameLoc);
5680     // We always return 'error' for this, as we're done with this
5681     // statement and don't need to match the 'instruction."
5682     return true;
5683   }
5684
5685   // Create the leading tokens for the mnemonic, split by '.' characters.
5686   size_t Start = 0, Next = Name.find('.');
5687   StringRef Mnemonic = Name.slice(Start, Next);
5688
5689   // Split out the predication code and carry setting flag from the mnemonic.
5690   unsigned PredicationCode;
5691   unsigned ProcessorIMod;
5692   bool CarrySetting;
5693   StringRef ITMask;
5694   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5695                            ProcessorIMod, ITMask);
5696
5697   // In Thumb1, only the branch (B) instruction can be predicated.
5698   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5699     Parser.eatToEndOfStatement();
5700     return Error(NameLoc, "conditional execution not supported in Thumb1");
5701   }
5702
5703   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5704
5705   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5706   // is the mask as it will be for the IT encoding if the conditional
5707   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5708   // where the conditional bit0 is zero, the instruction post-processing
5709   // will adjust the mask accordingly.
5710   if (Mnemonic == "it") {
5711     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5712     if (ITMask.size() > 3) {
5713       Parser.eatToEndOfStatement();
5714       return Error(Loc, "too many conditions on IT instruction");
5715     }
5716     unsigned Mask = 8;
5717     for (unsigned i = ITMask.size(); i != 0; --i) {
5718       char pos = ITMask[i - 1];
5719       if (pos != 't' && pos != 'e') {
5720         Parser.eatToEndOfStatement();
5721         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5722       }
5723       Mask >>= 1;
5724       if (ITMask[i - 1] == 't')
5725         Mask |= 8;
5726     }
5727     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5728   }
5729
5730   // FIXME: This is all a pretty gross hack. We should automatically handle
5731   // optional operands like this via tblgen.
5732
5733   // Next, add the CCOut and ConditionCode operands, if needed.
5734   //
5735   // For mnemonics which can ever incorporate a carry setting bit or predication
5736   // code, our matching model involves us always generating CCOut and
5737   // ConditionCode operands to match the mnemonic "as written" and then we let
5738   // the matcher deal with finding the right instruction or generating an
5739   // appropriate error.
5740   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5741   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5742
5743   // If we had a carry-set on an instruction that can't do that, issue an
5744   // error.
5745   if (!CanAcceptCarrySet && CarrySetting) {
5746     Parser.eatToEndOfStatement();
5747     return Error(NameLoc, "instruction '" + Mnemonic +
5748                  "' can not set flags, but 's' suffix specified");
5749   }
5750   // If we had a predication code on an instruction that can't do that, issue an
5751   // error.
5752   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5753     Parser.eatToEndOfStatement();
5754     return Error(NameLoc, "instruction '" + Mnemonic +
5755                  "' is not predicable, but condition code specified");
5756   }
5757
5758   // Add the carry setting operand, if necessary.
5759   if (CanAcceptCarrySet) {
5760     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5761     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5762                                                Loc));
5763   }
5764
5765   // Add the predication code operand, if necessary.
5766   if (CanAcceptPredicationCode) {
5767     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5768                                       CarrySetting);
5769     Operands.push_back(ARMOperand::CreateCondCode(
5770                          ARMCC::CondCodes(PredicationCode), Loc));
5771   }
5772
5773   // Add the processor imod operand, if necessary.
5774   if (ProcessorIMod) {
5775     Operands.push_back(ARMOperand::CreateImm(
5776           MCConstantExpr::create(ProcessorIMod, getContext()),
5777                                  NameLoc, NameLoc));
5778   } else if (Mnemonic == "cps" && isMClass()) {
5779     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5780   }
5781
5782   // Add the remaining tokens in the mnemonic.
5783   while (Next != StringRef::npos) {
5784     Start = Next;
5785     Next = Name.find('.', Start + 1);
5786     StringRef ExtraToken = Name.slice(Start, Next);
5787
5788     // Some NEON instructions have an optional datatype suffix that is
5789     // completely ignored. Check for that.
5790     if (isDataTypeToken(ExtraToken) &&
5791         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5792       continue;
5793
5794     // For for ARM mode generate an error if the .n qualifier is used.
5795     if (ExtraToken == ".n" && !isThumb()) {
5796       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5797       Parser.eatToEndOfStatement();
5798       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5799                    "arm mode");
5800     }
5801
5802     // The .n qualifier is always discarded as that is what the tables
5803     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5804     // so discard it to avoid errors that can be caused by the matcher.
5805     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5806       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5807       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5808     }
5809   }
5810
5811   // Read the remaining operands.
5812   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5813     // Read the first operand.
5814     if (parseOperand(Operands, Mnemonic)) {
5815       Parser.eatToEndOfStatement();
5816       return true;
5817     }
5818
5819     while (getLexer().is(AsmToken::Comma)) {
5820       Parser.Lex();  // Eat the comma.
5821
5822       // Parse and remember the operand.
5823       if (parseOperand(Operands, Mnemonic)) {
5824         Parser.eatToEndOfStatement();
5825         return true;
5826       }
5827     }
5828   }
5829
5830   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5831     SMLoc Loc = getLexer().getLoc();
5832     Parser.eatToEndOfStatement();
5833     return Error(Loc, "unexpected token in argument list");
5834   }
5835
5836   Parser.Lex(); // Consume the EndOfStatement
5837
5838   if (RequireVFPRegisterListCheck) {
5839     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5840     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5841       return Error(Op.getStartLoc(),
5842                    "VFP/Neon single precision register expected");
5843     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5844       return Error(Op.getStartLoc(),
5845                    "VFP/Neon double precision register expected");
5846   }
5847
5848   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
5849
5850   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5851   // do and don't have a cc_out optional-def operand. With some spot-checks
5852   // of the operand list, we can figure out which variant we're trying to
5853   // parse and adjust accordingly before actually matching. We shouldn't ever
5854   // try to remove a cc_out operand that was explicitly set on the
5855   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5856   // table driven matcher doesn't fit well with the ARM instruction set.
5857   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
5858     Operands.erase(Operands.begin() + 1);
5859
5860   // Some instructions have the same mnemonic, but don't always
5861   // have a predicate. Distinguish them here and delete the
5862   // predicate if needed.
5863   if (shouldOmitPredicateOperand(Mnemonic, Operands))
5864     Operands.erase(Operands.begin() + 1);
5865
5866   // ARM mode 'blx' need special handling, as the register operand version
5867   // is predicable, but the label operand version is not. So, we can't rely
5868   // on the Mnemonic based checking to correctly figure out when to put
5869   // a k_CondCode operand in the list. If we're trying to match the label
5870   // version, remove the k_CondCode operand here.
5871   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
5872       static_cast<ARMOperand &>(*Operands[2]).isImm())
5873     Operands.erase(Operands.begin() + 1);
5874
5875   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
5876   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
5877   // a single GPRPair reg operand is used in the .td file to replace the two
5878   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
5879   // expressed as a GPRPair, so we have to manually merge them.
5880   // FIXME: We would really like to be able to tablegen'erate this.
5881   if (!isThumb() && Operands.size() > 4 &&
5882       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
5883        Mnemonic == "stlexd")) {
5884     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
5885     unsigned Idx = isLoad ? 2 : 3;
5886     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
5887     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
5888
5889     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
5890     // Adjust only if Op1 and Op2 are GPRs.
5891     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
5892         MRC.contains(Op2.getReg())) {
5893       unsigned Reg1 = Op1.getReg();
5894       unsigned Reg2 = Op2.getReg();
5895       unsigned Rt = MRI->getEncodingValue(Reg1);
5896       unsigned Rt2 = MRI->getEncodingValue(Reg2);
5897
5898       // Rt2 must be Rt + 1 and Rt must be even.
5899       if (Rt + 1 != Rt2 || (Rt & 1)) {
5900         Error(Op2.getStartLoc(), isLoad
5901                                      ? "destination operands must be sequential"
5902                                      : "source operands must be sequential");
5903         return true;
5904       }
5905       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
5906           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
5907       Operands[Idx] =
5908           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
5909       Operands.erase(Operands.begin() + Idx + 1);
5910     }
5911   }
5912
5913   // GNU Assembler extension (compatibility)
5914   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
5915     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5916     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5917     if (Op3.isMem()) {
5918       assert(Op2.isReg() && "expected register argument");
5919
5920       unsigned SuperReg = MRI->getMatchingSuperReg(
5921           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
5922
5923       assert(SuperReg && "expected register pair");
5924
5925       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
5926
5927       Operands.insert(
5928           Operands.begin() + 3,
5929           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
5930     }
5931   }
5932
5933   // FIXME: As said above, this is all a pretty gross hack.  This instruction
5934   // does not fit with other "subs" and tblgen.
5935   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
5936   // so the Mnemonic is the original name "subs" and delete the predicate
5937   // operand so it will match the table entry.
5938   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
5939       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5940       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
5941       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5942       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
5943       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5944     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
5945     Operands.erase(Operands.begin() + 1);
5946   }
5947   return false;
5948 }
5949
5950 // Validate context-sensitive operand constraints.
5951
5952 // return 'true' if register list contains non-low GPR registers,
5953 // 'false' otherwise. If Reg is in the register list or is HiReg, set
5954 // 'containsReg' to true.
5955 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
5956                                  unsigned Reg, unsigned HiReg,
5957                                  bool &containsReg) {
5958   containsReg = false;
5959   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
5960     unsigned OpReg = Inst.getOperand(i).getReg();
5961     if (OpReg == Reg)
5962       containsReg = true;
5963     // Anything other than a low register isn't legal here.
5964     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
5965       return true;
5966   }
5967   return false;
5968 }
5969
5970 // Check if the specified regisgter is in the register list of the inst,
5971 // starting at the indicated operand number.
5972 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
5973   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
5974     unsigned OpReg = Inst.getOperand(i).getReg();
5975     if (OpReg == Reg)
5976       return true;
5977   }
5978   return false;
5979 }
5980
5981 // Return true if instruction has the interesting property of being
5982 // allowed in IT blocks, but not being predicable.
5983 static bool instIsBreakpoint(const MCInst &Inst) {
5984     return Inst.getOpcode() == ARM::tBKPT ||
5985            Inst.getOpcode() == ARM::BKPT ||
5986            Inst.getOpcode() == ARM::tHLT ||
5987            Inst.getOpcode() == ARM::HLT;
5988
5989 }
5990
5991 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
5992                                        const OperandVector &Operands,
5993                                        unsigned ListNo, bool IsARPop) {
5994   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
5995   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
5996
5997   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
5998   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
5999   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6000
6001   if (!IsARPop && ListContainsSP)
6002     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6003                  "SP may not be in the register list");
6004   else if (ListContainsPC && ListContainsLR)
6005     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6006                  "PC and LR may not be in the register list simultaneously");
6007   else if (inITBlock() && !lastInITBlock() && ListContainsPC)
6008     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6009                  "instruction must be outside of IT block or the last "
6010                  "instruction in an IT block");
6011   return false;
6012 }
6013
6014 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6015                                        const OperandVector &Operands,
6016                                        unsigned ListNo) {
6017   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6018   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6019
6020   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6021   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6022
6023   if (ListContainsSP && ListContainsPC)
6024     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6025                  "SP and PC may not be in the register list");
6026   else if (ListContainsSP)
6027     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6028                  "SP may not be in the register list");
6029   else if (ListContainsPC)
6030     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6031                  "PC may not be in the register list");
6032   return false;
6033 }
6034
6035 // FIXME: We would really like to be able to tablegen'erate this.
6036 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6037                                        const OperandVector &Operands) {
6038   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6039   SMLoc Loc = Operands[0]->getStartLoc();
6040
6041   // Check the IT block state first.
6042   // NOTE: BKPT and HLT instructions have the interesting property of being
6043   // allowed in IT blocks, but not being predicable. They just always execute.
6044   if (inITBlock() && !instIsBreakpoint(Inst)) {
6045     unsigned Bit = 1;
6046     if (ITState.FirstCond)
6047       ITState.FirstCond = false;
6048     else
6049       Bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
6050     // The instruction must be predicable.
6051     if (!MCID.isPredicable())
6052       return Error(Loc, "instructions in IT block must be predicable");
6053     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6054     unsigned ITCond = Bit ? ITState.Cond :
6055       ARMCC::getOppositeCondition(ITState.Cond);
6056     if (Cond != ITCond) {
6057       // Find the condition code Operand to get its SMLoc information.
6058       SMLoc CondLoc;
6059       for (unsigned I = 1; I < Operands.size(); ++I)
6060         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6061           CondLoc = Operands[I]->getStartLoc();
6062       return Error(CondLoc, "incorrect condition in IT block; got '" +
6063                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6064                    "', but expected '" +
6065                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
6066     }
6067   // Check for non-'al' condition codes outside of the IT block.
6068   } else if (isThumbTwo() && MCID.isPredicable() &&
6069              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6070              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6071              Inst.getOpcode() != ARM::t2Bcc)
6072     return Error(Loc, "predicated instructions must be in IT block");
6073
6074   const unsigned Opcode = Inst.getOpcode();
6075   switch (Opcode) {
6076   case ARM::LDRD:
6077   case ARM::LDRD_PRE:
6078   case ARM::LDRD_POST: {
6079     const unsigned RtReg = Inst.getOperand(0).getReg();
6080
6081     // Rt can't be R14.
6082     if (RtReg == ARM::LR)
6083       return Error(Operands[3]->getStartLoc(),
6084                    "Rt can't be R14");
6085
6086     const unsigned Rt = MRI->getEncodingValue(RtReg);
6087     // Rt must be even-numbered.
6088     if ((Rt & 1) == 1)
6089       return Error(Operands[3]->getStartLoc(),
6090                    "Rt must be even-numbered");
6091
6092     // Rt2 must be Rt + 1.
6093     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6094     if (Rt2 != Rt + 1)
6095       return Error(Operands[3]->getStartLoc(),
6096                    "destination operands must be sequential");
6097
6098     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6099       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6100       // For addressing modes with writeback, the base register needs to be
6101       // different from the destination registers.
6102       if (Rn == Rt || Rn == Rt2)
6103         return Error(Operands[3]->getStartLoc(),
6104                      "base register needs to be different from destination "
6105                      "registers");
6106     }
6107
6108     return false;
6109   }
6110   case ARM::t2LDRDi8:
6111   case ARM::t2LDRD_PRE:
6112   case ARM::t2LDRD_POST: {
6113     // Rt2 must be different from Rt.
6114     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6115     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6116     if (Rt2 == Rt)
6117       return Error(Operands[3]->getStartLoc(),
6118                    "destination operands can't be identical");
6119     return false;
6120   }
6121   case ARM::t2BXJ: {
6122     const unsigned RmReg = Inst.getOperand(0).getReg();
6123     // Rm = SP is no longer unpredictable in v8-A
6124     if (RmReg == ARM::SP && !hasV8Ops())
6125       return Error(Operands[2]->getStartLoc(),
6126                    "r13 (SP) is an unpredictable operand to BXJ");
6127     return false;
6128   }
6129   case ARM::STRD: {
6130     // Rt2 must be Rt + 1.
6131     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6132     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6133     if (Rt2 != Rt + 1)
6134       return Error(Operands[3]->getStartLoc(),
6135                    "source operands must be sequential");
6136     return false;
6137   }
6138   case ARM::STRD_PRE:
6139   case ARM::STRD_POST: {
6140     // Rt2 must be Rt + 1.
6141     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6142     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6143     if (Rt2 != Rt + 1)
6144       return Error(Operands[3]->getStartLoc(),
6145                    "source operands must be sequential");
6146     return false;
6147   }
6148   case ARM::STR_PRE_IMM:
6149   case ARM::STR_PRE_REG:
6150   case ARM::STR_POST_IMM:
6151   case ARM::STR_POST_REG:
6152   case ARM::STRH_PRE:
6153   case ARM::STRH_POST:
6154   case ARM::STRB_PRE_IMM:
6155   case ARM::STRB_PRE_REG:
6156   case ARM::STRB_POST_IMM:
6157   case ARM::STRB_POST_REG: {
6158     // Rt must be different from Rn.
6159     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6160     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6161
6162     if (Rt == Rn)
6163       return Error(Operands[3]->getStartLoc(),
6164                    "source register and base register can't be identical");
6165     return false;
6166   }
6167   case ARM::LDR_PRE_IMM:
6168   case ARM::LDR_PRE_REG:
6169   case ARM::LDR_POST_IMM:
6170   case ARM::LDR_POST_REG:
6171   case ARM::LDRH_PRE:
6172   case ARM::LDRH_POST:
6173   case ARM::LDRSH_PRE:
6174   case ARM::LDRSH_POST:
6175   case ARM::LDRB_PRE_IMM:
6176   case ARM::LDRB_PRE_REG:
6177   case ARM::LDRB_POST_IMM:
6178   case ARM::LDRB_POST_REG:
6179   case ARM::LDRSB_PRE:
6180   case ARM::LDRSB_POST: {
6181     // Rt must be different from Rn.
6182     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6183     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6184
6185     if (Rt == Rn)
6186       return Error(Operands[3]->getStartLoc(),
6187                    "destination register and base register can't be identical");
6188     return false;
6189   }
6190   case ARM::SBFX:
6191   case ARM::UBFX: {
6192     // Width must be in range [1, 32-lsb].
6193     unsigned LSB = Inst.getOperand(2).getImm();
6194     unsigned Widthm1 = Inst.getOperand(3).getImm();
6195     if (Widthm1 >= 32 - LSB)
6196       return Error(Operands[5]->getStartLoc(),
6197                    "bitfield width must be in range [1,32-lsb]");
6198     return false;
6199   }
6200   // Notionally handles ARM::tLDMIA_UPD too.
6201   case ARM::tLDMIA: {
6202     // If we're parsing Thumb2, the .w variant is available and handles
6203     // most cases that are normally illegal for a Thumb1 LDM instruction.
6204     // We'll make the transformation in processInstruction() if necessary.
6205     //
6206     // Thumb LDM instructions are writeback iff the base register is not
6207     // in the register list.
6208     unsigned Rn = Inst.getOperand(0).getReg();
6209     bool HasWritebackToken =
6210         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6211          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6212     bool ListContainsBase;
6213     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6214       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6215                    "registers must be in range r0-r7");
6216     // If we should have writeback, then there should be a '!' token.
6217     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6218       return Error(Operands[2]->getStartLoc(),
6219                    "writeback operator '!' expected");
6220     // If we should not have writeback, there must not be a '!'. This is
6221     // true even for the 32-bit wide encodings.
6222     if (ListContainsBase && HasWritebackToken)
6223       return Error(Operands[3]->getStartLoc(),
6224                    "writeback operator '!' not allowed when base register "
6225                    "in register list");
6226
6227     if (validatetLDMRegList(Inst, Operands, 3))
6228       return true;
6229     break;
6230   }
6231   case ARM::LDMIA_UPD:
6232   case ARM::LDMDB_UPD:
6233   case ARM::LDMIB_UPD:
6234   case ARM::LDMDA_UPD:
6235     // ARM variants loading and updating the same register are only officially
6236     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6237     if (!hasV7Ops())
6238       break;
6239     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6240       return Error(Operands.back()->getStartLoc(),
6241                    "writeback register not allowed in register list");
6242     break;
6243   case ARM::t2LDMIA:
6244   case ARM::t2LDMDB:
6245     if (validatetLDMRegList(Inst, Operands, 3))
6246       return true;
6247     break;
6248   case ARM::t2STMIA:
6249   case ARM::t2STMDB:
6250     if (validatetSTMRegList(Inst, Operands, 3))
6251       return true;
6252     break;
6253   case ARM::t2LDMIA_UPD:
6254   case ARM::t2LDMDB_UPD:
6255   case ARM::t2STMIA_UPD:
6256   case ARM::t2STMDB_UPD: {
6257     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6258       return Error(Operands.back()->getStartLoc(),
6259                    "writeback register not allowed in register list");
6260
6261     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6262       if (validatetLDMRegList(Inst, Operands, 3))
6263         return true;
6264     } else {
6265       if (validatetSTMRegList(Inst, Operands, 3))
6266         return true;
6267     }
6268     break;
6269   }
6270   case ARM::sysLDMIA_UPD:
6271   case ARM::sysLDMDA_UPD:
6272   case ARM::sysLDMDB_UPD:
6273   case ARM::sysLDMIB_UPD:
6274     if (!listContainsReg(Inst, 3, ARM::PC))
6275       return Error(Operands[4]->getStartLoc(),
6276                    "writeback register only allowed on system LDM "
6277                    "if PC in register-list");
6278     break;
6279   case ARM::sysSTMIA_UPD:
6280   case ARM::sysSTMDA_UPD:
6281   case ARM::sysSTMDB_UPD:
6282   case ARM::sysSTMIB_UPD:
6283     return Error(Operands[2]->getStartLoc(),
6284                  "system STM cannot have writeback register");
6285   case ARM::tMUL: {
6286     // The second source operand must be the same register as the destination
6287     // operand.
6288     //
6289     // In this case, we must directly check the parsed operands because the
6290     // cvtThumbMultiply() function is written in such a way that it guarantees
6291     // this first statement is always true for the new Inst.  Essentially, the
6292     // destination is unconditionally copied into the second source operand
6293     // without checking to see if it matches what we actually parsed.
6294     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6295                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6296         (((ARMOperand &)*Operands[3]).getReg() !=
6297          ((ARMOperand &)*Operands[4]).getReg())) {
6298       return Error(Operands[3]->getStartLoc(),
6299                    "destination register must match source register");
6300     }
6301     break;
6302   }
6303   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6304   // so only issue a diagnostic for thumb1. The instructions will be
6305   // switched to the t2 encodings in processInstruction() if necessary.
6306   case ARM::tPOP: {
6307     bool ListContainsBase;
6308     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6309         !isThumbTwo())
6310       return Error(Operands[2]->getStartLoc(),
6311                    "registers must be in range r0-r7 or pc");
6312     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6313       return true;
6314     break;
6315   }
6316   case ARM::tPUSH: {
6317     bool ListContainsBase;
6318     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6319         !isThumbTwo())
6320       return Error(Operands[2]->getStartLoc(),
6321                    "registers must be in range r0-r7 or lr");
6322     if (validatetSTMRegList(Inst, Operands, 2))
6323       return true;
6324     break;
6325   }
6326   case ARM::tSTMIA_UPD: {
6327     bool ListContainsBase, InvalidLowList;
6328     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6329                                           0, ListContainsBase);
6330     if (InvalidLowList && !isThumbTwo())
6331       return Error(Operands[4]->getStartLoc(),
6332                    "registers must be in range r0-r7");
6333
6334     // This would be converted to a 32-bit stm, but that's not valid if the
6335     // writeback register is in the list.
6336     if (InvalidLowList && ListContainsBase)
6337       return Error(Operands[4]->getStartLoc(),
6338                    "writeback operator '!' not allowed when base register "
6339                    "in register list");
6340
6341     if (validatetSTMRegList(Inst, Operands, 4))
6342       return true;
6343     break;
6344   }
6345   case ARM::tADDrSP: {
6346     // If the non-SP source operand and the destination operand are not the
6347     // same, we need thumb2 (for the wide encoding), or we have an error.
6348     if (!isThumbTwo() &&
6349         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6350       return Error(Operands[4]->getStartLoc(),
6351                    "source register must be the same as destination");
6352     }
6353     break;
6354   }
6355   // Final range checking for Thumb unconditional branch instructions.
6356   case ARM::tB:
6357     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6358       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6359     break;
6360   case ARM::t2B: {
6361     int op = (Operands[2]->isImm()) ? 2 : 3;
6362     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6363       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6364     break;
6365   }
6366   // Final range checking for Thumb conditional branch instructions.
6367   case ARM::tBcc:
6368     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6369       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6370     break;
6371   case ARM::t2Bcc: {
6372     int Op = (Operands[2]->isImm()) ? 2 : 3;
6373     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6374       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6375     break;
6376   }
6377   case ARM::MOVi16:
6378   case ARM::t2MOVi16:
6379   case ARM::t2MOVTi16:
6380     {
6381     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6382     // especially when we turn it into a movw and the expression <symbol> does
6383     // not have a :lower16: or :upper16 as part of the expression.  We don't
6384     // want the behavior of silently truncating, which can be unexpected and
6385     // lead to bugs that are difficult to find since this is an easy mistake
6386     // to make.
6387     int i = (Operands[3]->isImm()) ? 3 : 4;
6388     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6389     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6390     if (CE) break;
6391     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6392     if (!E) break;
6393     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6394     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6395                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6396       return Error(
6397           Op.getStartLoc(),
6398           "immediate expression for mov requires :lower16: or :upper16");
6399     break;
6400   }
6401   }
6402
6403   return false;
6404 }
6405
6406 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6407   switch(Opc) {
6408   default: llvm_unreachable("unexpected opcode!");
6409   // VST1LN
6410   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6411   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6412   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6413   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6414   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6415   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6416   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6417   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6418   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6419
6420   // VST2LN
6421   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6422   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6423   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6424   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6425   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6426
6427   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6428   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6429   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6430   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6431   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6432
6433   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6434   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6435   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6436   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6437   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6438
6439   // VST3LN
6440   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6441   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6442   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6443   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6444   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6445   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6446   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6447   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6448   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6449   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6450   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6451   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6452   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6453   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6454   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6455
6456   // VST3
6457   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6458   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6459   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6460   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6461   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6462   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6463   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6464   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6465   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6466   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6467   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6468   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6469   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6470   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6471   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6472   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6473   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6474   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6475
6476   // VST4LN
6477   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6478   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6479   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6480   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6481   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6482   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6483   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6484   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6485   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6486   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6487   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6488   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6489   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6490   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6491   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6492
6493   // VST4
6494   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6495   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6496   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6497   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6498   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6499   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6500   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6501   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6502   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6503   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6504   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6505   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6506   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6507   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6508   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6509   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6510   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6511   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6512   }
6513 }
6514
6515 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6516   switch(Opc) {
6517   default: llvm_unreachable("unexpected opcode!");
6518   // VLD1LN
6519   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6520   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6521   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6522   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6523   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6524   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6525   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6526   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6527   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6528
6529   // VLD2LN
6530   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6531   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6532   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6533   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6534   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6535   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6536   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6537   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6538   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6539   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6540   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6541   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6542   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6543   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6544   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6545
6546   // VLD3DUP
6547   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6548   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6549   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6550   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6551   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6552   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6553   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6554   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6555   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6556   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6557   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6558   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6559   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6560   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6561   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6562   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6563   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6564   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6565
6566   // VLD3LN
6567   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6568   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6569   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6570   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6571   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6572   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6573   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6574   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6575   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6576   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6577   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6578   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6579   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6580   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6581   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6582
6583   // VLD3
6584   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6585   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6586   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6587   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6588   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6589   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6590   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6591   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6592   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6593   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6594   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6595   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6596   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6597   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6598   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6599   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6600   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6601   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6602
6603   // VLD4LN
6604   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6605   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6606   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6607   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6608   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6609   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6610   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6611   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6612   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6613   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6614   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6615   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6616   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6617   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6618   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6619
6620   // VLD4DUP
6621   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6622   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6623   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6624   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6625   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6626   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6627   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6628   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6629   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6630   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6631   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6632   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6633   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6634   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6635   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6636   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6637   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6638   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6639
6640   // VLD4
6641   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6642   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6643   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6644   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6645   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6646   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6647   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6648   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6649   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6650   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6651   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6652   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6653   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6654   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6655   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6656   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6657   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6658   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6659   }
6660 }
6661
6662 bool ARMAsmParser::processInstruction(MCInst &Inst,
6663                                       const OperandVector &Operands,
6664                                       MCStreamer &Out) {
6665   switch (Inst.getOpcode()) {
6666   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6667   case ARM::LDRT_POST:
6668   case ARM::LDRBT_POST: {
6669     const unsigned Opcode =
6670       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6671                                            : ARM::LDRBT_POST_IMM;
6672     MCInst TmpInst;
6673     TmpInst.setOpcode(Opcode);
6674     TmpInst.addOperand(Inst.getOperand(0));
6675     TmpInst.addOperand(Inst.getOperand(1));
6676     TmpInst.addOperand(Inst.getOperand(1));
6677     TmpInst.addOperand(MCOperand::createReg(0));
6678     TmpInst.addOperand(MCOperand::createImm(0));
6679     TmpInst.addOperand(Inst.getOperand(2));
6680     TmpInst.addOperand(Inst.getOperand(3));
6681     Inst = TmpInst;
6682     return true;
6683   }
6684   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6685   case ARM::STRT_POST:
6686   case ARM::STRBT_POST: {
6687     const unsigned Opcode =
6688       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6689                                            : ARM::STRBT_POST_IMM;
6690     MCInst TmpInst;
6691     TmpInst.setOpcode(Opcode);
6692     TmpInst.addOperand(Inst.getOperand(1));
6693     TmpInst.addOperand(Inst.getOperand(0));
6694     TmpInst.addOperand(Inst.getOperand(1));
6695     TmpInst.addOperand(MCOperand::createReg(0));
6696     TmpInst.addOperand(MCOperand::createImm(0));
6697     TmpInst.addOperand(Inst.getOperand(2));
6698     TmpInst.addOperand(Inst.getOperand(3));
6699     Inst = TmpInst;
6700     return true;
6701   }
6702   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6703   case ARM::ADDri: {
6704     if (Inst.getOperand(1).getReg() != ARM::PC ||
6705         Inst.getOperand(5).getReg() != 0 ||
6706         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6707       return false;
6708     MCInst TmpInst;
6709     TmpInst.setOpcode(ARM::ADR);
6710     TmpInst.addOperand(Inst.getOperand(0));
6711     if (Inst.getOperand(2).isImm()) {
6712       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6713       // before passing it to the ADR instruction.
6714       unsigned Enc = Inst.getOperand(2).getImm();
6715       TmpInst.addOperand(MCOperand::createImm(
6716         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6717     } else {
6718       // Turn PC-relative expression into absolute expression.
6719       // Reading PC provides the start of the current instruction + 8 and
6720       // the transform to adr is biased by that.
6721       MCSymbol *Dot = getContext().createTempSymbol();
6722       Out.EmitLabel(Dot);
6723       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6724       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6725                                                      MCSymbolRefExpr::VK_None,
6726                                                      getContext());
6727       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6728       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6729                                                      getContext());
6730       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6731                                                         getContext());
6732       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6733     }
6734     TmpInst.addOperand(Inst.getOperand(3));
6735     TmpInst.addOperand(Inst.getOperand(4));
6736     Inst = TmpInst;
6737     return true;
6738   }
6739   // Aliases for alternate PC+imm syntax of LDR instructions.
6740   case ARM::t2LDRpcrel:
6741     // Select the narrow version if the immediate will fit.
6742     if (Inst.getOperand(1).getImm() > 0 &&
6743         Inst.getOperand(1).getImm() <= 0xff &&
6744         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6745           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
6746       Inst.setOpcode(ARM::tLDRpci);
6747     else
6748       Inst.setOpcode(ARM::t2LDRpci);
6749     return true;
6750   case ARM::t2LDRBpcrel:
6751     Inst.setOpcode(ARM::t2LDRBpci);
6752     return true;
6753   case ARM::t2LDRHpcrel:
6754     Inst.setOpcode(ARM::t2LDRHpci);
6755     return true;
6756   case ARM::t2LDRSBpcrel:
6757     Inst.setOpcode(ARM::t2LDRSBpci);
6758     return true;
6759   case ARM::t2LDRSHpcrel:
6760     Inst.setOpcode(ARM::t2LDRSHpci);
6761     return true;
6762   // Handle NEON VST complex aliases.
6763   case ARM::VST1LNdWB_register_Asm_8:
6764   case ARM::VST1LNdWB_register_Asm_16:
6765   case ARM::VST1LNdWB_register_Asm_32: {
6766     MCInst TmpInst;
6767     // Shuffle the operands around so the lane index operand is in the
6768     // right place.
6769     unsigned Spacing;
6770     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6771     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6772     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6773     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6774     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6775     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6776     TmpInst.addOperand(Inst.getOperand(1)); // lane
6777     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6778     TmpInst.addOperand(Inst.getOperand(6));
6779     Inst = TmpInst;
6780     return true;
6781   }
6782
6783   case ARM::VST2LNdWB_register_Asm_8:
6784   case ARM::VST2LNdWB_register_Asm_16:
6785   case ARM::VST2LNdWB_register_Asm_32:
6786   case ARM::VST2LNqWB_register_Asm_16:
6787   case ARM::VST2LNqWB_register_Asm_32: {
6788     MCInst TmpInst;
6789     // Shuffle the operands around so the lane index operand is in the
6790     // right place.
6791     unsigned Spacing;
6792     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6793     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6794     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6795     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6796     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6797     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6798     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6799                                             Spacing));
6800     TmpInst.addOperand(Inst.getOperand(1)); // lane
6801     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6802     TmpInst.addOperand(Inst.getOperand(6));
6803     Inst = TmpInst;
6804     return true;
6805   }
6806
6807   case ARM::VST3LNdWB_register_Asm_8:
6808   case ARM::VST3LNdWB_register_Asm_16:
6809   case ARM::VST3LNdWB_register_Asm_32:
6810   case ARM::VST3LNqWB_register_Asm_16:
6811   case ARM::VST3LNqWB_register_Asm_32: {
6812     MCInst TmpInst;
6813     // Shuffle the operands around so the lane index operand is in the
6814     // right place.
6815     unsigned Spacing;
6816     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6817     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6818     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6819     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6820     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6821     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6822     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6823                                             Spacing));
6824     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6825                                             Spacing * 2));
6826     TmpInst.addOperand(Inst.getOperand(1)); // lane
6827     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6828     TmpInst.addOperand(Inst.getOperand(6));
6829     Inst = TmpInst;
6830     return true;
6831   }
6832
6833   case ARM::VST4LNdWB_register_Asm_8:
6834   case ARM::VST4LNdWB_register_Asm_16:
6835   case ARM::VST4LNdWB_register_Asm_32:
6836   case ARM::VST4LNqWB_register_Asm_16:
6837   case ARM::VST4LNqWB_register_Asm_32: {
6838     MCInst TmpInst;
6839     // Shuffle the operands around so the lane index operand is in the
6840     // right place.
6841     unsigned Spacing;
6842     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6843     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6844     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6845     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6846     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6847     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6848     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6849                                             Spacing));
6850     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6851                                             Spacing * 2));
6852     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6853                                             Spacing * 3));
6854     TmpInst.addOperand(Inst.getOperand(1)); // lane
6855     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6856     TmpInst.addOperand(Inst.getOperand(6));
6857     Inst = TmpInst;
6858     return true;
6859   }
6860
6861   case ARM::VST1LNdWB_fixed_Asm_8:
6862   case ARM::VST1LNdWB_fixed_Asm_16:
6863   case ARM::VST1LNdWB_fixed_Asm_32: {
6864     MCInst TmpInst;
6865     // Shuffle the operands around so the lane index operand is in the
6866     // right place.
6867     unsigned Spacing;
6868     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6869     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6870     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6871     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6872     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6873     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6874     TmpInst.addOperand(Inst.getOperand(1)); // lane
6875     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6876     TmpInst.addOperand(Inst.getOperand(5));
6877     Inst = TmpInst;
6878     return true;
6879   }
6880
6881   case ARM::VST2LNdWB_fixed_Asm_8:
6882   case ARM::VST2LNdWB_fixed_Asm_16:
6883   case ARM::VST2LNdWB_fixed_Asm_32:
6884   case ARM::VST2LNqWB_fixed_Asm_16:
6885   case ARM::VST2LNqWB_fixed_Asm_32: {
6886     MCInst TmpInst;
6887     // Shuffle the operands around so the lane index operand is in the
6888     // right place.
6889     unsigned Spacing;
6890     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6891     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6892     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6893     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6894     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6895     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6896     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6897                                             Spacing));
6898     TmpInst.addOperand(Inst.getOperand(1)); // lane
6899     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6900     TmpInst.addOperand(Inst.getOperand(5));
6901     Inst = TmpInst;
6902     return true;
6903   }
6904
6905   case ARM::VST3LNdWB_fixed_Asm_8:
6906   case ARM::VST3LNdWB_fixed_Asm_16:
6907   case ARM::VST3LNdWB_fixed_Asm_32:
6908   case ARM::VST3LNqWB_fixed_Asm_16:
6909   case ARM::VST3LNqWB_fixed_Asm_32: {
6910     MCInst TmpInst;
6911     // Shuffle the operands around so the lane index operand is in the
6912     // right place.
6913     unsigned Spacing;
6914     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6915     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6916     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6917     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6918     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6919     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6920     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6921                                             Spacing));
6922     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6923                                             Spacing * 2));
6924     TmpInst.addOperand(Inst.getOperand(1)); // lane
6925     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6926     TmpInst.addOperand(Inst.getOperand(5));
6927     Inst = TmpInst;
6928     return true;
6929   }
6930
6931   case ARM::VST4LNdWB_fixed_Asm_8:
6932   case ARM::VST4LNdWB_fixed_Asm_16:
6933   case ARM::VST4LNdWB_fixed_Asm_32:
6934   case ARM::VST4LNqWB_fixed_Asm_16:
6935   case ARM::VST4LNqWB_fixed_Asm_32: {
6936     MCInst TmpInst;
6937     // Shuffle the operands around so the lane index operand is in the
6938     // right place.
6939     unsigned Spacing;
6940     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6941     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6942     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6943     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6944     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6945     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6946     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6947                                             Spacing));
6948     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6949                                             Spacing * 2));
6950     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6951                                             Spacing * 3));
6952     TmpInst.addOperand(Inst.getOperand(1)); // lane
6953     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6954     TmpInst.addOperand(Inst.getOperand(5));
6955     Inst = TmpInst;
6956     return true;
6957   }
6958
6959   case ARM::VST1LNdAsm_8:
6960   case ARM::VST1LNdAsm_16:
6961   case ARM::VST1LNdAsm_32: {
6962     MCInst TmpInst;
6963     // Shuffle the operands around so the lane index operand is in the
6964     // right place.
6965     unsigned Spacing;
6966     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6967     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6968     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6969     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6970     TmpInst.addOperand(Inst.getOperand(1)); // lane
6971     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6972     TmpInst.addOperand(Inst.getOperand(5));
6973     Inst = TmpInst;
6974     return true;
6975   }
6976
6977   case ARM::VST2LNdAsm_8:
6978   case ARM::VST2LNdAsm_16:
6979   case ARM::VST2LNdAsm_32:
6980   case ARM::VST2LNqAsm_16:
6981   case ARM::VST2LNqAsm_32: {
6982     MCInst TmpInst;
6983     // Shuffle the operands around so the lane index operand is in the
6984     // right place.
6985     unsigned Spacing;
6986     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6987     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6988     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6989     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6990     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6991                                             Spacing));
6992     TmpInst.addOperand(Inst.getOperand(1)); // lane
6993     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6994     TmpInst.addOperand(Inst.getOperand(5));
6995     Inst = TmpInst;
6996     return true;
6997   }
6998
6999   case ARM::VST3LNdAsm_8:
7000   case ARM::VST3LNdAsm_16:
7001   case ARM::VST3LNdAsm_32:
7002   case ARM::VST3LNqAsm_16:
7003   case ARM::VST3LNqAsm_32: {
7004     MCInst TmpInst;
7005     // Shuffle the operands around so the lane index operand is in the
7006     // right place.
7007     unsigned Spacing;
7008     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7009     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7010     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7011     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7012     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7013                                             Spacing));
7014     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7015                                             Spacing * 2));
7016     TmpInst.addOperand(Inst.getOperand(1)); // lane
7017     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7018     TmpInst.addOperand(Inst.getOperand(5));
7019     Inst = TmpInst;
7020     return true;
7021   }
7022
7023   case ARM::VST4LNdAsm_8:
7024   case ARM::VST4LNdAsm_16:
7025   case ARM::VST4LNdAsm_32:
7026   case ARM::VST4LNqAsm_16:
7027   case ARM::VST4LNqAsm_32: {
7028     MCInst TmpInst;
7029     // Shuffle the operands around so the lane index operand is in the
7030     // right place.
7031     unsigned Spacing;
7032     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7033     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7034     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7035     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7036     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7037                                             Spacing));
7038     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7039                                             Spacing * 2));
7040     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7041                                             Spacing * 3));
7042     TmpInst.addOperand(Inst.getOperand(1)); // lane
7043     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7044     TmpInst.addOperand(Inst.getOperand(5));
7045     Inst = TmpInst;
7046     return true;
7047   }
7048
7049   // Handle NEON VLD complex aliases.
7050   case ARM::VLD1LNdWB_register_Asm_8:
7051   case ARM::VLD1LNdWB_register_Asm_16:
7052   case ARM::VLD1LNdWB_register_Asm_32: {
7053     MCInst TmpInst;
7054     // Shuffle the operands around so the lane index operand is in the
7055     // right place.
7056     unsigned Spacing;
7057     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7058     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7059     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7060     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7061     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7062     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7063     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7064     TmpInst.addOperand(Inst.getOperand(1)); // lane
7065     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7066     TmpInst.addOperand(Inst.getOperand(6));
7067     Inst = TmpInst;
7068     return true;
7069   }
7070
7071   case ARM::VLD2LNdWB_register_Asm_8:
7072   case ARM::VLD2LNdWB_register_Asm_16:
7073   case ARM::VLD2LNdWB_register_Asm_32:
7074   case ARM::VLD2LNqWB_register_Asm_16:
7075   case ARM::VLD2LNqWB_register_Asm_32: {
7076     MCInst TmpInst;
7077     // Shuffle the operands around so the lane index operand is in the
7078     // right place.
7079     unsigned Spacing;
7080     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7081     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7082     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7083                                             Spacing));
7084     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7085     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7086     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7087     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7088     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7089     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7090                                             Spacing));
7091     TmpInst.addOperand(Inst.getOperand(1)); // lane
7092     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7093     TmpInst.addOperand(Inst.getOperand(6));
7094     Inst = TmpInst;
7095     return true;
7096   }
7097
7098   case ARM::VLD3LNdWB_register_Asm_8:
7099   case ARM::VLD3LNdWB_register_Asm_16:
7100   case ARM::VLD3LNdWB_register_Asm_32:
7101   case ARM::VLD3LNqWB_register_Asm_16:
7102   case ARM::VLD3LNqWB_register_Asm_32: {
7103     MCInst TmpInst;
7104     // Shuffle the operands around so the lane index operand is in the
7105     // right place.
7106     unsigned Spacing;
7107     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7108     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7109     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7110                                             Spacing));
7111     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7112                                             Spacing * 2));
7113     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7114     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7115     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7116     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7117     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7118     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7119                                             Spacing));
7120     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7121                                             Spacing * 2));
7122     TmpInst.addOperand(Inst.getOperand(1)); // lane
7123     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7124     TmpInst.addOperand(Inst.getOperand(6));
7125     Inst = TmpInst;
7126     return true;
7127   }
7128
7129   case ARM::VLD4LNdWB_register_Asm_8:
7130   case ARM::VLD4LNdWB_register_Asm_16:
7131   case ARM::VLD4LNdWB_register_Asm_32:
7132   case ARM::VLD4LNqWB_register_Asm_16:
7133   case ARM::VLD4LNqWB_register_Asm_32: {
7134     MCInst TmpInst;
7135     // Shuffle the operands around so the lane index operand is in the
7136     // right place.
7137     unsigned Spacing;
7138     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7139     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7140     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7141                                             Spacing));
7142     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7143                                             Spacing * 2));
7144     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7145                                             Spacing * 3));
7146     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7147     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7148     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7149     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7150     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7151     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7152                                             Spacing));
7153     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7154                                             Spacing * 2));
7155     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7156                                             Spacing * 3));
7157     TmpInst.addOperand(Inst.getOperand(1)); // lane
7158     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7159     TmpInst.addOperand(Inst.getOperand(6));
7160     Inst = TmpInst;
7161     return true;
7162   }
7163
7164   case ARM::VLD1LNdWB_fixed_Asm_8:
7165   case ARM::VLD1LNdWB_fixed_Asm_16:
7166   case ARM::VLD1LNdWB_fixed_Asm_32: {
7167     MCInst TmpInst;
7168     // Shuffle the operands around so the lane index operand is in the
7169     // right place.
7170     unsigned Spacing;
7171     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7172     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7173     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7174     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7175     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7176     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7177     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7178     TmpInst.addOperand(Inst.getOperand(1)); // lane
7179     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7180     TmpInst.addOperand(Inst.getOperand(5));
7181     Inst = TmpInst;
7182     return true;
7183   }
7184
7185   case ARM::VLD2LNdWB_fixed_Asm_8:
7186   case ARM::VLD2LNdWB_fixed_Asm_16:
7187   case ARM::VLD2LNdWB_fixed_Asm_32:
7188   case ARM::VLD2LNqWB_fixed_Asm_16:
7189   case ARM::VLD2LNqWB_fixed_Asm_32: {
7190     MCInst TmpInst;
7191     // Shuffle the operands around so the lane index operand is in the
7192     // right place.
7193     unsigned Spacing;
7194     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7195     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7196     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7197                                             Spacing));
7198     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7199     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7200     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7201     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7202     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7203     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7204                                             Spacing));
7205     TmpInst.addOperand(Inst.getOperand(1)); // lane
7206     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7207     TmpInst.addOperand(Inst.getOperand(5));
7208     Inst = TmpInst;
7209     return true;
7210   }
7211
7212   case ARM::VLD3LNdWB_fixed_Asm_8:
7213   case ARM::VLD3LNdWB_fixed_Asm_16:
7214   case ARM::VLD3LNdWB_fixed_Asm_32:
7215   case ARM::VLD3LNqWB_fixed_Asm_16:
7216   case ARM::VLD3LNqWB_fixed_Asm_32: {
7217     MCInst TmpInst;
7218     // Shuffle the operands around so the lane index operand is in the
7219     // right place.
7220     unsigned Spacing;
7221     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7222     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7223     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7224                                             Spacing));
7225     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7226                                             Spacing * 2));
7227     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7228     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7229     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7230     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7231     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7232     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7233                                             Spacing));
7234     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7235                                             Spacing * 2));
7236     TmpInst.addOperand(Inst.getOperand(1)); // lane
7237     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7238     TmpInst.addOperand(Inst.getOperand(5));
7239     Inst = TmpInst;
7240     return true;
7241   }
7242
7243   case ARM::VLD4LNdWB_fixed_Asm_8:
7244   case ARM::VLD4LNdWB_fixed_Asm_16:
7245   case ARM::VLD4LNdWB_fixed_Asm_32:
7246   case ARM::VLD4LNqWB_fixed_Asm_16:
7247   case ARM::VLD4LNqWB_fixed_Asm_32: {
7248     MCInst TmpInst;
7249     // Shuffle the operands around so the lane index operand is in the
7250     // right place.
7251     unsigned Spacing;
7252     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7253     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7254     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7255                                             Spacing));
7256     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7257                                             Spacing * 2));
7258     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7259                                             Spacing * 3));
7260     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7261     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7262     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7263     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7264     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7265     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7266                                             Spacing));
7267     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7268                                             Spacing * 2));
7269     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7270                                             Spacing * 3));
7271     TmpInst.addOperand(Inst.getOperand(1)); // lane
7272     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7273     TmpInst.addOperand(Inst.getOperand(5));
7274     Inst = TmpInst;
7275     return true;
7276   }
7277
7278   case ARM::VLD1LNdAsm_8:
7279   case ARM::VLD1LNdAsm_16:
7280   case ARM::VLD1LNdAsm_32: {
7281     MCInst TmpInst;
7282     // Shuffle the operands around so the lane index operand is in the
7283     // right place.
7284     unsigned Spacing;
7285     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7286     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7287     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7288     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7289     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7290     TmpInst.addOperand(Inst.getOperand(1)); // lane
7291     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7292     TmpInst.addOperand(Inst.getOperand(5));
7293     Inst = TmpInst;
7294     return true;
7295   }
7296
7297   case ARM::VLD2LNdAsm_8:
7298   case ARM::VLD2LNdAsm_16:
7299   case ARM::VLD2LNdAsm_32:
7300   case ARM::VLD2LNqAsm_16:
7301   case ARM::VLD2LNqAsm_32: {
7302     MCInst TmpInst;
7303     // Shuffle the operands around so the lane index operand is in the
7304     // right place.
7305     unsigned Spacing;
7306     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7307     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7308     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7309                                             Spacing));
7310     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7311     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7312     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7313     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7314                                             Spacing));
7315     TmpInst.addOperand(Inst.getOperand(1)); // lane
7316     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7317     TmpInst.addOperand(Inst.getOperand(5));
7318     Inst = TmpInst;
7319     return true;
7320   }
7321
7322   case ARM::VLD3LNdAsm_8:
7323   case ARM::VLD3LNdAsm_16:
7324   case ARM::VLD3LNdAsm_32:
7325   case ARM::VLD3LNqAsm_16:
7326   case ARM::VLD3LNqAsm_32: {
7327     MCInst TmpInst;
7328     // Shuffle the operands around so the lane index operand is in the
7329     // right place.
7330     unsigned Spacing;
7331     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7332     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7333     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7334                                             Spacing));
7335     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7336                                             Spacing * 2));
7337     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7338     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7339     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7340     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7341                                             Spacing));
7342     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7343                                             Spacing * 2));
7344     TmpInst.addOperand(Inst.getOperand(1)); // lane
7345     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7346     TmpInst.addOperand(Inst.getOperand(5));
7347     Inst = TmpInst;
7348     return true;
7349   }
7350
7351   case ARM::VLD4LNdAsm_8:
7352   case ARM::VLD4LNdAsm_16:
7353   case ARM::VLD4LNdAsm_32:
7354   case ARM::VLD4LNqAsm_16:
7355   case ARM::VLD4LNqAsm_32: {
7356     MCInst TmpInst;
7357     // Shuffle the operands around so the lane index operand is in the
7358     // right place.
7359     unsigned Spacing;
7360     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7361     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7362     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7363                                             Spacing));
7364     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7365                                             Spacing * 2));
7366     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7367                                             Spacing * 3));
7368     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7369     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7370     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7371     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7372                                             Spacing));
7373     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7374                                             Spacing * 2));
7375     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7376                                             Spacing * 3));
7377     TmpInst.addOperand(Inst.getOperand(1)); // lane
7378     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7379     TmpInst.addOperand(Inst.getOperand(5));
7380     Inst = TmpInst;
7381     return true;
7382   }
7383
7384   // VLD3DUP single 3-element structure to all lanes instructions.
7385   case ARM::VLD3DUPdAsm_8:
7386   case ARM::VLD3DUPdAsm_16:
7387   case ARM::VLD3DUPdAsm_32:
7388   case ARM::VLD3DUPqAsm_8:
7389   case ARM::VLD3DUPqAsm_16:
7390   case ARM::VLD3DUPqAsm_32: {
7391     MCInst TmpInst;
7392     unsigned Spacing;
7393     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7394     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7395     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7396                                             Spacing));
7397     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7398                                             Spacing * 2));
7399     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7400     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7401     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7402     TmpInst.addOperand(Inst.getOperand(4));
7403     Inst = TmpInst;
7404     return true;
7405   }
7406
7407   case ARM::VLD3DUPdWB_fixed_Asm_8:
7408   case ARM::VLD3DUPdWB_fixed_Asm_16:
7409   case ARM::VLD3DUPdWB_fixed_Asm_32:
7410   case ARM::VLD3DUPqWB_fixed_Asm_8:
7411   case ARM::VLD3DUPqWB_fixed_Asm_16:
7412   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7413     MCInst TmpInst;
7414     unsigned Spacing;
7415     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7416     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7417     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7418                                             Spacing));
7419     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7420                                             Spacing * 2));
7421     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7422     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7423     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7424     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7425     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7426     TmpInst.addOperand(Inst.getOperand(4));
7427     Inst = TmpInst;
7428     return true;
7429   }
7430
7431   case ARM::VLD3DUPdWB_register_Asm_8:
7432   case ARM::VLD3DUPdWB_register_Asm_16:
7433   case ARM::VLD3DUPdWB_register_Asm_32:
7434   case ARM::VLD3DUPqWB_register_Asm_8:
7435   case ARM::VLD3DUPqWB_register_Asm_16:
7436   case ARM::VLD3DUPqWB_register_Asm_32: {
7437     MCInst TmpInst;
7438     unsigned Spacing;
7439     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7440     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7441     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7442                                             Spacing));
7443     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7444                                             Spacing * 2));
7445     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7446     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7447     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7448     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7449     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7450     TmpInst.addOperand(Inst.getOperand(5));
7451     Inst = TmpInst;
7452     return true;
7453   }
7454
7455   // VLD3 multiple 3-element structure instructions.
7456   case ARM::VLD3dAsm_8:
7457   case ARM::VLD3dAsm_16:
7458   case ARM::VLD3dAsm_32:
7459   case ARM::VLD3qAsm_8:
7460   case ARM::VLD3qAsm_16:
7461   case ARM::VLD3qAsm_32: {
7462     MCInst TmpInst;
7463     unsigned Spacing;
7464     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7465     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7466     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7467                                             Spacing));
7468     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7469                                             Spacing * 2));
7470     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7471     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7472     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7473     TmpInst.addOperand(Inst.getOperand(4));
7474     Inst = TmpInst;
7475     return true;
7476   }
7477
7478   case ARM::VLD3dWB_fixed_Asm_8:
7479   case ARM::VLD3dWB_fixed_Asm_16:
7480   case ARM::VLD3dWB_fixed_Asm_32:
7481   case ARM::VLD3qWB_fixed_Asm_8:
7482   case ARM::VLD3qWB_fixed_Asm_16:
7483   case ARM::VLD3qWB_fixed_Asm_32: {
7484     MCInst TmpInst;
7485     unsigned Spacing;
7486     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7487     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7488     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7489                                             Spacing));
7490     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7491                                             Spacing * 2));
7492     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7493     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7494     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7495     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7496     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7497     TmpInst.addOperand(Inst.getOperand(4));
7498     Inst = TmpInst;
7499     return true;
7500   }
7501
7502   case ARM::VLD3dWB_register_Asm_8:
7503   case ARM::VLD3dWB_register_Asm_16:
7504   case ARM::VLD3dWB_register_Asm_32:
7505   case ARM::VLD3qWB_register_Asm_8:
7506   case ARM::VLD3qWB_register_Asm_16:
7507   case ARM::VLD3qWB_register_Asm_32: {
7508     MCInst TmpInst;
7509     unsigned Spacing;
7510     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7511     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7512     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7513                                             Spacing));
7514     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7515                                             Spacing * 2));
7516     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7517     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7518     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7519     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7520     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7521     TmpInst.addOperand(Inst.getOperand(5));
7522     Inst = TmpInst;
7523     return true;
7524   }
7525
7526   // VLD4DUP single 3-element structure to all lanes instructions.
7527   case ARM::VLD4DUPdAsm_8:
7528   case ARM::VLD4DUPdAsm_16:
7529   case ARM::VLD4DUPdAsm_32:
7530   case ARM::VLD4DUPqAsm_8:
7531   case ARM::VLD4DUPqAsm_16:
7532   case ARM::VLD4DUPqAsm_32: {
7533     MCInst TmpInst;
7534     unsigned Spacing;
7535     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7536     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7537     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7538                                             Spacing));
7539     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7540                                             Spacing * 2));
7541     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7542                                             Spacing * 3));
7543     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7544     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7545     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7546     TmpInst.addOperand(Inst.getOperand(4));
7547     Inst = TmpInst;
7548     return true;
7549   }
7550
7551   case ARM::VLD4DUPdWB_fixed_Asm_8:
7552   case ARM::VLD4DUPdWB_fixed_Asm_16:
7553   case ARM::VLD4DUPdWB_fixed_Asm_32:
7554   case ARM::VLD4DUPqWB_fixed_Asm_8:
7555   case ARM::VLD4DUPqWB_fixed_Asm_16:
7556   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7557     MCInst TmpInst;
7558     unsigned Spacing;
7559     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7560     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7561     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7562                                             Spacing));
7563     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7564                                             Spacing * 2));
7565     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7566                                             Spacing * 3));
7567     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7568     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7569     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7570     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7571     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7572     TmpInst.addOperand(Inst.getOperand(4));
7573     Inst = TmpInst;
7574     return true;
7575   }
7576
7577   case ARM::VLD4DUPdWB_register_Asm_8:
7578   case ARM::VLD4DUPdWB_register_Asm_16:
7579   case ARM::VLD4DUPdWB_register_Asm_32:
7580   case ARM::VLD4DUPqWB_register_Asm_8:
7581   case ARM::VLD4DUPqWB_register_Asm_16:
7582   case ARM::VLD4DUPqWB_register_Asm_32: {
7583     MCInst TmpInst;
7584     unsigned Spacing;
7585     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7586     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7587     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7588                                             Spacing));
7589     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7590                                             Spacing * 2));
7591     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7592                                             Spacing * 3));
7593     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7594     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7595     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7596     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7597     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7598     TmpInst.addOperand(Inst.getOperand(5));
7599     Inst = TmpInst;
7600     return true;
7601   }
7602
7603   // VLD4 multiple 4-element structure instructions.
7604   case ARM::VLD4dAsm_8:
7605   case ARM::VLD4dAsm_16:
7606   case ARM::VLD4dAsm_32:
7607   case ARM::VLD4qAsm_8:
7608   case ARM::VLD4qAsm_16:
7609   case ARM::VLD4qAsm_32: {
7610     MCInst TmpInst;
7611     unsigned Spacing;
7612     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7613     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7614     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7615                                             Spacing));
7616     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7617                                             Spacing * 2));
7618     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7619                                             Spacing * 3));
7620     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7621     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7622     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7623     TmpInst.addOperand(Inst.getOperand(4));
7624     Inst = TmpInst;
7625     return true;
7626   }
7627
7628   case ARM::VLD4dWB_fixed_Asm_8:
7629   case ARM::VLD4dWB_fixed_Asm_16:
7630   case ARM::VLD4dWB_fixed_Asm_32:
7631   case ARM::VLD4qWB_fixed_Asm_8:
7632   case ARM::VLD4qWB_fixed_Asm_16:
7633   case ARM::VLD4qWB_fixed_Asm_32: {
7634     MCInst TmpInst;
7635     unsigned Spacing;
7636     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7637     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7638     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7639                                             Spacing));
7640     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7641                                             Spacing * 2));
7642     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7643                                             Spacing * 3));
7644     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7645     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7646     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7647     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7648     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7649     TmpInst.addOperand(Inst.getOperand(4));
7650     Inst = TmpInst;
7651     return true;
7652   }
7653
7654   case ARM::VLD4dWB_register_Asm_8:
7655   case ARM::VLD4dWB_register_Asm_16:
7656   case ARM::VLD4dWB_register_Asm_32:
7657   case ARM::VLD4qWB_register_Asm_8:
7658   case ARM::VLD4qWB_register_Asm_16:
7659   case ARM::VLD4qWB_register_Asm_32: {
7660     MCInst TmpInst;
7661     unsigned Spacing;
7662     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7663     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7664     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7665                                             Spacing));
7666     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7667                                             Spacing * 2));
7668     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7669                                             Spacing * 3));
7670     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7671     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7672     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7673     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7674     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7675     TmpInst.addOperand(Inst.getOperand(5));
7676     Inst = TmpInst;
7677     return true;
7678   }
7679
7680   // VST3 multiple 3-element structure instructions.
7681   case ARM::VST3dAsm_8:
7682   case ARM::VST3dAsm_16:
7683   case ARM::VST3dAsm_32:
7684   case ARM::VST3qAsm_8:
7685   case ARM::VST3qAsm_16:
7686   case ARM::VST3qAsm_32: {
7687     MCInst TmpInst;
7688     unsigned Spacing;
7689     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7690     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7691     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7692     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7693     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7694                                             Spacing));
7695     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7696                                             Spacing * 2));
7697     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7698     TmpInst.addOperand(Inst.getOperand(4));
7699     Inst = TmpInst;
7700     return true;
7701   }
7702
7703   case ARM::VST3dWB_fixed_Asm_8:
7704   case ARM::VST3dWB_fixed_Asm_16:
7705   case ARM::VST3dWB_fixed_Asm_32:
7706   case ARM::VST3qWB_fixed_Asm_8:
7707   case ARM::VST3qWB_fixed_Asm_16:
7708   case ARM::VST3qWB_fixed_Asm_32: {
7709     MCInst TmpInst;
7710     unsigned Spacing;
7711     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7712     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7713     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7714     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7715     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7716     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7717     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7718                                             Spacing));
7719     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7720                                             Spacing * 2));
7721     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7722     TmpInst.addOperand(Inst.getOperand(4));
7723     Inst = TmpInst;
7724     return true;
7725   }
7726
7727   case ARM::VST3dWB_register_Asm_8:
7728   case ARM::VST3dWB_register_Asm_16:
7729   case ARM::VST3dWB_register_Asm_32:
7730   case ARM::VST3qWB_register_Asm_8:
7731   case ARM::VST3qWB_register_Asm_16:
7732   case ARM::VST3qWB_register_Asm_32: {
7733     MCInst TmpInst;
7734     unsigned Spacing;
7735     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7736     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7737     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7738     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7739     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7740     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7741     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7742                                             Spacing));
7743     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7744                                             Spacing * 2));
7745     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7746     TmpInst.addOperand(Inst.getOperand(5));
7747     Inst = TmpInst;
7748     return true;
7749   }
7750
7751   // VST4 multiple 3-element structure instructions.
7752   case ARM::VST4dAsm_8:
7753   case ARM::VST4dAsm_16:
7754   case ARM::VST4dAsm_32:
7755   case ARM::VST4qAsm_8:
7756   case ARM::VST4qAsm_16:
7757   case ARM::VST4qAsm_32: {
7758     MCInst TmpInst;
7759     unsigned Spacing;
7760     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7761     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7762     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7763     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7764     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7765                                             Spacing));
7766     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7767                                             Spacing * 2));
7768     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7769                                             Spacing * 3));
7770     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7771     TmpInst.addOperand(Inst.getOperand(4));
7772     Inst = TmpInst;
7773     return true;
7774   }
7775
7776   case ARM::VST4dWB_fixed_Asm_8:
7777   case ARM::VST4dWB_fixed_Asm_16:
7778   case ARM::VST4dWB_fixed_Asm_32:
7779   case ARM::VST4qWB_fixed_Asm_8:
7780   case ARM::VST4qWB_fixed_Asm_16:
7781   case ARM::VST4qWB_fixed_Asm_32: {
7782     MCInst TmpInst;
7783     unsigned Spacing;
7784     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7785     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7786     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7787     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7788     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7789     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7790     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7791                                             Spacing));
7792     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7793                                             Spacing * 2));
7794     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7795                                             Spacing * 3));
7796     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7797     TmpInst.addOperand(Inst.getOperand(4));
7798     Inst = TmpInst;
7799     return true;
7800   }
7801
7802   case ARM::VST4dWB_register_Asm_8:
7803   case ARM::VST4dWB_register_Asm_16:
7804   case ARM::VST4dWB_register_Asm_32:
7805   case ARM::VST4qWB_register_Asm_8:
7806   case ARM::VST4qWB_register_Asm_16:
7807   case ARM::VST4qWB_register_Asm_32: {
7808     MCInst TmpInst;
7809     unsigned Spacing;
7810     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7811     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7812     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7813     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7814     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7815     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7816     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7817                                             Spacing));
7818     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7819                                             Spacing * 2));
7820     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7821                                             Spacing * 3));
7822     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7823     TmpInst.addOperand(Inst.getOperand(5));
7824     Inst = TmpInst;
7825     return true;
7826   }
7827
7828   // Handle encoding choice for the shift-immediate instructions.
7829   case ARM::t2LSLri:
7830   case ARM::t2LSRri:
7831   case ARM::t2ASRri: {
7832     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7833         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7834         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
7835         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7836           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
7837       unsigned NewOpc;
7838       switch (Inst.getOpcode()) {
7839       default: llvm_unreachable("unexpected opcode");
7840       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
7841       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
7842       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
7843       }
7844       // The Thumb1 operands aren't in the same order. Awesome, eh?
7845       MCInst TmpInst;
7846       TmpInst.setOpcode(NewOpc);
7847       TmpInst.addOperand(Inst.getOperand(0));
7848       TmpInst.addOperand(Inst.getOperand(5));
7849       TmpInst.addOperand(Inst.getOperand(1));
7850       TmpInst.addOperand(Inst.getOperand(2));
7851       TmpInst.addOperand(Inst.getOperand(3));
7852       TmpInst.addOperand(Inst.getOperand(4));
7853       Inst = TmpInst;
7854       return true;
7855     }
7856     return false;
7857   }
7858
7859   // Handle the Thumb2 mode MOV complex aliases.
7860   case ARM::t2MOVsr:
7861   case ARM::t2MOVSsr: {
7862     // Which instruction to expand to depends on the CCOut operand and
7863     // whether we're in an IT block if the register operands are low
7864     // registers.
7865     bool isNarrow = false;
7866     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7867         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7868         isARMLowRegister(Inst.getOperand(2).getReg()) &&
7869         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7870         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
7871       isNarrow = true;
7872     MCInst TmpInst;
7873     unsigned newOpc;
7874     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
7875     default: llvm_unreachable("unexpected opcode!");
7876     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
7877     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
7878     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
7879     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
7880     }
7881     TmpInst.setOpcode(newOpc);
7882     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7883     if (isNarrow)
7884       TmpInst.addOperand(MCOperand::createReg(
7885           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7886     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7887     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7888     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7889     TmpInst.addOperand(Inst.getOperand(5));
7890     if (!isNarrow)
7891       TmpInst.addOperand(MCOperand::createReg(
7892           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7893     Inst = TmpInst;
7894     return true;
7895   }
7896   case ARM::t2MOVsi:
7897   case ARM::t2MOVSsi: {
7898     // Which instruction to expand to depends on the CCOut operand and
7899     // whether we're in an IT block if the register operands are low
7900     // registers.
7901     bool isNarrow = false;
7902     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7903         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7904         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
7905       isNarrow = true;
7906     MCInst TmpInst;
7907     unsigned newOpc;
7908     switch(ARM_AM::getSORegShOp(Inst.getOperand(2).getImm())) {
7909     default: llvm_unreachable("unexpected opcode!");
7910     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
7911     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
7912     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
7913     case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
7914     case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
7915     }
7916     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
7917     if (Amount == 32) Amount = 0;
7918     TmpInst.setOpcode(newOpc);
7919     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7920     if (isNarrow)
7921       TmpInst.addOperand(MCOperand::createReg(
7922           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7923     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7924     if (newOpc != ARM::t2RRX)
7925       TmpInst.addOperand(MCOperand::createImm(Amount));
7926     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7927     TmpInst.addOperand(Inst.getOperand(4));
7928     if (!isNarrow)
7929       TmpInst.addOperand(MCOperand::createReg(
7930           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7931     Inst = TmpInst;
7932     return true;
7933   }
7934   // Handle the ARM mode MOV complex aliases.
7935   case ARM::ASRr:
7936   case ARM::LSRr:
7937   case ARM::LSLr:
7938   case ARM::RORr: {
7939     ARM_AM::ShiftOpc ShiftTy;
7940     switch(Inst.getOpcode()) {
7941     default: llvm_unreachable("unexpected opcode!");
7942     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
7943     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
7944     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
7945     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
7946     }
7947     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
7948     MCInst TmpInst;
7949     TmpInst.setOpcode(ARM::MOVsr);
7950     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7951     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7952     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7953     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7954     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7955     TmpInst.addOperand(Inst.getOperand(4));
7956     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7957     Inst = TmpInst;
7958     return true;
7959   }
7960   case ARM::ASRi:
7961   case ARM::LSRi:
7962   case ARM::LSLi:
7963   case ARM::RORi: {
7964     ARM_AM::ShiftOpc ShiftTy;
7965     switch(Inst.getOpcode()) {
7966     default: llvm_unreachable("unexpected opcode!");
7967     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
7968     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
7969     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
7970     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
7971     }
7972     // A shift by zero is a plain MOVr, not a MOVsi.
7973     unsigned Amt = Inst.getOperand(2).getImm();
7974     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
7975     // A shift by 32 should be encoded as 0 when permitted
7976     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
7977       Amt = 0;
7978     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
7979     MCInst TmpInst;
7980     TmpInst.setOpcode(Opc);
7981     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7982     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7983     if (Opc == ARM::MOVsi)
7984       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7985     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7986     TmpInst.addOperand(Inst.getOperand(4));
7987     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7988     Inst = TmpInst;
7989     return true;
7990   }
7991   case ARM::RRXi: {
7992     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
7993     MCInst TmpInst;
7994     TmpInst.setOpcode(ARM::MOVsi);
7995     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7996     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7997     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7998     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7999     TmpInst.addOperand(Inst.getOperand(3));
8000     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8001     Inst = TmpInst;
8002     return true;
8003   }
8004   case ARM::t2LDMIA_UPD: {
8005     // If this is a load of a single register, then we should use
8006     // a post-indexed LDR instruction instead, per the ARM ARM.
8007     if (Inst.getNumOperands() != 5)
8008       return false;
8009     MCInst TmpInst;
8010     TmpInst.setOpcode(ARM::t2LDR_POST);
8011     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8012     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8013     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8014     TmpInst.addOperand(MCOperand::createImm(4));
8015     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8016     TmpInst.addOperand(Inst.getOperand(3));
8017     Inst = TmpInst;
8018     return true;
8019   }
8020   case ARM::t2STMDB_UPD: {
8021     // If this is a store of a single register, then we should use
8022     // a pre-indexed STR instruction instead, per the ARM ARM.
8023     if (Inst.getNumOperands() != 5)
8024       return false;
8025     MCInst TmpInst;
8026     TmpInst.setOpcode(ARM::t2STR_PRE);
8027     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8028     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8029     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8030     TmpInst.addOperand(MCOperand::createImm(-4));
8031     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8032     TmpInst.addOperand(Inst.getOperand(3));
8033     Inst = TmpInst;
8034     return true;
8035   }
8036   case ARM::LDMIA_UPD:
8037     // If this is a load of a single register via a 'pop', then we should use
8038     // a post-indexed LDR instruction instead, per the ARM ARM.
8039     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8040         Inst.getNumOperands() == 5) {
8041       MCInst TmpInst;
8042       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8043       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8044       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8045       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8046       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8047       TmpInst.addOperand(MCOperand::createImm(4));
8048       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8049       TmpInst.addOperand(Inst.getOperand(3));
8050       Inst = TmpInst;
8051       return true;
8052     }
8053     break;
8054   case ARM::STMDB_UPD:
8055     // If this is a store of a single register via a 'push', then we should use
8056     // a pre-indexed STR instruction instead, per the ARM ARM.
8057     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8058         Inst.getNumOperands() == 5) {
8059       MCInst TmpInst;
8060       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8061       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8062       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8063       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8064       TmpInst.addOperand(MCOperand::createImm(-4));
8065       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8066       TmpInst.addOperand(Inst.getOperand(3));
8067       Inst = TmpInst;
8068     }
8069     break;
8070   case ARM::t2ADDri12:
8071     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8072     // mnemonic was used (not "addw"), encoding T3 is preferred.
8073     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8074         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8075       break;
8076     Inst.setOpcode(ARM::t2ADDri);
8077     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8078     break;
8079   case ARM::t2SUBri12:
8080     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8081     // mnemonic was used (not "subw"), encoding T3 is preferred.
8082     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8083         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8084       break;
8085     Inst.setOpcode(ARM::t2SUBri);
8086     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8087     break;
8088   case ARM::tADDi8:
8089     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8090     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8091     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8092     // to encoding T1 if <Rd> is omitted."
8093     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8094       Inst.setOpcode(ARM::tADDi3);
8095       return true;
8096     }
8097     break;
8098   case ARM::tSUBi8:
8099     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8100     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8101     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8102     // to encoding T1 if <Rd> is omitted."
8103     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8104       Inst.setOpcode(ARM::tSUBi3);
8105       return true;
8106     }
8107     break;
8108   case ARM::t2ADDri:
8109   case ARM::t2SUBri: {
8110     // If the destination and first source operand are the same, and
8111     // the flags are compatible with the current IT status, use encoding T2
8112     // instead of T3. For compatibility with the system 'as'. Make sure the
8113     // wide encoding wasn't explicit.
8114     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8115         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8116         (unsigned)Inst.getOperand(2).getImm() > 255 ||
8117         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
8118          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
8119         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8120          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8121       break;
8122     MCInst TmpInst;
8123     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8124                       ARM::tADDi8 : ARM::tSUBi8);
8125     TmpInst.addOperand(Inst.getOperand(0));
8126     TmpInst.addOperand(Inst.getOperand(5));
8127     TmpInst.addOperand(Inst.getOperand(0));
8128     TmpInst.addOperand(Inst.getOperand(2));
8129     TmpInst.addOperand(Inst.getOperand(3));
8130     TmpInst.addOperand(Inst.getOperand(4));
8131     Inst = TmpInst;
8132     return true;
8133   }
8134   case ARM::t2ADDrr: {
8135     // If the destination and first source operand are the same, and
8136     // there's no setting of the flags, use encoding T2 instead of T3.
8137     // Note that this is only for ADD, not SUB. This mirrors the system
8138     // 'as' behaviour.  Also take advantage of ADD being commutative.
8139     // Make sure the wide encoding wasn't explicit.
8140     bool Swap = false;
8141     auto DestReg = Inst.getOperand(0).getReg();
8142     bool Transform = DestReg == Inst.getOperand(1).getReg();
8143     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8144       Transform = true;
8145       Swap = true;
8146     }
8147     if (!Transform ||
8148         Inst.getOperand(5).getReg() != 0 ||
8149         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8150          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8151       break;
8152     MCInst TmpInst;
8153     TmpInst.setOpcode(ARM::tADDhirr);
8154     TmpInst.addOperand(Inst.getOperand(0));
8155     TmpInst.addOperand(Inst.getOperand(0));
8156     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8157     TmpInst.addOperand(Inst.getOperand(3));
8158     TmpInst.addOperand(Inst.getOperand(4));
8159     Inst = TmpInst;
8160     return true;
8161   }
8162   case ARM::tADDrSP: {
8163     // If the non-SP source operand and the destination operand are not the
8164     // same, we need to use the 32-bit encoding if it's available.
8165     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8166       Inst.setOpcode(ARM::t2ADDrr);
8167       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8168       return true;
8169     }
8170     break;
8171   }
8172   case ARM::tB:
8173     // A Thumb conditional branch outside of an IT block is a tBcc.
8174     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8175       Inst.setOpcode(ARM::tBcc);
8176       return true;
8177     }
8178     break;
8179   case ARM::t2B:
8180     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8181     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8182       Inst.setOpcode(ARM::t2Bcc);
8183       return true;
8184     }
8185     break;
8186   case ARM::t2Bcc:
8187     // If the conditional is AL or we're in an IT block, we really want t2B.
8188     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8189       Inst.setOpcode(ARM::t2B);
8190       return true;
8191     }
8192     break;
8193   case ARM::tBcc:
8194     // If the conditional is AL, we really want tB.
8195     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8196       Inst.setOpcode(ARM::tB);
8197       return true;
8198     }
8199     break;
8200   case ARM::tLDMIA: {
8201     // If the register list contains any high registers, or if the writeback
8202     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8203     // instead if we're in Thumb2. Otherwise, this should have generated
8204     // an error in validateInstruction().
8205     unsigned Rn = Inst.getOperand(0).getReg();
8206     bool hasWritebackToken =
8207         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8208          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8209     bool listContainsBase;
8210     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8211         (!listContainsBase && !hasWritebackToken) ||
8212         (listContainsBase && hasWritebackToken)) {
8213       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8214       assert (isThumbTwo());
8215       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8216       // If we're switching to the updating version, we need to insert
8217       // the writeback tied operand.
8218       if (hasWritebackToken)
8219         Inst.insert(Inst.begin(),
8220                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8221       return true;
8222     }
8223     break;
8224   }
8225   case ARM::tSTMIA_UPD: {
8226     // If the register list contains any high registers, we need to use
8227     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8228     // should have generated an error in validateInstruction().
8229     unsigned Rn = Inst.getOperand(0).getReg();
8230     bool listContainsBase;
8231     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8232       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8233       assert (isThumbTwo());
8234       Inst.setOpcode(ARM::t2STMIA_UPD);
8235       return true;
8236     }
8237     break;
8238   }
8239   case ARM::tPOP: {
8240     bool listContainsBase;
8241     // If the register list contains any high registers, we need to use
8242     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8243     // should have generated an error in validateInstruction().
8244     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8245       return false;
8246     assert (isThumbTwo());
8247     Inst.setOpcode(ARM::t2LDMIA_UPD);
8248     // Add the base register and writeback operands.
8249     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8250     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8251     return true;
8252   }
8253   case ARM::tPUSH: {
8254     bool listContainsBase;
8255     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8256       return false;
8257     assert (isThumbTwo());
8258     Inst.setOpcode(ARM::t2STMDB_UPD);
8259     // Add the base register and writeback operands.
8260     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8261     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8262     return true;
8263   }
8264   case ARM::t2MOVi: {
8265     // If we can use the 16-bit encoding and the user didn't explicitly
8266     // request the 32-bit variant, transform it here.
8267     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8268         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8269         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8270           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8271          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8272         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8273          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8274       // The operands aren't in the same order for tMOVi8...
8275       MCInst TmpInst;
8276       TmpInst.setOpcode(ARM::tMOVi8);
8277       TmpInst.addOperand(Inst.getOperand(0));
8278       TmpInst.addOperand(Inst.getOperand(4));
8279       TmpInst.addOperand(Inst.getOperand(1));
8280       TmpInst.addOperand(Inst.getOperand(2));
8281       TmpInst.addOperand(Inst.getOperand(3));
8282       Inst = TmpInst;
8283       return true;
8284     }
8285     break;
8286   }
8287   case ARM::t2MOVr: {
8288     // If we can use the 16-bit encoding and the user didn't explicitly
8289     // request the 32-bit variant, transform it here.
8290     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8291         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8292         Inst.getOperand(2).getImm() == ARMCC::AL &&
8293         Inst.getOperand(4).getReg() == ARM::CPSR &&
8294         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8295          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8296       // The operands aren't the same for tMOV[S]r... (no cc_out)
8297       MCInst TmpInst;
8298       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8299       TmpInst.addOperand(Inst.getOperand(0));
8300       TmpInst.addOperand(Inst.getOperand(1));
8301       TmpInst.addOperand(Inst.getOperand(2));
8302       TmpInst.addOperand(Inst.getOperand(3));
8303       Inst = TmpInst;
8304       return true;
8305     }
8306     break;
8307   }
8308   case ARM::t2SXTH:
8309   case ARM::t2SXTB:
8310   case ARM::t2UXTH:
8311   case ARM::t2UXTB: {
8312     // If we can use the 16-bit encoding and the user didn't explicitly
8313     // request the 32-bit variant, transform it here.
8314     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8315         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8316         Inst.getOperand(2).getImm() == 0 &&
8317         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8318          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8319       unsigned NewOpc;
8320       switch (Inst.getOpcode()) {
8321       default: llvm_unreachable("Illegal opcode!");
8322       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8323       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8324       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8325       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8326       }
8327       // The operands aren't the same for thumb1 (no rotate operand).
8328       MCInst TmpInst;
8329       TmpInst.setOpcode(NewOpc);
8330       TmpInst.addOperand(Inst.getOperand(0));
8331       TmpInst.addOperand(Inst.getOperand(1));
8332       TmpInst.addOperand(Inst.getOperand(3));
8333       TmpInst.addOperand(Inst.getOperand(4));
8334       Inst = TmpInst;
8335       return true;
8336     }
8337     break;
8338   }
8339   case ARM::MOVsi: {
8340     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8341     // rrx shifts and asr/lsr of #32 is encoded as 0
8342     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr) 
8343       return false;
8344     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8345       // Shifting by zero is accepted as a vanilla 'MOVr'
8346       MCInst TmpInst;
8347       TmpInst.setOpcode(ARM::MOVr);
8348       TmpInst.addOperand(Inst.getOperand(0));
8349       TmpInst.addOperand(Inst.getOperand(1));
8350       TmpInst.addOperand(Inst.getOperand(3));
8351       TmpInst.addOperand(Inst.getOperand(4));
8352       TmpInst.addOperand(Inst.getOperand(5));
8353       Inst = TmpInst;
8354       return true;
8355     }
8356     return false;
8357   }
8358   case ARM::ANDrsi:
8359   case ARM::ORRrsi:
8360   case ARM::EORrsi:
8361   case ARM::BICrsi:
8362   case ARM::SUBrsi:
8363   case ARM::ADDrsi: {
8364     unsigned newOpc;
8365     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8366     if (SOpc == ARM_AM::rrx) return false;
8367     switch (Inst.getOpcode()) {
8368     default: llvm_unreachable("unexpected opcode!");
8369     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8370     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8371     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8372     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8373     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8374     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8375     }
8376     // If the shift is by zero, use the non-shifted instruction definition.
8377     // The exception is for right shifts, where 0 == 32
8378     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8379         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8380       MCInst TmpInst;
8381       TmpInst.setOpcode(newOpc);
8382       TmpInst.addOperand(Inst.getOperand(0));
8383       TmpInst.addOperand(Inst.getOperand(1));
8384       TmpInst.addOperand(Inst.getOperand(2));
8385       TmpInst.addOperand(Inst.getOperand(4));
8386       TmpInst.addOperand(Inst.getOperand(5));
8387       TmpInst.addOperand(Inst.getOperand(6));
8388       Inst = TmpInst;
8389       return true;
8390     }
8391     return false;
8392   }
8393   case ARM::ITasm:
8394   case ARM::t2IT: {
8395     // The mask bits for all but the first condition are represented as
8396     // the low bit of the condition code value implies 't'. We currently
8397     // always have 1 implies 't', so XOR toggle the bits if the low bit
8398     // of the condition code is zero. 
8399     MCOperand &MO = Inst.getOperand(1);
8400     unsigned Mask = MO.getImm();
8401     unsigned OrigMask = Mask;
8402     unsigned TZ = countTrailingZeros(Mask);
8403     if ((Inst.getOperand(0).getImm() & 1) == 0) {
8404       assert(Mask && TZ <= 3 && "illegal IT mask value!");
8405       Mask ^= (0xE << TZ) & 0xF;
8406     }
8407     MO.setImm(Mask);
8408
8409     // Set up the IT block state according to the IT instruction we just
8410     // matched.
8411     assert(!inITBlock() && "nested IT blocks?!");
8412     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8413     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
8414     ITState.CurPosition = 0;
8415     ITState.FirstCond = true;
8416     break;
8417   }
8418   case ARM::t2LSLrr:
8419   case ARM::t2LSRrr:
8420   case ARM::t2ASRrr:
8421   case ARM::t2SBCrr:
8422   case ARM::t2RORrr:
8423   case ARM::t2BICrr:
8424   {
8425     // Assemblers should use the narrow encodings of these instructions when permissible.
8426     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8427          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8428         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8429         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8430          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8431         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8432          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8433              ".w"))) {
8434       unsigned NewOpc;
8435       switch (Inst.getOpcode()) {
8436         default: llvm_unreachable("unexpected opcode");
8437         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8438         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8439         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8440         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8441         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8442         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8443       }
8444       MCInst TmpInst;
8445       TmpInst.setOpcode(NewOpc);
8446       TmpInst.addOperand(Inst.getOperand(0));
8447       TmpInst.addOperand(Inst.getOperand(5));
8448       TmpInst.addOperand(Inst.getOperand(1));
8449       TmpInst.addOperand(Inst.getOperand(2));
8450       TmpInst.addOperand(Inst.getOperand(3));
8451       TmpInst.addOperand(Inst.getOperand(4));
8452       Inst = TmpInst;
8453       return true;
8454     }
8455     return false;
8456   }
8457   case ARM::t2ANDrr:
8458   case ARM::t2EORrr:
8459   case ARM::t2ADCrr:
8460   case ARM::t2ORRrr:
8461   {
8462     // Assemblers should use the narrow encodings of these instructions when permissible.
8463     // These instructions are special in that they are commutable, so shorter encodings
8464     // are available more often.
8465     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8466          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8467         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8468          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8469         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8470          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8471         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8472          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8473              ".w"))) {
8474       unsigned NewOpc;
8475       switch (Inst.getOpcode()) {
8476         default: llvm_unreachable("unexpected opcode");
8477         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8478         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8479         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8480         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8481       }
8482       MCInst TmpInst;
8483       TmpInst.setOpcode(NewOpc);
8484       TmpInst.addOperand(Inst.getOperand(0));
8485       TmpInst.addOperand(Inst.getOperand(5));
8486       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8487         TmpInst.addOperand(Inst.getOperand(1));
8488         TmpInst.addOperand(Inst.getOperand(2));
8489       } else {
8490         TmpInst.addOperand(Inst.getOperand(2));
8491         TmpInst.addOperand(Inst.getOperand(1));
8492       }
8493       TmpInst.addOperand(Inst.getOperand(3));
8494       TmpInst.addOperand(Inst.getOperand(4));
8495       Inst = TmpInst;
8496       return true;
8497     }
8498     return false;
8499   }
8500   }
8501   return false;
8502 }
8503
8504 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8505   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8506   // suffix depending on whether they're in an IT block or not.
8507   unsigned Opc = Inst.getOpcode();
8508   const MCInstrDesc &MCID = MII.get(Opc);
8509   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8510     assert(MCID.hasOptionalDef() &&
8511            "optionally flag setting instruction missing optional def operand");
8512     assert(MCID.NumOperands == Inst.getNumOperands() &&
8513            "operand count mismatch!");
8514     // Find the optional-def operand (cc_out).
8515     unsigned OpNo;
8516     for (OpNo = 0;
8517          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8518          ++OpNo)
8519       ;
8520     // If we're parsing Thumb1, reject it completely.
8521     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8522       return Match_MnemonicFail;
8523     // If we're parsing Thumb2, which form is legal depends on whether we're
8524     // in an IT block.
8525     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8526         !inITBlock())
8527       return Match_RequiresITBlock;
8528     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8529         inITBlock())
8530       return Match_RequiresNotITBlock;
8531   }
8532   // Some high-register supporting Thumb1 encodings only allow both registers
8533   // to be from r0-r7 when in Thumb2.
8534   else if (Opc == ARM::tADDhirr && isThumbOne() && !hasV6MOps() &&
8535            isARMLowRegister(Inst.getOperand(1).getReg()) &&
8536            isARMLowRegister(Inst.getOperand(2).getReg()))
8537     return Match_RequiresThumb2;
8538   // Others only require ARMv6 or later.
8539   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
8540            isARMLowRegister(Inst.getOperand(0).getReg()) &&
8541            isARMLowRegister(Inst.getOperand(1).getReg()))
8542     return Match_RequiresV6;
8543   return Match_Success;
8544 }
8545
8546 namespace llvm {
8547 template <> inline bool IsCPSRDead<MCInst>(MCInst *Instr) {
8548   return true; // In an assembly source, no need to second-guess
8549 }
8550 }
8551
8552 static const char *getSubtargetFeatureName(uint64_t Val);
8553 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8554                                            OperandVector &Operands,
8555                                            MCStreamer &Out, uint64_t &ErrorInfo,
8556                                            bool MatchingInlineAsm) {
8557   MCInst Inst;
8558   unsigned MatchResult;
8559
8560   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
8561                                      MatchingInlineAsm);
8562   switch (MatchResult) {
8563   case Match_Success:
8564     // Context sensitive operand constraints aren't handled by the matcher,
8565     // so check them here.
8566     if (validateInstruction(Inst, Operands)) {
8567       // Still progress the IT block, otherwise one wrong condition causes
8568       // nasty cascading errors.
8569       forwardITPosition();
8570       return true;
8571     }
8572
8573     { // processInstruction() updates inITBlock state, we need to save it away
8574       bool wasInITBlock = inITBlock();
8575
8576       // Some instructions need post-processing to, for example, tweak which
8577       // encoding is selected. Loop on it while changes happen so the
8578       // individual transformations can chain off each other. E.g.,
8579       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
8580       while (processInstruction(Inst, Operands, Out))
8581         ;
8582
8583       // Only after the instruction is fully processed, we can validate it
8584       if (wasInITBlock && hasV8Ops() && isThumb() &&
8585           !isV8EligibleForIT(&Inst)) {
8586         Warning(IDLoc, "deprecated instruction in IT block");
8587       }
8588     }
8589
8590     // Only move forward at the very end so that everything in validate
8591     // and process gets a consistent answer about whether we're in an IT
8592     // block.
8593     forwardITPosition();
8594
8595     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
8596     // doesn't actually encode.
8597     if (Inst.getOpcode() == ARM::ITasm)
8598       return false;
8599
8600     Inst.setLoc(IDLoc);
8601     Out.EmitInstruction(Inst, STI);
8602     return false;
8603   case Match_MissingFeature: {
8604     assert(ErrorInfo && "Unknown missing feature!");
8605     // Special case the error message for the very common case where only
8606     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
8607     std::string Msg = "instruction requires:";
8608     uint64_t Mask = 1;
8609     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
8610       if (ErrorInfo & Mask) {
8611         Msg += " ";
8612         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
8613       }
8614       Mask <<= 1;
8615     }
8616     return Error(IDLoc, Msg);
8617   }
8618   case Match_InvalidOperand: {
8619     SMLoc ErrorLoc = IDLoc;
8620     if (ErrorInfo != ~0ULL) {
8621       if (ErrorInfo >= Operands.size())
8622         return Error(IDLoc, "too few operands for instruction");
8623
8624       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8625       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8626     }
8627
8628     return Error(ErrorLoc, "invalid operand for instruction");
8629   }
8630   case Match_MnemonicFail:
8631     return Error(IDLoc, "invalid instruction",
8632                  ((ARMOperand &)*Operands[0]).getLocRange());
8633   case Match_RequiresNotITBlock:
8634     return Error(IDLoc, "flag setting instruction only valid outside IT block");
8635   case Match_RequiresITBlock:
8636     return Error(IDLoc, "instruction only valid inside IT block");
8637   case Match_RequiresV6:
8638     return Error(IDLoc, "instruction variant requires ARMv6 or later");
8639   case Match_RequiresThumb2:
8640     return Error(IDLoc, "instruction variant requires Thumb2");
8641   case Match_ImmRange0_15: {
8642     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8643     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8644     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
8645   }
8646   case Match_ImmRange0_239: {
8647     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8648     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8649     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
8650   }
8651   case Match_AlignedMemoryRequiresNone:
8652   case Match_DupAlignedMemoryRequiresNone:
8653   case Match_AlignedMemoryRequires16:
8654   case Match_DupAlignedMemoryRequires16:
8655   case Match_AlignedMemoryRequires32:
8656   case Match_DupAlignedMemoryRequires32:
8657   case Match_AlignedMemoryRequires64:
8658   case Match_DupAlignedMemoryRequires64:
8659   case Match_AlignedMemoryRequires64or128:
8660   case Match_DupAlignedMemoryRequires64or128:
8661   case Match_AlignedMemoryRequires64or128or256:
8662   {
8663     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
8664     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8665     switch (MatchResult) {
8666       default:
8667         llvm_unreachable("Missing Match_Aligned type");
8668       case Match_AlignedMemoryRequiresNone:
8669       case Match_DupAlignedMemoryRequiresNone:
8670         return Error(ErrorLoc, "alignment must be omitted");
8671       case Match_AlignedMemoryRequires16:
8672       case Match_DupAlignedMemoryRequires16:
8673         return Error(ErrorLoc, "alignment must be 16 or omitted");
8674       case Match_AlignedMemoryRequires32:
8675       case Match_DupAlignedMemoryRequires32:
8676         return Error(ErrorLoc, "alignment must be 32 or omitted");
8677       case Match_AlignedMemoryRequires64:
8678       case Match_DupAlignedMemoryRequires64:
8679         return Error(ErrorLoc, "alignment must be 64 or omitted");
8680       case Match_AlignedMemoryRequires64or128:
8681       case Match_DupAlignedMemoryRequires64or128:
8682         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
8683       case Match_AlignedMemoryRequires64or128or256:
8684         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
8685     }
8686   }
8687   }
8688
8689   llvm_unreachable("Implement any new match types added!");
8690 }
8691
8692 /// parseDirective parses the arm specific directives
8693 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
8694   const MCObjectFileInfo::Environment Format =
8695     getContext().getObjectFileInfo()->getObjectFileType();
8696   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8697   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
8698
8699   StringRef IDVal = DirectiveID.getIdentifier();
8700   if (IDVal == ".word")
8701     return parseLiteralValues(4, DirectiveID.getLoc());
8702   else if (IDVal == ".short" || IDVal == ".hword")
8703     return parseLiteralValues(2, DirectiveID.getLoc());
8704   else if (IDVal == ".thumb")
8705     return parseDirectiveThumb(DirectiveID.getLoc());
8706   else if (IDVal == ".arm")
8707     return parseDirectiveARM(DirectiveID.getLoc());
8708   else if (IDVal == ".thumb_func")
8709     return parseDirectiveThumbFunc(DirectiveID.getLoc());
8710   else if (IDVal == ".code")
8711     return parseDirectiveCode(DirectiveID.getLoc());
8712   else if (IDVal == ".syntax")
8713     return parseDirectiveSyntax(DirectiveID.getLoc());
8714   else if (IDVal == ".unreq")
8715     return parseDirectiveUnreq(DirectiveID.getLoc());
8716   else if (IDVal == ".fnend")
8717     return parseDirectiveFnEnd(DirectiveID.getLoc());
8718   else if (IDVal == ".cantunwind")
8719     return parseDirectiveCantUnwind(DirectiveID.getLoc());
8720   else if (IDVal == ".personality")
8721     return parseDirectivePersonality(DirectiveID.getLoc());
8722   else if (IDVal == ".handlerdata")
8723     return parseDirectiveHandlerData(DirectiveID.getLoc());
8724   else if (IDVal == ".setfp")
8725     return parseDirectiveSetFP(DirectiveID.getLoc());
8726   else if (IDVal == ".pad")
8727     return parseDirectivePad(DirectiveID.getLoc());
8728   else if (IDVal == ".save")
8729     return parseDirectiveRegSave(DirectiveID.getLoc(), false);
8730   else if (IDVal == ".vsave")
8731     return parseDirectiveRegSave(DirectiveID.getLoc(), true);
8732   else if (IDVal == ".ltorg" || IDVal == ".pool")
8733     return parseDirectiveLtorg(DirectiveID.getLoc());
8734   else if (IDVal == ".even")
8735     return parseDirectiveEven(DirectiveID.getLoc());
8736   else if (IDVal == ".personalityindex")
8737     return parseDirectivePersonalityIndex(DirectiveID.getLoc());
8738   else if (IDVal == ".unwind_raw")
8739     return parseDirectiveUnwindRaw(DirectiveID.getLoc());
8740   else if (IDVal == ".movsp")
8741     return parseDirectiveMovSP(DirectiveID.getLoc());
8742   else if (IDVal == ".arch_extension")
8743     return parseDirectiveArchExtension(DirectiveID.getLoc());
8744   else if (IDVal == ".align")
8745     return parseDirectiveAlign(DirectiveID.getLoc());
8746   else if (IDVal == ".thumb_set")
8747     return parseDirectiveThumbSet(DirectiveID.getLoc());
8748
8749   if (!IsMachO && !IsCOFF) {
8750     if (IDVal == ".arch")
8751       return parseDirectiveArch(DirectiveID.getLoc());
8752     else if (IDVal == ".cpu")
8753       return parseDirectiveCPU(DirectiveID.getLoc());
8754     else if (IDVal == ".eabi_attribute")
8755       return parseDirectiveEabiAttr(DirectiveID.getLoc());
8756     else if (IDVal == ".fpu")
8757       return parseDirectiveFPU(DirectiveID.getLoc());
8758     else if (IDVal == ".fnstart")
8759       return parseDirectiveFnStart(DirectiveID.getLoc());
8760     else if (IDVal == ".inst")
8761       return parseDirectiveInst(DirectiveID.getLoc());
8762     else if (IDVal == ".inst.n")
8763       return parseDirectiveInst(DirectiveID.getLoc(), 'n');
8764     else if (IDVal == ".inst.w")
8765       return parseDirectiveInst(DirectiveID.getLoc(), 'w');
8766     else if (IDVal == ".object_arch")
8767       return parseDirectiveObjectArch(DirectiveID.getLoc());
8768     else if (IDVal == ".tlsdescseq")
8769       return parseDirectiveTLSDescSeq(DirectiveID.getLoc());
8770   }
8771
8772   return true;
8773 }
8774
8775 /// parseLiteralValues
8776 ///  ::= .hword expression [, expression]*
8777 ///  ::= .short expression [, expression]*
8778 ///  ::= .word expression [, expression]*
8779 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
8780   MCAsmParser &Parser = getParser();
8781   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8782     for (;;) {
8783       const MCExpr *Value;
8784       if (getParser().parseExpression(Value)) {
8785         Parser.eatToEndOfStatement();
8786         return false;
8787       }
8788
8789       getParser().getStreamer().EmitValue(Value, Size);
8790
8791       if (getLexer().is(AsmToken::EndOfStatement))
8792         break;
8793
8794       // FIXME: Improve diagnostic.
8795       if (getLexer().isNot(AsmToken::Comma)) {
8796         Error(L, "unexpected token in directive");
8797         return false;
8798       }
8799       Parser.Lex();
8800     }
8801   }
8802
8803   Parser.Lex();
8804   return false;
8805 }
8806
8807 /// parseDirectiveThumb
8808 ///  ::= .thumb
8809 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
8810   MCAsmParser &Parser = getParser();
8811   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8812     Error(L, "unexpected token in directive");
8813     return false;
8814   }
8815   Parser.Lex();
8816
8817   if (!hasThumb()) {
8818     Error(L, "target does not support Thumb mode");
8819     return false;
8820   }
8821
8822   if (!isThumb())
8823     SwitchMode();
8824
8825   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8826   return false;
8827 }
8828
8829 /// parseDirectiveARM
8830 ///  ::= .arm
8831 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
8832   MCAsmParser &Parser = getParser();
8833   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8834     Error(L, "unexpected token in directive");
8835     return false;
8836   }
8837   Parser.Lex();
8838
8839   if (!hasARM()) {
8840     Error(L, "target does not support ARM mode");
8841     return false;
8842   }
8843
8844   if (isThumb())
8845     SwitchMode();
8846
8847   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8848   return false;
8849 }
8850
8851 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
8852   if (NextSymbolIsThumb) {
8853     getParser().getStreamer().EmitThumbFunc(Symbol);
8854     NextSymbolIsThumb = false;
8855   }
8856 }
8857
8858 /// parseDirectiveThumbFunc
8859 ///  ::= .thumbfunc symbol_name
8860 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
8861   MCAsmParser &Parser = getParser();
8862   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
8863   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8864
8865   // Darwin asm has (optionally) function name after .thumb_func direction
8866   // ELF doesn't
8867   if (IsMachO) {
8868     const AsmToken &Tok = Parser.getTok();
8869     if (Tok.isNot(AsmToken::EndOfStatement)) {
8870       if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String)) {
8871         Error(L, "unexpected token in .thumb_func directive");
8872         return false;
8873       }
8874
8875       MCSymbol *Func =
8876           getParser().getContext().getOrCreateSymbol(Tok.getIdentifier());
8877       getParser().getStreamer().EmitThumbFunc(Func);
8878       Parser.Lex(); // Consume the identifier token.
8879       return false;
8880     }
8881   }
8882
8883   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8884     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8885     Parser.eatToEndOfStatement();
8886     return false;
8887   }
8888
8889   NextSymbolIsThumb = true;
8890   return false;
8891 }
8892
8893 /// parseDirectiveSyntax
8894 ///  ::= .syntax unified | divided
8895 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
8896   MCAsmParser &Parser = getParser();
8897   const AsmToken &Tok = Parser.getTok();
8898   if (Tok.isNot(AsmToken::Identifier)) {
8899     Error(L, "unexpected token in .syntax directive");
8900     return false;
8901   }
8902
8903   StringRef Mode = Tok.getString();
8904   if (Mode == "unified" || Mode == "UNIFIED") {
8905     Parser.Lex();
8906   } else if (Mode == "divided" || Mode == "DIVIDED") {
8907     Error(L, "'.syntax divided' arm asssembly not supported");
8908     return false;
8909   } else {
8910     Error(L, "unrecognized syntax mode in .syntax directive");
8911     return false;
8912   }
8913
8914   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8915     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8916     return false;
8917   }
8918   Parser.Lex();
8919
8920   // TODO tell the MC streamer the mode
8921   // getParser().getStreamer().Emit???();
8922   return false;
8923 }
8924
8925 /// parseDirectiveCode
8926 ///  ::= .code 16 | 32
8927 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
8928   MCAsmParser &Parser = getParser();
8929   const AsmToken &Tok = Parser.getTok();
8930   if (Tok.isNot(AsmToken::Integer)) {
8931     Error(L, "unexpected token in .code directive");
8932     return false;
8933   }
8934   int64_t Val = Parser.getTok().getIntVal();
8935   if (Val != 16 && Val != 32) {
8936     Error(L, "invalid operand to .code directive");
8937     return false;
8938   }
8939   Parser.Lex();
8940
8941   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8942     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8943     return false;
8944   }
8945   Parser.Lex();
8946
8947   if (Val == 16) {
8948     if (!hasThumb()) {
8949       Error(L, "target does not support Thumb mode");
8950       return false;
8951     }
8952
8953     if (!isThumb())
8954       SwitchMode();
8955     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8956   } else {
8957     if (!hasARM()) {
8958       Error(L, "target does not support ARM mode");
8959       return false;
8960     }
8961
8962     if (isThumb())
8963       SwitchMode();
8964     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8965   }
8966
8967   return false;
8968 }
8969
8970 /// parseDirectiveReq
8971 ///  ::= name .req registername
8972 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
8973   MCAsmParser &Parser = getParser();
8974   Parser.Lex(); // Eat the '.req' token.
8975   unsigned Reg;
8976   SMLoc SRegLoc, ERegLoc;
8977   if (ParseRegister(Reg, SRegLoc, ERegLoc)) {
8978     Parser.eatToEndOfStatement();
8979     Error(SRegLoc, "register name expected");
8980     return false;
8981   }
8982
8983   // Shouldn't be anything else.
8984   if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
8985     Parser.eatToEndOfStatement();
8986     Error(Parser.getTok().getLoc(), "unexpected input in .req directive.");
8987     return false;
8988   }
8989
8990   Parser.Lex(); // Consume the EndOfStatement
8991
8992   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg) {
8993     Error(SRegLoc, "redefinition of '" + Name + "' does not match original.");
8994     return false;
8995   }
8996
8997   return false;
8998 }
8999
9000 /// parseDirectiveUneq
9001 ///  ::= .unreq registername
9002 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9003   MCAsmParser &Parser = getParser();
9004   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9005     Parser.eatToEndOfStatement();
9006     Error(L, "unexpected input in .unreq directive.");
9007     return false;
9008   }
9009   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9010   Parser.Lex(); // Eat the identifier.
9011   return false;
9012 }
9013
9014 /// parseDirectiveArch
9015 ///  ::= .arch token
9016 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9017   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9018
9019   unsigned ID = ARMTargetParser::parseArch(Arch);
9020
9021   if (ID == ARM::AK_INVALID) {
9022     Error(L, "Unknown arch name");
9023     return false;
9024   }
9025
9026   getTargetStreamer().emitArch(ID);
9027   return false;
9028 }
9029
9030 /// parseDirectiveEabiAttr
9031 ///  ::= .eabi_attribute int, int [, "str"]
9032 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9033 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9034   MCAsmParser &Parser = getParser();
9035   int64_t Tag;
9036   SMLoc TagLoc;
9037   TagLoc = Parser.getTok().getLoc();
9038   if (Parser.getTok().is(AsmToken::Identifier)) {
9039     StringRef Name = Parser.getTok().getIdentifier();
9040     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9041     if (Tag == -1) {
9042       Error(TagLoc, "attribute name not recognised: " + Name);
9043       Parser.eatToEndOfStatement();
9044       return false;
9045     }
9046     Parser.Lex();
9047   } else {
9048     const MCExpr *AttrExpr;
9049
9050     TagLoc = Parser.getTok().getLoc();
9051     if (Parser.parseExpression(AttrExpr)) {
9052       Parser.eatToEndOfStatement();
9053       return false;
9054     }
9055
9056     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9057     if (!CE) {
9058       Error(TagLoc, "expected numeric constant");
9059       Parser.eatToEndOfStatement();
9060       return false;
9061     }
9062
9063     Tag = CE->getValue();
9064   }
9065
9066   if (Parser.getTok().isNot(AsmToken::Comma)) {
9067     Error(Parser.getTok().getLoc(), "comma expected");
9068     Parser.eatToEndOfStatement();
9069     return false;
9070   }
9071   Parser.Lex(); // skip comma
9072
9073   StringRef StringValue = "";
9074   bool IsStringValue = false;
9075
9076   int64_t IntegerValue = 0;
9077   bool IsIntegerValue = false;
9078
9079   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9080     IsStringValue = true;
9081   else if (Tag == ARMBuildAttrs::compatibility) {
9082     IsStringValue = true;
9083     IsIntegerValue = true;
9084   } else if (Tag < 32 || Tag % 2 == 0)
9085     IsIntegerValue = true;
9086   else if (Tag % 2 == 1)
9087     IsStringValue = true;
9088   else
9089     llvm_unreachable("invalid tag type");
9090
9091   if (IsIntegerValue) {
9092     const MCExpr *ValueExpr;
9093     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9094     if (Parser.parseExpression(ValueExpr)) {
9095       Parser.eatToEndOfStatement();
9096       return false;
9097     }
9098
9099     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9100     if (!CE) {
9101       Error(ValueExprLoc, "expected numeric constant");
9102       Parser.eatToEndOfStatement();
9103       return false;
9104     }
9105
9106     IntegerValue = CE->getValue();
9107   }
9108
9109   if (Tag == ARMBuildAttrs::compatibility) {
9110     if (Parser.getTok().isNot(AsmToken::Comma))
9111       IsStringValue = false;
9112     if (Parser.getTok().isNot(AsmToken::Comma)) {
9113       Error(Parser.getTok().getLoc(), "comma expected");
9114       Parser.eatToEndOfStatement();
9115       return false;
9116     } else {
9117        Parser.Lex();
9118     }
9119   }
9120
9121   if (IsStringValue) {
9122     if (Parser.getTok().isNot(AsmToken::String)) {
9123       Error(Parser.getTok().getLoc(), "bad string constant");
9124       Parser.eatToEndOfStatement();
9125       return false;
9126     }
9127
9128     StringValue = Parser.getTok().getStringContents();
9129     Parser.Lex();
9130   }
9131
9132   if (IsIntegerValue && IsStringValue) {
9133     assert(Tag == ARMBuildAttrs::compatibility);
9134     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9135   } else if (IsIntegerValue)
9136     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9137   else if (IsStringValue)
9138     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9139   return false;
9140 }
9141
9142 /// parseDirectiveCPU
9143 ///  ::= .cpu str
9144 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9145   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9146   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9147
9148   // FIXME: This is using table-gen data, but should be moved to
9149   // ARMTargetParser once that is table-gen'd.
9150   if (!STI.isCPUStringValid(CPU)) {
9151     Error(L, "Unknown CPU name");
9152     return false;
9153   }
9154
9155   STI.setDefaultFeatures(CPU);
9156   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9157
9158   return false;
9159 }
9160 /// parseDirectiveFPU
9161 ///  ::= .fpu str
9162 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9163   SMLoc FPUNameLoc = getTok().getLoc();
9164   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9165
9166   unsigned ID = ARMTargetParser::parseFPU(FPU);
9167   std::vector<const char *> Features;
9168   if (!ARMTargetParser::getFPUFeatures(ID, Features)) {
9169     Error(FPUNameLoc, "Unknown FPU name");
9170     return false;
9171   }
9172
9173   for (auto Feature : Features)
9174     STI.ApplyFeatureFlag(Feature);
9175   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9176
9177   getTargetStreamer().emitFPU(ID);
9178   return false;
9179 }
9180
9181 /// parseDirectiveFnStart
9182 ///  ::= .fnstart
9183 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9184   if (UC.hasFnStart()) {
9185     Error(L, ".fnstart starts before the end of previous one");
9186     UC.emitFnStartLocNotes();
9187     return false;
9188   }
9189
9190   // Reset the unwind directives parser state
9191   UC.reset();
9192
9193   getTargetStreamer().emitFnStart();
9194
9195   UC.recordFnStart(L);
9196   return false;
9197 }
9198
9199 /// parseDirectiveFnEnd
9200 ///  ::= .fnend
9201 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9202   // Check the ordering of unwind directives
9203   if (!UC.hasFnStart()) {
9204     Error(L, ".fnstart must precede .fnend directive");
9205     return false;
9206   }
9207
9208   // Reset the unwind directives parser state
9209   getTargetStreamer().emitFnEnd();
9210
9211   UC.reset();
9212   return false;
9213 }
9214
9215 /// parseDirectiveCantUnwind
9216 ///  ::= .cantunwind
9217 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9218   UC.recordCantUnwind(L);
9219
9220   // Check the ordering of unwind directives
9221   if (!UC.hasFnStart()) {
9222     Error(L, ".fnstart must precede .cantunwind directive");
9223     return false;
9224   }
9225   if (UC.hasHandlerData()) {
9226     Error(L, ".cantunwind can't be used with .handlerdata directive");
9227     UC.emitHandlerDataLocNotes();
9228     return false;
9229   }
9230   if (UC.hasPersonality()) {
9231     Error(L, ".cantunwind can't be used with .personality directive");
9232     UC.emitPersonalityLocNotes();
9233     return false;
9234   }
9235
9236   getTargetStreamer().emitCantUnwind();
9237   return false;
9238 }
9239
9240 /// parseDirectivePersonality
9241 ///  ::= .personality name
9242 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9243   MCAsmParser &Parser = getParser();
9244   bool HasExistingPersonality = UC.hasPersonality();
9245
9246   UC.recordPersonality(L);
9247
9248   // Check the ordering of unwind directives
9249   if (!UC.hasFnStart()) {
9250     Error(L, ".fnstart must precede .personality directive");
9251     return false;
9252   }
9253   if (UC.cantUnwind()) {
9254     Error(L, ".personality can't be used with .cantunwind directive");
9255     UC.emitCantUnwindLocNotes();
9256     return false;
9257   }
9258   if (UC.hasHandlerData()) {
9259     Error(L, ".personality must precede .handlerdata directive");
9260     UC.emitHandlerDataLocNotes();
9261     return false;
9262   }
9263   if (HasExistingPersonality) {
9264     Parser.eatToEndOfStatement();
9265     Error(L, "multiple personality directives");
9266     UC.emitPersonalityLocNotes();
9267     return false;
9268   }
9269
9270   // Parse the name of the personality routine
9271   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9272     Parser.eatToEndOfStatement();
9273     Error(L, "unexpected input in .personality directive.");
9274     return false;
9275   }
9276   StringRef Name(Parser.getTok().getIdentifier());
9277   Parser.Lex();
9278
9279   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9280   getTargetStreamer().emitPersonality(PR);
9281   return false;
9282 }
9283
9284 /// parseDirectiveHandlerData
9285 ///  ::= .handlerdata
9286 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9287   UC.recordHandlerData(L);
9288
9289   // Check the ordering of unwind directives
9290   if (!UC.hasFnStart()) {
9291     Error(L, ".fnstart must precede .personality directive");
9292     return false;
9293   }
9294   if (UC.cantUnwind()) {
9295     Error(L, ".handlerdata can't be used with .cantunwind directive");
9296     UC.emitCantUnwindLocNotes();
9297     return false;
9298   }
9299
9300   getTargetStreamer().emitHandlerData();
9301   return false;
9302 }
9303
9304 /// parseDirectiveSetFP
9305 ///  ::= .setfp fpreg, spreg [, offset]
9306 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9307   MCAsmParser &Parser = getParser();
9308   // Check the ordering of unwind directives
9309   if (!UC.hasFnStart()) {
9310     Error(L, ".fnstart must precede .setfp directive");
9311     return false;
9312   }
9313   if (UC.hasHandlerData()) {
9314     Error(L, ".setfp must precede .handlerdata directive");
9315     return false;
9316   }
9317
9318   // Parse fpreg
9319   SMLoc FPRegLoc = Parser.getTok().getLoc();
9320   int FPReg = tryParseRegister();
9321   if (FPReg == -1) {
9322     Error(FPRegLoc, "frame pointer register expected");
9323     return false;
9324   }
9325
9326   // Consume comma
9327   if (Parser.getTok().isNot(AsmToken::Comma)) {
9328     Error(Parser.getTok().getLoc(), "comma expected");
9329     return false;
9330   }
9331   Parser.Lex(); // skip comma
9332
9333   // Parse spreg
9334   SMLoc SPRegLoc = Parser.getTok().getLoc();
9335   int SPReg = tryParseRegister();
9336   if (SPReg == -1) {
9337     Error(SPRegLoc, "stack pointer register expected");
9338     return false;
9339   }
9340
9341   if (SPReg != ARM::SP && SPReg != UC.getFPReg()) {
9342     Error(SPRegLoc, "register should be either $sp or the latest fp register");
9343     return false;
9344   }
9345
9346   // Update the frame pointer register
9347   UC.saveFPReg(FPReg);
9348
9349   // Parse offset
9350   int64_t Offset = 0;
9351   if (Parser.getTok().is(AsmToken::Comma)) {
9352     Parser.Lex(); // skip comma
9353
9354     if (Parser.getTok().isNot(AsmToken::Hash) &&
9355         Parser.getTok().isNot(AsmToken::Dollar)) {
9356       Error(Parser.getTok().getLoc(), "'#' expected");
9357       return false;
9358     }
9359     Parser.Lex(); // skip hash token.
9360
9361     const MCExpr *OffsetExpr;
9362     SMLoc ExLoc = Parser.getTok().getLoc();
9363     SMLoc EndLoc;
9364     if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9365       Error(ExLoc, "malformed setfp offset");
9366       return false;
9367     }
9368     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9369     if (!CE) {
9370       Error(ExLoc, "setfp offset must be an immediate");
9371       return false;
9372     }
9373
9374     Offset = CE->getValue();
9375   }
9376
9377   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9378                                 static_cast<unsigned>(SPReg), Offset);
9379   return false;
9380 }
9381
9382 /// parseDirective
9383 ///  ::= .pad offset
9384 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9385   MCAsmParser &Parser = getParser();
9386   // Check the ordering of unwind directives
9387   if (!UC.hasFnStart()) {
9388     Error(L, ".fnstart must precede .pad directive");
9389     return false;
9390   }
9391   if (UC.hasHandlerData()) {
9392     Error(L, ".pad must precede .handlerdata directive");
9393     return false;
9394   }
9395
9396   // Parse the offset
9397   if (Parser.getTok().isNot(AsmToken::Hash) &&
9398       Parser.getTok().isNot(AsmToken::Dollar)) {
9399     Error(Parser.getTok().getLoc(), "'#' expected");
9400     return false;
9401   }
9402   Parser.Lex(); // skip hash token.
9403
9404   const MCExpr *OffsetExpr;
9405   SMLoc ExLoc = Parser.getTok().getLoc();
9406   SMLoc EndLoc;
9407   if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9408     Error(ExLoc, "malformed pad offset");
9409     return false;
9410   }
9411   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9412   if (!CE) {
9413     Error(ExLoc, "pad offset must be an immediate");
9414     return false;
9415   }
9416
9417   getTargetStreamer().emitPad(CE->getValue());
9418   return false;
9419 }
9420
9421 /// parseDirectiveRegSave
9422 ///  ::= .save  { registers }
9423 ///  ::= .vsave { registers }
9424 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9425   // Check the ordering of unwind directives
9426   if (!UC.hasFnStart()) {
9427     Error(L, ".fnstart must precede .save or .vsave directives");
9428     return false;
9429   }
9430   if (UC.hasHandlerData()) {
9431     Error(L, ".save or .vsave must precede .handlerdata directive");
9432     return false;
9433   }
9434
9435   // RAII object to make sure parsed operands are deleted.
9436   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9437
9438   // Parse the register list
9439   if (parseRegisterList(Operands))
9440     return false;
9441   ARMOperand &Op = (ARMOperand &)*Operands[0];
9442   if (!IsVector && !Op.isRegList()) {
9443     Error(L, ".save expects GPR registers");
9444     return false;
9445   }
9446   if (IsVector && !Op.isDPRRegList()) {
9447     Error(L, ".vsave expects DPR registers");
9448     return false;
9449   }
9450
9451   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9452   return false;
9453 }
9454
9455 /// parseDirectiveInst
9456 ///  ::= .inst opcode [, ...]
9457 ///  ::= .inst.n opcode [, ...]
9458 ///  ::= .inst.w opcode [, ...]
9459 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9460   MCAsmParser &Parser = getParser();
9461   int Width;
9462
9463   if (isThumb()) {
9464     switch (Suffix) {
9465     case 'n':
9466       Width = 2;
9467       break;
9468     case 'w':
9469       Width = 4;
9470       break;
9471     default:
9472       Parser.eatToEndOfStatement();
9473       Error(Loc, "cannot determine Thumb instruction size, "
9474                  "use inst.n/inst.w instead");
9475       return false;
9476     }
9477   } else {
9478     if (Suffix) {
9479       Parser.eatToEndOfStatement();
9480       Error(Loc, "width suffixes are invalid in ARM mode");
9481       return false;
9482     }
9483     Width = 4;
9484   }
9485
9486   if (getLexer().is(AsmToken::EndOfStatement)) {
9487     Parser.eatToEndOfStatement();
9488     Error(Loc, "expected expression following directive");
9489     return false;
9490   }
9491
9492   for (;;) {
9493     const MCExpr *Expr;
9494
9495     if (getParser().parseExpression(Expr)) {
9496       Error(Loc, "expected expression");
9497       return false;
9498     }
9499
9500     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9501     if (!Value) {
9502       Error(Loc, "expected constant expression");
9503       return false;
9504     }
9505
9506     switch (Width) {
9507     case 2:
9508       if (Value->getValue() > 0xffff) {
9509         Error(Loc, "inst.n operand is too big, use inst.w instead");
9510         return false;
9511       }
9512       break;
9513     case 4:
9514       if (Value->getValue() > 0xffffffff) {
9515         Error(Loc,
9516               StringRef(Suffix ? "inst.w" : "inst") + " operand is too big");
9517         return false;
9518       }
9519       break;
9520     default:
9521       llvm_unreachable("only supported widths are 2 and 4");
9522     }
9523
9524     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9525
9526     if (getLexer().is(AsmToken::EndOfStatement))
9527       break;
9528
9529     if (getLexer().isNot(AsmToken::Comma)) {
9530       Error(Loc, "unexpected token in directive");
9531       return false;
9532     }
9533
9534     Parser.Lex();
9535   }
9536
9537   Parser.Lex();
9538   return false;
9539 }
9540
9541 /// parseDirectiveLtorg
9542 ///  ::= .ltorg | .pool
9543 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9544   getTargetStreamer().emitCurrentConstantPool();
9545   return false;
9546 }
9547
9548 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9549   const MCSection *Section = getStreamer().getCurrentSection().first;
9550
9551   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9552     TokError("unexpected token in directive");
9553     return false;
9554   }
9555
9556   if (!Section) {
9557     getStreamer().InitSections(false);
9558     Section = getStreamer().getCurrentSection().first;
9559   }
9560
9561   assert(Section && "must have section to emit alignment");
9562   if (Section->UseCodeAlign())
9563     getStreamer().EmitCodeAlignment(2);
9564   else
9565     getStreamer().EmitValueToAlignment(2);
9566
9567   return false;
9568 }
9569
9570 /// parseDirectivePersonalityIndex
9571 ///   ::= .personalityindex index
9572 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9573   MCAsmParser &Parser = getParser();
9574   bool HasExistingPersonality = UC.hasPersonality();
9575
9576   UC.recordPersonalityIndex(L);
9577
9578   if (!UC.hasFnStart()) {
9579     Parser.eatToEndOfStatement();
9580     Error(L, ".fnstart must precede .personalityindex directive");
9581     return false;
9582   }
9583   if (UC.cantUnwind()) {
9584     Parser.eatToEndOfStatement();
9585     Error(L, ".personalityindex cannot be used with .cantunwind");
9586     UC.emitCantUnwindLocNotes();
9587     return false;
9588   }
9589   if (UC.hasHandlerData()) {
9590     Parser.eatToEndOfStatement();
9591     Error(L, ".personalityindex must precede .handlerdata directive");
9592     UC.emitHandlerDataLocNotes();
9593     return false;
9594   }
9595   if (HasExistingPersonality) {
9596     Parser.eatToEndOfStatement();
9597     Error(L, "multiple personality directives");
9598     UC.emitPersonalityLocNotes();
9599     return false;
9600   }
9601
9602   const MCExpr *IndexExpression;
9603   SMLoc IndexLoc = Parser.getTok().getLoc();
9604   if (Parser.parseExpression(IndexExpression)) {
9605     Parser.eatToEndOfStatement();
9606     return false;
9607   }
9608
9609   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9610   if (!CE) {
9611     Parser.eatToEndOfStatement();
9612     Error(IndexLoc, "index must be a constant number");
9613     return false;
9614   }
9615   if (CE->getValue() < 0 ||
9616       CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX) {
9617     Parser.eatToEndOfStatement();
9618     Error(IndexLoc, "personality routine index should be in range [0-3]");
9619     return false;
9620   }
9621
9622   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9623   return false;
9624 }
9625
9626 /// parseDirectiveUnwindRaw
9627 ///   ::= .unwind_raw offset, opcode [, opcode...]
9628 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9629   MCAsmParser &Parser = getParser();
9630   if (!UC.hasFnStart()) {
9631     Parser.eatToEndOfStatement();
9632     Error(L, ".fnstart must precede .unwind_raw directives");
9633     return false;
9634   }
9635
9636   int64_t StackOffset;
9637
9638   const MCExpr *OffsetExpr;
9639   SMLoc OffsetLoc = getLexer().getLoc();
9640   if (getLexer().is(AsmToken::EndOfStatement) ||
9641       getParser().parseExpression(OffsetExpr)) {
9642     Error(OffsetLoc, "expected expression");
9643     Parser.eatToEndOfStatement();
9644     return false;
9645   }
9646
9647   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9648   if (!CE) {
9649     Error(OffsetLoc, "offset must be a constant");
9650     Parser.eatToEndOfStatement();
9651     return false;
9652   }
9653
9654   StackOffset = CE->getValue();
9655
9656   if (getLexer().isNot(AsmToken::Comma)) {
9657     Error(getLexer().getLoc(), "expected comma");
9658     Parser.eatToEndOfStatement();
9659     return false;
9660   }
9661   Parser.Lex();
9662
9663   SmallVector<uint8_t, 16> Opcodes;
9664   for (;;) {
9665     const MCExpr *OE;
9666
9667     SMLoc OpcodeLoc = getLexer().getLoc();
9668     if (getLexer().is(AsmToken::EndOfStatement) || Parser.parseExpression(OE)) {
9669       Error(OpcodeLoc, "expected opcode expression");
9670       Parser.eatToEndOfStatement();
9671       return false;
9672     }
9673
9674     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9675     if (!OC) {
9676       Error(OpcodeLoc, "opcode value must be a constant");
9677       Parser.eatToEndOfStatement();
9678       return false;
9679     }
9680
9681     const int64_t Opcode = OC->getValue();
9682     if (Opcode & ~0xff) {
9683       Error(OpcodeLoc, "invalid opcode");
9684       Parser.eatToEndOfStatement();
9685       return false;
9686     }
9687
9688     Opcodes.push_back(uint8_t(Opcode));
9689
9690     if (getLexer().is(AsmToken::EndOfStatement))
9691       break;
9692
9693     if (getLexer().isNot(AsmToken::Comma)) {
9694       Error(getLexer().getLoc(), "unexpected token in directive");
9695       Parser.eatToEndOfStatement();
9696       return false;
9697     }
9698
9699     Parser.Lex();
9700   }
9701
9702   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9703
9704   Parser.Lex();
9705   return false;
9706 }
9707
9708 /// parseDirectiveTLSDescSeq
9709 ///   ::= .tlsdescseq tls-variable
9710 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9711   MCAsmParser &Parser = getParser();
9712
9713   if (getLexer().isNot(AsmToken::Identifier)) {
9714     TokError("expected variable after '.tlsdescseq' directive");
9715     Parser.eatToEndOfStatement();
9716     return false;
9717   }
9718
9719   const MCSymbolRefExpr *SRE =
9720     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
9721                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9722   Lex();
9723
9724   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9725     Error(Parser.getTok().getLoc(), "unexpected token");
9726     Parser.eatToEndOfStatement();
9727     return false;
9728   }
9729
9730   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9731   return false;
9732 }
9733
9734 /// parseDirectiveMovSP
9735 ///  ::= .movsp reg [, #offset]
9736 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
9737   MCAsmParser &Parser = getParser();
9738   if (!UC.hasFnStart()) {
9739     Parser.eatToEndOfStatement();
9740     Error(L, ".fnstart must precede .movsp directives");
9741     return false;
9742   }
9743   if (UC.getFPReg() != ARM::SP) {
9744     Parser.eatToEndOfStatement();
9745     Error(L, "unexpected .movsp directive");
9746     return false;
9747   }
9748
9749   SMLoc SPRegLoc = Parser.getTok().getLoc();
9750   int SPReg = tryParseRegister();
9751   if (SPReg == -1) {
9752     Parser.eatToEndOfStatement();
9753     Error(SPRegLoc, "register expected");
9754     return false;
9755   }
9756
9757   if (SPReg == ARM::SP || SPReg == ARM::PC) {
9758     Parser.eatToEndOfStatement();
9759     Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
9760     return false;
9761   }
9762
9763   int64_t Offset = 0;
9764   if (Parser.getTok().is(AsmToken::Comma)) {
9765     Parser.Lex();
9766
9767     if (Parser.getTok().isNot(AsmToken::Hash)) {
9768       Error(Parser.getTok().getLoc(), "expected #constant");
9769       Parser.eatToEndOfStatement();
9770       return false;
9771     }
9772     Parser.Lex();
9773
9774     const MCExpr *OffsetExpr;
9775     SMLoc OffsetLoc = Parser.getTok().getLoc();
9776     if (Parser.parseExpression(OffsetExpr)) {
9777       Parser.eatToEndOfStatement();
9778       Error(OffsetLoc, "malformed offset expression");
9779       return false;
9780     }
9781
9782     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9783     if (!CE) {
9784       Parser.eatToEndOfStatement();
9785       Error(OffsetLoc, "offset must be an immediate constant");
9786       return false;
9787     }
9788
9789     Offset = CE->getValue();
9790   }
9791
9792   getTargetStreamer().emitMovSP(SPReg, Offset);
9793   UC.saveFPReg(SPReg);
9794
9795   return false;
9796 }
9797
9798 /// parseDirectiveObjectArch
9799 ///   ::= .object_arch name
9800 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
9801   MCAsmParser &Parser = getParser();
9802   if (getLexer().isNot(AsmToken::Identifier)) {
9803     Error(getLexer().getLoc(), "unexpected token");
9804     Parser.eatToEndOfStatement();
9805     return false;
9806   }
9807
9808   StringRef Arch = Parser.getTok().getString();
9809   SMLoc ArchLoc = Parser.getTok().getLoc();
9810   getLexer().Lex();
9811
9812   unsigned ID = ARMTargetParser::parseArch(Arch);
9813
9814   if (ID == ARM::AK_INVALID) {
9815     Error(ArchLoc, "unknown architecture '" + Arch + "'");
9816     Parser.eatToEndOfStatement();
9817     return false;
9818   }
9819
9820   getTargetStreamer().emitObjectArch(ID);
9821
9822   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9823     Error(getLexer().getLoc(), "unexpected token");
9824     Parser.eatToEndOfStatement();
9825   }
9826
9827   return false;
9828 }
9829
9830 /// parseDirectiveAlign
9831 ///   ::= .align
9832 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
9833   // NOTE: if this is not the end of the statement, fall back to the target
9834   // agnostic handling for this directive which will correctly handle this.
9835   if (getLexer().isNot(AsmToken::EndOfStatement))
9836     return true;
9837
9838   // '.align' is target specifically handled to mean 2**2 byte alignment.
9839   if (getStreamer().getCurrentSection().first->UseCodeAlign())
9840     getStreamer().EmitCodeAlignment(4, 0);
9841   else
9842     getStreamer().EmitValueToAlignment(4, 0, 1, 0);
9843
9844   return false;
9845 }
9846
9847 /// parseDirectiveThumbSet
9848 ///  ::= .thumb_set name, value
9849 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
9850   MCAsmParser &Parser = getParser();
9851
9852   StringRef Name;
9853   if (Parser.parseIdentifier(Name)) {
9854     TokError("expected identifier after '.thumb_set'");
9855     Parser.eatToEndOfStatement();
9856     return false;
9857   }
9858
9859   if (getLexer().isNot(AsmToken::Comma)) {
9860     TokError("expected comma after name '" + Name + "'");
9861     Parser.eatToEndOfStatement();
9862     return false;
9863   }
9864   Lex();
9865
9866   MCSymbol *Sym;
9867   const MCExpr *Value;
9868   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
9869                                                Parser, Sym, Value))
9870     return true;
9871
9872   getTargetStreamer().emitThumbSet(Sym, Value);
9873   return false;
9874 }
9875
9876 /// Force static initialization.
9877 extern "C" void LLVMInitializeARMAsmParser() {
9878   RegisterMCAsmParser<ARMAsmParser> X(TheARMLETarget);
9879   RegisterMCAsmParser<ARMAsmParser> Y(TheARMBETarget);
9880   RegisterMCAsmParser<ARMAsmParser> A(TheThumbLETarget);
9881   RegisterMCAsmParser<ARMAsmParser> B(TheThumbBETarget);
9882 }
9883
9884 #define GET_REGISTER_MATCHER
9885 #define GET_SUBTARGET_FEATURE_NAME
9886 #define GET_MATCHER_IMPLEMENTATION
9887 #include "ARMGenAsmMatcher.inc"
9888
9889 // FIXME: This structure should be moved inside ARMTargetParser
9890 // when we start to table-generate them, and we can use the ARM
9891 // flags below, that were generated by table-gen.
9892 static const struct {
9893   const unsigned Kind;
9894   const unsigned ArchCheck;
9895   const FeatureBitset Features;
9896 } Extensions[] = {
9897   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
9898   { ARM::AEK_CRYPTO,  Feature_HasV8,
9899     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
9900   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
9901   { (ARM::AEK_HWDIV | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
9902     {ARM::FeatureHWDiv, ARM::FeatureHWDivARM} },
9903   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
9904   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
9905   // FIXME: Also available in ARMv6-K
9906   { ARM::AEK_SEC, Feature_HasV7, {ARM::FeatureTrustZone} },
9907   // FIXME: Only available in A-class, isel not predicated
9908   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
9909   // FIXME: Unsupported extensions.
9910   { ARM::AEK_OS, Feature_None, {} },
9911   { ARM::AEK_IWMMXT, Feature_None, {} },
9912   { ARM::AEK_IWMMXT2, Feature_None, {} },
9913   { ARM::AEK_MAVERICK, Feature_None, {} },
9914   { ARM::AEK_XSCALE, Feature_None, {} },
9915 };
9916
9917 /// parseDirectiveArchExtension
9918 ///   ::= .arch_extension [no]feature
9919 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
9920   MCAsmParser &Parser = getParser();
9921
9922   if (getLexer().isNot(AsmToken::Identifier)) {
9923     Error(getLexer().getLoc(), "unexpected token");
9924     Parser.eatToEndOfStatement();
9925     return false;
9926   }
9927
9928   StringRef Name = Parser.getTok().getString();
9929   SMLoc ExtLoc = Parser.getTok().getLoc();
9930   getLexer().Lex();
9931
9932   bool EnableFeature = true;
9933   if (Name.startswith_lower("no")) {
9934     EnableFeature = false;
9935     Name = Name.substr(2);
9936   }
9937   unsigned FeatureKind = ARMTargetParser::parseArchExt(Name);
9938   if (FeatureKind == ARM::AEK_INVALID)
9939     Error(ExtLoc, "unknown architectural extension: " + Name);
9940
9941   for (const auto &Extension : Extensions) {
9942     if (Extension.Kind != FeatureKind)
9943       continue;
9944
9945     if (Extension.Features.none())
9946       report_fatal_error("unsupported architectural extension: " + Name);
9947
9948     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck) {
9949       Error(ExtLoc, "architectural extension '" + Name + "' is not "
9950             "allowed for the current base architecture");
9951       return false;
9952     }
9953
9954     FeatureBitset ToggleFeatures = EnableFeature
9955       ? (~STI.getFeatureBits() & Extension.Features)
9956       : ( STI.getFeatureBits() & Extension.Features);
9957
9958     uint64_t Features =
9959         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
9960     setAvailableFeatures(Features);
9961     return false;
9962   }
9963
9964   Error(ExtLoc, "unknown architectural extension: " + Name);
9965   Parser.eatToEndOfStatement();
9966   return false;
9967 }
9968
9969 // Define this matcher function after the auto-generated include so we
9970 // have the match class enum definitions.
9971 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
9972                                                   unsigned Kind) {
9973   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
9974   // If the kind is a token for a literal immediate, check if our asm
9975   // operand matches. This is for InstAliases which have a fixed-value
9976   // immediate in the syntax.
9977   switch (Kind) {
9978   default: break;
9979   case MCK__35_0:
9980     if (Op.isImm())
9981       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
9982         if (CE->getValue() == 0)
9983           return Match_Success;
9984     break;
9985   case MCK_ModImm:
9986     if (Op.isImm()) {
9987       const MCExpr *SOExpr = Op.getImm();
9988       int64_t Value;
9989       if (!SOExpr->evaluateAsAbsolute(Value))
9990         return Match_Success;
9991       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
9992              "expression value must be representable in 32 bits");
9993     }
9994     break;
9995   case MCK_GPRPair:
9996     if (Op.isReg() &&
9997         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
9998       return Match_Success;
9999     break;
10000   }
10001   return Match_InvalidOperand;
10002 }