73f3308775667523a432b89dedbd0a146d39fd46
[oota-llvm.git] / lib / Target / ARM / AsmParser / ARMAsmParser.cpp
1 //===-- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "ARMFeatures.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMMCExpr.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCELFStreamer.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCObjectFileInfo.h"
30 #include "llvm/MC/MCParser/MCAsmLexer.h"
31 #include "llvm/MC/MCParser/MCAsmParser.h"
32 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
33 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSubtargetInfo.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/MC/MCTargetAsmParser.h"
40 #include "llvm/Support/ARMBuildAttributes.h"
41 #include "llvm/Support/ARMEHABI.h"
42 #include "llvm/Support/TargetParser.h"
43 #include "llvm/Support/COFF.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ELF.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/raw_ostream.h"
50
51 using namespace llvm;
52
53 namespace {
54
55 class ARMOperand;
56
57 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
58
59 class UnwindContext {
60   MCAsmParser &Parser;
61
62   typedef SmallVector<SMLoc, 4> Locs;
63
64   Locs FnStartLocs;
65   Locs CantUnwindLocs;
66   Locs PersonalityLocs;
67   Locs PersonalityIndexLocs;
68   Locs HandlerDataLocs;
69   int FPReg;
70
71 public:
72   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
73
74   bool hasFnStart() const { return !FnStartLocs.empty(); }
75   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
76   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
77   bool hasPersonality() const {
78     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
79   }
80
81   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
82   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
83   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
84   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
85   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
86
87   void saveFPReg(int Reg) { FPReg = Reg; }
88   int getFPReg() const { return FPReg; }
89
90   void emitFnStartLocNotes() const {
91     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
92          FI != FE; ++FI)
93       Parser.Note(*FI, ".fnstart was specified here");
94   }
95   void emitCantUnwindLocNotes() const {
96     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
97                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
98       Parser.Note(*UI, ".cantunwind was specified here");
99   }
100   void emitHandlerDataLocNotes() const {
101     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
102                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
103       Parser.Note(*HI, ".handlerdata was specified here");
104   }
105   void emitPersonalityLocNotes() const {
106     for (Locs::const_iterator PI = PersonalityLocs.begin(),
107                               PE = PersonalityLocs.end(),
108                               PII = PersonalityIndexLocs.begin(),
109                               PIE = PersonalityIndexLocs.end();
110          PI != PE || PII != PIE;) {
111       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
112         Parser.Note(*PI++, ".personality was specified here");
113       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
114         Parser.Note(*PII++, ".personalityindex was specified here");
115       else
116         llvm_unreachable(".personality and .personalityindex cannot be "
117                          "at the same location");
118     }
119   }
120
121   void reset() {
122     FnStartLocs = Locs();
123     CantUnwindLocs = Locs();
124     PersonalityLocs = Locs();
125     HandlerDataLocs = Locs();
126     PersonalityIndexLocs = Locs();
127     FPReg = ARM::SP;
128   }
129 };
130
131 class ARMAsmParser : public MCTargetAsmParser {
132   const MCInstrInfo &MII;
133   const MCRegisterInfo *MRI;
134   UnwindContext UC;
135
136   ARMTargetStreamer &getTargetStreamer() {
137     assert(getParser().getStreamer().getTargetStreamer() &&
138            "do not have a target streamer");
139     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
140     return static_cast<ARMTargetStreamer &>(TS);
141   }
142
143   // Map of register aliases registers via the .req directive.
144   StringMap<unsigned> RegisterReqs;
145
146   bool NextSymbolIsThumb;
147
148   struct {
149     ARMCC::CondCodes Cond;    // Condition for IT block.
150     unsigned Mask:4;          // Condition mask for instructions.
151                               // Starting at first 1 (from lsb).
152                               //   '1'  condition as indicated in IT.
153                               //   '0'  inverse of condition (else).
154                               // Count of instructions in IT block is
155                               // 4 - trailingzeroes(mask)
156
157     bool FirstCond;           // Explicit flag for when we're parsing the
158                               // First instruction in the IT block. It's
159                               // implied in the mask, so needs special
160                               // handling.
161
162     unsigned CurPosition;     // Current position in parsing of IT
163                               // block. In range [0,3]. Initialized
164                               // according to count of instructions in block.
165                               // ~0U if no active IT block.
166   } ITState;
167   bool inITBlock() { return ITState.CurPosition != ~0U; }
168   bool lastInITBlock() {
169     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
170   }
171   void forwardITPosition() {
172     if (!inITBlock()) return;
173     // Move to the next instruction in the IT block, if there is one. If not,
174     // mark the block as done.
175     unsigned TZ = countTrailingZeros(ITState.Mask);
176     if (++ITState.CurPosition == 5 - TZ)
177       ITState.CurPosition = ~0U; // Done with the IT block after this.
178   }
179
180   void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None) {
181     return getParser().Note(L, Msg, Ranges);
182   }
183   bool Warning(SMLoc L, const Twine &Msg,
184                ArrayRef<SMRange> Ranges = None) {
185     return getParser().Warning(L, Msg, Ranges);
186   }
187   bool Error(SMLoc L, const Twine &Msg,
188              ArrayRef<SMRange> Ranges = None) {
189     return getParser().Error(L, Msg, Ranges);
190   }
191
192   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
193                            unsigned ListNo, bool IsARPop = false);
194   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
195                            unsigned ListNo);
196
197   int tryParseRegister();
198   bool tryParseRegisterWithWriteBack(OperandVector &);
199   int tryParseShiftRegister(OperandVector &);
200   bool parseRegisterList(OperandVector &);
201   bool parseMemory(OperandVector &);
202   bool parseOperand(OperandVector &, StringRef Mnemonic);
203   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
204   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
205                               unsigned &ShiftAmount);
206   bool parseLiteralValues(unsigned Size, SMLoc L);
207   bool parseDirectiveThumb(SMLoc L);
208   bool parseDirectiveARM(SMLoc L);
209   bool parseDirectiveThumbFunc(SMLoc L);
210   bool parseDirectiveCode(SMLoc L);
211   bool parseDirectiveSyntax(SMLoc L);
212   bool parseDirectiveReq(StringRef Name, SMLoc L);
213   bool parseDirectiveUnreq(SMLoc L);
214   bool parseDirectiveArch(SMLoc L);
215   bool parseDirectiveEabiAttr(SMLoc L);
216   bool parseDirectiveCPU(SMLoc L);
217   bool parseDirectiveFPU(SMLoc L);
218   bool parseDirectiveFnStart(SMLoc L);
219   bool parseDirectiveFnEnd(SMLoc L);
220   bool parseDirectiveCantUnwind(SMLoc L);
221   bool parseDirectivePersonality(SMLoc L);
222   bool parseDirectiveHandlerData(SMLoc L);
223   bool parseDirectiveSetFP(SMLoc L);
224   bool parseDirectivePad(SMLoc L);
225   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
226   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
227   bool parseDirectiveLtorg(SMLoc L);
228   bool parseDirectiveEven(SMLoc L);
229   bool parseDirectivePersonalityIndex(SMLoc L);
230   bool parseDirectiveUnwindRaw(SMLoc L);
231   bool parseDirectiveTLSDescSeq(SMLoc L);
232   bool parseDirectiveMovSP(SMLoc L);
233   bool parseDirectiveObjectArch(SMLoc L);
234   bool parseDirectiveArchExtension(SMLoc L);
235   bool parseDirectiveAlign(SMLoc L);
236   bool parseDirectiveThumbSet(SMLoc L);
237
238   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
239                           bool &CarrySetting, unsigned &ProcessorIMod,
240                           StringRef &ITMask);
241   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
242                              bool &CanAcceptCarrySet,
243                              bool &CanAcceptPredicationCode);
244
245   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
246                                      OperandVector &Operands);
247   bool isThumb() const {
248     // FIXME: Can tablegen auto-generate this?
249     return getSTI().getFeatureBits()[ARM::ModeThumb];
250   }
251   bool isThumbOne() const {
252     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
253   }
254   bool isThumbTwo() const {
255     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
256   }
257   bool hasThumb() const {
258     return getSTI().getFeatureBits()[ARM::HasV4TOps];
259   }
260   bool hasV6Ops() const {
261     return getSTI().getFeatureBits()[ARM::HasV6Ops];
262   }
263   bool hasV6MOps() const {
264     return getSTI().getFeatureBits()[ARM::HasV6MOps];
265   }
266   bool hasV7Ops() const {
267     return getSTI().getFeatureBits()[ARM::HasV7Ops];
268   }
269   bool hasV8Ops() const {
270     return getSTI().getFeatureBits()[ARM::HasV8Ops];
271   }
272   bool hasARM() const {
273     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
274   }
275   bool hasDSP() const {
276     return getSTI().getFeatureBits()[ARM::FeatureDSP];
277   }
278   bool hasD16() const {
279     return getSTI().getFeatureBits()[ARM::FeatureD16];
280   }
281   bool hasV8_1aOps() const {
282     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
283   }
284
285   void SwitchMode() {
286     MCSubtargetInfo &STI = copySTI();
287     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
288     setAvailableFeatures(FB);
289   }
290   bool isMClass() const {
291     return getSTI().getFeatureBits()[ARM::FeatureMClass];
292   }
293
294   /// @name Auto-generated Match Functions
295   /// {
296
297 #define GET_ASSEMBLER_HEADER
298 #include "ARMGenAsmMatcher.inc"
299
300   /// }
301
302   OperandMatchResultTy parseITCondCode(OperandVector &);
303   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
304   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
305   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
306   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
307   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
308   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
309   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
310   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
311   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
312                                    int High);
313   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
314     return parsePKHImm(O, "lsl", 0, 31);
315   }
316   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
317     return parsePKHImm(O, "asr", 1, 32);
318   }
319   OperandMatchResultTy parseSetEndImm(OperandVector &);
320   OperandMatchResultTy parseShifterImm(OperandVector &);
321   OperandMatchResultTy parseRotImm(OperandVector &);
322   OperandMatchResultTy parseModImm(OperandVector &);
323   OperandMatchResultTy parseBitfield(OperandVector &);
324   OperandMatchResultTy parsePostIdxReg(OperandVector &);
325   OperandMatchResultTy parseAM3Offset(OperandVector &);
326   OperandMatchResultTy parseFPImm(OperandVector &);
327   OperandMatchResultTy parseVectorList(OperandVector &);
328   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
329                                        SMLoc &EndLoc);
330
331   // Asm Match Converter Methods
332   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
333   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
334
335   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
336   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
337   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
338   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
339
340 public:
341   enum ARMMatchResultTy {
342     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
343     Match_RequiresNotITBlock,
344     Match_RequiresV6,
345     Match_RequiresThumb2,
346     Match_RequiresV8,
347 #define GET_OPERAND_DIAGNOSTIC_TYPES
348 #include "ARMGenAsmMatcher.inc"
349
350   };
351
352   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
353                const MCInstrInfo &MII, const MCTargetOptions &Options)
354     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
355     MCAsmParserExtension::Initialize(Parser);
356
357     // Cache the MCRegisterInfo.
358     MRI = getContext().getRegisterInfo();
359
360     // Initialize the set of available features.
361     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
362
363     // Not in an ITBlock to start with.
364     ITState.CurPosition = ~0U;
365
366     NextSymbolIsThumb = false;
367   }
368
369   // Implementation of the MCTargetAsmParser interface:
370   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
371   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
372                         SMLoc NameLoc, OperandVector &Operands) override;
373   bool ParseDirective(AsmToken DirectiveID) override;
374
375   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
376                                       unsigned Kind) override;
377   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
378
379   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
380                                OperandVector &Operands, MCStreamer &Out,
381                                uint64_t &ErrorInfo,
382                                bool MatchingInlineAsm) override;
383   void onLabelParsed(MCSymbol *Symbol) override;
384 };
385 } // end anonymous namespace
386
387 namespace {
388
389 /// ARMOperand - Instances of this class represent a parsed ARM machine
390 /// operand.
391 class ARMOperand : public MCParsedAsmOperand {
392   enum KindTy {
393     k_CondCode,
394     k_CCOut,
395     k_ITCondMask,
396     k_CoprocNum,
397     k_CoprocReg,
398     k_CoprocOption,
399     k_Immediate,
400     k_MemBarrierOpt,
401     k_InstSyncBarrierOpt,
402     k_Memory,
403     k_PostIndexRegister,
404     k_MSRMask,
405     k_BankedReg,
406     k_ProcIFlags,
407     k_VectorIndex,
408     k_Register,
409     k_RegisterList,
410     k_DPRRegisterList,
411     k_SPRRegisterList,
412     k_VectorList,
413     k_VectorListAllLanes,
414     k_VectorListIndexed,
415     k_ShiftedRegister,
416     k_ShiftedImmediate,
417     k_ShifterImmediate,
418     k_RotateImmediate,
419     k_ModifiedImmediate,
420     k_BitfieldDescriptor,
421     k_Token
422   } Kind;
423
424   SMLoc StartLoc, EndLoc, AlignmentLoc;
425   SmallVector<unsigned, 8> Registers;
426
427   struct CCOp {
428     ARMCC::CondCodes Val;
429   };
430
431   struct CopOp {
432     unsigned Val;
433   };
434
435   struct CoprocOptionOp {
436     unsigned Val;
437   };
438
439   struct ITMaskOp {
440     unsigned Mask:4;
441   };
442
443   struct MBOptOp {
444     ARM_MB::MemBOpt Val;
445   };
446
447   struct ISBOptOp {
448     ARM_ISB::InstSyncBOpt Val;
449   };
450
451   struct IFlagsOp {
452     ARM_PROC::IFlags Val;
453   };
454
455   struct MMaskOp {
456     unsigned Val;
457   };
458
459   struct BankedRegOp {
460     unsigned Val;
461   };
462
463   struct TokOp {
464     const char *Data;
465     unsigned Length;
466   };
467
468   struct RegOp {
469     unsigned RegNum;
470   };
471
472   // A vector register list is a sequential list of 1 to 4 registers.
473   struct VectorListOp {
474     unsigned RegNum;
475     unsigned Count;
476     unsigned LaneIndex;
477     bool isDoubleSpaced;
478   };
479
480   struct VectorIndexOp {
481     unsigned Val;
482   };
483
484   struct ImmOp {
485     const MCExpr *Val;
486   };
487
488   /// Combined record for all forms of ARM address expressions.
489   struct MemoryOp {
490     unsigned BaseRegNum;
491     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
492     // was specified.
493     const MCConstantExpr *OffsetImm;  // Offset immediate value
494     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
495     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
496     unsigned ShiftImm;        // shift for OffsetReg.
497     unsigned Alignment;       // 0 = no alignment specified
498     // n = alignment in bytes (2, 4, 8, 16, or 32)
499     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
500   };
501
502   struct PostIdxRegOp {
503     unsigned RegNum;
504     bool isAdd;
505     ARM_AM::ShiftOpc ShiftTy;
506     unsigned ShiftImm;
507   };
508
509   struct ShifterImmOp {
510     bool isASR;
511     unsigned Imm;
512   };
513
514   struct RegShiftedRegOp {
515     ARM_AM::ShiftOpc ShiftTy;
516     unsigned SrcReg;
517     unsigned ShiftReg;
518     unsigned ShiftImm;
519   };
520
521   struct RegShiftedImmOp {
522     ARM_AM::ShiftOpc ShiftTy;
523     unsigned SrcReg;
524     unsigned ShiftImm;
525   };
526
527   struct RotImmOp {
528     unsigned Imm;
529   };
530
531   struct ModImmOp {
532     unsigned Bits;
533     unsigned Rot;
534   };
535
536   struct BitfieldOp {
537     unsigned LSB;
538     unsigned Width;
539   };
540
541   union {
542     struct CCOp CC;
543     struct CopOp Cop;
544     struct CoprocOptionOp CoprocOption;
545     struct MBOptOp MBOpt;
546     struct ISBOptOp ISBOpt;
547     struct ITMaskOp ITMask;
548     struct IFlagsOp IFlags;
549     struct MMaskOp MMask;
550     struct BankedRegOp BankedReg;
551     struct TokOp Tok;
552     struct RegOp Reg;
553     struct VectorListOp VectorList;
554     struct VectorIndexOp VectorIndex;
555     struct ImmOp Imm;
556     struct MemoryOp Memory;
557     struct PostIdxRegOp PostIdxReg;
558     struct ShifterImmOp ShifterImm;
559     struct RegShiftedRegOp RegShiftedReg;
560     struct RegShiftedImmOp RegShiftedImm;
561     struct RotImmOp RotImm;
562     struct ModImmOp ModImm;
563     struct BitfieldOp Bitfield;
564   };
565
566 public:
567   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
568
569   /// getStartLoc - Get the location of the first token of this operand.
570   SMLoc getStartLoc() const override { return StartLoc; }
571   /// getEndLoc - Get the location of the last token of this operand.
572   SMLoc getEndLoc() const override { return EndLoc; }
573   /// getLocRange - Get the range between the first and last token of this
574   /// operand.
575   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
576
577   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
578   SMLoc getAlignmentLoc() const {
579     assert(Kind == k_Memory && "Invalid access!");
580     return AlignmentLoc;
581   }
582
583   ARMCC::CondCodes getCondCode() const {
584     assert(Kind == k_CondCode && "Invalid access!");
585     return CC.Val;
586   }
587
588   unsigned getCoproc() const {
589     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
590     return Cop.Val;
591   }
592
593   StringRef getToken() const {
594     assert(Kind == k_Token && "Invalid access!");
595     return StringRef(Tok.Data, Tok.Length);
596   }
597
598   unsigned getReg() const override {
599     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
600     return Reg.RegNum;
601   }
602
603   const SmallVectorImpl<unsigned> &getRegList() const {
604     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
605             Kind == k_SPRRegisterList) && "Invalid access!");
606     return Registers;
607   }
608
609   const MCExpr *getImm() const {
610     assert(isImm() && "Invalid access!");
611     return Imm.Val;
612   }
613
614   unsigned getVectorIndex() const {
615     assert(Kind == k_VectorIndex && "Invalid access!");
616     return VectorIndex.Val;
617   }
618
619   ARM_MB::MemBOpt getMemBarrierOpt() const {
620     assert(Kind == k_MemBarrierOpt && "Invalid access!");
621     return MBOpt.Val;
622   }
623
624   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
625     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
626     return ISBOpt.Val;
627   }
628
629   ARM_PROC::IFlags getProcIFlags() const {
630     assert(Kind == k_ProcIFlags && "Invalid access!");
631     return IFlags.Val;
632   }
633
634   unsigned getMSRMask() const {
635     assert(Kind == k_MSRMask && "Invalid access!");
636     return MMask.Val;
637   }
638
639   unsigned getBankedReg() const {
640     assert(Kind == k_BankedReg && "Invalid access!");
641     return BankedReg.Val;
642   }
643
644   bool isCoprocNum() const { return Kind == k_CoprocNum; }
645   bool isCoprocReg() const { return Kind == k_CoprocReg; }
646   bool isCoprocOption() const { return Kind == k_CoprocOption; }
647   bool isCondCode() const { return Kind == k_CondCode; }
648   bool isCCOut() const { return Kind == k_CCOut; }
649   bool isITMask() const { return Kind == k_ITCondMask; }
650   bool isITCondCode() const { return Kind == k_CondCode; }
651   bool isImm() const override { return Kind == k_Immediate; }
652   // checks whether this operand is an unsigned offset which fits is a field
653   // of specified width and scaled by a specific number of bits
654   template<unsigned width, unsigned scale>
655   bool isUnsignedOffset() const {
656     if (!isImm()) return false;
657     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
658     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
659       int64_t Val = CE->getValue();
660       int64_t Align = 1LL << scale;
661       int64_t Max = Align * ((1LL << width) - 1);
662       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
663     }
664     return false;
665   }
666   // checks whether this operand is an signed offset which fits is a field
667   // of specified width and scaled by a specific number of bits
668   template<unsigned width, unsigned scale>
669   bool isSignedOffset() const {
670     if (!isImm()) return false;
671     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
672     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
673       int64_t Val = CE->getValue();
674       int64_t Align = 1LL << scale;
675       int64_t Max = Align * ((1LL << (width-1)) - 1);
676       int64_t Min = -Align * (1LL << (width-1));
677       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
678     }
679     return false;
680   }
681
682   // checks whether this operand is a memory operand computed as an offset
683   // applied to PC. the offset may have 8 bits of magnitude and is represented
684   // with two bits of shift. textually it may be either [pc, #imm], #imm or 
685   // relocable expression...
686   bool isThumbMemPC() const {
687     int64_t Val = 0;
688     if (isImm()) {
689       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
690       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
691       if (!CE) return false;
692       Val = CE->getValue();
693     }
694     else if (isMem()) {
695       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
696       if(Memory.BaseRegNum != ARM::PC) return false;
697       Val = Memory.OffsetImm->getValue();
698     }
699     else return false;
700     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
701   }
702   bool isFPImm() const {
703     if (!isImm()) return false;
704     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
705     if (!CE) return false;
706     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
707     return Val != -1;
708   }
709   bool isFBits16() const {
710     if (!isImm()) return false;
711     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
712     if (!CE) return false;
713     int64_t Value = CE->getValue();
714     return Value >= 0 && Value <= 16;
715   }
716   bool isFBits32() const {
717     if (!isImm()) return false;
718     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
719     if (!CE) return false;
720     int64_t Value = CE->getValue();
721     return Value >= 1 && Value <= 32;
722   }
723   bool isImm8s4() const {
724     if (!isImm()) return false;
725     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
726     if (!CE) return false;
727     int64_t Value = CE->getValue();
728     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
729   }
730   bool isImm0_1020s4() const {
731     if (!isImm()) return false;
732     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
733     if (!CE) return false;
734     int64_t Value = CE->getValue();
735     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
736   }
737   bool isImm0_508s4() const {
738     if (!isImm()) return false;
739     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
740     if (!CE) return false;
741     int64_t Value = CE->getValue();
742     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
743   }
744   bool isImm0_508s4Neg() const {
745     if (!isImm()) return false;
746     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
747     if (!CE) return false;
748     int64_t Value = -CE->getValue();
749     // explicitly exclude zero. we want that to use the normal 0_508 version.
750     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
751   }
752   bool isImm0_239() const {
753     if (!isImm()) return false;
754     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
755     if (!CE) return false;
756     int64_t Value = CE->getValue();
757     return Value >= 0 && Value < 240;
758   }
759   bool isImm0_255() const {
760     if (!isImm()) return false;
761     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
762     if (!CE) return false;
763     int64_t Value = CE->getValue();
764     return Value >= 0 && Value < 256;
765   }
766   bool isImm0_4095() const {
767     if (!isImm()) return false;
768     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
769     if (!CE) return false;
770     int64_t Value = CE->getValue();
771     return Value >= 0 && Value < 4096;
772   }
773   bool isImm0_4095Neg() const {
774     if (!isImm()) return false;
775     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
776     if (!CE) return false;
777     int64_t Value = -CE->getValue();
778     return Value > 0 && Value < 4096;
779   }
780   bool isImm0_1() const {
781     if (!isImm()) return false;
782     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
783     if (!CE) return false;
784     int64_t Value = CE->getValue();
785     return Value >= 0 && Value < 2;
786   }
787   bool isImm0_3() const {
788     if (!isImm()) return false;
789     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
790     if (!CE) return false;
791     int64_t Value = CE->getValue();
792     return Value >= 0 && Value < 4;
793   }
794   bool isImm0_7() const {
795     if (!isImm()) return false;
796     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
797     if (!CE) return false;
798     int64_t Value = CE->getValue();
799     return Value >= 0 && Value < 8;
800   }
801   bool isImm0_15() const {
802     if (!isImm()) return false;
803     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
804     if (!CE) return false;
805     int64_t Value = CE->getValue();
806     return Value >= 0 && Value < 16;
807   }
808   bool isImm0_31() const {
809     if (!isImm()) return false;
810     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
811     if (!CE) return false;
812     int64_t Value = CE->getValue();
813     return Value >= 0 && Value < 32;
814   }
815   bool isImm0_63() const {
816     if (!isImm()) return false;
817     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
818     if (!CE) return false;
819     int64_t Value = CE->getValue();
820     return Value >= 0 && Value < 64;
821   }
822   bool isImm8() const {
823     if (!isImm()) return false;
824     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
825     if (!CE) return false;
826     int64_t Value = CE->getValue();
827     return Value == 8;
828   }
829   bool isImm16() const {
830     if (!isImm()) return false;
831     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
832     if (!CE) return false;
833     int64_t Value = CE->getValue();
834     return Value == 16;
835   }
836   bool isImm32() const {
837     if (!isImm()) return false;
838     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
839     if (!CE) return false;
840     int64_t Value = CE->getValue();
841     return Value == 32;
842   }
843   bool isShrImm8() const {
844     if (!isImm()) return false;
845     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
846     if (!CE) return false;
847     int64_t Value = CE->getValue();
848     return Value > 0 && Value <= 8;
849   }
850   bool isShrImm16() const {
851     if (!isImm()) return false;
852     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
853     if (!CE) return false;
854     int64_t Value = CE->getValue();
855     return Value > 0 && Value <= 16;
856   }
857   bool isShrImm32() const {
858     if (!isImm()) return false;
859     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
860     if (!CE) return false;
861     int64_t Value = CE->getValue();
862     return Value > 0 && Value <= 32;
863   }
864   bool isShrImm64() const {
865     if (!isImm()) return false;
866     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
867     if (!CE) return false;
868     int64_t Value = CE->getValue();
869     return Value > 0 && Value <= 64;
870   }
871   bool isImm1_7() const {
872     if (!isImm()) return false;
873     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
874     if (!CE) return false;
875     int64_t Value = CE->getValue();
876     return Value > 0 && Value < 8;
877   }
878   bool isImm1_15() const {
879     if (!isImm()) return false;
880     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
881     if (!CE) return false;
882     int64_t Value = CE->getValue();
883     return Value > 0 && Value < 16;
884   }
885   bool isImm1_31() const {
886     if (!isImm()) return false;
887     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
888     if (!CE) return false;
889     int64_t Value = CE->getValue();
890     return Value > 0 && Value < 32;
891   }
892   bool isImm1_16() const {
893     if (!isImm()) return false;
894     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
895     if (!CE) return false;
896     int64_t Value = CE->getValue();
897     return Value > 0 && Value < 17;
898   }
899   bool isImm1_32() const {
900     if (!isImm()) return false;
901     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
902     if (!CE) return false;
903     int64_t Value = CE->getValue();
904     return Value > 0 && Value < 33;
905   }
906   bool isImm0_32() const {
907     if (!isImm()) return false;
908     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
909     if (!CE) return false;
910     int64_t Value = CE->getValue();
911     return Value >= 0 && Value < 33;
912   }
913   bool isImm0_65535() const {
914     if (!isImm()) return false;
915     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
916     if (!CE) return false;
917     int64_t Value = CE->getValue();
918     return Value >= 0 && Value < 65536;
919   }
920   bool isImm256_65535Expr() const {
921     if (!isImm()) return false;
922     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
923     // If it's not a constant expression, it'll generate a fixup and be
924     // handled later.
925     if (!CE) return true;
926     int64_t Value = CE->getValue();
927     return Value >= 256 && Value < 65536;
928   }
929   bool isImm0_65535Expr() const {
930     if (!isImm()) return false;
931     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
932     // If it's not a constant expression, it'll generate a fixup and be
933     // handled later.
934     if (!CE) return true;
935     int64_t Value = CE->getValue();
936     return Value >= 0 && Value < 65536;
937   }
938   bool isImm24bit() const {
939     if (!isImm()) return false;
940     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
941     if (!CE) return false;
942     int64_t Value = CE->getValue();
943     return Value >= 0 && Value <= 0xffffff;
944   }
945   bool isImmThumbSR() const {
946     if (!isImm()) return false;
947     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
948     if (!CE) return false;
949     int64_t Value = CE->getValue();
950     return Value > 0 && Value < 33;
951   }
952   bool isPKHLSLImm() const {
953     if (!isImm()) return false;
954     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
955     if (!CE) return false;
956     int64_t Value = CE->getValue();
957     return Value >= 0 && Value < 32;
958   }
959   bool isPKHASRImm() const {
960     if (!isImm()) return false;
961     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
962     if (!CE) return false;
963     int64_t Value = CE->getValue();
964     return Value > 0 && Value <= 32;
965   }
966   bool isAdrLabel() const {
967     // If we have an immediate that's not a constant, treat it as a label
968     // reference needing a fixup.
969     if (isImm() && !isa<MCConstantExpr>(getImm()))
970       return true;
971
972     // If it is a constant, it must fit into a modified immediate encoding.
973     if (!isImm()) return false;
974     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
975     if (!CE) return false;
976     int64_t Value = CE->getValue();
977     return (ARM_AM::getSOImmVal(Value) != -1 ||
978             ARM_AM::getSOImmVal(-Value) != -1);
979   }
980   bool isT2SOImm() const {
981     if (!isImm()) return false;
982     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
983     if (!CE) return false;
984     int64_t Value = CE->getValue();
985     return ARM_AM::getT2SOImmVal(Value) != -1;
986   }
987   bool isT2SOImmNot() const {
988     if (!isImm()) return false;
989     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
990     if (!CE) return false;
991     int64_t Value = CE->getValue();
992     return ARM_AM::getT2SOImmVal(Value) == -1 &&
993       ARM_AM::getT2SOImmVal(~Value) != -1;
994   }
995   bool isT2SOImmNeg() const {
996     if (!isImm()) return false;
997     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
998     if (!CE) return false;
999     int64_t Value = CE->getValue();
1000     // Only use this when not representable as a plain so_imm.
1001     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1002       ARM_AM::getT2SOImmVal(-Value) != -1;
1003   }
1004   bool isSetEndImm() const {
1005     if (!isImm()) return false;
1006     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1007     if (!CE) return false;
1008     int64_t Value = CE->getValue();
1009     return Value == 1 || Value == 0;
1010   }
1011   bool isReg() const override { return Kind == k_Register; }
1012   bool isRegList() const { return Kind == k_RegisterList; }
1013   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1014   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1015   bool isToken() const override { return Kind == k_Token; }
1016   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1017   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1018   bool isMem() const override { return Kind == k_Memory; }
1019   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1020   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1021   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1022   bool isRotImm() const { return Kind == k_RotateImmediate; }
1023   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1024   bool isModImmNot() const {
1025     if (!isImm()) return false;
1026     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1027     if (!CE) return false;
1028     int64_t Value = CE->getValue();
1029     return ARM_AM::getSOImmVal(~Value) != -1;
1030   }
1031   bool isModImmNeg() const {
1032     if (!isImm()) return false;
1033     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1034     if (!CE) return false;
1035     int64_t Value = CE->getValue();
1036     return ARM_AM::getSOImmVal(Value) == -1 &&
1037       ARM_AM::getSOImmVal(-Value) != -1;
1038   }
1039   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1040   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1041   bool isPostIdxReg() const {
1042     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1043   }
1044   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1045     if (!isMem())
1046       return false;
1047     // No offset of any kind.
1048     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1049      (alignOK || Memory.Alignment == Alignment);
1050   }
1051   bool isMemPCRelImm12() const {
1052     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1053       return false;
1054     // Base register must be PC.
1055     if (Memory.BaseRegNum != ARM::PC)
1056       return false;
1057     // Immediate offset in range [-4095, 4095].
1058     if (!Memory.OffsetImm) return true;
1059     int64_t Val = Memory.OffsetImm->getValue();
1060     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1061   }
1062   bool isAlignedMemory() const {
1063     return isMemNoOffset(true);
1064   }
1065   bool isAlignedMemoryNone() const {
1066     return isMemNoOffset(false, 0);
1067   }
1068   bool isDupAlignedMemoryNone() const {
1069     return isMemNoOffset(false, 0);
1070   }
1071   bool isAlignedMemory16() const {
1072     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1073       return true;
1074     return isMemNoOffset(false, 0);
1075   }
1076   bool isDupAlignedMemory16() const {
1077     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1078       return true;
1079     return isMemNoOffset(false, 0);
1080   }
1081   bool isAlignedMemory32() const {
1082     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1083       return true;
1084     return isMemNoOffset(false, 0);
1085   }
1086   bool isDupAlignedMemory32() const {
1087     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1088       return true;
1089     return isMemNoOffset(false, 0);
1090   }
1091   bool isAlignedMemory64() const {
1092     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1093       return true;
1094     return isMemNoOffset(false, 0);
1095   }
1096   bool isDupAlignedMemory64() const {
1097     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1098       return true;
1099     return isMemNoOffset(false, 0);
1100   }
1101   bool isAlignedMemory64or128() const {
1102     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1103       return true;
1104     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1105       return true;
1106     return isMemNoOffset(false, 0);
1107   }
1108   bool isDupAlignedMemory64or128() const {
1109     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1110       return true;
1111     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1112       return true;
1113     return isMemNoOffset(false, 0);
1114   }
1115   bool isAlignedMemory64or128or256() const {
1116     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1117       return true;
1118     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1119       return true;
1120     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1121       return true;
1122     return isMemNoOffset(false, 0);
1123   }
1124   bool isAddrMode2() const {
1125     if (!isMem() || Memory.Alignment != 0) return false;
1126     // Check for register offset.
1127     if (Memory.OffsetRegNum) return true;
1128     // Immediate offset in range [-4095, 4095].
1129     if (!Memory.OffsetImm) return true;
1130     int64_t Val = Memory.OffsetImm->getValue();
1131     return Val > -4096 && Val < 4096;
1132   }
1133   bool isAM2OffsetImm() const {
1134     if (!isImm()) return false;
1135     // Immediate offset in range [-4095, 4095].
1136     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1137     if (!CE) return false;
1138     int64_t Val = CE->getValue();
1139     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1140   }
1141   bool isAddrMode3() const {
1142     // If we have an immediate that's not a constant, treat it as a label
1143     // reference needing a fixup. If it is a constant, it's something else
1144     // and we reject it.
1145     if (isImm() && !isa<MCConstantExpr>(getImm()))
1146       return true;
1147     if (!isMem() || Memory.Alignment != 0) return false;
1148     // No shifts are legal for AM3.
1149     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1150     // Check for register offset.
1151     if (Memory.OffsetRegNum) return true;
1152     // Immediate offset in range [-255, 255].
1153     if (!Memory.OffsetImm) return true;
1154     int64_t Val = Memory.OffsetImm->getValue();
1155     // The #-0 offset is encoded as INT32_MIN, and we have to check 
1156     // for this too.
1157     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1158   }
1159   bool isAM3Offset() const {
1160     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1161       return false;
1162     if (Kind == k_PostIndexRegister)
1163       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1164     // Immediate offset in range [-255, 255].
1165     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1166     if (!CE) return false;
1167     int64_t Val = CE->getValue();
1168     // Special case, #-0 is INT32_MIN.
1169     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1170   }
1171   bool isAddrMode5() const {
1172     // If we have an immediate that's not a constant, treat it as a label
1173     // reference needing a fixup. If it is a constant, it's something else
1174     // and we reject it.
1175     if (isImm() && !isa<MCConstantExpr>(getImm()))
1176       return true;
1177     if (!isMem() || Memory.Alignment != 0) return false;
1178     // Check for register offset.
1179     if (Memory.OffsetRegNum) return false;
1180     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1181     if (!Memory.OffsetImm) return true;
1182     int64_t Val = Memory.OffsetImm->getValue();
1183     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1184       Val == INT32_MIN;
1185   }
1186   bool isMemTBB() const {
1187     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1188         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1189       return false;
1190     return true;
1191   }
1192   bool isMemTBH() const {
1193     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1194         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1195         Memory.Alignment != 0 )
1196       return false;
1197     return true;
1198   }
1199   bool isMemRegOffset() const {
1200     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1201       return false;
1202     return true;
1203   }
1204   bool isT2MemRegOffset() const {
1205     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1206         Memory.Alignment != 0)
1207       return false;
1208     // Only lsl #{0, 1, 2, 3} allowed.
1209     if (Memory.ShiftType == ARM_AM::no_shift)
1210       return true;
1211     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1212       return false;
1213     return true;
1214   }
1215   bool isMemThumbRR() const {
1216     // Thumb reg+reg addressing is simple. Just two registers, a base and
1217     // an offset. No shifts, negations or any other complicating factors.
1218     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1219         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1220       return false;
1221     return isARMLowRegister(Memory.BaseRegNum) &&
1222       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1223   }
1224   bool isMemThumbRIs4() const {
1225     if (!isMem() || Memory.OffsetRegNum != 0 ||
1226         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1227       return false;
1228     // Immediate offset, multiple of 4 in range [0, 124].
1229     if (!Memory.OffsetImm) return true;
1230     int64_t Val = Memory.OffsetImm->getValue();
1231     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1232   }
1233   bool isMemThumbRIs2() const {
1234     if (!isMem() || Memory.OffsetRegNum != 0 ||
1235         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1236       return false;
1237     // Immediate offset, multiple of 4 in range [0, 62].
1238     if (!Memory.OffsetImm) return true;
1239     int64_t Val = Memory.OffsetImm->getValue();
1240     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1241   }
1242   bool isMemThumbRIs1() const {
1243     if (!isMem() || Memory.OffsetRegNum != 0 ||
1244         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1245       return false;
1246     // Immediate offset in range [0, 31].
1247     if (!Memory.OffsetImm) return true;
1248     int64_t Val = Memory.OffsetImm->getValue();
1249     return Val >= 0 && Val <= 31;
1250   }
1251   bool isMemThumbSPI() const {
1252     if (!isMem() || Memory.OffsetRegNum != 0 ||
1253         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1254       return false;
1255     // Immediate offset, multiple of 4 in range [0, 1020].
1256     if (!Memory.OffsetImm) return true;
1257     int64_t Val = Memory.OffsetImm->getValue();
1258     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1259   }
1260   bool isMemImm8s4Offset() const {
1261     // If we have an immediate that's not a constant, treat it as a label
1262     // reference needing a fixup. If it is a constant, it's something else
1263     // and we reject it.
1264     if (isImm() && !isa<MCConstantExpr>(getImm()))
1265       return true;
1266     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1267       return false;
1268     // Immediate offset a multiple of 4 in range [-1020, 1020].
1269     if (!Memory.OffsetImm) return true;
1270     int64_t Val = Memory.OffsetImm->getValue();
1271     // Special case, #-0 is INT32_MIN.
1272     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1273   }
1274   bool isMemImm0_1020s4Offset() const {
1275     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1276       return false;
1277     // Immediate offset a multiple of 4 in range [0, 1020].
1278     if (!Memory.OffsetImm) return true;
1279     int64_t Val = Memory.OffsetImm->getValue();
1280     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1281   }
1282   bool isMemImm8Offset() const {
1283     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1284       return false;
1285     // Base reg of PC isn't allowed for these encodings.
1286     if (Memory.BaseRegNum == ARM::PC) return false;
1287     // Immediate offset in range [-255, 255].
1288     if (!Memory.OffsetImm) return true;
1289     int64_t Val = Memory.OffsetImm->getValue();
1290     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1291   }
1292   bool isMemPosImm8Offset() const {
1293     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1294       return false;
1295     // Immediate offset in range [0, 255].
1296     if (!Memory.OffsetImm) return true;
1297     int64_t Val = Memory.OffsetImm->getValue();
1298     return Val >= 0 && Val < 256;
1299   }
1300   bool isMemNegImm8Offset() const {
1301     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1302       return false;
1303     // Base reg of PC isn't allowed for these encodings.
1304     if (Memory.BaseRegNum == ARM::PC) return false;
1305     // Immediate offset in range [-255, -1].
1306     if (!Memory.OffsetImm) return false;
1307     int64_t Val = Memory.OffsetImm->getValue();
1308     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1309   }
1310   bool isMemUImm12Offset() const {
1311     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1312       return false;
1313     // Immediate offset in range [0, 4095].
1314     if (!Memory.OffsetImm) return true;
1315     int64_t Val = Memory.OffsetImm->getValue();
1316     return (Val >= 0 && Val < 4096);
1317   }
1318   bool isMemImm12Offset() const {
1319     // If we have an immediate that's not a constant, treat it as a label
1320     // reference needing a fixup. If it is a constant, it's something else
1321     // and we reject it.
1322     if (isImm() && !isa<MCConstantExpr>(getImm()))
1323       return true;
1324
1325     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1326       return false;
1327     // Immediate offset in range [-4095, 4095].
1328     if (!Memory.OffsetImm) return true;
1329     int64_t Val = Memory.OffsetImm->getValue();
1330     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1331   }
1332   bool isPostIdxImm8() const {
1333     if (!isImm()) return false;
1334     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1335     if (!CE) return false;
1336     int64_t Val = CE->getValue();
1337     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1338   }
1339   bool isPostIdxImm8s4() const {
1340     if (!isImm()) return false;
1341     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1342     if (!CE) return false;
1343     int64_t Val = CE->getValue();
1344     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1345       (Val == INT32_MIN);
1346   }
1347
1348   bool isMSRMask() const { return Kind == k_MSRMask; }
1349   bool isBankedReg() const { return Kind == k_BankedReg; }
1350   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1351
1352   // NEON operands.
1353   bool isSingleSpacedVectorList() const {
1354     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1355   }
1356   bool isDoubleSpacedVectorList() const {
1357     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1358   }
1359   bool isVecListOneD() const {
1360     if (!isSingleSpacedVectorList()) return false;
1361     return VectorList.Count == 1;
1362   }
1363
1364   bool isVecListDPair() const {
1365     if (!isSingleSpacedVectorList()) return false;
1366     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1367               .contains(VectorList.RegNum));
1368   }
1369
1370   bool isVecListThreeD() const {
1371     if (!isSingleSpacedVectorList()) return false;
1372     return VectorList.Count == 3;
1373   }
1374
1375   bool isVecListFourD() const {
1376     if (!isSingleSpacedVectorList()) return false;
1377     return VectorList.Count == 4;
1378   }
1379
1380   bool isVecListDPairSpaced() const {
1381     if (Kind != k_VectorList) return false;
1382     if (isSingleSpacedVectorList()) return false;
1383     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1384               .contains(VectorList.RegNum));
1385   }
1386
1387   bool isVecListThreeQ() const {
1388     if (!isDoubleSpacedVectorList()) return false;
1389     return VectorList.Count == 3;
1390   }
1391
1392   bool isVecListFourQ() const {
1393     if (!isDoubleSpacedVectorList()) return false;
1394     return VectorList.Count == 4;
1395   }
1396
1397   bool isSingleSpacedVectorAllLanes() const {
1398     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1399   }
1400   bool isDoubleSpacedVectorAllLanes() const {
1401     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1402   }
1403   bool isVecListOneDAllLanes() const {
1404     if (!isSingleSpacedVectorAllLanes()) return false;
1405     return VectorList.Count == 1;
1406   }
1407
1408   bool isVecListDPairAllLanes() const {
1409     if (!isSingleSpacedVectorAllLanes()) return false;
1410     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1411               .contains(VectorList.RegNum));
1412   }
1413
1414   bool isVecListDPairSpacedAllLanes() const {
1415     if (!isDoubleSpacedVectorAllLanes()) return false;
1416     return VectorList.Count == 2;
1417   }
1418
1419   bool isVecListThreeDAllLanes() const {
1420     if (!isSingleSpacedVectorAllLanes()) return false;
1421     return VectorList.Count == 3;
1422   }
1423
1424   bool isVecListThreeQAllLanes() const {
1425     if (!isDoubleSpacedVectorAllLanes()) return false;
1426     return VectorList.Count == 3;
1427   }
1428
1429   bool isVecListFourDAllLanes() const {
1430     if (!isSingleSpacedVectorAllLanes()) return false;
1431     return VectorList.Count == 4;
1432   }
1433
1434   bool isVecListFourQAllLanes() const {
1435     if (!isDoubleSpacedVectorAllLanes()) return false;
1436     return VectorList.Count == 4;
1437   }
1438
1439   bool isSingleSpacedVectorIndexed() const {
1440     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1441   }
1442   bool isDoubleSpacedVectorIndexed() const {
1443     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1444   }
1445   bool isVecListOneDByteIndexed() const {
1446     if (!isSingleSpacedVectorIndexed()) return false;
1447     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1448   }
1449
1450   bool isVecListOneDHWordIndexed() const {
1451     if (!isSingleSpacedVectorIndexed()) return false;
1452     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1453   }
1454
1455   bool isVecListOneDWordIndexed() const {
1456     if (!isSingleSpacedVectorIndexed()) return false;
1457     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1458   }
1459
1460   bool isVecListTwoDByteIndexed() const {
1461     if (!isSingleSpacedVectorIndexed()) return false;
1462     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1463   }
1464
1465   bool isVecListTwoDHWordIndexed() const {
1466     if (!isSingleSpacedVectorIndexed()) return false;
1467     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1468   }
1469
1470   bool isVecListTwoQWordIndexed() const {
1471     if (!isDoubleSpacedVectorIndexed()) return false;
1472     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1473   }
1474
1475   bool isVecListTwoQHWordIndexed() const {
1476     if (!isDoubleSpacedVectorIndexed()) return false;
1477     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1478   }
1479
1480   bool isVecListTwoDWordIndexed() const {
1481     if (!isSingleSpacedVectorIndexed()) return false;
1482     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1483   }
1484
1485   bool isVecListThreeDByteIndexed() const {
1486     if (!isSingleSpacedVectorIndexed()) return false;
1487     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1488   }
1489
1490   bool isVecListThreeDHWordIndexed() const {
1491     if (!isSingleSpacedVectorIndexed()) return false;
1492     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1493   }
1494
1495   bool isVecListThreeQWordIndexed() const {
1496     if (!isDoubleSpacedVectorIndexed()) return false;
1497     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1498   }
1499
1500   bool isVecListThreeQHWordIndexed() const {
1501     if (!isDoubleSpacedVectorIndexed()) return false;
1502     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1503   }
1504
1505   bool isVecListThreeDWordIndexed() const {
1506     if (!isSingleSpacedVectorIndexed()) return false;
1507     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1508   }
1509
1510   bool isVecListFourDByteIndexed() const {
1511     if (!isSingleSpacedVectorIndexed()) return false;
1512     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1513   }
1514
1515   bool isVecListFourDHWordIndexed() const {
1516     if (!isSingleSpacedVectorIndexed()) return false;
1517     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1518   }
1519
1520   bool isVecListFourQWordIndexed() const {
1521     if (!isDoubleSpacedVectorIndexed()) return false;
1522     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1523   }
1524
1525   bool isVecListFourQHWordIndexed() const {
1526     if (!isDoubleSpacedVectorIndexed()) return false;
1527     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1528   }
1529
1530   bool isVecListFourDWordIndexed() const {
1531     if (!isSingleSpacedVectorIndexed()) return false;
1532     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1533   }
1534
1535   bool isVectorIndex8() const {
1536     if (Kind != k_VectorIndex) return false;
1537     return VectorIndex.Val < 8;
1538   }
1539   bool isVectorIndex16() const {
1540     if (Kind != k_VectorIndex) return false;
1541     return VectorIndex.Val < 4;
1542   }
1543   bool isVectorIndex32() const {
1544     if (Kind != k_VectorIndex) return false;
1545     return VectorIndex.Val < 2;
1546   }
1547
1548   bool isNEONi8splat() const {
1549     if (!isImm()) return false;
1550     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1551     // Must be a constant.
1552     if (!CE) return false;
1553     int64_t Value = CE->getValue();
1554     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1555     // value.
1556     return Value >= 0 && Value < 256;
1557   }
1558
1559   bool isNEONi16splat() const {
1560     if (isNEONByteReplicate(2))
1561       return false; // Leave that for bytes replication and forbid by default.
1562     if (!isImm())
1563       return false;
1564     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1565     // Must be a constant.
1566     if (!CE) return false;
1567     unsigned Value = CE->getValue();
1568     return ARM_AM::isNEONi16splat(Value);
1569   }
1570
1571   bool isNEONi16splatNot() const {
1572     if (!isImm())
1573       return false;
1574     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1575     // Must be a constant.
1576     if (!CE) return false;
1577     unsigned Value = CE->getValue();
1578     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1579   }
1580
1581   bool isNEONi32splat() const {
1582     if (isNEONByteReplicate(4))
1583       return false; // Leave that for bytes replication and forbid by default.
1584     if (!isImm())
1585       return false;
1586     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1587     // Must be a constant.
1588     if (!CE) return false;
1589     unsigned Value = CE->getValue();
1590     return ARM_AM::isNEONi32splat(Value);
1591   }
1592
1593   bool isNEONi32splatNot() const {
1594     if (!isImm())
1595       return false;
1596     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1597     // Must be a constant.
1598     if (!CE) return false;
1599     unsigned Value = CE->getValue();
1600     return ARM_AM::isNEONi32splat(~Value);
1601   }
1602
1603   bool isNEONByteReplicate(unsigned NumBytes) const {
1604     if (!isImm())
1605       return false;
1606     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1607     // Must be a constant.
1608     if (!CE)
1609       return false;
1610     int64_t Value = CE->getValue();
1611     if (!Value)
1612       return false; // Don't bother with zero.
1613
1614     unsigned char B = Value & 0xff;
1615     for (unsigned i = 1; i < NumBytes; ++i) {
1616       Value >>= 8;
1617       if ((Value & 0xff) != B)
1618         return false;
1619     }
1620     return true;
1621   }
1622   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1623   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1624   bool isNEONi32vmov() const {
1625     if (isNEONByteReplicate(4))
1626       return false; // Let it to be classified as byte-replicate case.
1627     if (!isImm())
1628       return false;
1629     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1630     // Must be a constant.
1631     if (!CE)
1632       return false;
1633     int64_t Value = CE->getValue();
1634     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1635     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1636     // FIXME: This is probably wrong and a copy and paste from previous example
1637     return (Value >= 0 && Value < 256) ||
1638       (Value >= 0x0100 && Value <= 0xff00) ||
1639       (Value >= 0x010000 && Value <= 0xff0000) ||
1640       (Value >= 0x01000000 && Value <= 0xff000000) ||
1641       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1642       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1643   }
1644   bool isNEONi32vmovNeg() const {
1645     if (!isImm()) return false;
1646     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1647     // Must be a constant.
1648     if (!CE) return false;
1649     int64_t Value = ~CE->getValue();
1650     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1651     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1652     // FIXME: This is probably wrong and a copy and paste from previous example
1653     return (Value >= 0 && Value < 256) ||
1654       (Value >= 0x0100 && Value <= 0xff00) ||
1655       (Value >= 0x010000 && Value <= 0xff0000) ||
1656       (Value >= 0x01000000 && Value <= 0xff000000) ||
1657       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1658       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1659   }
1660
1661   bool isNEONi64splat() const {
1662     if (!isImm()) return false;
1663     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1664     // Must be a constant.
1665     if (!CE) return false;
1666     uint64_t Value = CE->getValue();
1667     // i64 value with each byte being either 0 or 0xff.
1668     for (unsigned i = 0; i < 8; ++i)
1669       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1670     return true;
1671   }
1672
1673   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1674     // Add as immediates when possible.  Null MCExpr = 0.
1675     if (!Expr)
1676       Inst.addOperand(MCOperand::createImm(0));
1677     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1678       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1679     else
1680       Inst.addOperand(MCOperand::createExpr(Expr));
1681   }
1682
1683   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1684     assert(N == 2 && "Invalid number of operands!");
1685     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1686     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1687     Inst.addOperand(MCOperand::createReg(RegNum));
1688   }
1689
1690   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1691     assert(N == 1 && "Invalid number of operands!");
1692     Inst.addOperand(MCOperand::createImm(getCoproc()));
1693   }
1694
1695   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1696     assert(N == 1 && "Invalid number of operands!");
1697     Inst.addOperand(MCOperand::createImm(getCoproc()));
1698   }
1699
1700   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1701     assert(N == 1 && "Invalid number of operands!");
1702     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1703   }
1704
1705   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1706     assert(N == 1 && "Invalid number of operands!");
1707     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1708   }
1709
1710   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1711     assert(N == 1 && "Invalid number of operands!");
1712     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1713   }
1714
1715   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1716     assert(N == 1 && "Invalid number of operands!");
1717     Inst.addOperand(MCOperand::createReg(getReg()));
1718   }
1719
1720   void addRegOperands(MCInst &Inst, unsigned N) const {
1721     assert(N == 1 && "Invalid number of operands!");
1722     Inst.addOperand(MCOperand::createReg(getReg()));
1723   }
1724
1725   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1726     assert(N == 3 && "Invalid number of operands!");
1727     assert(isRegShiftedReg() &&
1728            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1729     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1730     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1731     Inst.addOperand(MCOperand::createImm(
1732       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1733   }
1734
1735   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1736     assert(N == 2 && "Invalid number of operands!");
1737     assert(isRegShiftedImm() &&
1738            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1739     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1740     // Shift of #32 is encoded as 0 where permitted
1741     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1742     Inst.addOperand(MCOperand::createImm(
1743       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1744   }
1745
1746   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1747     assert(N == 1 && "Invalid number of operands!");
1748     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1749                                          ShifterImm.Imm));
1750   }
1751
1752   void addRegListOperands(MCInst &Inst, unsigned N) const {
1753     assert(N == 1 && "Invalid number of operands!");
1754     const SmallVectorImpl<unsigned> &RegList = getRegList();
1755     for (SmallVectorImpl<unsigned>::const_iterator
1756            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1757       Inst.addOperand(MCOperand::createReg(*I));
1758   }
1759
1760   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1761     addRegListOperands(Inst, N);
1762   }
1763
1764   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1765     addRegListOperands(Inst, N);
1766   }
1767
1768   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1769     assert(N == 1 && "Invalid number of operands!");
1770     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1771     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1772   }
1773
1774   void addModImmOperands(MCInst &Inst, unsigned N) const {
1775     assert(N == 1 && "Invalid number of operands!");
1776
1777     // Support for fixups (MCFixup)
1778     if (isImm())
1779       return addImmOperands(Inst, N);
1780
1781     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
1782   }
1783
1784   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1785     assert(N == 1 && "Invalid number of operands!");
1786     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1787     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1788     Inst.addOperand(MCOperand::createImm(Enc));
1789   }
1790
1791   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1792     assert(N == 1 && "Invalid number of operands!");
1793     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1794     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1795     Inst.addOperand(MCOperand::createImm(Enc));
1796   }
1797
1798   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1799     assert(N == 1 && "Invalid number of operands!");
1800     // Munge the lsb/width into a bitfield mask.
1801     unsigned lsb = Bitfield.LSB;
1802     unsigned width = Bitfield.Width;
1803     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1804     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1805                       (32 - (lsb + width)));
1806     Inst.addOperand(MCOperand::createImm(Mask));
1807   }
1808
1809   void addImmOperands(MCInst &Inst, unsigned N) const {
1810     assert(N == 1 && "Invalid number of operands!");
1811     addExpr(Inst, getImm());
1812   }
1813
1814   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1815     assert(N == 1 && "Invalid number of operands!");
1816     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1817     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
1818   }
1819
1820   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1821     assert(N == 1 && "Invalid number of operands!");
1822     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1823     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
1824   }
1825
1826   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1827     assert(N == 1 && "Invalid number of operands!");
1828     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1829     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1830     Inst.addOperand(MCOperand::createImm(Val));
1831   }
1832
1833   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1834     assert(N == 1 && "Invalid number of operands!");
1835     // FIXME: We really want to scale the value here, but the LDRD/STRD
1836     // instruction don't encode operands that way yet.
1837     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1838     Inst.addOperand(MCOperand::createImm(CE->getValue()));
1839   }
1840
1841   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1842     assert(N == 1 && "Invalid number of operands!");
1843     // The immediate is scaled by four in the encoding and is stored
1844     // in the MCInst as such. Lop off the low two bits here.
1845     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1846     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1847   }
1848
1849   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1850     assert(N == 1 && "Invalid number of operands!");
1851     // The immediate is scaled by four in the encoding and is stored
1852     // in the MCInst as such. Lop off the low two bits here.
1853     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1854     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
1855   }
1856
1857   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1858     assert(N == 1 && "Invalid number of operands!");
1859     // The immediate is scaled by four in the encoding and is stored
1860     // in the MCInst as such. Lop off the low two bits here.
1861     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1862     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
1863   }
1864
1865   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1866     assert(N == 1 && "Invalid number of operands!");
1867     // The constant encodes as the immediate-1, and we store in the instruction
1868     // the bits as encoded, so subtract off one here.
1869     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1870     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1871   }
1872
1873   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1874     assert(N == 1 && "Invalid number of operands!");
1875     // The constant encodes as the immediate-1, and we store in the instruction
1876     // the bits as encoded, so subtract off one here.
1877     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1878     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
1879   }
1880
1881   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1882     assert(N == 1 && "Invalid number of operands!");
1883     // The constant encodes as the immediate, except for 32, which encodes as
1884     // zero.
1885     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1886     unsigned Imm = CE->getValue();
1887     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
1888   }
1889
1890   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1891     assert(N == 1 && "Invalid number of operands!");
1892     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1893     // the instruction as well.
1894     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1895     int Val = CE->getValue();
1896     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
1897   }
1898
1899   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
1900     assert(N == 1 && "Invalid number of operands!");
1901     // The operand is actually a t2_so_imm, but we have its bitwise
1902     // negation in the assembly source, so twiddle it here.
1903     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1904     Inst.addOperand(MCOperand::createImm(~CE->getValue()));
1905   }
1906
1907   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
1908     assert(N == 1 && "Invalid number of operands!");
1909     // The operand is actually a t2_so_imm, but we have its
1910     // negation in the assembly source, so twiddle it here.
1911     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1912     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1913   }
1914
1915   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
1916     assert(N == 1 && "Invalid number of operands!");
1917     // The operand is actually an imm0_4095, but we have its
1918     // negation in the assembly source, so twiddle it here.
1919     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1920     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
1921   }
1922
1923   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
1924     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
1925       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
1926       return;
1927     }
1928
1929     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1930     assert(SR && "Unknown value type!");
1931     Inst.addOperand(MCOperand::createExpr(SR));
1932   }
1933
1934   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
1935     assert(N == 1 && "Invalid number of operands!");
1936     if (isImm()) {
1937       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1938       if (CE) {
1939         Inst.addOperand(MCOperand::createImm(CE->getValue()));
1940         return;
1941       }
1942
1943       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
1944       assert(SR && "Unknown value type!");
1945       Inst.addOperand(MCOperand::createExpr(SR));
1946       return;
1947     }
1948
1949     assert(isMem()  && "Unknown value type!");
1950     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
1951     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
1952   }
1953
1954   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
1955     assert(N == 1 && "Invalid number of operands!");
1956     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
1957   }
1958
1959   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
1960     assert(N == 1 && "Invalid number of operands!");
1961     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
1962   }
1963
1964   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
1965     assert(N == 1 && "Invalid number of operands!");
1966     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
1967   }
1968
1969   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
1970     assert(N == 1 && "Invalid number of operands!");
1971     int32_t Imm = Memory.OffsetImm->getValue();
1972     Inst.addOperand(MCOperand::createImm(Imm));
1973   }
1974
1975   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
1976     assert(N == 1 && "Invalid number of operands!");
1977     assert(isImm() && "Not an immediate!");
1978
1979     // If we have an immediate that's not a constant, treat it as a label
1980     // reference needing a fixup. 
1981     if (!isa<MCConstantExpr>(getImm())) {
1982       Inst.addOperand(MCOperand::createExpr(getImm()));
1983       return;
1984     }
1985
1986     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1987     int Val = CE->getValue();
1988     Inst.addOperand(MCOperand::createImm(Val));
1989   }
1990
1991   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
1992     assert(N == 2 && "Invalid number of operands!");
1993     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
1994     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
1995   }
1996
1997   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
1998     addAlignedMemoryOperands(Inst, N);
1999   }
2000
2001   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2002     addAlignedMemoryOperands(Inst, N);
2003   }
2004
2005   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2006     addAlignedMemoryOperands(Inst, N);
2007   }
2008
2009   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2010     addAlignedMemoryOperands(Inst, N);
2011   }
2012
2013   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2014     addAlignedMemoryOperands(Inst, N);
2015   }
2016
2017   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2018     addAlignedMemoryOperands(Inst, N);
2019   }
2020
2021   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2022     addAlignedMemoryOperands(Inst, N);
2023   }
2024
2025   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2026     addAlignedMemoryOperands(Inst, N);
2027   }
2028
2029   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2030     addAlignedMemoryOperands(Inst, N);
2031   }
2032
2033   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2034     addAlignedMemoryOperands(Inst, N);
2035   }
2036
2037   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2038     addAlignedMemoryOperands(Inst, N);
2039   }
2040
2041   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2042     assert(N == 3 && "Invalid number of operands!");
2043     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2044     if (!Memory.OffsetRegNum) {
2045       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2046       // Special case for #-0
2047       if (Val == INT32_MIN) Val = 0;
2048       if (Val < 0) Val = -Val;
2049       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2050     } else {
2051       // For register offset, we encode the shift type and negation flag
2052       // here.
2053       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2054                               Memory.ShiftImm, Memory.ShiftType);
2055     }
2056     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2057     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2058     Inst.addOperand(MCOperand::createImm(Val));
2059   }
2060
2061   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2062     assert(N == 2 && "Invalid number of operands!");
2063     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2064     assert(CE && "non-constant AM2OffsetImm operand!");
2065     int32_t Val = CE->getValue();
2066     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2067     // Special case for #-0
2068     if (Val == INT32_MIN) Val = 0;
2069     if (Val < 0) Val = -Val;
2070     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2071     Inst.addOperand(MCOperand::createReg(0));
2072     Inst.addOperand(MCOperand::createImm(Val));
2073   }
2074
2075   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2076     assert(N == 3 && "Invalid number of operands!");
2077     // If we have an immediate that's not a constant, treat it as a label
2078     // reference needing a fixup. If it is a constant, it's something else
2079     // and we reject it.
2080     if (isImm()) {
2081       Inst.addOperand(MCOperand::createExpr(getImm()));
2082       Inst.addOperand(MCOperand::createReg(0));
2083       Inst.addOperand(MCOperand::createImm(0));
2084       return;
2085     }
2086
2087     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2088     if (!Memory.OffsetRegNum) {
2089       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2090       // Special case for #-0
2091       if (Val == INT32_MIN) Val = 0;
2092       if (Val < 0) Val = -Val;
2093       Val = ARM_AM::getAM3Opc(AddSub, Val);
2094     } else {
2095       // For register offset, we encode the shift type and negation flag
2096       // here.
2097       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2098     }
2099     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2100     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2101     Inst.addOperand(MCOperand::createImm(Val));
2102   }
2103
2104   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2105     assert(N == 2 && "Invalid number of operands!");
2106     if (Kind == k_PostIndexRegister) {
2107       int32_t Val =
2108         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2109       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2110       Inst.addOperand(MCOperand::createImm(Val));
2111       return;
2112     }
2113
2114     // Constant offset.
2115     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2116     int32_t Val = CE->getValue();
2117     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2118     // Special case for #-0
2119     if (Val == INT32_MIN) Val = 0;
2120     if (Val < 0) Val = -Val;
2121     Val = ARM_AM::getAM3Opc(AddSub, Val);
2122     Inst.addOperand(MCOperand::createReg(0));
2123     Inst.addOperand(MCOperand::createImm(Val));
2124   }
2125
2126   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2127     assert(N == 2 && "Invalid number of operands!");
2128     // If we have an immediate that's not a constant, treat it as a label
2129     // reference needing a fixup. If it is a constant, it's something else
2130     // and we reject it.
2131     if (isImm()) {
2132       Inst.addOperand(MCOperand::createExpr(getImm()));
2133       Inst.addOperand(MCOperand::createImm(0));
2134       return;
2135     }
2136
2137     // The lower two bits are always zero and as such are not encoded.
2138     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2139     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2140     // Special case for #-0
2141     if (Val == INT32_MIN) Val = 0;
2142     if (Val < 0) Val = -Val;
2143     Val = ARM_AM::getAM5Opc(AddSub, Val);
2144     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2145     Inst.addOperand(MCOperand::createImm(Val));
2146   }
2147
2148   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2149     assert(N == 2 && "Invalid number of operands!");
2150     // If we have an immediate that's not a constant, treat it as a label
2151     // reference needing a fixup. If it is a constant, it's something else
2152     // and we reject it.
2153     if (isImm()) {
2154       Inst.addOperand(MCOperand::createExpr(getImm()));
2155       Inst.addOperand(MCOperand::createImm(0));
2156       return;
2157     }
2158
2159     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2160     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2161     Inst.addOperand(MCOperand::createImm(Val));
2162   }
2163
2164   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2165     assert(N == 2 && "Invalid number of operands!");
2166     // The lower two bits are always zero and as such are not encoded.
2167     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2168     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2169     Inst.addOperand(MCOperand::createImm(Val));
2170   }
2171
2172   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2173     assert(N == 2 && "Invalid number of operands!");
2174     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2175     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2176     Inst.addOperand(MCOperand::createImm(Val));
2177   }
2178
2179   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2180     addMemImm8OffsetOperands(Inst, N);
2181   }
2182
2183   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2184     addMemImm8OffsetOperands(Inst, N);
2185   }
2186
2187   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2188     assert(N == 2 && "Invalid number of operands!");
2189     // If this is an immediate, it's a label reference.
2190     if (isImm()) {
2191       addExpr(Inst, getImm());
2192       Inst.addOperand(MCOperand::createImm(0));
2193       return;
2194     }
2195
2196     // Otherwise, it's a normal memory reg+offset.
2197     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2198     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2199     Inst.addOperand(MCOperand::createImm(Val));
2200   }
2201
2202   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2203     assert(N == 2 && "Invalid number of operands!");
2204     // If this is an immediate, it's a label reference.
2205     if (isImm()) {
2206       addExpr(Inst, getImm());
2207       Inst.addOperand(MCOperand::createImm(0));
2208       return;
2209     }
2210
2211     // Otherwise, it's a normal memory reg+offset.
2212     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2213     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2214     Inst.addOperand(MCOperand::createImm(Val));
2215   }
2216
2217   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2218     assert(N == 2 && "Invalid number of operands!");
2219     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2220     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2221   }
2222
2223   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2224     assert(N == 2 && "Invalid number of operands!");
2225     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2226     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2227   }
2228
2229   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2230     assert(N == 3 && "Invalid number of operands!");
2231     unsigned Val =
2232       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2233                         Memory.ShiftImm, Memory.ShiftType);
2234     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2235     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2236     Inst.addOperand(MCOperand::createImm(Val));
2237   }
2238
2239   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2240     assert(N == 3 && "Invalid number of operands!");
2241     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2242     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2243     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2244   }
2245
2246   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2247     assert(N == 2 && "Invalid number of operands!");
2248     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2249     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2250   }
2251
2252   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2253     assert(N == 2 && "Invalid number of operands!");
2254     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2255     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2256     Inst.addOperand(MCOperand::createImm(Val));
2257   }
2258
2259   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2260     assert(N == 2 && "Invalid number of operands!");
2261     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2262     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2263     Inst.addOperand(MCOperand::createImm(Val));
2264   }
2265
2266   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2267     assert(N == 2 && "Invalid number of operands!");
2268     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2269     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2270     Inst.addOperand(MCOperand::createImm(Val));
2271   }
2272
2273   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2274     assert(N == 2 && "Invalid number of operands!");
2275     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2276     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2277     Inst.addOperand(MCOperand::createImm(Val));
2278   }
2279
2280   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2281     assert(N == 1 && "Invalid number of operands!");
2282     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2283     assert(CE && "non-constant post-idx-imm8 operand!");
2284     int Imm = CE->getValue();
2285     bool isAdd = Imm >= 0;
2286     if (Imm == INT32_MIN) Imm = 0;
2287     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2288     Inst.addOperand(MCOperand::createImm(Imm));
2289   }
2290
2291   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2292     assert(N == 1 && "Invalid number of operands!");
2293     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2294     assert(CE && "non-constant post-idx-imm8s4 operand!");
2295     int Imm = CE->getValue();
2296     bool isAdd = Imm >= 0;
2297     if (Imm == INT32_MIN) Imm = 0;
2298     // Immediate is scaled by 4.
2299     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2300     Inst.addOperand(MCOperand::createImm(Imm));
2301   }
2302
2303   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2304     assert(N == 2 && "Invalid number of operands!");
2305     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2306     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2307   }
2308
2309   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2310     assert(N == 2 && "Invalid number of operands!");
2311     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2312     // The sign, shift type, and shift amount are encoded in a single operand
2313     // using the AM2 encoding helpers.
2314     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2315     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2316                                      PostIdxReg.ShiftTy);
2317     Inst.addOperand(MCOperand::createImm(Imm));
2318   }
2319
2320   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2321     assert(N == 1 && "Invalid number of operands!");
2322     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2323   }
2324
2325   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2326     assert(N == 1 && "Invalid number of operands!");
2327     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2328   }
2329
2330   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2331     assert(N == 1 && "Invalid number of operands!");
2332     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2333   }
2334
2335   void addVecListOperands(MCInst &Inst, unsigned N) const {
2336     assert(N == 1 && "Invalid number of operands!");
2337     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2338   }
2339
2340   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2341     assert(N == 2 && "Invalid number of operands!");
2342     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2343     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2344   }
2345
2346   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2347     assert(N == 1 && "Invalid number of operands!");
2348     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2349   }
2350
2351   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2352     assert(N == 1 && "Invalid number of operands!");
2353     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2354   }
2355
2356   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2357     assert(N == 1 && "Invalid number of operands!");
2358     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2359   }
2360
2361   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2362     assert(N == 1 && "Invalid number of operands!");
2363     // The immediate encodes the type of constant as well as the value.
2364     // Mask in that this is an i8 splat.
2365     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2366     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2367   }
2368
2369   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2370     assert(N == 1 && "Invalid number of operands!");
2371     // The immediate encodes the type of constant as well as the value.
2372     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2373     unsigned Value = CE->getValue();
2374     Value = ARM_AM::encodeNEONi16splat(Value);
2375     Inst.addOperand(MCOperand::createImm(Value));
2376   }
2377
2378   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2379     assert(N == 1 && "Invalid number of operands!");
2380     // The immediate encodes the type of constant as well as the value.
2381     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2382     unsigned Value = CE->getValue();
2383     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2384     Inst.addOperand(MCOperand::createImm(Value));
2385   }
2386
2387   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2388     assert(N == 1 && "Invalid number of operands!");
2389     // The immediate encodes the type of constant as well as the value.
2390     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2391     unsigned Value = CE->getValue();
2392     Value = ARM_AM::encodeNEONi32splat(Value);
2393     Inst.addOperand(MCOperand::createImm(Value));
2394   }
2395
2396   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2397     assert(N == 1 && "Invalid number of operands!");
2398     // The immediate encodes the type of constant as well as the value.
2399     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2400     unsigned Value = CE->getValue();
2401     Value = ARM_AM::encodeNEONi32splat(~Value);
2402     Inst.addOperand(MCOperand::createImm(Value));
2403   }
2404
2405   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2406     assert(N == 1 && "Invalid number of operands!");
2407     // The immediate encodes the type of constant as well as the value.
2408     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2409     unsigned Value = CE->getValue();
2410     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2411             Inst.getOpcode() == ARM::VMOVv16i8) &&
2412            "All vmvn instructions that wants to replicate non-zero byte "
2413            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2414     unsigned B = ((~Value) & 0xff);
2415     B |= 0xe00; // cmode = 0b1110
2416     Inst.addOperand(MCOperand::createImm(B));
2417   }
2418   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2419     assert(N == 1 && "Invalid number of operands!");
2420     // The immediate encodes the type of constant as well as the value.
2421     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2422     unsigned Value = CE->getValue();
2423     if (Value >= 256 && Value <= 0xffff)
2424       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2425     else if (Value > 0xffff && Value <= 0xffffff)
2426       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2427     else if (Value > 0xffffff)
2428       Value = (Value >> 24) | 0x600;
2429     Inst.addOperand(MCOperand::createImm(Value));
2430   }
2431
2432   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2433     assert(N == 1 && "Invalid number of operands!");
2434     // The immediate encodes the type of constant as well as the value.
2435     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2436     unsigned Value = CE->getValue();
2437     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2438             Inst.getOpcode() == ARM::VMOVv16i8) &&
2439            "All instructions that wants to replicate non-zero byte "
2440            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2441     unsigned B = Value & 0xff;
2442     B |= 0xe00; // cmode = 0b1110
2443     Inst.addOperand(MCOperand::createImm(B));
2444   }
2445   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2446     assert(N == 1 && "Invalid number of operands!");
2447     // The immediate encodes the type of constant as well as the value.
2448     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2449     unsigned Value = ~CE->getValue();
2450     if (Value >= 256 && Value <= 0xffff)
2451       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2452     else if (Value > 0xffff && Value <= 0xffffff)
2453       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2454     else if (Value > 0xffffff)
2455       Value = (Value >> 24) | 0x600;
2456     Inst.addOperand(MCOperand::createImm(Value));
2457   }
2458
2459   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2460     assert(N == 1 && "Invalid number of operands!");
2461     // The immediate encodes the type of constant as well as the value.
2462     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2463     uint64_t Value = CE->getValue();
2464     unsigned Imm = 0;
2465     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2466       Imm |= (Value & 1) << i;
2467     }
2468     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2469   }
2470
2471   void print(raw_ostream &OS) const override;
2472
2473   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2474     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2475     Op->ITMask.Mask = Mask;
2476     Op->StartLoc = S;
2477     Op->EndLoc = S;
2478     return Op;
2479   }
2480
2481   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2482                                                     SMLoc S) {
2483     auto Op = make_unique<ARMOperand>(k_CondCode);
2484     Op->CC.Val = CC;
2485     Op->StartLoc = S;
2486     Op->EndLoc = S;
2487     return Op;
2488   }
2489
2490   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2491     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2492     Op->Cop.Val = CopVal;
2493     Op->StartLoc = S;
2494     Op->EndLoc = S;
2495     return Op;
2496   }
2497
2498   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2499     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2500     Op->Cop.Val = CopVal;
2501     Op->StartLoc = S;
2502     Op->EndLoc = S;
2503     return Op;
2504   }
2505
2506   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2507                                                         SMLoc E) {
2508     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2509     Op->Cop.Val = Val;
2510     Op->StartLoc = S;
2511     Op->EndLoc = E;
2512     return Op;
2513   }
2514
2515   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2516     auto Op = make_unique<ARMOperand>(k_CCOut);
2517     Op->Reg.RegNum = RegNum;
2518     Op->StartLoc = S;
2519     Op->EndLoc = S;
2520     return Op;
2521   }
2522
2523   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2524     auto Op = make_unique<ARMOperand>(k_Token);
2525     Op->Tok.Data = Str.data();
2526     Op->Tok.Length = Str.size();
2527     Op->StartLoc = S;
2528     Op->EndLoc = S;
2529     return Op;
2530   }
2531
2532   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2533                                                SMLoc E) {
2534     auto Op = make_unique<ARMOperand>(k_Register);
2535     Op->Reg.RegNum = RegNum;
2536     Op->StartLoc = S;
2537     Op->EndLoc = E;
2538     return Op;
2539   }
2540
2541   static std::unique_ptr<ARMOperand>
2542   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2543                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2544                         SMLoc E) {
2545     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2546     Op->RegShiftedReg.ShiftTy = ShTy;
2547     Op->RegShiftedReg.SrcReg = SrcReg;
2548     Op->RegShiftedReg.ShiftReg = ShiftReg;
2549     Op->RegShiftedReg.ShiftImm = ShiftImm;
2550     Op->StartLoc = S;
2551     Op->EndLoc = E;
2552     return Op;
2553   }
2554
2555   static std::unique_ptr<ARMOperand>
2556   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2557                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2558     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2559     Op->RegShiftedImm.ShiftTy = ShTy;
2560     Op->RegShiftedImm.SrcReg = SrcReg;
2561     Op->RegShiftedImm.ShiftImm = ShiftImm;
2562     Op->StartLoc = S;
2563     Op->EndLoc = E;
2564     return Op;
2565   }
2566
2567   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2568                                                       SMLoc S, SMLoc E) {
2569     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2570     Op->ShifterImm.isASR = isASR;
2571     Op->ShifterImm.Imm = Imm;
2572     Op->StartLoc = S;
2573     Op->EndLoc = E;
2574     return Op;
2575   }
2576
2577   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2578                                                   SMLoc E) {
2579     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2580     Op->RotImm.Imm = Imm;
2581     Op->StartLoc = S;
2582     Op->EndLoc = E;
2583     return Op;
2584   }
2585
2586   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2587                                                   SMLoc S, SMLoc E) {
2588     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2589     Op->ModImm.Bits = Bits;
2590     Op->ModImm.Rot = Rot;
2591     Op->StartLoc = S;
2592     Op->EndLoc = E;
2593     return Op;
2594   }
2595
2596   static std::unique_ptr<ARMOperand>
2597   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2598     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2599     Op->Bitfield.LSB = LSB;
2600     Op->Bitfield.Width = Width;
2601     Op->StartLoc = S;
2602     Op->EndLoc = E;
2603     return Op;
2604   }
2605
2606   static std::unique_ptr<ARMOperand>
2607   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2608                 SMLoc StartLoc, SMLoc EndLoc) {
2609     assert (Regs.size() > 0 && "RegList contains no registers?");
2610     KindTy Kind = k_RegisterList;
2611
2612     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2613       Kind = k_DPRRegisterList;
2614     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2615              contains(Regs.front().second))
2616       Kind = k_SPRRegisterList;
2617
2618     // Sort based on the register encoding values.
2619     array_pod_sort(Regs.begin(), Regs.end());
2620
2621     auto Op = make_unique<ARMOperand>(Kind);
2622     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2623            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2624       Op->Registers.push_back(I->second);
2625     Op->StartLoc = StartLoc;
2626     Op->EndLoc = EndLoc;
2627     return Op;
2628   }
2629
2630   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2631                                                       unsigned Count,
2632                                                       bool isDoubleSpaced,
2633                                                       SMLoc S, SMLoc E) {
2634     auto Op = make_unique<ARMOperand>(k_VectorList);
2635     Op->VectorList.RegNum = RegNum;
2636     Op->VectorList.Count = Count;
2637     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2638     Op->StartLoc = S;
2639     Op->EndLoc = E;
2640     return Op;
2641   }
2642
2643   static std::unique_ptr<ARMOperand>
2644   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2645                            SMLoc S, SMLoc E) {
2646     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2647     Op->VectorList.RegNum = RegNum;
2648     Op->VectorList.Count = Count;
2649     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2650     Op->StartLoc = S;
2651     Op->EndLoc = E;
2652     return Op;
2653   }
2654
2655   static std::unique_ptr<ARMOperand>
2656   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2657                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2658     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2659     Op->VectorList.RegNum = RegNum;
2660     Op->VectorList.Count = Count;
2661     Op->VectorList.LaneIndex = Index;
2662     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2663     Op->StartLoc = S;
2664     Op->EndLoc = E;
2665     return Op;
2666   }
2667
2668   static std::unique_ptr<ARMOperand>
2669   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2670     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2671     Op->VectorIndex.Val = Idx;
2672     Op->StartLoc = S;
2673     Op->EndLoc = E;
2674     return Op;
2675   }
2676
2677   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2678                                                SMLoc E) {
2679     auto Op = make_unique<ARMOperand>(k_Immediate);
2680     Op->Imm.Val = Val;
2681     Op->StartLoc = S;
2682     Op->EndLoc = E;
2683     return Op;
2684   }
2685
2686   static std::unique_ptr<ARMOperand>
2687   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2688             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2689             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2690             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2691     auto Op = make_unique<ARMOperand>(k_Memory);
2692     Op->Memory.BaseRegNum = BaseRegNum;
2693     Op->Memory.OffsetImm = OffsetImm;
2694     Op->Memory.OffsetRegNum = OffsetRegNum;
2695     Op->Memory.ShiftType = ShiftType;
2696     Op->Memory.ShiftImm = ShiftImm;
2697     Op->Memory.Alignment = Alignment;
2698     Op->Memory.isNegative = isNegative;
2699     Op->StartLoc = S;
2700     Op->EndLoc = E;
2701     Op->AlignmentLoc = AlignmentLoc;
2702     return Op;
2703   }
2704
2705   static std::unique_ptr<ARMOperand>
2706   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2707                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2708     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2709     Op->PostIdxReg.RegNum = RegNum;
2710     Op->PostIdxReg.isAdd = isAdd;
2711     Op->PostIdxReg.ShiftTy = ShiftTy;
2712     Op->PostIdxReg.ShiftImm = ShiftImm;
2713     Op->StartLoc = S;
2714     Op->EndLoc = E;
2715     return Op;
2716   }
2717
2718   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2719                                                          SMLoc S) {
2720     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2721     Op->MBOpt.Val = Opt;
2722     Op->StartLoc = S;
2723     Op->EndLoc = S;
2724     return Op;
2725   }
2726
2727   static std::unique_ptr<ARMOperand>
2728   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2729     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2730     Op->ISBOpt.Val = Opt;
2731     Op->StartLoc = S;
2732     Op->EndLoc = S;
2733     return Op;
2734   }
2735
2736   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2737                                                       SMLoc S) {
2738     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2739     Op->IFlags.Val = IFlags;
2740     Op->StartLoc = S;
2741     Op->EndLoc = S;
2742     return Op;
2743   }
2744
2745   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2746     auto Op = make_unique<ARMOperand>(k_MSRMask);
2747     Op->MMask.Val = MMask;
2748     Op->StartLoc = S;
2749     Op->EndLoc = S;
2750     return Op;
2751   }
2752
2753   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2754     auto Op = make_unique<ARMOperand>(k_BankedReg);
2755     Op->BankedReg.Val = Reg;
2756     Op->StartLoc = S;
2757     Op->EndLoc = S;
2758     return Op;
2759   }
2760 };
2761
2762 } // end anonymous namespace.
2763
2764 void ARMOperand::print(raw_ostream &OS) const {
2765   switch (Kind) {
2766   case k_CondCode:
2767     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2768     break;
2769   case k_CCOut:
2770     OS << "<ccout " << getReg() << ">";
2771     break;
2772   case k_ITCondMask: {
2773     static const char *const MaskStr[] = {
2774       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2775       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2776     };
2777     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2778     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2779     break;
2780   }
2781   case k_CoprocNum:
2782     OS << "<coprocessor number: " << getCoproc() << ">";
2783     break;
2784   case k_CoprocReg:
2785     OS << "<coprocessor register: " << getCoproc() << ">";
2786     break;
2787   case k_CoprocOption:
2788     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2789     break;
2790   case k_MSRMask:
2791     OS << "<mask: " << getMSRMask() << ">";
2792     break;
2793   case k_BankedReg:
2794     OS << "<banked reg: " << getBankedReg() << ">";
2795     break;
2796   case k_Immediate:
2797     OS << *getImm();
2798     break;
2799   case k_MemBarrierOpt:
2800     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2801     break;
2802   case k_InstSyncBarrierOpt:
2803     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2804     break;
2805   case k_Memory:
2806     OS << "<memory "
2807        << " base:" << Memory.BaseRegNum;
2808     OS << ">";
2809     break;
2810   case k_PostIndexRegister:
2811     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2812        << PostIdxReg.RegNum;
2813     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2814       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2815          << PostIdxReg.ShiftImm;
2816     OS << ">";
2817     break;
2818   case k_ProcIFlags: {
2819     OS << "<ARM_PROC::";
2820     unsigned IFlags = getProcIFlags();
2821     for (int i=2; i >= 0; --i)
2822       if (IFlags & (1 << i))
2823         OS << ARM_PROC::IFlagsToString(1 << i);
2824     OS << ">";
2825     break;
2826   }
2827   case k_Register:
2828     OS << "<register " << getReg() << ">";
2829     break;
2830   case k_ShifterImmediate:
2831     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2832        << " #" << ShifterImm.Imm << ">";
2833     break;
2834   case k_ShiftedRegister:
2835     OS << "<so_reg_reg "
2836        << RegShiftedReg.SrcReg << " "
2837        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2838        << " " << RegShiftedReg.ShiftReg << ">";
2839     break;
2840   case k_ShiftedImmediate:
2841     OS << "<so_reg_imm "
2842        << RegShiftedImm.SrcReg << " "
2843        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2844        << " #" << RegShiftedImm.ShiftImm << ">";
2845     break;
2846   case k_RotateImmediate:
2847     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2848     break;
2849   case k_ModifiedImmediate:
2850     OS << "<mod_imm #" << ModImm.Bits << ", #"
2851        <<  ModImm.Rot << ")>";
2852     break;
2853   case k_BitfieldDescriptor:
2854     OS << "<bitfield " << "lsb: " << Bitfield.LSB
2855        << ", width: " << Bitfield.Width << ">";
2856     break;
2857   case k_RegisterList:
2858   case k_DPRRegisterList:
2859   case k_SPRRegisterList: {
2860     OS << "<register_list ";
2861
2862     const SmallVectorImpl<unsigned> &RegList = getRegList();
2863     for (SmallVectorImpl<unsigned>::const_iterator
2864            I = RegList.begin(), E = RegList.end(); I != E; ) {
2865       OS << *I;
2866       if (++I < E) OS << ", ";
2867     }
2868
2869     OS << ">";
2870     break;
2871   }
2872   case k_VectorList:
2873     OS << "<vector_list " << VectorList.Count << " * "
2874        << VectorList.RegNum << ">";
2875     break;
2876   case k_VectorListAllLanes:
2877     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
2878        << VectorList.RegNum << ">";
2879     break;
2880   case k_VectorListIndexed:
2881     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
2882        << VectorList.Count << " * " << VectorList.RegNum << ">";
2883     break;
2884   case k_Token:
2885     OS << "'" << getToken() << "'";
2886     break;
2887   case k_VectorIndex:
2888     OS << "<vectorindex " << getVectorIndex() << ">";
2889     break;
2890   }
2891 }
2892
2893 /// @name Auto-generated Match Functions
2894 /// {
2895
2896 static unsigned MatchRegisterName(StringRef Name);
2897
2898 /// }
2899
2900 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
2901                                  SMLoc &StartLoc, SMLoc &EndLoc) {
2902   const AsmToken &Tok = getParser().getTok();
2903   StartLoc = Tok.getLoc();
2904   EndLoc = Tok.getEndLoc();
2905   RegNo = tryParseRegister();
2906
2907   return (RegNo == (unsigned)-1);
2908 }
2909
2910 /// Try to parse a register name.  The token must be an Identifier when called,
2911 /// and if it is a register name the token is eaten and the register number is
2912 /// returned.  Otherwise return -1.
2913 ///
2914 int ARMAsmParser::tryParseRegister() {
2915   MCAsmParser &Parser = getParser();
2916   const AsmToken &Tok = Parser.getTok();
2917   if (Tok.isNot(AsmToken::Identifier)) return -1;
2918
2919   std::string lowerCase = Tok.getString().lower();
2920   unsigned RegNum = MatchRegisterName(lowerCase);
2921   if (!RegNum) {
2922     RegNum = StringSwitch<unsigned>(lowerCase)
2923       .Case("r13", ARM::SP)
2924       .Case("r14", ARM::LR)
2925       .Case("r15", ARM::PC)
2926       .Case("ip", ARM::R12)
2927       // Additional register name aliases for 'gas' compatibility.
2928       .Case("a1", ARM::R0)
2929       .Case("a2", ARM::R1)
2930       .Case("a3", ARM::R2)
2931       .Case("a4", ARM::R3)
2932       .Case("v1", ARM::R4)
2933       .Case("v2", ARM::R5)
2934       .Case("v3", ARM::R6)
2935       .Case("v4", ARM::R7)
2936       .Case("v5", ARM::R8)
2937       .Case("v6", ARM::R9)
2938       .Case("v7", ARM::R10)
2939       .Case("v8", ARM::R11)
2940       .Case("sb", ARM::R9)
2941       .Case("sl", ARM::R10)
2942       .Case("fp", ARM::R11)
2943       .Default(0);
2944   }
2945   if (!RegNum) {
2946     // Check for aliases registered via .req. Canonicalize to lower case.
2947     // That's more consistent since register names are case insensitive, and
2948     // it's how the original entry was passed in from MC/MCParser/AsmParser.
2949     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
2950     // If no match, return failure.
2951     if (Entry == RegisterReqs.end())
2952       return -1;
2953     Parser.Lex(); // Eat identifier token.
2954     return Entry->getValue();
2955   }
2956
2957   // Some FPUs only have 16 D registers, so D16-D31 are invalid
2958   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
2959     return -1;
2960
2961   Parser.Lex(); // Eat identifier token.
2962
2963   return RegNum;
2964 }
2965
2966 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
2967 // If a recoverable error occurs, return 1. If an irrecoverable error
2968 // occurs, return -1. An irrecoverable error is one where tokens have been
2969 // consumed in the process of trying to parse the shifter (i.e., when it is
2970 // indeed a shifter operand, but malformed).
2971 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
2972   MCAsmParser &Parser = getParser();
2973   SMLoc S = Parser.getTok().getLoc();
2974   const AsmToken &Tok = Parser.getTok();
2975   if (Tok.isNot(AsmToken::Identifier))
2976     return -1; 
2977
2978   std::string lowerCase = Tok.getString().lower();
2979   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
2980       .Case("asl", ARM_AM::lsl)
2981       .Case("lsl", ARM_AM::lsl)
2982       .Case("lsr", ARM_AM::lsr)
2983       .Case("asr", ARM_AM::asr)
2984       .Case("ror", ARM_AM::ror)
2985       .Case("rrx", ARM_AM::rrx)
2986       .Default(ARM_AM::no_shift);
2987
2988   if (ShiftTy == ARM_AM::no_shift)
2989     return 1;
2990
2991   Parser.Lex(); // Eat the operator.
2992
2993   // The source register for the shift has already been added to the
2994   // operand list, so we need to pop it off and combine it into the shifted
2995   // register operand instead.
2996   std::unique_ptr<ARMOperand> PrevOp(
2997       (ARMOperand *)Operands.pop_back_val().release());
2998   if (!PrevOp->isReg())
2999     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3000   int SrcReg = PrevOp->getReg();
3001
3002   SMLoc EndLoc;
3003   int64_t Imm = 0;
3004   int ShiftReg = 0;
3005   if (ShiftTy == ARM_AM::rrx) {
3006     // RRX Doesn't have an explicit shift amount. The encoder expects
3007     // the shift register to be the same as the source register. Seems odd,
3008     // but OK.
3009     ShiftReg = SrcReg;
3010   } else {
3011     // Figure out if this is shifted by a constant or a register (for non-RRX).
3012     if (Parser.getTok().is(AsmToken::Hash) ||
3013         Parser.getTok().is(AsmToken::Dollar)) {
3014       Parser.Lex(); // Eat hash.
3015       SMLoc ImmLoc = Parser.getTok().getLoc();
3016       const MCExpr *ShiftExpr = nullptr;
3017       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3018         Error(ImmLoc, "invalid immediate shift value");
3019         return -1;
3020       }
3021       // The expression must be evaluatable as an immediate.
3022       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3023       if (!CE) {
3024         Error(ImmLoc, "invalid immediate shift value");
3025         return -1;
3026       }
3027       // Range check the immediate.
3028       // lsl, ror: 0 <= imm <= 31
3029       // lsr, asr: 0 <= imm <= 32
3030       Imm = CE->getValue();
3031       if (Imm < 0 ||
3032           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3033           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3034         Error(ImmLoc, "immediate shift value out of range");
3035         return -1;
3036       }
3037       // shift by zero is a nop. Always send it through as lsl.
3038       // ('as' compatibility)
3039       if (Imm == 0)
3040         ShiftTy = ARM_AM::lsl;
3041     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3042       SMLoc L = Parser.getTok().getLoc();
3043       EndLoc = Parser.getTok().getEndLoc();
3044       ShiftReg = tryParseRegister();
3045       if (ShiftReg == -1) {
3046         Error(L, "expected immediate or register in shift operand");
3047         return -1;
3048       }
3049     } else {
3050       Error(Parser.getTok().getLoc(),
3051             "expected immediate or register in shift operand");
3052       return -1;
3053     }
3054   }
3055
3056   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3057     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3058                                                          ShiftReg, Imm,
3059                                                          S, EndLoc));
3060   else
3061     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3062                                                           S, EndLoc));
3063
3064   return 0;
3065 }
3066
3067
3068 /// Try to parse a register name.  The token must be an Identifier when called.
3069 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3070 /// if there is a "writeback". 'true' if it's not a register.
3071 ///
3072 /// TODO this is likely to change to allow different register types and or to
3073 /// parse for a specific register type.
3074 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3075   MCAsmParser &Parser = getParser();
3076   const AsmToken &RegTok = Parser.getTok();
3077   int RegNo = tryParseRegister();
3078   if (RegNo == -1)
3079     return true;
3080
3081   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3082                                            RegTok.getEndLoc()));
3083
3084   const AsmToken &ExclaimTok = Parser.getTok();
3085   if (ExclaimTok.is(AsmToken::Exclaim)) {
3086     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3087                                                ExclaimTok.getLoc()));
3088     Parser.Lex(); // Eat exclaim token
3089     return false;
3090   }
3091
3092   // Also check for an index operand. This is only legal for vector registers,
3093   // but that'll get caught OK in operand matching, so we don't need to
3094   // explicitly filter everything else out here.
3095   if (Parser.getTok().is(AsmToken::LBrac)) {
3096     SMLoc SIdx = Parser.getTok().getLoc();
3097     Parser.Lex(); // Eat left bracket token.
3098
3099     const MCExpr *ImmVal;
3100     if (getParser().parseExpression(ImmVal))
3101       return true;
3102     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3103     if (!MCE)
3104       return TokError("immediate value expected for vector index");
3105
3106     if (Parser.getTok().isNot(AsmToken::RBrac))
3107       return Error(Parser.getTok().getLoc(), "']' expected");
3108
3109     SMLoc E = Parser.getTok().getEndLoc();
3110     Parser.Lex(); // Eat right bracket token.
3111
3112     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3113                                                      SIdx, E,
3114                                                      getContext()));
3115   }
3116
3117   return false;
3118 }
3119
3120 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3121 /// instruction with a symbolic operand name.
3122 /// We accept "crN" syntax for GAS compatibility.
3123 /// <operand-name> ::= <prefix><number>
3124 /// If CoprocOp is 'c', then:
3125 ///   <prefix> ::= c | cr
3126 /// If CoprocOp is 'p', then :
3127 ///   <prefix> ::= p
3128 /// <number> ::= integer in range [0, 15]
3129 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3130   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3131   // but efficient.
3132   if (Name.size() < 2 || Name[0] != CoprocOp)
3133     return -1;
3134   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3135
3136   switch (Name.size()) {
3137   default: return -1;
3138   case 1:
3139     switch (Name[0]) {
3140     default:  return -1;
3141     case '0': return 0;
3142     case '1': return 1;
3143     case '2': return 2;
3144     case '3': return 3;
3145     case '4': return 4;
3146     case '5': return 5;
3147     case '6': return 6;
3148     case '7': return 7;
3149     case '8': return 8;
3150     case '9': return 9;
3151     }
3152   case 2:
3153     if (Name[0] != '1')
3154       return -1;
3155     switch (Name[1]) {
3156     default:  return -1;
3157     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3158     // However, old cores (v5/v6) did use them in that way.
3159     case '0': return 10;
3160     case '1': return 11;
3161     case '2': return 12;
3162     case '3': return 13;
3163     case '4': return 14;
3164     case '5': return 15;
3165     }
3166   }
3167 }
3168
3169 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3170 ARMAsmParser::OperandMatchResultTy
3171 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3172   MCAsmParser &Parser = getParser();
3173   SMLoc S = Parser.getTok().getLoc();
3174   const AsmToken &Tok = Parser.getTok();
3175   if (!Tok.is(AsmToken::Identifier))
3176     return MatchOperand_NoMatch;
3177   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3178     .Case("eq", ARMCC::EQ)
3179     .Case("ne", ARMCC::NE)
3180     .Case("hs", ARMCC::HS)
3181     .Case("cs", ARMCC::HS)
3182     .Case("lo", ARMCC::LO)
3183     .Case("cc", ARMCC::LO)
3184     .Case("mi", ARMCC::MI)
3185     .Case("pl", ARMCC::PL)
3186     .Case("vs", ARMCC::VS)
3187     .Case("vc", ARMCC::VC)
3188     .Case("hi", ARMCC::HI)
3189     .Case("ls", ARMCC::LS)
3190     .Case("ge", ARMCC::GE)
3191     .Case("lt", ARMCC::LT)
3192     .Case("gt", ARMCC::GT)
3193     .Case("le", ARMCC::LE)
3194     .Case("al", ARMCC::AL)
3195     .Default(~0U);
3196   if (CC == ~0U)
3197     return MatchOperand_NoMatch;
3198   Parser.Lex(); // Eat the token.
3199
3200   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3201
3202   return MatchOperand_Success;
3203 }
3204
3205 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3206 /// token must be an Identifier when called, and if it is a coprocessor
3207 /// number, the token is eaten and the operand is added to the operand list.
3208 ARMAsmParser::OperandMatchResultTy
3209 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3210   MCAsmParser &Parser = getParser();
3211   SMLoc S = Parser.getTok().getLoc();
3212   const AsmToken &Tok = Parser.getTok();
3213   if (Tok.isNot(AsmToken::Identifier))
3214     return MatchOperand_NoMatch;
3215
3216   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3217   if (Num == -1)
3218     return MatchOperand_NoMatch;
3219   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3220   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3221     return MatchOperand_NoMatch;
3222
3223   Parser.Lex(); // Eat identifier token.
3224   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3225   return MatchOperand_Success;
3226 }
3227
3228 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3229 /// token must be an Identifier when called, and if it is a coprocessor
3230 /// number, the token is eaten and the operand is added to the operand list.
3231 ARMAsmParser::OperandMatchResultTy
3232 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3233   MCAsmParser &Parser = getParser();
3234   SMLoc S = Parser.getTok().getLoc();
3235   const AsmToken &Tok = Parser.getTok();
3236   if (Tok.isNot(AsmToken::Identifier))
3237     return MatchOperand_NoMatch;
3238
3239   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3240   if (Reg == -1)
3241     return MatchOperand_NoMatch;
3242
3243   Parser.Lex(); // Eat identifier token.
3244   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3245   return MatchOperand_Success;
3246 }
3247
3248 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3249 /// coproc_option : '{' imm0_255 '}'
3250 ARMAsmParser::OperandMatchResultTy
3251 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3252   MCAsmParser &Parser = getParser();
3253   SMLoc S = Parser.getTok().getLoc();
3254
3255   // If this isn't a '{', this isn't a coprocessor immediate operand.
3256   if (Parser.getTok().isNot(AsmToken::LCurly))
3257     return MatchOperand_NoMatch;
3258   Parser.Lex(); // Eat the '{'
3259
3260   const MCExpr *Expr;
3261   SMLoc Loc = Parser.getTok().getLoc();
3262   if (getParser().parseExpression(Expr)) {
3263     Error(Loc, "illegal expression");
3264     return MatchOperand_ParseFail;
3265   }
3266   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3267   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3268     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3269     return MatchOperand_ParseFail;
3270   }
3271   int Val = CE->getValue();
3272
3273   // Check for and consume the closing '}'
3274   if (Parser.getTok().isNot(AsmToken::RCurly))
3275     return MatchOperand_ParseFail;
3276   SMLoc E = Parser.getTok().getEndLoc();
3277   Parser.Lex(); // Eat the '}'
3278
3279   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3280   return MatchOperand_Success;
3281 }
3282
3283 // For register list parsing, we need to map from raw GPR register numbering
3284 // to the enumeration values. The enumeration values aren't sorted by
3285 // register number due to our using "sp", "lr" and "pc" as canonical names.
3286 static unsigned getNextRegister(unsigned Reg) {
3287   // If this is a GPR, we need to do it manually, otherwise we can rely
3288   // on the sort ordering of the enumeration since the other reg-classes
3289   // are sane.
3290   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3291     return Reg + 1;
3292   switch(Reg) {
3293   default: llvm_unreachable("Invalid GPR number!");
3294   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3295   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3296   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3297   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3298   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3299   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3300   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3301   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3302   }
3303 }
3304
3305 // Return the low-subreg of a given Q register.
3306 static unsigned getDRegFromQReg(unsigned QReg) {
3307   switch (QReg) {
3308   default: llvm_unreachable("expected a Q register!");
3309   case ARM::Q0:  return ARM::D0;
3310   case ARM::Q1:  return ARM::D2;
3311   case ARM::Q2:  return ARM::D4;
3312   case ARM::Q3:  return ARM::D6;
3313   case ARM::Q4:  return ARM::D8;
3314   case ARM::Q5:  return ARM::D10;
3315   case ARM::Q6:  return ARM::D12;
3316   case ARM::Q7:  return ARM::D14;
3317   case ARM::Q8:  return ARM::D16;
3318   case ARM::Q9:  return ARM::D18;
3319   case ARM::Q10: return ARM::D20;
3320   case ARM::Q11: return ARM::D22;
3321   case ARM::Q12: return ARM::D24;
3322   case ARM::Q13: return ARM::D26;
3323   case ARM::Q14: return ARM::D28;
3324   case ARM::Q15: return ARM::D30;
3325   }
3326 }
3327
3328 /// Parse a register list.
3329 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3330   MCAsmParser &Parser = getParser();
3331   assert(Parser.getTok().is(AsmToken::LCurly) &&
3332          "Token is not a Left Curly Brace");
3333   SMLoc S = Parser.getTok().getLoc();
3334   Parser.Lex(); // Eat '{' token.
3335   SMLoc RegLoc = Parser.getTok().getLoc();
3336
3337   // Check the first register in the list to see what register class
3338   // this is a list of.
3339   int Reg = tryParseRegister();
3340   if (Reg == -1)
3341     return Error(RegLoc, "register expected");
3342
3343   // The reglist instructions have at most 16 registers, so reserve
3344   // space for that many.
3345   int EReg = 0;
3346   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3347
3348   // Allow Q regs and just interpret them as the two D sub-registers.
3349   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3350     Reg = getDRegFromQReg(Reg);
3351     EReg = MRI->getEncodingValue(Reg);
3352     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3353     ++Reg;
3354   }
3355   const MCRegisterClass *RC;
3356   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3357     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3358   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3359     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3360   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3361     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3362   else
3363     return Error(RegLoc, "invalid register in register list");
3364
3365   // Store the register.
3366   EReg = MRI->getEncodingValue(Reg);
3367   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3368
3369   // This starts immediately after the first register token in the list,
3370   // so we can see either a comma or a minus (range separator) as a legal
3371   // next token.
3372   while (Parser.getTok().is(AsmToken::Comma) ||
3373          Parser.getTok().is(AsmToken::Minus)) {
3374     if (Parser.getTok().is(AsmToken::Minus)) {
3375       Parser.Lex(); // Eat the minus.
3376       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3377       int EndReg = tryParseRegister();
3378       if (EndReg == -1)
3379         return Error(AfterMinusLoc, "register expected");
3380       // Allow Q regs and just interpret them as the two D sub-registers.
3381       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3382         EndReg = getDRegFromQReg(EndReg) + 1;
3383       // If the register is the same as the start reg, there's nothing
3384       // more to do.
3385       if (Reg == EndReg)
3386         continue;
3387       // The register must be in the same register class as the first.
3388       if (!RC->contains(EndReg))
3389         return Error(AfterMinusLoc, "invalid register in register list");
3390       // Ranges must go from low to high.
3391       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3392         return Error(AfterMinusLoc, "bad range in register list");
3393
3394       // Add all the registers in the range to the register list.
3395       while (Reg != EndReg) {
3396         Reg = getNextRegister(Reg);
3397         EReg = MRI->getEncodingValue(Reg);
3398         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3399       }
3400       continue;
3401     }
3402     Parser.Lex(); // Eat the comma.
3403     RegLoc = Parser.getTok().getLoc();
3404     int OldReg = Reg;
3405     const AsmToken RegTok = Parser.getTok();
3406     Reg = tryParseRegister();
3407     if (Reg == -1)
3408       return Error(RegLoc, "register expected");
3409     // Allow Q regs and just interpret them as the two D sub-registers.
3410     bool isQReg = false;
3411     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3412       Reg = getDRegFromQReg(Reg);
3413       isQReg = true;
3414     }
3415     // The register must be in the same register class as the first.
3416     if (!RC->contains(Reg))
3417       return Error(RegLoc, "invalid register in register list");
3418     // List must be monotonically increasing.
3419     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3420       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3421         Warning(RegLoc, "register list not in ascending order");
3422       else
3423         return Error(RegLoc, "register list not in ascending order");
3424     }
3425     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3426       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3427               ") in register list");
3428       continue;
3429     }
3430     // VFP register lists must also be contiguous.
3431     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3432         Reg != OldReg + 1)
3433       return Error(RegLoc, "non-contiguous register range");
3434     EReg = MRI->getEncodingValue(Reg);
3435     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3436     if (isQReg) {
3437       EReg = MRI->getEncodingValue(++Reg);
3438       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3439     }
3440   }
3441
3442   if (Parser.getTok().isNot(AsmToken::RCurly))
3443     return Error(Parser.getTok().getLoc(), "'}' expected");
3444   SMLoc E = Parser.getTok().getEndLoc();
3445   Parser.Lex(); // Eat '}' token.
3446
3447   // Push the register list operand.
3448   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3449
3450   // The ARM system instruction variants for LDM/STM have a '^' token here.
3451   if (Parser.getTok().is(AsmToken::Caret)) {
3452     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3453     Parser.Lex(); // Eat '^' token.
3454   }
3455
3456   return false;
3457 }
3458
3459 // Helper function to parse the lane index for vector lists.
3460 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3461 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3462   MCAsmParser &Parser = getParser();
3463   Index = 0; // Always return a defined index value.
3464   if (Parser.getTok().is(AsmToken::LBrac)) {
3465     Parser.Lex(); // Eat the '['.
3466     if (Parser.getTok().is(AsmToken::RBrac)) {
3467       // "Dn[]" is the 'all lanes' syntax.
3468       LaneKind = AllLanes;
3469       EndLoc = Parser.getTok().getEndLoc();
3470       Parser.Lex(); // Eat the ']'.
3471       return MatchOperand_Success;
3472     }
3473
3474     // There's an optional '#' token here. Normally there wouldn't be, but
3475     // inline assemble puts one in, and it's friendly to accept that.
3476     if (Parser.getTok().is(AsmToken::Hash))
3477       Parser.Lex(); // Eat '#' or '$'.
3478
3479     const MCExpr *LaneIndex;
3480     SMLoc Loc = Parser.getTok().getLoc();
3481     if (getParser().parseExpression(LaneIndex)) {
3482       Error(Loc, "illegal expression");
3483       return MatchOperand_ParseFail;
3484     }
3485     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3486     if (!CE) {
3487       Error(Loc, "lane index must be empty or an integer");
3488       return MatchOperand_ParseFail;
3489     }
3490     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3491       Error(Parser.getTok().getLoc(), "']' expected");
3492       return MatchOperand_ParseFail;
3493     }
3494     EndLoc = Parser.getTok().getEndLoc();
3495     Parser.Lex(); // Eat the ']'.
3496     int64_t Val = CE->getValue();
3497
3498     // FIXME: Make this range check context sensitive for .8, .16, .32.
3499     if (Val < 0 || Val > 7) {
3500       Error(Parser.getTok().getLoc(), "lane index out of range");
3501       return MatchOperand_ParseFail;
3502     }
3503     Index = Val;
3504     LaneKind = IndexedLane;
3505     return MatchOperand_Success;
3506   }
3507   LaneKind = NoLanes;
3508   return MatchOperand_Success;
3509 }
3510
3511 // parse a vector register list
3512 ARMAsmParser::OperandMatchResultTy
3513 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3514   MCAsmParser &Parser = getParser();
3515   VectorLaneTy LaneKind;
3516   unsigned LaneIndex;
3517   SMLoc S = Parser.getTok().getLoc();
3518   // As an extension (to match gas), support a plain D register or Q register
3519   // (without encosing curly braces) as a single or double entry list,
3520   // respectively.
3521   if (Parser.getTok().is(AsmToken::Identifier)) {
3522     SMLoc E = Parser.getTok().getEndLoc();
3523     int Reg = tryParseRegister();
3524     if (Reg == -1)
3525       return MatchOperand_NoMatch;
3526     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3527       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3528       if (Res != MatchOperand_Success)
3529         return Res;
3530       switch (LaneKind) {
3531       case NoLanes:
3532         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3533         break;
3534       case AllLanes:
3535         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3536                                                                 S, E));
3537         break;
3538       case IndexedLane:
3539         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3540                                                                LaneIndex,
3541                                                                false, S, E));
3542         break;
3543       }
3544       return MatchOperand_Success;
3545     }
3546     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3547       Reg = getDRegFromQReg(Reg);
3548       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3549       if (Res != MatchOperand_Success)
3550         return Res;
3551       switch (LaneKind) {
3552       case NoLanes:
3553         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3554                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3555         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3556         break;
3557       case AllLanes:
3558         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3559                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3560         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3561                                                                 S, E));
3562         break;
3563       case IndexedLane:
3564         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3565                                                                LaneIndex,
3566                                                                false, S, E));
3567         break;
3568       }
3569       return MatchOperand_Success;
3570     }
3571     Error(S, "vector register expected");
3572     return MatchOperand_ParseFail;
3573   }
3574
3575   if (Parser.getTok().isNot(AsmToken::LCurly))
3576     return MatchOperand_NoMatch;
3577
3578   Parser.Lex(); // Eat '{' token.
3579   SMLoc RegLoc = Parser.getTok().getLoc();
3580
3581   int Reg = tryParseRegister();
3582   if (Reg == -1) {
3583     Error(RegLoc, "register expected");
3584     return MatchOperand_ParseFail;
3585   }
3586   unsigned Count = 1;
3587   int Spacing = 0;
3588   unsigned FirstReg = Reg;
3589   // The list is of D registers, but we also allow Q regs and just interpret
3590   // them as the two D sub-registers.
3591   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3592     FirstReg = Reg = getDRegFromQReg(Reg);
3593     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3594                  // it's ambiguous with four-register single spaced.
3595     ++Reg;
3596     ++Count;
3597   }
3598
3599   SMLoc E;
3600   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3601     return MatchOperand_ParseFail;
3602
3603   while (Parser.getTok().is(AsmToken::Comma) ||
3604          Parser.getTok().is(AsmToken::Minus)) {
3605     if (Parser.getTok().is(AsmToken::Minus)) {
3606       if (!Spacing)
3607         Spacing = 1; // Register range implies a single spaced list.
3608       else if (Spacing == 2) {
3609         Error(Parser.getTok().getLoc(),
3610               "sequential registers in double spaced list");
3611         return MatchOperand_ParseFail;
3612       }
3613       Parser.Lex(); // Eat the minus.
3614       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3615       int EndReg = tryParseRegister();
3616       if (EndReg == -1) {
3617         Error(AfterMinusLoc, "register expected");
3618         return MatchOperand_ParseFail;
3619       }
3620       // Allow Q regs and just interpret them as the two D sub-registers.
3621       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3622         EndReg = getDRegFromQReg(EndReg) + 1;
3623       // If the register is the same as the start reg, there's nothing
3624       // more to do.
3625       if (Reg == EndReg)
3626         continue;
3627       // The register must be in the same register class as the first.
3628       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3629         Error(AfterMinusLoc, "invalid register in register list");
3630         return MatchOperand_ParseFail;
3631       }
3632       // Ranges must go from low to high.
3633       if (Reg > EndReg) {
3634         Error(AfterMinusLoc, "bad range in register list");
3635         return MatchOperand_ParseFail;
3636       }
3637       // Parse the lane specifier if present.
3638       VectorLaneTy NextLaneKind;
3639       unsigned NextLaneIndex;
3640       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3641           MatchOperand_Success)
3642         return MatchOperand_ParseFail;
3643       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3644         Error(AfterMinusLoc, "mismatched lane index in register list");
3645         return MatchOperand_ParseFail;
3646       }
3647
3648       // Add all the registers in the range to the register list.
3649       Count += EndReg - Reg;
3650       Reg = EndReg;
3651       continue;
3652     }
3653     Parser.Lex(); // Eat the comma.
3654     RegLoc = Parser.getTok().getLoc();
3655     int OldReg = Reg;
3656     Reg = tryParseRegister();
3657     if (Reg == -1) {
3658       Error(RegLoc, "register expected");
3659       return MatchOperand_ParseFail;
3660     }
3661     // vector register lists must be contiguous.
3662     // It's OK to use the enumeration values directly here rather, as the
3663     // VFP register classes have the enum sorted properly.
3664     //
3665     // The list is of D registers, but we also allow Q regs and just interpret
3666     // them as the two D sub-registers.
3667     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3668       if (!Spacing)
3669         Spacing = 1; // Register range implies a single spaced list.
3670       else if (Spacing == 2) {
3671         Error(RegLoc,
3672               "invalid register in double-spaced list (must be 'D' register')");
3673         return MatchOperand_ParseFail;
3674       }
3675       Reg = getDRegFromQReg(Reg);
3676       if (Reg != OldReg + 1) {
3677         Error(RegLoc, "non-contiguous register range");
3678         return MatchOperand_ParseFail;
3679       }
3680       ++Reg;
3681       Count += 2;
3682       // Parse the lane specifier if present.
3683       VectorLaneTy NextLaneKind;
3684       unsigned NextLaneIndex;
3685       SMLoc LaneLoc = Parser.getTok().getLoc();
3686       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3687           MatchOperand_Success)
3688         return MatchOperand_ParseFail;
3689       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3690         Error(LaneLoc, "mismatched lane index in register list");
3691         return MatchOperand_ParseFail;
3692       }
3693       continue;
3694     }
3695     // Normal D register.
3696     // Figure out the register spacing (single or double) of the list if
3697     // we don't know it already.
3698     if (!Spacing)
3699       Spacing = 1 + (Reg == OldReg + 2);
3700
3701     // Just check that it's contiguous and keep going.
3702     if (Reg != OldReg + Spacing) {
3703       Error(RegLoc, "non-contiguous register range");
3704       return MatchOperand_ParseFail;
3705     }
3706     ++Count;
3707     // Parse the lane specifier if present.
3708     VectorLaneTy NextLaneKind;
3709     unsigned NextLaneIndex;
3710     SMLoc EndLoc = Parser.getTok().getLoc();
3711     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3712       return MatchOperand_ParseFail;
3713     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3714       Error(EndLoc, "mismatched lane index in register list");
3715       return MatchOperand_ParseFail;
3716     }
3717   }
3718
3719   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3720     Error(Parser.getTok().getLoc(), "'}' expected");
3721     return MatchOperand_ParseFail;
3722   }
3723   E = Parser.getTok().getEndLoc();
3724   Parser.Lex(); // Eat '}' token.
3725
3726   switch (LaneKind) {
3727   case NoLanes:
3728     // Two-register operands have been converted to the
3729     // composite register classes.
3730     if (Count == 2) {
3731       const MCRegisterClass *RC = (Spacing == 1) ?
3732         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3733         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3734       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3735     }
3736
3737     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3738                                                     (Spacing == 2), S, E));
3739     break;
3740   case AllLanes:
3741     // Two-register operands have been converted to the
3742     // composite register classes.
3743     if (Count == 2) {
3744       const MCRegisterClass *RC = (Spacing == 1) ?
3745         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3746         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3747       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3748     }
3749     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3750                                                             (Spacing == 2),
3751                                                             S, E));
3752     break;
3753   case IndexedLane:
3754     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3755                                                            LaneIndex,
3756                                                            (Spacing == 2),
3757                                                            S, E));
3758     break;
3759   }
3760   return MatchOperand_Success;
3761 }
3762
3763 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3764 ARMAsmParser::OperandMatchResultTy
3765 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3766   MCAsmParser &Parser = getParser();
3767   SMLoc S = Parser.getTok().getLoc();
3768   const AsmToken &Tok = Parser.getTok();
3769   unsigned Opt;
3770
3771   if (Tok.is(AsmToken::Identifier)) {
3772     StringRef OptStr = Tok.getString();
3773
3774     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3775       .Case("sy",    ARM_MB::SY)
3776       .Case("st",    ARM_MB::ST)
3777       .Case("ld",    ARM_MB::LD)
3778       .Case("sh",    ARM_MB::ISH)
3779       .Case("ish",   ARM_MB::ISH)
3780       .Case("shst",  ARM_MB::ISHST)
3781       .Case("ishst", ARM_MB::ISHST)
3782       .Case("ishld", ARM_MB::ISHLD)
3783       .Case("nsh",   ARM_MB::NSH)
3784       .Case("un",    ARM_MB::NSH)
3785       .Case("nshst", ARM_MB::NSHST)
3786       .Case("nshld", ARM_MB::NSHLD)
3787       .Case("unst",  ARM_MB::NSHST)
3788       .Case("osh",   ARM_MB::OSH)
3789       .Case("oshst", ARM_MB::OSHST)
3790       .Case("oshld", ARM_MB::OSHLD)
3791       .Default(~0U);
3792
3793     // ishld, oshld, nshld and ld are only available from ARMv8.
3794     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3795                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3796       Opt = ~0U;
3797
3798     if (Opt == ~0U)
3799       return MatchOperand_NoMatch;
3800
3801     Parser.Lex(); // Eat identifier token.
3802   } else if (Tok.is(AsmToken::Hash) ||
3803              Tok.is(AsmToken::Dollar) ||
3804              Tok.is(AsmToken::Integer)) {
3805     if (Parser.getTok().isNot(AsmToken::Integer))
3806       Parser.Lex(); // Eat '#' or '$'.
3807     SMLoc Loc = Parser.getTok().getLoc();
3808
3809     const MCExpr *MemBarrierID;
3810     if (getParser().parseExpression(MemBarrierID)) {
3811       Error(Loc, "illegal expression");
3812       return MatchOperand_ParseFail;
3813     }
3814
3815     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3816     if (!CE) {
3817       Error(Loc, "constant expression expected");
3818       return MatchOperand_ParseFail;
3819     }
3820
3821     int Val = CE->getValue();
3822     if (Val & ~0xf) {
3823       Error(Loc, "immediate value out of range");
3824       return MatchOperand_ParseFail;
3825     }
3826
3827     Opt = ARM_MB::RESERVED_0 + Val;
3828   } else
3829     return MatchOperand_ParseFail;
3830
3831   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3832   return MatchOperand_Success;
3833 }
3834
3835 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3836 ARMAsmParser::OperandMatchResultTy
3837 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3838   MCAsmParser &Parser = getParser();
3839   SMLoc S = Parser.getTok().getLoc();
3840   const AsmToken &Tok = Parser.getTok();
3841   unsigned Opt;
3842
3843   if (Tok.is(AsmToken::Identifier)) {
3844     StringRef OptStr = Tok.getString();
3845
3846     if (OptStr.equals_lower("sy"))
3847       Opt = ARM_ISB::SY;
3848     else
3849       return MatchOperand_NoMatch;
3850
3851     Parser.Lex(); // Eat identifier token.
3852   } else if (Tok.is(AsmToken::Hash) ||
3853              Tok.is(AsmToken::Dollar) ||
3854              Tok.is(AsmToken::Integer)) {
3855     if (Parser.getTok().isNot(AsmToken::Integer))
3856       Parser.Lex(); // Eat '#' or '$'.
3857     SMLoc Loc = Parser.getTok().getLoc();
3858
3859     const MCExpr *ISBarrierID;
3860     if (getParser().parseExpression(ISBarrierID)) {
3861       Error(Loc, "illegal expression");
3862       return MatchOperand_ParseFail;
3863     }
3864
3865     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
3866     if (!CE) {
3867       Error(Loc, "constant expression expected");
3868       return MatchOperand_ParseFail;
3869     }
3870
3871     int Val = CE->getValue();
3872     if (Val & ~0xf) {
3873       Error(Loc, "immediate value out of range");
3874       return MatchOperand_ParseFail;
3875     }
3876
3877     Opt = ARM_ISB::RESERVED_0 + Val;
3878   } else
3879     return MatchOperand_ParseFail;
3880
3881   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
3882           (ARM_ISB::InstSyncBOpt)Opt, S));
3883   return MatchOperand_Success;
3884 }
3885
3886
3887 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
3888 ARMAsmParser::OperandMatchResultTy
3889 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
3890   MCAsmParser &Parser = getParser();
3891   SMLoc S = Parser.getTok().getLoc();
3892   const AsmToken &Tok = Parser.getTok();
3893   if (!Tok.is(AsmToken::Identifier)) 
3894     return MatchOperand_NoMatch;
3895   StringRef IFlagsStr = Tok.getString();
3896
3897   // An iflags string of "none" is interpreted to mean that none of the AIF
3898   // bits are set.  Not a terribly useful instruction, but a valid encoding.
3899   unsigned IFlags = 0;
3900   if (IFlagsStr != "none") {
3901         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
3902       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
3903         .Case("a", ARM_PROC::A)
3904         .Case("i", ARM_PROC::I)
3905         .Case("f", ARM_PROC::F)
3906         .Default(~0U);
3907
3908       // If some specific iflag is already set, it means that some letter is
3909       // present more than once, this is not acceptable.
3910       if (Flag == ~0U || (IFlags & Flag))
3911         return MatchOperand_NoMatch;
3912
3913       IFlags |= Flag;
3914     }
3915   }
3916
3917   Parser.Lex(); // Eat identifier token.
3918   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
3919   return MatchOperand_Success;
3920 }
3921
3922 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
3923 ARMAsmParser::OperandMatchResultTy
3924 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
3925   MCAsmParser &Parser = getParser();
3926   SMLoc S = Parser.getTok().getLoc();
3927   const AsmToken &Tok = Parser.getTok();
3928   if (!Tok.is(AsmToken::Identifier))
3929     return MatchOperand_NoMatch;
3930   StringRef Mask = Tok.getString();
3931
3932   if (isMClass()) {
3933     // See ARMv6-M 10.1.1
3934     std::string Name = Mask.lower();
3935     unsigned FlagsVal = StringSwitch<unsigned>(Name)
3936       // Note: in the documentation:
3937       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
3938       //  for MSR APSR_nzcvq.
3939       // but we do make it an alias here.  This is so to get the "mask encoding"
3940       // bits correct on MSR APSR writes.
3941       //
3942       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
3943       // should really only be allowed when writing a special register.  Note
3944       // they get dropped in the MRS instruction reading a special register as
3945       // the SYSm field is only 8 bits.
3946       .Case("apsr", 0x800)
3947       .Case("apsr_nzcvq", 0x800)
3948       .Case("apsr_g", 0x400)
3949       .Case("apsr_nzcvqg", 0xc00)
3950       .Case("iapsr", 0x801)
3951       .Case("iapsr_nzcvq", 0x801)
3952       .Case("iapsr_g", 0x401)
3953       .Case("iapsr_nzcvqg", 0xc01)
3954       .Case("eapsr", 0x802)
3955       .Case("eapsr_nzcvq", 0x802)
3956       .Case("eapsr_g", 0x402)
3957       .Case("eapsr_nzcvqg", 0xc02)
3958       .Case("xpsr", 0x803)
3959       .Case("xpsr_nzcvq", 0x803)
3960       .Case("xpsr_g", 0x403)
3961       .Case("xpsr_nzcvqg", 0xc03)
3962       .Case("ipsr", 0x805)
3963       .Case("epsr", 0x806)
3964       .Case("iepsr", 0x807)
3965       .Case("msp", 0x808)
3966       .Case("psp", 0x809)
3967       .Case("primask", 0x810)
3968       .Case("basepri", 0x811)
3969       .Case("basepri_max", 0x812)
3970       .Case("faultmask", 0x813)
3971       .Case("control", 0x814)
3972       .Default(~0U);
3973
3974     if (FlagsVal == ~0U)
3975       return MatchOperand_NoMatch;
3976
3977     if (!hasDSP() && (FlagsVal & 0x400))
3978       // The _g and _nzcvqg versions are only valid if the DSP extension is
3979       // available.
3980       return MatchOperand_NoMatch;
3981
3982     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
3983       // basepri, basepri_max and faultmask only valid for V7m.
3984       return MatchOperand_NoMatch;
3985
3986     Parser.Lex(); // Eat identifier token.
3987     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
3988     return MatchOperand_Success;
3989   }
3990
3991   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
3992   size_t Start = 0, Next = Mask.find('_');
3993   StringRef Flags = "";
3994   std::string SpecReg = Mask.slice(Start, Next).lower();
3995   if (Next != StringRef::npos)
3996     Flags = Mask.slice(Next+1, Mask.size());
3997
3998   // FlagsVal contains the complete mask:
3999   // 3-0: Mask
4000   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4001   unsigned FlagsVal = 0;
4002
4003   if (SpecReg == "apsr") {
4004     FlagsVal = StringSwitch<unsigned>(Flags)
4005     .Case("nzcvq",  0x8) // same as CPSR_f
4006     .Case("g",      0x4) // same as CPSR_s
4007     .Case("nzcvqg", 0xc) // same as CPSR_fs
4008     .Default(~0U);
4009
4010     if (FlagsVal == ~0U) {
4011       if (!Flags.empty())
4012         return MatchOperand_NoMatch;
4013       else
4014         FlagsVal = 8; // No flag
4015     }
4016   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4017     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4018     if (Flags == "all" || Flags == "")
4019       Flags = "fc";
4020     for (int i = 0, e = Flags.size(); i != e; ++i) {
4021       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4022       .Case("c", 1)
4023       .Case("x", 2)
4024       .Case("s", 4)
4025       .Case("f", 8)
4026       .Default(~0U);
4027
4028       // If some specific flag is already set, it means that some letter is
4029       // present more than once, this is not acceptable.
4030       if (FlagsVal == ~0U || (FlagsVal & Flag))
4031         return MatchOperand_NoMatch;
4032       FlagsVal |= Flag;
4033     }
4034   } else // No match for special register.
4035     return MatchOperand_NoMatch;
4036
4037   // Special register without flags is NOT equivalent to "fc" flags.
4038   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4039   // two lines would enable gas compatibility at the expense of breaking
4040   // round-tripping.
4041   //
4042   // if (!FlagsVal)
4043   //  FlagsVal = 0x9;
4044
4045   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4046   if (SpecReg == "spsr")
4047     FlagsVal |= 16;
4048
4049   Parser.Lex(); // Eat identifier token.
4050   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4051   return MatchOperand_Success;
4052 }
4053
4054 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4055 /// use in the MRS/MSR instructions added to support virtualization.
4056 ARMAsmParser::OperandMatchResultTy
4057 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4058   MCAsmParser &Parser = getParser();
4059   SMLoc S = Parser.getTok().getLoc();
4060   const AsmToken &Tok = Parser.getTok();
4061   if (!Tok.is(AsmToken::Identifier))
4062     return MatchOperand_NoMatch;
4063   StringRef RegName = Tok.getString();
4064
4065   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4066   // and bit 5 is R.
4067   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4068                           .Case("r8_usr", 0x00)
4069                           .Case("r9_usr", 0x01)
4070                           .Case("r10_usr", 0x02)
4071                           .Case("r11_usr", 0x03)
4072                           .Case("r12_usr", 0x04)
4073                           .Case("sp_usr", 0x05)
4074                           .Case("lr_usr", 0x06)
4075                           .Case("r8_fiq", 0x08)
4076                           .Case("r9_fiq", 0x09)
4077                           .Case("r10_fiq", 0x0a)
4078                           .Case("r11_fiq", 0x0b)
4079                           .Case("r12_fiq", 0x0c)
4080                           .Case("sp_fiq", 0x0d)
4081                           .Case("lr_fiq", 0x0e)
4082                           .Case("lr_irq", 0x10)
4083                           .Case("sp_irq", 0x11)
4084                           .Case("lr_svc", 0x12)
4085                           .Case("sp_svc", 0x13)
4086                           .Case("lr_abt", 0x14)
4087                           .Case("sp_abt", 0x15)
4088                           .Case("lr_und", 0x16)
4089                           .Case("sp_und", 0x17)
4090                           .Case("lr_mon", 0x1c)
4091                           .Case("sp_mon", 0x1d)
4092                           .Case("elr_hyp", 0x1e)
4093                           .Case("sp_hyp", 0x1f)
4094                           .Case("spsr_fiq", 0x2e)
4095                           .Case("spsr_irq", 0x30)
4096                           .Case("spsr_svc", 0x32)
4097                           .Case("spsr_abt", 0x34)
4098                           .Case("spsr_und", 0x36)
4099                           .Case("spsr_mon", 0x3c)
4100                           .Case("spsr_hyp", 0x3e)
4101                           .Default(~0U);
4102
4103   if (Encoding == ~0U)
4104     return MatchOperand_NoMatch;
4105
4106   Parser.Lex(); // Eat identifier token.
4107   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4108   return MatchOperand_Success;
4109 }
4110
4111 ARMAsmParser::OperandMatchResultTy
4112 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4113                           int High) {
4114   MCAsmParser &Parser = getParser();
4115   const AsmToken &Tok = Parser.getTok();
4116   if (Tok.isNot(AsmToken::Identifier)) {
4117     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4118     return MatchOperand_ParseFail;
4119   }
4120   StringRef ShiftName = Tok.getString();
4121   std::string LowerOp = Op.lower();
4122   std::string UpperOp = Op.upper();
4123   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4124     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4125     return MatchOperand_ParseFail;
4126   }
4127   Parser.Lex(); // Eat shift type token.
4128
4129   // There must be a '#' and a shift amount.
4130   if (Parser.getTok().isNot(AsmToken::Hash) &&
4131       Parser.getTok().isNot(AsmToken::Dollar)) {
4132     Error(Parser.getTok().getLoc(), "'#' expected");
4133     return MatchOperand_ParseFail;
4134   }
4135   Parser.Lex(); // Eat hash token.
4136
4137   const MCExpr *ShiftAmount;
4138   SMLoc Loc = Parser.getTok().getLoc();
4139   SMLoc EndLoc;
4140   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4141     Error(Loc, "illegal expression");
4142     return MatchOperand_ParseFail;
4143   }
4144   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4145   if (!CE) {
4146     Error(Loc, "constant expression expected");
4147     return MatchOperand_ParseFail;
4148   }
4149   int Val = CE->getValue();
4150   if (Val < Low || Val > High) {
4151     Error(Loc, "immediate value out of range");
4152     return MatchOperand_ParseFail;
4153   }
4154
4155   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4156
4157   return MatchOperand_Success;
4158 }
4159
4160 ARMAsmParser::OperandMatchResultTy
4161 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4162   MCAsmParser &Parser = getParser();
4163   const AsmToken &Tok = Parser.getTok();
4164   SMLoc S = Tok.getLoc();
4165   if (Tok.isNot(AsmToken::Identifier)) {
4166     Error(S, "'be' or 'le' operand expected");
4167     return MatchOperand_ParseFail;
4168   }
4169   int Val = StringSwitch<int>(Tok.getString().lower())
4170     .Case("be", 1)
4171     .Case("le", 0)
4172     .Default(-1);
4173   Parser.Lex(); // Eat the token.
4174
4175   if (Val == -1) {
4176     Error(S, "'be' or 'le' operand expected");
4177     return MatchOperand_ParseFail;
4178   }
4179   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4180                                                                   getContext()),
4181                                            S, Tok.getEndLoc()));
4182   return MatchOperand_Success;
4183 }
4184
4185 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4186 /// instructions. Legal values are:
4187 ///     lsl #n  'n' in [0,31]
4188 ///     asr #n  'n' in [1,32]
4189 ///             n == 32 encoded as n == 0.
4190 ARMAsmParser::OperandMatchResultTy
4191 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4192   MCAsmParser &Parser = getParser();
4193   const AsmToken &Tok = Parser.getTok();
4194   SMLoc S = Tok.getLoc();
4195   if (Tok.isNot(AsmToken::Identifier)) {
4196     Error(S, "shift operator 'asr' or 'lsl' expected");
4197     return MatchOperand_ParseFail;
4198   }
4199   StringRef ShiftName = Tok.getString();
4200   bool isASR;
4201   if (ShiftName == "lsl" || ShiftName == "LSL")
4202     isASR = false;
4203   else if (ShiftName == "asr" || ShiftName == "ASR")
4204     isASR = true;
4205   else {
4206     Error(S, "shift operator 'asr' or 'lsl' expected");
4207     return MatchOperand_ParseFail;
4208   }
4209   Parser.Lex(); // Eat the operator.
4210
4211   // A '#' and a shift amount.
4212   if (Parser.getTok().isNot(AsmToken::Hash) &&
4213       Parser.getTok().isNot(AsmToken::Dollar)) {
4214     Error(Parser.getTok().getLoc(), "'#' expected");
4215     return MatchOperand_ParseFail;
4216   }
4217   Parser.Lex(); // Eat hash token.
4218   SMLoc ExLoc = Parser.getTok().getLoc();
4219
4220   const MCExpr *ShiftAmount;
4221   SMLoc EndLoc;
4222   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4223     Error(ExLoc, "malformed shift expression");
4224     return MatchOperand_ParseFail;
4225   }
4226   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4227   if (!CE) {
4228     Error(ExLoc, "shift amount must be an immediate");
4229     return MatchOperand_ParseFail;
4230   }
4231
4232   int64_t Val = CE->getValue();
4233   if (isASR) {
4234     // Shift amount must be in [1,32]
4235     if (Val < 1 || Val > 32) {
4236       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4237       return MatchOperand_ParseFail;
4238     }
4239     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4240     if (isThumb() && Val == 32) {
4241       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4242       return MatchOperand_ParseFail;
4243     }
4244     if (Val == 32) Val = 0;
4245   } else {
4246     // Shift amount must be in [1,32]
4247     if (Val < 0 || Val > 31) {
4248       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4249       return MatchOperand_ParseFail;
4250     }
4251   }
4252
4253   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4254
4255   return MatchOperand_Success;
4256 }
4257
4258 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4259 /// of instructions. Legal values are:
4260 ///     ror #n  'n' in {0, 8, 16, 24}
4261 ARMAsmParser::OperandMatchResultTy
4262 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4263   MCAsmParser &Parser = getParser();
4264   const AsmToken &Tok = Parser.getTok();
4265   SMLoc S = Tok.getLoc();
4266   if (Tok.isNot(AsmToken::Identifier))
4267     return MatchOperand_NoMatch;
4268   StringRef ShiftName = Tok.getString();
4269   if (ShiftName != "ror" && ShiftName != "ROR")
4270     return MatchOperand_NoMatch;
4271   Parser.Lex(); // Eat the operator.
4272
4273   // A '#' and a rotate amount.
4274   if (Parser.getTok().isNot(AsmToken::Hash) &&
4275       Parser.getTok().isNot(AsmToken::Dollar)) {
4276     Error(Parser.getTok().getLoc(), "'#' expected");
4277     return MatchOperand_ParseFail;
4278   }
4279   Parser.Lex(); // Eat hash token.
4280   SMLoc ExLoc = Parser.getTok().getLoc();
4281
4282   const MCExpr *ShiftAmount;
4283   SMLoc EndLoc;
4284   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4285     Error(ExLoc, "malformed rotate expression");
4286     return MatchOperand_ParseFail;
4287   }
4288   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4289   if (!CE) {
4290     Error(ExLoc, "rotate amount must be an immediate");
4291     return MatchOperand_ParseFail;
4292   }
4293
4294   int64_t Val = CE->getValue();
4295   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4296   // normally, zero is represented in asm by omitting the rotate operand
4297   // entirely.
4298   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4299     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4300     return MatchOperand_ParseFail;
4301   }
4302
4303   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4304
4305   return MatchOperand_Success;
4306 }
4307
4308 ARMAsmParser::OperandMatchResultTy
4309 ARMAsmParser::parseModImm(OperandVector &Operands) {
4310   MCAsmParser &Parser = getParser();
4311   MCAsmLexer &Lexer = getLexer();
4312   int64_t Imm1, Imm2;
4313
4314   SMLoc S = Parser.getTok().getLoc();
4315
4316   // 1) A mod_imm operand can appear in the place of a register name:
4317   //   add r0, #mod_imm
4318   //   add r0, r0, #mod_imm
4319   // to correctly handle the latter, we bail out as soon as we see an
4320   // identifier.
4321   //
4322   // 2) Similarly, we do not want to parse into complex operands:
4323   //   mov r0, #mod_imm
4324   //   mov r0, :lower16:(_foo)
4325   if (Parser.getTok().is(AsmToken::Identifier) ||
4326       Parser.getTok().is(AsmToken::Colon))
4327     return MatchOperand_NoMatch;
4328
4329   // Hash (dollar) is optional as per the ARMARM
4330   if (Parser.getTok().is(AsmToken::Hash) ||
4331       Parser.getTok().is(AsmToken::Dollar)) {
4332     // Avoid parsing into complex operands (#:)
4333     if (Lexer.peekTok().is(AsmToken::Colon))
4334       return MatchOperand_NoMatch;
4335
4336     // Eat the hash (dollar)
4337     Parser.Lex();
4338   }
4339
4340   SMLoc Sx1, Ex1;
4341   Sx1 = Parser.getTok().getLoc();
4342   const MCExpr *Imm1Exp;
4343   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4344     Error(Sx1, "malformed expression");
4345     return MatchOperand_ParseFail;
4346   }
4347
4348   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4349
4350   if (CE) {
4351     // Immediate must fit within 32-bits
4352     Imm1 = CE->getValue();
4353     int Enc = ARM_AM::getSOImmVal(Imm1);
4354     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4355       // We have a match!
4356       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4357                                                   (Enc & 0xF00) >> 7,
4358                                                   Sx1, Ex1));
4359       return MatchOperand_Success;
4360     }
4361
4362     // We have parsed an immediate which is not for us, fallback to a plain
4363     // immediate. This can happen for instruction aliases. For an example,
4364     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4365     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4366     // instruction with a mod_imm operand. The alias is defined such that the
4367     // parser method is shared, that's why we have to do this here.
4368     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4369       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4370       return MatchOperand_Success;
4371     }
4372   } else {
4373     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4374     // MCFixup). Fallback to a plain immediate.
4375     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4376     return MatchOperand_Success;
4377   }
4378
4379   // From this point onward, we expect the input to be a (#bits, #rot) pair
4380   if (Parser.getTok().isNot(AsmToken::Comma)) {
4381     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4382     return MatchOperand_ParseFail;
4383   }
4384
4385   if (Imm1 & ~0xFF) {
4386     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4387     return MatchOperand_ParseFail;
4388   }
4389
4390   // Eat the comma
4391   Parser.Lex();
4392
4393   // Repeat for #rot
4394   SMLoc Sx2, Ex2;
4395   Sx2 = Parser.getTok().getLoc();
4396
4397   // Eat the optional hash (dollar)
4398   if (Parser.getTok().is(AsmToken::Hash) ||
4399       Parser.getTok().is(AsmToken::Dollar))
4400     Parser.Lex();
4401
4402   const MCExpr *Imm2Exp;
4403   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4404     Error(Sx2, "malformed expression");
4405     return MatchOperand_ParseFail;
4406   }
4407
4408   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4409
4410   if (CE) {
4411     Imm2 = CE->getValue();
4412     if (!(Imm2 & ~0x1E)) {
4413       // We have a match!
4414       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4415       return MatchOperand_Success;
4416     }
4417     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4418     return MatchOperand_ParseFail;
4419   } else {
4420     Error(Sx2, "constant expression expected");
4421     return MatchOperand_ParseFail;
4422   }
4423 }
4424
4425 ARMAsmParser::OperandMatchResultTy
4426 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4427   MCAsmParser &Parser = getParser();
4428   SMLoc S = Parser.getTok().getLoc();
4429   // The bitfield descriptor is really two operands, the LSB and the width.
4430   if (Parser.getTok().isNot(AsmToken::Hash) &&
4431       Parser.getTok().isNot(AsmToken::Dollar)) {
4432     Error(Parser.getTok().getLoc(), "'#' expected");
4433     return MatchOperand_ParseFail;
4434   }
4435   Parser.Lex(); // Eat hash token.
4436
4437   const MCExpr *LSBExpr;
4438   SMLoc E = Parser.getTok().getLoc();
4439   if (getParser().parseExpression(LSBExpr)) {
4440     Error(E, "malformed immediate expression");
4441     return MatchOperand_ParseFail;
4442   }
4443   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4444   if (!CE) {
4445     Error(E, "'lsb' operand must be an immediate");
4446     return MatchOperand_ParseFail;
4447   }
4448
4449   int64_t LSB = CE->getValue();
4450   // The LSB must be in the range [0,31]
4451   if (LSB < 0 || LSB > 31) {
4452     Error(E, "'lsb' operand must be in the range [0,31]");
4453     return MatchOperand_ParseFail;
4454   }
4455   E = Parser.getTok().getLoc();
4456
4457   // Expect another immediate operand.
4458   if (Parser.getTok().isNot(AsmToken::Comma)) {
4459     Error(Parser.getTok().getLoc(), "too few operands");
4460     return MatchOperand_ParseFail;
4461   }
4462   Parser.Lex(); // Eat hash token.
4463   if (Parser.getTok().isNot(AsmToken::Hash) &&
4464       Parser.getTok().isNot(AsmToken::Dollar)) {
4465     Error(Parser.getTok().getLoc(), "'#' expected");
4466     return MatchOperand_ParseFail;
4467   }
4468   Parser.Lex(); // Eat hash token.
4469
4470   const MCExpr *WidthExpr;
4471   SMLoc EndLoc;
4472   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4473     Error(E, "malformed immediate expression");
4474     return MatchOperand_ParseFail;
4475   }
4476   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4477   if (!CE) {
4478     Error(E, "'width' operand must be an immediate");
4479     return MatchOperand_ParseFail;
4480   }
4481
4482   int64_t Width = CE->getValue();
4483   // The LSB must be in the range [1,32-lsb]
4484   if (Width < 1 || Width > 32 - LSB) {
4485     Error(E, "'width' operand must be in the range [1,32-lsb]");
4486     return MatchOperand_ParseFail;
4487   }
4488
4489   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4490
4491   return MatchOperand_Success;
4492 }
4493
4494 ARMAsmParser::OperandMatchResultTy
4495 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4496   // Check for a post-index addressing register operand. Specifically:
4497   // postidx_reg := '+' register {, shift}
4498   //              | '-' register {, shift}
4499   //              | register {, shift}
4500
4501   // This method must return MatchOperand_NoMatch without consuming any tokens
4502   // in the case where there is no match, as other alternatives take other
4503   // parse methods.
4504   MCAsmParser &Parser = getParser();
4505   AsmToken Tok = Parser.getTok();
4506   SMLoc S = Tok.getLoc();
4507   bool haveEaten = false;
4508   bool isAdd = true;
4509   if (Tok.is(AsmToken::Plus)) {
4510     Parser.Lex(); // Eat the '+' token.
4511     haveEaten = true;
4512   } else if (Tok.is(AsmToken::Minus)) {
4513     Parser.Lex(); // Eat the '-' token.
4514     isAdd = false;
4515     haveEaten = true;
4516   }
4517
4518   SMLoc E = Parser.getTok().getEndLoc();
4519   int Reg = tryParseRegister();
4520   if (Reg == -1) {
4521     if (!haveEaten)
4522       return MatchOperand_NoMatch;
4523     Error(Parser.getTok().getLoc(), "register expected");
4524     return MatchOperand_ParseFail;
4525   }
4526
4527   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4528   unsigned ShiftImm = 0;
4529   if (Parser.getTok().is(AsmToken::Comma)) {
4530     Parser.Lex(); // Eat the ','.
4531     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4532       return MatchOperand_ParseFail;
4533
4534     // FIXME: Only approximates end...may include intervening whitespace.
4535     E = Parser.getTok().getLoc();
4536   }
4537
4538   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4539                                                   ShiftImm, S, E));
4540
4541   return MatchOperand_Success;
4542 }
4543
4544 ARMAsmParser::OperandMatchResultTy
4545 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4546   // Check for a post-index addressing register operand. Specifically:
4547   // am3offset := '+' register
4548   //              | '-' register
4549   //              | register
4550   //              | # imm
4551   //              | # + imm
4552   //              | # - imm
4553
4554   // This method must return MatchOperand_NoMatch without consuming any tokens
4555   // in the case where there is no match, as other alternatives take other
4556   // parse methods.
4557   MCAsmParser &Parser = getParser();
4558   AsmToken Tok = Parser.getTok();
4559   SMLoc S = Tok.getLoc();
4560
4561   // Do immediates first, as we always parse those if we have a '#'.
4562   if (Parser.getTok().is(AsmToken::Hash) ||
4563       Parser.getTok().is(AsmToken::Dollar)) {
4564     Parser.Lex(); // Eat '#' or '$'.
4565     // Explicitly look for a '-', as we need to encode negative zero
4566     // differently.
4567     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4568     const MCExpr *Offset;
4569     SMLoc E;
4570     if (getParser().parseExpression(Offset, E))
4571       return MatchOperand_ParseFail;
4572     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4573     if (!CE) {
4574       Error(S, "constant expression expected");
4575       return MatchOperand_ParseFail;
4576     }
4577     // Negative zero is encoded as the flag value INT32_MIN.
4578     int32_t Val = CE->getValue();
4579     if (isNegative && Val == 0)
4580       Val = INT32_MIN;
4581
4582     Operands.push_back(
4583       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4584
4585     return MatchOperand_Success;
4586   }
4587
4588
4589   bool haveEaten = false;
4590   bool isAdd = true;
4591   if (Tok.is(AsmToken::Plus)) {
4592     Parser.Lex(); // Eat the '+' token.
4593     haveEaten = true;
4594   } else if (Tok.is(AsmToken::Minus)) {
4595     Parser.Lex(); // Eat the '-' token.
4596     isAdd = false;
4597     haveEaten = true;
4598   }
4599
4600   Tok = Parser.getTok();
4601   int Reg = tryParseRegister();
4602   if (Reg == -1) {
4603     if (!haveEaten)
4604       return MatchOperand_NoMatch;
4605     Error(Tok.getLoc(), "register expected");
4606     return MatchOperand_ParseFail;
4607   }
4608
4609   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4610                                                   0, S, Tok.getEndLoc()));
4611
4612   return MatchOperand_Success;
4613 }
4614
4615 /// Convert parsed operands to MCInst.  Needed here because this instruction
4616 /// only has two register operands, but multiplication is commutative so
4617 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4618 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4619                                     const OperandVector &Operands) {
4620   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4621   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4622   // If we have a three-operand form, make sure to set Rn to be the operand
4623   // that isn't the same as Rd.
4624   unsigned RegOp = 4;
4625   if (Operands.size() == 6 &&
4626       ((ARMOperand &)*Operands[4]).getReg() ==
4627           ((ARMOperand &)*Operands[3]).getReg())
4628     RegOp = 5;
4629   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4630   Inst.addOperand(Inst.getOperand(0));
4631   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4632 }
4633
4634 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4635                                     const OperandVector &Operands) {
4636   int CondOp = -1, ImmOp = -1;
4637   switch(Inst.getOpcode()) {
4638     case ARM::tB:
4639     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4640
4641     case ARM::t2B:
4642     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4643
4644     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4645   }
4646   // first decide whether or not the branch should be conditional
4647   // by looking at it's location relative to an IT block
4648   if(inITBlock()) {
4649     // inside an IT block we cannot have any conditional branches. any 
4650     // such instructions needs to be converted to unconditional form
4651     switch(Inst.getOpcode()) {
4652       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4653       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4654     }
4655   } else {
4656     // outside IT blocks we can only have unconditional branches with AL
4657     // condition code or conditional branches with non-AL condition code
4658     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4659     switch(Inst.getOpcode()) {
4660       case ARM::tB:
4661       case ARM::tBcc: 
4662         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc); 
4663         break;
4664       case ARM::t2B:
4665       case ARM::t2Bcc: 
4666         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4667         break;
4668     }
4669   }
4670
4671   // now decide on encoding size based on branch target range
4672   switch(Inst.getOpcode()) {
4673     // classify tB as either t2B or t1B based on range of immediate operand
4674     case ARM::tB: {
4675       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4676       if (!op.isSignedOffset<11, 1>() && isThumbTwo())
4677         Inst.setOpcode(ARM::t2B);
4678       break;
4679     }
4680     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4681     case ARM::tBcc: {
4682       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4683       if (!op.isSignedOffset<8, 1>() && isThumbTwo())
4684         Inst.setOpcode(ARM::t2Bcc);
4685       break;
4686     }
4687   }
4688   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4689   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4690 }
4691
4692 /// Parse an ARM memory expression, return false if successful else return true
4693 /// or an error.  The first token must be a '[' when called.
4694 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4695   MCAsmParser &Parser = getParser();
4696   SMLoc S, E;
4697   assert(Parser.getTok().is(AsmToken::LBrac) &&
4698          "Token is not a Left Bracket");
4699   S = Parser.getTok().getLoc();
4700   Parser.Lex(); // Eat left bracket token.
4701
4702   const AsmToken &BaseRegTok = Parser.getTok();
4703   int BaseRegNum = tryParseRegister();
4704   if (BaseRegNum == -1)
4705     return Error(BaseRegTok.getLoc(), "register expected");
4706
4707   // The next token must either be a comma, a colon or a closing bracket.
4708   const AsmToken &Tok = Parser.getTok();
4709   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4710       !Tok.is(AsmToken::RBrac))
4711     return Error(Tok.getLoc(), "malformed memory operand");
4712
4713   if (Tok.is(AsmToken::RBrac)) {
4714     E = Tok.getEndLoc();
4715     Parser.Lex(); // Eat right bracket token.
4716
4717     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4718                                              ARM_AM::no_shift, 0, 0, false,
4719                                              S, E));
4720
4721     // If there's a pre-indexing writeback marker, '!', just add it as a token
4722     // operand. It's rather odd, but syntactically valid.
4723     if (Parser.getTok().is(AsmToken::Exclaim)) {
4724       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4725       Parser.Lex(); // Eat the '!'.
4726     }
4727
4728     return false;
4729   }
4730
4731   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4732          "Lost colon or comma in memory operand?!");
4733   if (Tok.is(AsmToken::Comma)) {
4734     Parser.Lex(); // Eat the comma.
4735   }
4736
4737   // If we have a ':', it's an alignment specifier.
4738   if (Parser.getTok().is(AsmToken::Colon)) {
4739     Parser.Lex(); // Eat the ':'.
4740     E = Parser.getTok().getLoc();
4741     SMLoc AlignmentLoc = Tok.getLoc();
4742
4743     const MCExpr *Expr;
4744     if (getParser().parseExpression(Expr))
4745      return true;
4746
4747     // The expression has to be a constant. Memory references with relocations
4748     // don't come through here, as they use the <label> forms of the relevant
4749     // instructions.
4750     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4751     if (!CE)
4752       return Error (E, "constant expression expected");
4753
4754     unsigned Align = 0;
4755     switch (CE->getValue()) {
4756     default:
4757       return Error(E,
4758                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4759     case 16:  Align = 2; break;
4760     case 32:  Align = 4; break;
4761     case 64:  Align = 8; break;
4762     case 128: Align = 16; break;
4763     case 256: Align = 32; break;
4764     }
4765
4766     // Now we should have the closing ']'
4767     if (Parser.getTok().isNot(AsmToken::RBrac))
4768       return Error(Parser.getTok().getLoc(), "']' expected");
4769     E = Parser.getTok().getEndLoc();
4770     Parser.Lex(); // Eat right bracket token.
4771
4772     // Don't worry about range checking the value here. That's handled by
4773     // the is*() predicates.
4774     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4775                                              ARM_AM::no_shift, 0, Align,
4776                                              false, S, E, AlignmentLoc));
4777
4778     // If there's a pre-indexing writeback marker, '!', just add it as a token
4779     // operand.
4780     if (Parser.getTok().is(AsmToken::Exclaim)) {
4781       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4782       Parser.Lex(); // Eat the '!'.
4783     }
4784
4785     return false;
4786   }
4787
4788   // If we have a '#', it's an immediate offset, else assume it's a register
4789   // offset. Be friendly and also accept a plain integer (without a leading
4790   // hash) for gas compatibility.
4791   if (Parser.getTok().is(AsmToken::Hash) ||
4792       Parser.getTok().is(AsmToken::Dollar) ||
4793       Parser.getTok().is(AsmToken::Integer)) {
4794     if (Parser.getTok().isNot(AsmToken::Integer))
4795       Parser.Lex(); // Eat '#' or '$'.
4796     E = Parser.getTok().getLoc();
4797
4798     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4799     const MCExpr *Offset;
4800     if (getParser().parseExpression(Offset))
4801      return true;
4802
4803     // The expression has to be a constant. Memory references with relocations
4804     // don't come through here, as they use the <label> forms of the relevant
4805     // instructions.
4806     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4807     if (!CE)
4808       return Error (E, "constant expression expected");
4809
4810     // If the constant was #-0, represent it as INT32_MIN.
4811     int32_t Val = CE->getValue();
4812     if (isNegative && Val == 0)
4813       CE = MCConstantExpr::create(INT32_MIN, getContext());
4814
4815     // Now we should have the closing ']'
4816     if (Parser.getTok().isNot(AsmToken::RBrac))
4817       return Error(Parser.getTok().getLoc(), "']' expected");
4818     E = Parser.getTok().getEndLoc();
4819     Parser.Lex(); // Eat right bracket token.
4820
4821     // Don't worry about range checking the value here. That's handled by
4822     // the is*() predicates.
4823     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4824                                              ARM_AM::no_shift, 0, 0,
4825                                              false, S, E));
4826
4827     // If there's a pre-indexing writeback marker, '!', just add it as a token
4828     // operand.
4829     if (Parser.getTok().is(AsmToken::Exclaim)) {
4830       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4831       Parser.Lex(); // Eat the '!'.
4832     }
4833
4834     return false;
4835   }
4836
4837   // The register offset is optionally preceded by a '+' or '-'
4838   bool isNegative = false;
4839   if (Parser.getTok().is(AsmToken::Minus)) {
4840     isNegative = true;
4841     Parser.Lex(); // Eat the '-'.
4842   } else if (Parser.getTok().is(AsmToken::Plus)) {
4843     // Nothing to do.
4844     Parser.Lex(); // Eat the '+'.
4845   }
4846
4847   E = Parser.getTok().getLoc();
4848   int OffsetRegNum = tryParseRegister();
4849   if (OffsetRegNum == -1)
4850     return Error(E, "register expected");
4851
4852   // If there's a shift operator, handle it.
4853   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4854   unsigned ShiftImm = 0;
4855   if (Parser.getTok().is(AsmToken::Comma)) {
4856     Parser.Lex(); // Eat the ','.
4857     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4858       return true;
4859   }
4860
4861   // Now we should have the closing ']'
4862   if (Parser.getTok().isNot(AsmToken::RBrac))
4863     return Error(Parser.getTok().getLoc(), "']' expected");
4864   E = Parser.getTok().getEndLoc();
4865   Parser.Lex(); // Eat right bracket token.
4866
4867   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
4868                                            ShiftType, ShiftImm, 0, isNegative,
4869                                            S, E));
4870
4871   // If there's a pre-indexing writeback marker, '!', just add it as a token
4872   // operand.
4873   if (Parser.getTok().is(AsmToken::Exclaim)) {
4874     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4875     Parser.Lex(); // Eat the '!'.
4876   }
4877
4878   return false;
4879 }
4880
4881 /// parseMemRegOffsetShift - one of these two:
4882 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4883 ///   rrx
4884 /// return true if it parses a shift otherwise it returns false.
4885 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4886                                           unsigned &Amount) {
4887   MCAsmParser &Parser = getParser();
4888   SMLoc Loc = Parser.getTok().getLoc();
4889   const AsmToken &Tok = Parser.getTok();
4890   if (Tok.isNot(AsmToken::Identifier))
4891     return true;
4892   StringRef ShiftName = Tok.getString();
4893   if (ShiftName == "lsl" || ShiftName == "LSL" ||
4894       ShiftName == "asl" || ShiftName == "ASL")
4895     St = ARM_AM::lsl;
4896   else if (ShiftName == "lsr" || ShiftName == "LSR")
4897     St = ARM_AM::lsr;
4898   else if (ShiftName == "asr" || ShiftName == "ASR")
4899     St = ARM_AM::asr;
4900   else if (ShiftName == "ror" || ShiftName == "ROR")
4901     St = ARM_AM::ror;
4902   else if (ShiftName == "rrx" || ShiftName == "RRX")
4903     St = ARM_AM::rrx;
4904   else
4905     return Error(Loc, "illegal shift operator");
4906   Parser.Lex(); // Eat shift type token.
4907
4908   // rrx stands alone.
4909   Amount = 0;
4910   if (St != ARM_AM::rrx) {
4911     Loc = Parser.getTok().getLoc();
4912     // A '#' and a shift amount.
4913     const AsmToken &HashTok = Parser.getTok();
4914     if (HashTok.isNot(AsmToken::Hash) &&
4915         HashTok.isNot(AsmToken::Dollar))
4916       return Error(HashTok.getLoc(), "'#' expected");
4917     Parser.Lex(); // Eat hash token.
4918
4919     const MCExpr *Expr;
4920     if (getParser().parseExpression(Expr))
4921       return true;
4922     // Range check the immediate.
4923     // lsl, ror: 0 <= imm <= 31
4924     // lsr, asr: 0 <= imm <= 32
4925     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4926     if (!CE)
4927       return Error(Loc, "shift amount must be an immediate");
4928     int64_t Imm = CE->getValue();
4929     if (Imm < 0 ||
4930         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
4931         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
4932       return Error(Loc, "immediate shift value out of range");
4933     // If <ShiftTy> #0, turn it into a no_shift.
4934     if (Imm == 0)
4935       St = ARM_AM::lsl;
4936     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
4937     if (Imm == 32)
4938       Imm = 0;
4939     Amount = Imm;
4940   }
4941
4942   return false;
4943 }
4944
4945 /// parseFPImm - A floating point immediate expression operand.
4946 ARMAsmParser::OperandMatchResultTy
4947 ARMAsmParser::parseFPImm(OperandVector &Operands) {
4948   MCAsmParser &Parser = getParser();
4949   // Anything that can accept a floating point constant as an operand
4950   // needs to go through here, as the regular parseExpression is
4951   // integer only.
4952   //
4953   // This routine still creates a generic Immediate operand, containing
4954   // a bitcast of the 64-bit floating point value. The various operands
4955   // that accept floats can check whether the value is valid for them
4956   // via the standard is*() predicates.
4957
4958   SMLoc S = Parser.getTok().getLoc();
4959
4960   if (Parser.getTok().isNot(AsmToken::Hash) &&
4961       Parser.getTok().isNot(AsmToken::Dollar))
4962     return MatchOperand_NoMatch;
4963
4964   // Disambiguate the VMOV forms that can accept an FP immediate.
4965   // vmov.f32 <sreg>, #imm
4966   // vmov.f64 <dreg>, #imm
4967   // vmov.f32 <dreg>, #imm  @ vector f32x2
4968   // vmov.f32 <qreg>, #imm  @ vector f32x4
4969   //
4970   // There are also the NEON VMOV instructions which expect an
4971   // integer constant. Make sure we don't try to parse an FPImm
4972   // for these:
4973   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
4974   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
4975   bool isVmovf = TyOp.isToken() &&
4976                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64");
4977   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
4978   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
4979                                          Mnemonic.getToken() == "fconsts");
4980   if (!(isVmovf || isFconst))
4981     return MatchOperand_NoMatch;
4982
4983   Parser.Lex(); // Eat '#' or '$'.
4984
4985   // Handle negation, as that still comes through as a separate token.
4986   bool isNegative = false;
4987   if (Parser.getTok().is(AsmToken::Minus)) {
4988     isNegative = true;
4989     Parser.Lex();
4990   }
4991   const AsmToken &Tok = Parser.getTok();
4992   SMLoc Loc = Tok.getLoc();
4993   if (Tok.is(AsmToken::Real) && isVmovf) {
4994     APFloat RealVal(APFloat::IEEEsingle, Tok.getString());
4995     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
4996     // If we had a '-' in front, toggle the sign bit.
4997     IntVal ^= (uint64_t)isNegative << 31;
4998     Parser.Lex(); // Eat the token.
4999     Operands.push_back(ARMOperand::CreateImm(
5000           MCConstantExpr::create(IntVal, getContext()),
5001           S, Parser.getTok().getLoc()));
5002     return MatchOperand_Success;
5003   }
5004   // Also handle plain integers. Instructions which allow floating point
5005   // immediates also allow a raw encoded 8-bit value.
5006   if (Tok.is(AsmToken::Integer) && isFconst) {
5007     int64_t Val = Tok.getIntVal();
5008     Parser.Lex(); // Eat the token.
5009     if (Val > 255 || Val < 0) {
5010       Error(Loc, "encoded floating point value out of range");
5011       return MatchOperand_ParseFail;
5012     }
5013     float RealVal = ARM_AM::getFPImmFloat(Val);
5014     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5015
5016     Operands.push_back(ARMOperand::CreateImm(
5017         MCConstantExpr::create(Val, getContext()), S,
5018         Parser.getTok().getLoc()));
5019     return MatchOperand_Success;
5020   }
5021
5022   Error(Loc, "invalid floating point immediate");
5023   return MatchOperand_ParseFail;
5024 }
5025
5026 /// Parse a arm instruction operand.  For now this parses the operand regardless
5027 /// of the mnemonic.
5028 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5029   MCAsmParser &Parser = getParser();
5030   SMLoc S, E;
5031
5032   // Check if the current operand has a custom associated parser, if so, try to
5033   // custom parse the operand, or fallback to the general approach.
5034   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5035   if (ResTy == MatchOperand_Success)
5036     return false;
5037   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5038   // there was a match, but an error occurred, in which case, just return that
5039   // the operand parsing failed.
5040   if (ResTy == MatchOperand_ParseFail)
5041     return true;
5042
5043   switch (getLexer().getKind()) {
5044   default:
5045     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5046     return true;
5047   case AsmToken::Identifier: {
5048     // If we've seen a branch mnemonic, the next operand must be a label.  This
5049     // is true even if the label is a register name.  So "br r1" means branch to
5050     // label "r1".
5051     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5052     if (!ExpectLabel) {
5053       if (!tryParseRegisterWithWriteBack(Operands))
5054         return false;
5055       int Res = tryParseShiftRegister(Operands);
5056       if (Res == 0) // success
5057         return false;
5058       else if (Res == -1) // irrecoverable error
5059         return true;
5060       // If this is VMRS, check for the apsr_nzcv operand.
5061       if (Mnemonic == "vmrs" &&
5062           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5063         S = Parser.getTok().getLoc();
5064         Parser.Lex();
5065         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5066         return false;
5067       }
5068     }
5069
5070     // Fall though for the Identifier case that is not a register or a
5071     // special name.
5072   }
5073   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5074   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5075   case AsmToken::String:  // quoted label names.
5076   case AsmToken::Dot: {   // . as a branch target
5077     // This was not a register so parse other operands that start with an
5078     // identifier (like labels) as expressions and create them as immediates.
5079     const MCExpr *IdVal;
5080     S = Parser.getTok().getLoc();
5081     if (getParser().parseExpression(IdVal))
5082       return true;
5083     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5084     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5085     return false;
5086   }
5087   case AsmToken::LBrac:
5088     return parseMemory(Operands);
5089   case AsmToken::LCurly:
5090     return parseRegisterList(Operands);
5091   case AsmToken::Dollar:
5092   case AsmToken::Hash: {
5093     // #42 -> immediate.
5094     S = Parser.getTok().getLoc();
5095     Parser.Lex();
5096
5097     if (Parser.getTok().isNot(AsmToken::Colon)) {
5098       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5099       const MCExpr *ImmVal;
5100       if (getParser().parseExpression(ImmVal))
5101         return true;
5102       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5103       if (CE) {
5104         int32_t Val = CE->getValue();
5105         if (isNegative && Val == 0)
5106           ImmVal = MCConstantExpr::create(INT32_MIN, getContext());
5107       }
5108       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5109       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5110
5111       // There can be a trailing '!' on operands that we want as a separate
5112       // '!' Token operand. Handle that here. For example, the compatibility
5113       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5114       if (Parser.getTok().is(AsmToken::Exclaim)) {
5115         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5116                                                    Parser.getTok().getLoc()));
5117         Parser.Lex(); // Eat exclaim token
5118       }
5119       return false;
5120     }
5121     // w/ a ':' after the '#', it's just like a plain ':'.
5122     // FALLTHROUGH
5123   }
5124   case AsmToken::Colon: {
5125     S = Parser.getTok().getLoc();
5126     // ":lower16:" and ":upper16:" expression prefixes
5127     // FIXME: Check it's an expression prefix,
5128     // e.g. (FOO - :lower16:BAR) isn't legal.
5129     ARMMCExpr::VariantKind RefKind;
5130     if (parsePrefix(RefKind))
5131       return true;
5132
5133     const MCExpr *SubExprVal;
5134     if (getParser().parseExpression(SubExprVal))
5135       return true;
5136
5137     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5138                                               getContext());
5139     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5140     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5141     return false;
5142   }
5143   case AsmToken::Equal: {
5144     S = Parser.getTok().getLoc();
5145     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5146       return Error(S, "unexpected token in operand");
5147
5148     Parser.Lex(); // Eat '='
5149     const MCExpr *SubExprVal;
5150     if (getParser().parseExpression(SubExprVal))
5151       return true;
5152     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5153
5154     const MCExpr *CPLoc =
5155         getTargetStreamer().addConstantPoolEntry(SubExprVal, S);
5156     Operands.push_back(ARMOperand::CreateImm(CPLoc, S, E));
5157     return false;
5158   }
5159   }
5160 }
5161
5162 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5163 //  :lower16: and :upper16:.
5164 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5165   MCAsmParser &Parser = getParser();
5166   RefKind = ARMMCExpr::VK_ARM_None;
5167
5168   // consume an optional '#' (GNU compatibility)
5169   if (getLexer().is(AsmToken::Hash))
5170     Parser.Lex();
5171
5172   // :lower16: and :upper16: modifiers
5173   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5174   Parser.Lex(); // Eat ':'
5175
5176   if (getLexer().isNot(AsmToken::Identifier)) {
5177     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5178     return true;
5179   }
5180
5181   enum {
5182     COFF = (1 << MCObjectFileInfo::IsCOFF),
5183     ELF = (1 << MCObjectFileInfo::IsELF),
5184     MACHO = (1 << MCObjectFileInfo::IsMachO)
5185   };
5186   static const struct PrefixEntry {
5187     const char *Spelling;
5188     ARMMCExpr::VariantKind VariantKind;
5189     uint8_t SupportedFormats;
5190   } PrefixEntries[] = {
5191     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5192     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5193   };
5194
5195   StringRef IDVal = Parser.getTok().getIdentifier();
5196
5197   const auto &Prefix =
5198       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5199                    [&IDVal](const PrefixEntry &PE) {
5200                       return PE.Spelling == IDVal;
5201                    });
5202   if (Prefix == std::end(PrefixEntries)) {
5203     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5204     return true;
5205   }
5206
5207   uint8_t CurrentFormat;
5208   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5209   case MCObjectFileInfo::IsMachO:
5210     CurrentFormat = MACHO;
5211     break;
5212   case MCObjectFileInfo::IsELF:
5213     CurrentFormat = ELF;
5214     break;
5215   case MCObjectFileInfo::IsCOFF:
5216     CurrentFormat = COFF;
5217     break;
5218   }
5219
5220   if (~Prefix->SupportedFormats & CurrentFormat) {
5221     Error(Parser.getTok().getLoc(),
5222           "cannot represent relocation in the current file format");
5223     return true;
5224   }
5225
5226   RefKind = Prefix->VariantKind;
5227   Parser.Lex();
5228
5229   if (getLexer().isNot(AsmToken::Colon)) {
5230     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5231     return true;
5232   }
5233   Parser.Lex(); // Eat the last ':'
5234
5235   return false;
5236 }
5237
5238 /// \brief Given a mnemonic, split out possible predication code and carry
5239 /// setting letters to form a canonical mnemonic and flags.
5240 //
5241 // FIXME: Would be nice to autogen this.
5242 // FIXME: This is a bit of a maze of special cases.
5243 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5244                                       unsigned &PredicationCode,
5245                                       bool &CarrySetting,
5246                                       unsigned &ProcessorIMod,
5247                                       StringRef &ITMask) {
5248   PredicationCode = ARMCC::AL;
5249   CarrySetting = false;
5250   ProcessorIMod = 0;
5251
5252   // Ignore some mnemonics we know aren't predicated forms.
5253   //
5254   // FIXME: Would be nice to autogen this.
5255   if ((Mnemonic == "movs" && isThumb()) ||
5256       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5257       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5258       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5259       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5260       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5261       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5262       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5263       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5264       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5265       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5266       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5267       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5268       Mnemonic.startswith("vsel"))
5269     return Mnemonic;
5270
5271   // First, split out any predication code. Ignore mnemonics we know aren't
5272   // predicated but do have a carry-set and so weren't caught above.
5273   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5274       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5275       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5276       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5277     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5278       .Case("eq", ARMCC::EQ)
5279       .Case("ne", ARMCC::NE)
5280       .Case("hs", ARMCC::HS)
5281       .Case("cs", ARMCC::HS)
5282       .Case("lo", ARMCC::LO)
5283       .Case("cc", ARMCC::LO)
5284       .Case("mi", ARMCC::MI)
5285       .Case("pl", ARMCC::PL)
5286       .Case("vs", ARMCC::VS)
5287       .Case("vc", ARMCC::VC)
5288       .Case("hi", ARMCC::HI)
5289       .Case("ls", ARMCC::LS)
5290       .Case("ge", ARMCC::GE)
5291       .Case("lt", ARMCC::LT)
5292       .Case("gt", ARMCC::GT)
5293       .Case("le", ARMCC::LE)
5294       .Case("al", ARMCC::AL)
5295       .Default(~0U);
5296     if (CC != ~0U) {
5297       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5298       PredicationCode = CC;
5299     }
5300   }
5301
5302   // Next, determine if we have a carry setting bit. We explicitly ignore all
5303   // the instructions we know end in 's'.
5304   if (Mnemonic.endswith("s") &&
5305       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5306         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5307         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5308         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5309         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5310         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5311         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5312         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5313         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5314         (Mnemonic == "movs" && isThumb()))) {
5315     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5316     CarrySetting = true;
5317   }
5318
5319   // The "cps" instruction can have a interrupt mode operand which is glued into
5320   // the mnemonic. Check if this is the case, split it and parse the imod op
5321   if (Mnemonic.startswith("cps")) {
5322     // Split out any imod code.
5323     unsigned IMod =
5324       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5325       .Case("ie", ARM_PROC::IE)
5326       .Case("id", ARM_PROC::ID)
5327       .Default(~0U);
5328     if (IMod != ~0U) {
5329       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5330       ProcessorIMod = IMod;
5331     }
5332   }
5333
5334   // The "it" instruction has the condition mask on the end of the mnemonic.
5335   if (Mnemonic.startswith("it")) {
5336     ITMask = Mnemonic.slice(2, Mnemonic.size());
5337     Mnemonic = Mnemonic.slice(0, 2);
5338   }
5339
5340   return Mnemonic;
5341 }
5342
5343 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5344 /// inclusion of carry set or predication code operands.
5345 //
5346 // FIXME: It would be nice to autogen this.
5347 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5348                                          bool &CanAcceptCarrySet,
5349                                          bool &CanAcceptPredicationCode) {
5350   CanAcceptCarrySet =
5351       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5352       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5353       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5354       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5355       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5356       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5357       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5358       (!isThumb() &&
5359        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5360         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5361
5362   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5363       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5364       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5365       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5366       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5367       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5368       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5369       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5370       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5371       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5372       (FullInst.startswith("vmull") && FullInst.endswith(".p64"))) {
5373     // These mnemonics are never predicable
5374     CanAcceptPredicationCode = false;
5375   } else if (!isThumb()) {
5376     // Some instructions are only predicable in Thumb mode
5377     CanAcceptPredicationCode =
5378         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5379         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5380         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5381         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5382         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5383         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5384         !Mnemonic.startswith("srs");
5385   } else if (isThumbOne()) {
5386     if (hasV6MOps())
5387       CanAcceptPredicationCode = Mnemonic != "movs";
5388     else
5389       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5390   } else
5391     CanAcceptPredicationCode = true;
5392 }
5393
5394 // \brief Some Thumb instructions have two operand forms that are not
5395 // available as three operand, convert to two operand form if possible.
5396 //
5397 // FIXME: We would really like to be able to tablegen'erate this.
5398 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5399                                                  bool CarrySetting,
5400                                                  OperandVector &Operands) {
5401   if (Operands.size() != 6)
5402     return;
5403
5404   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5405         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5406   if (!Op3.isReg() || !Op4.isReg())
5407     return;
5408
5409   auto Op3Reg = Op3.getReg();
5410   auto Op4Reg = Op4.getReg();
5411
5412   // For most Thumb2 cases we just generate the 3 operand form and reduce
5413   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5414   // won't accept SP or PC so we do the transformation here taking care
5415   // with immediate range in the 'add sp, sp #imm' case.
5416   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5417   if (isThumbTwo()) {
5418     if (Mnemonic != "add")
5419       return;
5420     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5421                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5422     if (!TryTransform) {
5423       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5424                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5425                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5426                        Op5.isImm() && !Op5.isImm0_508s4());
5427     }
5428     if (!TryTransform)
5429       return;
5430   } else if (!isThumbOne())
5431     return;
5432
5433   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5434         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5435         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5436         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5437     return;
5438
5439   // If first 2 operands of a 3 operand instruction are the same
5440   // then transform to 2 operand version of the same instruction
5441   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5442   bool Transform = Op3Reg == Op4Reg;
5443
5444   // For communtative operations, we might be able to transform if we swap
5445   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5446   // as tADDrsp.
5447   const ARMOperand *LastOp = &Op5;
5448   bool Swap = false;
5449   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5450       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5451        Mnemonic == "and" || Mnemonic == "eor" ||
5452        Mnemonic == "adc" || Mnemonic == "orr")) {
5453     Swap = true;
5454     LastOp = &Op4;
5455     Transform = true;
5456   }
5457
5458   // If both registers are the same then remove one of them from
5459   // the operand list, with certain exceptions.
5460   if (Transform) {
5461     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5462     // 2 operand forms don't exist.
5463     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5464         LastOp->isReg())
5465       Transform = false;
5466
5467     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5468     // 3-bits because the ARMARM says not to.
5469     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5470       Transform = false;
5471   }
5472
5473   if (Transform) {
5474     if (Swap)
5475       std::swap(Op4, Op5);
5476     Operands.erase(Operands.begin() + 3);
5477   }
5478 }
5479
5480 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5481                                           OperandVector &Operands) {
5482   // FIXME: This is all horribly hacky. We really need a better way to deal
5483   // with optional operands like this in the matcher table.
5484
5485   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5486   // another does not. Specifically, the MOVW instruction does not. So we
5487   // special case it here and remove the defaulted (non-setting) cc_out
5488   // operand if that's the instruction we're trying to match.
5489   //
5490   // We do this as post-processing of the explicit operands rather than just
5491   // conditionally adding the cc_out in the first place because we need
5492   // to check the type of the parsed immediate operand.
5493   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5494       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5495       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5496       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5497     return true;
5498
5499   // Register-register 'add' for thumb does not have a cc_out operand
5500   // when there are only two register operands.
5501   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5502       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5503       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5504       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5505     return true;
5506   // Register-register 'add' for thumb does not have a cc_out operand
5507   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5508   // have to check the immediate range here since Thumb2 has a variant
5509   // that can handle a different range and has a cc_out operand.
5510   if (((isThumb() && Mnemonic == "add") ||
5511        (isThumbTwo() && Mnemonic == "sub")) &&
5512       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5513       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5514       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5515       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5516       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5517        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5518     return true;
5519   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5520   // imm0_4095 variant. That's the least-preferred variant when
5521   // selecting via the generic "add" mnemonic, so to know that we
5522   // should remove the cc_out operand, we have to explicitly check that
5523   // it's not one of the other variants. Ugh.
5524   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5525       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5526       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5527       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5528     // Nest conditions rather than one big 'if' statement for readability.
5529     //
5530     // If both registers are low, we're in an IT block, and the immediate is
5531     // in range, we should use encoding T1 instead, which has a cc_out.
5532     if (inITBlock() &&
5533         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5534         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5535         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5536       return false;
5537     // Check against T3. If the second register is the PC, this is an
5538     // alternate form of ADR, which uses encoding T4, so check for that too.
5539     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5540         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5541       return false;
5542
5543     // Otherwise, we use encoding T4, which does not have a cc_out
5544     // operand.
5545     return true;
5546   }
5547
5548   // The thumb2 multiply instruction doesn't have a CCOut register, so
5549   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5550   // use the 16-bit encoding or not.
5551   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5552       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5553       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5554       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5555       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5556       // If the registers aren't low regs, the destination reg isn't the
5557       // same as one of the source regs, or the cc_out operand is zero
5558       // outside of an IT block, we have to use the 32-bit encoding, so
5559       // remove the cc_out operand.
5560       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5561        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5562        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5563        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5564                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5565                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5566                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5567     return true;
5568
5569   // Also check the 'mul' syntax variant that doesn't specify an explicit
5570   // destination register.
5571   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5572       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5573       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5574       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5575       // If the registers aren't low regs  or the cc_out operand is zero
5576       // outside of an IT block, we have to use the 32-bit encoding, so
5577       // remove the cc_out operand.
5578       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5579        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5580        !inITBlock()))
5581     return true;
5582
5583
5584
5585   // Register-register 'add/sub' for thumb does not have a cc_out operand
5586   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5587   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5588   // right, this will result in better diagnostics (which operand is off)
5589   // anyway.
5590   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5591       (Operands.size() == 5 || Operands.size() == 6) &&
5592       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5593       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5594       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5595       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5596        (Operands.size() == 6 &&
5597         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5598     return true;
5599
5600   return false;
5601 }
5602
5603 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5604                                               OperandVector &Operands) {
5605   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5606   unsigned RegIdx = 3;
5607   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5608       static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32") {
5609     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5610         static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32")
5611       RegIdx = 4;
5612
5613     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5614         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5615              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5616          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5617              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5618       return true;
5619   }
5620   return false;
5621 }
5622
5623 static bool isDataTypeToken(StringRef Tok) {
5624   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5625     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5626     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5627     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5628     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5629     Tok == ".f" || Tok == ".d";
5630 }
5631
5632 // FIXME: This bit should probably be handled via an explicit match class
5633 // in the .td files that matches the suffix instead of having it be
5634 // a literal string token the way it is now.
5635 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5636   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5637 }
5638 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5639                                  unsigned VariantID);
5640
5641 static bool RequiresVFPRegListValidation(StringRef Inst,
5642                                          bool &AcceptSinglePrecisionOnly,
5643                                          bool &AcceptDoublePrecisionOnly) {
5644   if (Inst.size() < 7)
5645     return false;
5646
5647   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5648     StringRef AddressingMode = Inst.substr(4, 2);
5649     if (AddressingMode == "ia" || AddressingMode == "db" ||
5650         AddressingMode == "ea" || AddressingMode == "fd") {
5651       AcceptSinglePrecisionOnly = Inst[6] == 's';
5652       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5653       return true;
5654     }
5655   }
5656
5657   return false;
5658 }
5659
5660 /// Parse an arm instruction mnemonic followed by its operands.
5661 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5662                                     SMLoc NameLoc, OperandVector &Operands) {
5663   MCAsmParser &Parser = getParser();
5664   // FIXME: Can this be done via tablegen in some fashion?
5665   bool RequireVFPRegisterListCheck;
5666   bool AcceptSinglePrecisionOnly;
5667   bool AcceptDoublePrecisionOnly;
5668   RequireVFPRegisterListCheck =
5669     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5670                                  AcceptDoublePrecisionOnly);
5671
5672   // Apply mnemonic aliases before doing anything else, as the destination
5673   // mnemonic may include suffices and we want to handle them normally.
5674   // The generic tblgen'erated code does this later, at the start of
5675   // MatchInstructionImpl(), but that's too late for aliases that include
5676   // any sort of suffix.
5677   uint64_t AvailableFeatures = getAvailableFeatures();
5678   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5679   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5680
5681   // First check for the ARM-specific .req directive.
5682   if (Parser.getTok().is(AsmToken::Identifier) &&
5683       Parser.getTok().getIdentifier() == ".req") {
5684     parseDirectiveReq(Name, NameLoc);
5685     // We always return 'error' for this, as we're done with this
5686     // statement and don't need to match the 'instruction."
5687     return true;
5688   }
5689
5690   // Create the leading tokens for the mnemonic, split by '.' characters.
5691   size_t Start = 0, Next = Name.find('.');
5692   StringRef Mnemonic = Name.slice(Start, Next);
5693
5694   // Split out the predication code and carry setting flag from the mnemonic.
5695   unsigned PredicationCode;
5696   unsigned ProcessorIMod;
5697   bool CarrySetting;
5698   StringRef ITMask;
5699   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5700                            ProcessorIMod, ITMask);
5701
5702   // In Thumb1, only the branch (B) instruction can be predicated.
5703   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5704     Parser.eatToEndOfStatement();
5705     return Error(NameLoc, "conditional execution not supported in Thumb1");
5706   }
5707
5708   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5709
5710   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5711   // is the mask as it will be for the IT encoding if the conditional
5712   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5713   // where the conditional bit0 is zero, the instruction post-processing
5714   // will adjust the mask accordingly.
5715   if (Mnemonic == "it") {
5716     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5717     if (ITMask.size() > 3) {
5718       Parser.eatToEndOfStatement();
5719       return Error(Loc, "too many conditions on IT instruction");
5720     }
5721     unsigned Mask = 8;
5722     for (unsigned i = ITMask.size(); i != 0; --i) {
5723       char pos = ITMask[i - 1];
5724       if (pos != 't' && pos != 'e') {
5725         Parser.eatToEndOfStatement();
5726         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5727       }
5728       Mask >>= 1;
5729       if (ITMask[i - 1] == 't')
5730         Mask |= 8;
5731     }
5732     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5733   }
5734
5735   // FIXME: This is all a pretty gross hack. We should automatically handle
5736   // optional operands like this via tblgen.
5737
5738   // Next, add the CCOut and ConditionCode operands, if needed.
5739   //
5740   // For mnemonics which can ever incorporate a carry setting bit or predication
5741   // code, our matching model involves us always generating CCOut and
5742   // ConditionCode operands to match the mnemonic "as written" and then we let
5743   // the matcher deal with finding the right instruction or generating an
5744   // appropriate error.
5745   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5746   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5747
5748   // If we had a carry-set on an instruction that can't do that, issue an
5749   // error.
5750   if (!CanAcceptCarrySet && CarrySetting) {
5751     Parser.eatToEndOfStatement();
5752     return Error(NameLoc, "instruction '" + Mnemonic +
5753                  "' can not set flags, but 's' suffix specified");
5754   }
5755   // If we had a predication code on an instruction that can't do that, issue an
5756   // error.
5757   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5758     Parser.eatToEndOfStatement();
5759     return Error(NameLoc, "instruction '" + Mnemonic +
5760                  "' is not predicable, but condition code specified");
5761   }
5762
5763   // Add the carry setting operand, if necessary.
5764   if (CanAcceptCarrySet) {
5765     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5766     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5767                                                Loc));
5768   }
5769
5770   // Add the predication code operand, if necessary.
5771   if (CanAcceptPredicationCode) {
5772     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5773                                       CarrySetting);
5774     Operands.push_back(ARMOperand::CreateCondCode(
5775                          ARMCC::CondCodes(PredicationCode), Loc));
5776   }
5777
5778   // Add the processor imod operand, if necessary.
5779   if (ProcessorIMod) {
5780     Operands.push_back(ARMOperand::CreateImm(
5781           MCConstantExpr::create(ProcessorIMod, getContext()),
5782                                  NameLoc, NameLoc));
5783   } else if (Mnemonic == "cps" && isMClass()) {
5784     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5785   }
5786
5787   // Add the remaining tokens in the mnemonic.
5788   while (Next != StringRef::npos) {
5789     Start = Next;
5790     Next = Name.find('.', Start + 1);
5791     StringRef ExtraToken = Name.slice(Start, Next);
5792
5793     // Some NEON instructions have an optional datatype suffix that is
5794     // completely ignored. Check for that.
5795     if (isDataTypeToken(ExtraToken) &&
5796         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5797       continue;
5798
5799     // For for ARM mode generate an error if the .n qualifier is used.
5800     if (ExtraToken == ".n" && !isThumb()) {
5801       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5802       Parser.eatToEndOfStatement();
5803       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5804                    "arm mode");
5805     }
5806
5807     // The .n qualifier is always discarded as that is what the tables
5808     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5809     // so discard it to avoid errors that can be caused by the matcher.
5810     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5811       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5812       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5813     }
5814   }
5815
5816   // Read the remaining operands.
5817   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5818     // Read the first operand.
5819     if (parseOperand(Operands, Mnemonic)) {
5820       Parser.eatToEndOfStatement();
5821       return true;
5822     }
5823
5824     while (getLexer().is(AsmToken::Comma)) {
5825       Parser.Lex();  // Eat the comma.
5826
5827       // Parse and remember the operand.
5828       if (parseOperand(Operands, Mnemonic)) {
5829         Parser.eatToEndOfStatement();
5830         return true;
5831       }
5832     }
5833   }
5834
5835   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5836     SMLoc Loc = getLexer().getLoc();
5837     Parser.eatToEndOfStatement();
5838     return Error(Loc, "unexpected token in argument list");
5839   }
5840
5841   Parser.Lex(); // Consume the EndOfStatement
5842
5843   if (RequireVFPRegisterListCheck) {
5844     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5845     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5846       return Error(Op.getStartLoc(),
5847                    "VFP/Neon single precision register expected");
5848     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5849       return Error(Op.getStartLoc(),
5850                    "VFP/Neon double precision register expected");
5851   }
5852
5853   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
5854
5855   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5856   // do and don't have a cc_out optional-def operand. With some spot-checks
5857   // of the operand list, we can figure out which variant we're trying to
5858   // parse and adjust accordingly before actually matching. We shouldn't ever
5859   // try to remove a cc_out operand that was explicitly set on the
5860   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5861   // table driven matcher doesn't fit well with the ARM instruction set.
5862   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
5863     Operands.erase(Operands.begin() + 1);
5864
5865   // Some instructions have the same mnemonic, but don't always
5866   // have a predicate. Distinguish them here and delete the
5867   // predicate if needed.
5868   if (shouldOmitPredicateOperand(Mnemonic, Operands))
5869     Operands.erase(Operands.begin() + 1);
5870
5871   // ARM mode 'blx' need special handling, as the register operand version
5872   // is predicable, but the label operand version is not. So, we can't rely
5873   // on the Mnemonic based checking to correctly figure out when to put
5874   // a k_CondCode operand in the list. If we're trying to match the label
5875   // version, remove the k_CondCode operand here.
5876   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
5877       static_cast<ARMOperand &>(*Operands[2]).isImm())
5878     Operands.erase(Operands.begin() + 1);
5879
5880   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
5881   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
5882   // a single GPRPair reg operand is used in the .td file to replace the two
5883   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
5884   // expressed as a GPRPair, so we have to manually merge them.
5885   // FIXME: We would really like to be able to tablegen'erate this.
5886   if (!isThumb() && Operands.size() > 4 &&
5887       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
5888        Mnemonic == "stlexd")) {
5889     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
5890     unsigned Idx = isLoad ? 2 : 3;
5891     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
5892     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
5893
5894     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
5895     // Adjust only if Op1 and Op2 are GPRs.
5896     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
5897         MRC.contains(Op2.getReg())) {
5898       unsigned Reg1 = Op1.getReg();
5899       unsigned Reg2 = Op2.getReg();
5900       unsigned Rt = MRI->getEncodingValue(Reg1);
5901       unsigned Rt2 = MRI->getEncodingValue(Reg2);
5902
5903       // Rt2 must be Rt + 1 and Rt must be even.
5904       if (Rt + 1 != Rt2 || (Rt & 1)) {
5905         Error(Op2.getStartLoc(), isLoad
5906                                      ? "destination operands must be sequential"
5907                                      : "source operands must be sequential");
5908         return true;
5909       }
5910       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
5911           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
5912       Operands[Idx] =
5913           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
5914       Operands.erase(Operands.begin() + Idx + 1);
5915     }
5916   }
5917
5918   // GNU Assembler extension (compatibility)
5919   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
5920     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5921     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5922     if (Op3.isMem()) {
5923       assert(Op2.isReg() && "expected register argument");
5924
5925       unsigned SuperReg = MRI->getMatchingSuperReg(
5926           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
5927
5928       assert(SuperReg && "expected register pair");
5929
5930       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
5931
5932       Operands.insert(
5933           Operands.begin() + 3,
5934           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
5935     }
5936   }
5937
5938   // FIXME: As said above, this is all a pretty gross hack.  This instruction
5939   // does not fit with other "subs" and tblgen.
5940   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
5941   // so the Mnemonic is the original name "subs" and delete the predicate
5942   // operand so it will match the table entry.
5943   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
5944       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5945       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
5946       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5947       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
5948       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5949     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
5950     Operands.erase(Operands.begin() + 1);
5951   }
5952   return false;
5953 }
5954
5955 // Validate context-sensitive operand constraints.
5956
5957 // return 'true' if register list contains non-low GPR registers,
5958 // 'false' otherwise. If Reg is in the register list or is HiReg, set
5959 // 'containsReg' to true.
5960 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
5961                                  unsigned Reg, unsigned HiReg,
5962                                  bool &containsReg) {
5963   containsReg = false;
5964   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
5965     unsigned OpReg = Inst.getOperand(i).getReg();
5966     if (OpReg == Reg)
5967       containsReg = true;
5968     // Anything other than a low register isn't legal here.
5969     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
5970       return true;
5971   }
5972   return false;
5973 }
5974
5975 // Check if the specified regisgter is in the register list of the inst,
5976 // starting at the indicated operand number.
5977 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
5978   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
5979     unsigned OpReg = Inst.getOperand(i).getReg();
5980     if (OpReg == Reg)
5981       return true;
5982   }
5983   return false;
5984 }
5985
5986 // Return true if instruction has the interesting property of being
5987 // allowed in IT blocks, but not being predicable.
5988 static bool instIsBreakpoint(const MCInst &Inst) {
5989     return Inst.getOpcode() == ARM::tBKPT ||
5990            Inst.getOpcode() == ARM::BKPT ||
5991            Inst.getOpcode() == ARM::tHLT ||
5992            Inst.getOpcode() == ARM::HLT;
5993
5994 }
5995
5996 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
5997                                        const OperandVector &Operands,
5998                                        unsigned ListNo, bool IsARPop) {
5999   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6000   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6001
6002   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6003   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6004   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6005
6006   if (!IsARPop && ListContainsSP)
6007     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6008                  "SP may not be in the register list");
6009   else if (ListContainsPC && ListContainsLR)
6010     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6011                  "PC and LR may not be in the register list simultaneously");
6012   else if (inITBlock() && !lastInITBlock() && ListContainsPC)
6013     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6014                  "instruction must be outside of IT block or the last "
6015                  "instruction in an IT block");
6016   return false;
6017 }
6018
6019 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6020                                        const OperandVector &Operands,
6021                                        unsigned ListNo) {
6022   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6023   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6024
6025   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6026   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6027
6028   if (ListContainsSP && ListContainsPC)
6029     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6030                  "SP and PC may not be in the register list");
6031   else if (ListContainsSP)
6032     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6033                  "SP may not be in the register list");
6034   else if (ListContainsPC)
6035     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6036                  "PC may not be in the register list");
6037   return false;
6038 }
6039
6040 // FIXME: We would really like to be able to tablegen'erate this.
6041 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6042                                        const OperandVector &Operands) {
6043   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6044   SMLoc Loc = Operands[0]->getStartLoc();
6045
6046   // Check the IT block state first.
6047   // NOTE: BKPT and HLT instructions have the interesting property of being
6048   // allowed in IT blocks, but not being predicable. They just always execute.
6049   if (inITBlock() && !instIsBreakpoint(Inst)) {
6050     unsigned Bit = 1;
6051     if (ITState.FirstCond)
6052       ITState.FirstCond = false;
6053     else
6054       Bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
6055     // The instruction must be predicable.
6056     if (!MCID.isPredicable())
6057       return Error(Loc, "instructions in IT block must be predicable");
6058     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6059     unsigned ITCond = Bit ? ITState.Cond :
6060       ARMCC::getOppositeCondition(ITState.Cond);
6061     if (Cond != ITCond) {
6062       // Find the condition code Operand to get its SMLoc information.
6063       SMLoc CondLoc;
6064       for (unsigned I = 1; I < Operands.size(); ++I)
6065         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6066           CondLoc = Operands[I]->getStartLoc();
6067       return Error(CondLoc, "incorrect condition in IT block; got '" +
6068                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6069                    "', but expected '" +
6070                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
6071     }
6072   // Check for non-'al' condition codes outside of the IT block.
6073   } else if (isThumbTwo() && MCID.isPredicable() &&
6074              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6075              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6076              Inst.getOpcode() != ARM::t2Bcc)
6077     return Error(Loc, "predicated instructions must be in IT block");
6078
6079   const unsigned Opcode = Inst.getOpcode();
6080   switch (Opcode) {
6081   case ARM::LDRD:
6082   case ARM::LDRD_PRE:
6083   case ARM::LDRD_POST: {
6084     const unsigned RtReg = Inst.getOperand(0).getReg();
6085
6086     // Rt can't be R14.
6087     if (RtReg == ARM::LR)
6088       return Error(Operands[3]->getStartLoc(),
6089                    "Rt can't be R14");
6090
6091     const unsigned Rt = MRI->getEncodingValue(RtReg);
6092     // Rt must be even-numbered.
6093     if ((Rt & 1) == 1)
6094       return Error(Operands[3]->getStartLoc(),
6095                    "Rt must be even-numbered");
6096
6097     // Rt2 must be Rt + 1.
6098     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6099     if (Rt2 != Rt + 1)
6100       return Error(Operands[3]->getStartLoc(),
6101                    "destination operands must be sequential");
6102
6103     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6104       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6105       // For addressing modes with writeback, the base register needs to be
6106       // different from the destination registers.
6107       if (Rn == Rt || Rn == Rt2)
6108         return Error(Operands[3]->getStartLoc(),
6109                      "base register needs to be different from destination "
6110                      "registers");
6111     }
6112
6113     return false;
6114   }
6115   case ARM::t2LDRDi8:
6116   case ARM::t2LDRD_PRE:
6117   case ARM::t2LDRD_POST: {
6118     // Rt2 must be different from Rt.
6119     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6120     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6121     if (Rt2 == Rt)
6122       return Error(Operands[3]->getStartLoc(),
6123                    "destination operands can't be identical");
6124     return false;
6125   }
6126   case ARM::t2BXJ: {
6127     const unsigned RmReg = Inst.getOperand(0).getReg();
6128     // Rm = SP is no longer unpredictable in v8-A
6129     if (RmReg == ARM::SP && !hasV8Ops())
6130       return Error(Operands[2]->getStartLoc(),
6131                    "r13 (SP) is an unpredictable operand to BXJ");
6132     return false;
6133   }
6134   case ARM::STRD: {
6135     // Rt2 must be Rt + 1.
6136     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6137     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6138     if (Rt2 != Rt + 1)
6139       return Error(Operands[3]->getStartLoc(),
6140                    "source operands must be sequential");
6141     return false;
6142   }
6143   case ARM::STRD_PRE:
6144   case ARM::STRD_POST: {
6145     // Rt2 must be Rt + 1.
6146     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6147     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6148     if (Rt2 != Rt + 1)
6149       return Error(Operands[3]->getStartLoc(),
6150                    "source operands must be sequential");
6151     return false;
6152   }
6153   case ARM::STR_PRE_IMM:
6154   case ARM::STR_PRE_REG:
6155   case ARM::STR_POST_IMM:
6156   case ARM::STR_POST_REG:
6157   case ARM::STRH_PRE:
6158   case ARM::STRH_POST:
6159   case ARM::STRB_PRE_IMM:
6160   case ARM::STRB_PRE_REG:
6161   case ARM::STRB_POST_IMM:
6162   case ARM::STRB_POST_REG: {
6163     // Rt must be different from Rn.
6164     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6165     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6166
6167     if (Rt == Rn)
6168       return Error(Operands[3]->getStartLoc(),
6169                    "source register and base register can't be identical");
6170     return false;
6171   }
6172   case ARM::LDR_PRE_IMM:
6173   case ARM::LDR_PRE_REG:
6174   case ARM::LDR_POST_IMM:
6175   case ARM::LDR_POST_REG:
6176   case ARM::LDRH_PRE:
6177   case ARM::LDRH_POST:
6178   case ARM::LDRSH_PRE:
6179   case ARM::LDRSH_POST:
6180   case ARM::LDRB_PRE_IMM:
6181   case ARM::LDRB_PRE_REG:
6182   case ARM::LDRB_POST_IMM:
6183   case ARM::LDRB_POST_REG:
6184   case ARM::LDRSB_PRE:
6185   case ARM::LDRSB_POST: {
6186     // Rt must be different from Rn.
6187     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6188     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6189
6190     if (Rt == Rn)
6191       return Error(Operands[3]->getStartLoc(),
6192                    "destination register and base register can't be identical");
6193     return false;
6194   }
6195   case ARM::SBFX:
6196   case ARM::UBFX: {
6197     // Width must be in range [1, 32-lsb].
6198     unsigned LSB = Inst.getOperand(2).getImm();
6199     unsigned Widthm1 = Inst.getOperand(3).getImm();
6200     if (Widthm1 >= 32 - LSB)
6201       return Error(Operands[5]->getStartLoc(),
6202                    "bitfield width must be in range [1,32-lsb]");
6203     return false;
6204   }
6205   // Notionally handles ARM::tLDMIA_UPD too.
6206   case ARM::tLDMIA: {
6207     // If we're parsing Thumb2, the .w variant is available and handles
6208     // most cases that are normally illegal for a Thumb1 LDM instruction.
6209     // We'll make the transformation in processInstruction() if necessary.
6210     //
6211     // Thumb LDM instructions are writeback iff the base register is not
6212     // in the register list.
6213     unsigned Rn = Inst.getOperand(0).getReg();
6214     bool HasWritebackToken =
6215         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6216          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6217     bool ListContainsBase;
6218     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6219       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6220                    "registers must be in range r0-r7");
6221     // If we should have writeback, then there should be a '!' token.
6222     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6223       return Error(Operands[2]->getStartLoc(),
6224                    "writeback operator '!' expected");
6225     // If we should not have writeback, there must not be a '!'. This is
6226     // true even for the 32-bit wide encodings.
6227     if (ListContainsBase && HasWritebackToken)
6228       return Error(Operands[3]->getStartLoc(),
6229                    "writeback operator '!' not allowed when base register "
6230                    "in register list");
6231
6232     if (validatetLDMRegList(Inst, Operands, 3))
6233       return true;
6234     break;
6235   }
6236   case ARM::LDMIA_UPD:
6237   case ARM::LDMDB_UPD:
6238   case ARM::LDMIB_UPD:
6239   case ARM::LDMDA_UPD:
6240     // ARM variants loading and updating the same register are only officially
6241     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6242     if (!hasV7Ops())
6243       break;
6244     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6245       return Error(Operands.back()->getStartLoc(),
6246                    "writeback register not allowed in register list");
6247     break;
6248   case ARM::t2LDMIA:
6249   case ARM::t2LDMDB:
6250     if (validatetLDMRegList(Inst, Operands, 3))
6251       return true;
6252     break;
6253   case ARM::t2STMIA:
6254   case ARM::t2STMDB:
6255     if (validatetSTMRegList(Inst, Operands, 3))
6256       return true;
6257     break;
6258   case ARM::t2LDMIA_UPD:
6259   case ARM::t2LDMDB_UPD:
6260   case ARM::t2STMIA_UPD:
6261   case ARM::t2STMDB_UPD: {
6262     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6263       return Error(Operands.back()->getStartLoc(),
6264                    "writeback register not allowed in register list");
6265
6266     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6267       if (validatetLDMRegList(Inst, Operands, 3))
6268         return true;
6269     } else {
6270       if (validatetSTMRegList(Inst, Operands, 3))
6271         return true;
6272     }
6273     break;
6274   }
6275   case ARM::sysLDMIA_UPD:
6276   case ARM::sysLDMDA_UPD:
6277   case ARM::sysLDMDB_UPD:
6278   case ARM::sysLDMIB_UPD:
6279     if (!listContainsReg(Inst, 3, ARM::PC))
6280       return Error(Operands[4]->getStartLoc(),
6281                    "writeback register only allowed on system LDM "
6282                    "if PC in register-list");
6283     break;
6284   case ARM::sysSTMIA_UPD:
6285   case ARM::sysSTMDA_UPD:
6286   case ARM::sysSTMDB_UPD:
6287   case ARM::sysSTMIB_UPD:
6288     return Error(Operands[2]->getStartLoc(),
6289                  "system STM cannot have writeback register");
6290   case ARM::tMUL: {
6291     // The second source operand must be the same register as the destination
6292     // operand.
6293     //
6294     // In this case, we must directly check the parsed operands because the
6295     // cvtThumbMultiply() function is written in such a way that it guarantees
6296     // this first statement is always true for the new Inst.  Essentially, the
6297     // destination is unconditionally copied into the second source operand
6298     // without checking to see if it matches what we actually parsed.
6299     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6300                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6301         (((ARMOperand &)*Operands[3]).getReg() !=
6302          ((ARMOperand &)*Operands[4]).getReg())) {
6303       return Error(Operands[3]->getStartLoc(),
6304                    "destination register must match source register");
6305     }
6306     break;
6307   }
6308   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6309   // so only issue a diagnostic for thumb1. The instructions will be
6310   // switched to the t2 encodings in processInstruction() if necessary.
6311   case ARM::tPOP: {
6312     bool ListContainsBase;
6313     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6314         !isThumbTwo())
6315       return Error(Operands[2]->getStartLoc(),
6316                    "registers must be in range r0-r7 or pc");
6317     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6318       return true;
6319     break;
6320   }
6321   case ARM::tPUSH: {
6322     bool ListContainsBase;
6323     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6324         !isThumbTwo())
6325       return Error(Operands[2]->getStartLoc(),
6326                    "registers must be in range r0-r7 or lr");
6327     if (validatetSTMRegList(Inst, Operands, 2))
6328       return true;
6329     break;
6330   }
6331   case ARM::tSTMIA_UPD: {
6332     bool ListContainsBase, InvalidLowList;
6333     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6334                                           0, ListContainsBase);
6335     if (InvalidLowList && !isThumbTwo())
6336       return Error(Operands[4]->getStartLoc(),
6337                    "registers must be in range r0-r7");
6338
6339     // This would be converted to a 32-bit stm, but that's not valid if the
6340     // writeback register is in the list.
6341     if (InvalidLowList && ListContainsBase)
6342       return Error(Operands[4]->getStartLoc(),
6343                    "writeback operator '!' not allowed when base register "
6344                    "in register list");
6345
6346     if (validatetSTMRegList(Inst, Operands, 4))
6347       return true;
6348     break;
6349   }
6350   case ARM::tADDrSP: {
6351     // If the non-SP source operand and the destination operand are not the
6352     // same, we need thumb2 (for the wide encoding), or we have an error.
6353     if (!isThumbTwo() &&
6354         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6355       return Error(Operands[4]->getStartLoc(),
6356                    "source register must be the same as destination");
6357     }
6358     break;
6359   }
6360   // Final range checking for Thumb unconditional branch instructions.
6361   case ARM::tB:
6362     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6363       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6364     break;
6365   case ARM::t2B: {
6366     int op = (Operands[2]->isImm()) ? 2 : 3;
6367     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6368       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6369     break;
6370   }
6371   // Final range checking for Thumb conditional branch instructions.
6372   case ARM::tBcc:
6373     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6374       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6375     break;
6376   case ARM::t2Bcc: {
6377     int Op = (Operands[2]->isImm()) ? 2 : 3;
6378     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6379       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6380     break;
6381   }
6382   case ARM::MOVi16:
6383   case ARM::t2MOVi16:
6384   case ARM::t2MOVTi16:
6385     {
6386     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6387     // especially when we turn it into a movw and the expression <symbol> does
6388     // not have a :lower16: or :upper16 as part of the expression.  We don't
6389     // want the behavior of silently truncating, which can be unexpected and
6390     // lead to bugs that are difficult to find since this is an easy mistake
6391     // to make.
6392     int i = (Operands[3]->isImm()) ? 3 : 4;
6393     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6394     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6395     if (CE) break;
6396     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6397     if (!E) break;
6398     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6399     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6400                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6401       return Error(
6402           Op.getStartLoc(),
6403           "immediate expression for mov requires :lower16: or :upper16");
6404     break;
6405   }
6406   }
6407
6408   return false;
6409 }
6410
6411 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6412   switch(Opc) {
6413   default: llvm_unreachable("unexpected opcode!");
6414   // VST1LN
6415   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6416   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6417   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6418   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6419   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6420   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6421   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6422   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6423   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6424
6425   // VST2LN
6426   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6427   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6428   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6429   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6430   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6431
6432   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6433   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6434   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6435   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6436   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6437
6438   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6439   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6440   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6441   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6442   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6443
6444   // VST3LN
6445   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6446   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6447   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6448   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6449   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6450   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6451   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6452   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6453   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6454   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6455   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6456   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6457   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6458   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6459   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6460
6461   // VST3
6462   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6463   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6464   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6465   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6466   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6467   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6468   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6469   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6470   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6471   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6472   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6473   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6474   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6475   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6476   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6477   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6478   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6479   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6480
6481   // VST4LN
6482   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6483   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6484   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6485   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6486   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6487   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6488   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6489   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6490   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6491   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6492   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6493   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6494   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6495   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6496   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6497
6498   // VST4
6499   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6500   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6501   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6502   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6503   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6504   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6505   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6506   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6507   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6508   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6509   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6510   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6511   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6512   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6513   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6514   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6515   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6516   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6517   }
6518 }
6519
6520 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6521   switch(Opc) {
6522   default: llvm_unreachable("unexpected opcode!");
6523   // VLD1LN
6524   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6525   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6526   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6527   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6528   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6529   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6530   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6531   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6532   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6533
6534   // VLD2LN
6535   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6536   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6537   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6538   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6539   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6540   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6541   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6542   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6543   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6544   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6545   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6546   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6547   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6548   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6549   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6550
6551   // VLD3DUP
6552   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6553   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6554   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6555   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6556   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6557   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6558   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6559   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6560   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6561   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6562   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6563   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6564   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6565   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6566   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6567   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6568   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6569   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6570
6571   // VLD3LN
6572   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6573   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6574   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6575   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6576   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6577   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6578   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6579   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6580   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6581   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6582   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6583   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6584   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6585   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6586   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6587
6588   // VLD3
6589   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6590   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6591   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6592   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6593   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6594   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6595   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6596   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6597   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6598   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6599   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6600   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6601   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6602   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6603   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6604   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6605   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6606   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6607
6608   // VLD4LN
6609   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6610   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6611   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6612   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6613   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6614   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6615   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6616   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6617   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6618   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6619   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6620   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6621   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6622   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6623   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6624
6625   // VLD4DUP
6626   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6627   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6628   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6629   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6630   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6631   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6632   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6633   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6634   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6635   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6636   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6637   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6638   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6639   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6640   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6641   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6642   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6643   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6644
6645   // VLD4
6646   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6647   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6648   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6649   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6650   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6651   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6652   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6653   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6654   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6655   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6656   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6657   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6658   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6659   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6660   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6661   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6662   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6663   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6664   }
6665 }
6666
6667 bool ARMAsmParser::processInstruction(MCInst &Inst,
6668                                       const OperandVector &Operands,
6669                                       MCStreamer &Out) {
6670   switch (Inst.getOpcode()) {
6671   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6672   case ARM::LDRT_POST:
6673   case ARM::LDRBT_POST: {
6674     const unsigned Opcode =
6675       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6676                                            : ARM::LDRBT_POST_IMM;
6677     MCInst TmpInst;
6678     TmpInst.setOpcode(Opcode);
6679     TmpInst.addOperand(Inst.getOperand(0));
6680     TmpInst.addOperand(Inst.getOperand(1));
6681     TmpInst.addOperand(Inst.getOperand(1));
6682     TmpInst.addOperand(MCOperand::createReg(0));
6683     TmpInst.addOperand(MCOperand::createImm(0));
6684     TmpInst.addOperand(Inst.getOperand(2));
6685     TmpInst.addOperand(Inst.getOperand(3));
6686     Inst = TmpInst;
6687     return true;
6688   }
6689   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6690   case ARM::STRT_POST:
6691   case ARM::STRBT_POST: {
6692     const unsigned Opcode =
6693       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6694                                            : ARM::STRBT_POST_IMM;
6695     MCInst TmpInst;
6696     TmpInst.setOpcode(Opcode);
6697     TmpInst.addOperand(Inst.getOperand(1));
6698     TmpInst.addOperand(Inst.getOperand(0));
6699     TmpInst.addOperand(Inst.getOperand(1));
6700     TmpInst.addOperand(MCOperand::createReg(0));
6701     TmpInst.addOperand(MCOperand::createImm(0));
6702     TmpInst.addOperand(Inst.getOperand(2));
6703     TmpInst.addOperand(Inst.getOperand(3));
6704     Inst = TmpInst;
6705     return true;
6706   }
6707   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6708   case ARM::ADDri: {
6709     if (Inst.getOperand(1).getReg() != ARM::PC ||
6710         Inst.getOperand(5).getReg() != 0 ||
6711         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6712       return false;
6713     MCInst TmpInst;
6714     TmpInst.setOpcode(ARM::ADR);
6715     TmpInst.addOperand(Inst.getOperand(0));
6716     if (Inst.getOperand(2).isImm()) {
6717       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6718       // before passing it to the ADR instruction.
6719       unsigned Enc = Inst.getOperand(2).getImm();
6720       TmpInst.addOperand(MCOperand::createImm(
6721         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6722     } else {
6723       // Turn PC-relative expression into absolute expression.
6724       // Reading PC provides the start of the current instruction + 8 and
6725       // the transform to adr is biased by that.
6726       MCSymbol *Dot = getContext().createTempSymbol();
6727       Out.EmitLabel(Dot);
6728       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6729       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6730                                                      MCSymbolRefExpr::VK_None,
6731                                                      getContext());
6732       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6733       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6734                                                      getContext());
6735       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6736                                                         getContext());
6737       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6738     }
6739     TmpInst.addOperand(Inst.getOperand(3));
6740     TmpInst.addOperand(Inst.getOperand(4));
6741     Inst = TmpInst;
6742     return true;
6743   }
6744   // Aliases for alternate PC+imm syntax of LDR instructions.
6745   case ARM::t2LDRpcrel:
6746     // Select the narrow version if the immediate will fit.
6747     if (Inst.getOperand(1).getImm() > 0 &&
6748         Inst.getOperand(1).getImm() <= 0xff &&
6749         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6750           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
6751       Inst.setOpcode(ARM::tLDRpci);
6752     else
6753       Inst.setOpcode(ARM::t2LDRpci);
6754     return true;
6755   case ARM::t2LDRBpcrel:
6756     Inst.setOpcode(ARM::t2LDRBpci);
6757     return true;
6758   case ARM::t2LDRHpcrel:
6759     Inst.setOpcode(ARM::t2LDRHpci);
6760     return true;
6761   case ARM::t2LDRSBpcrel:
6762     Inst.setOpcode(ARM::t2LDRSBpci);
6763     return true;
6764   case ARM::t2LDRSHpcrel:
6765     Inst.setOpcode(ARM::t2LDRSHpci);
6766     return true;
6767   // Handle NEON VST complex aliases.
6768   case ARM::VST1LNdWB_register_Asm_8:
6769   case ARM::VST1LNdWB_register_Asm_16:
6770   case ARM::VST1LNdWB_register_Asm_32: {
6771     MCInst TmpInst;
6772     // Shuffle the operands around so the lane index operand is in the
6773     // right place.
6774     unsigned Spacing;
6775     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6776     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6777     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6778     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6779     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6780     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6781     TmpInst.addOperand(Inst.getOperand(1)); // lane
6782     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6783     TmpInst.addOperand(Inst.getOperand(6));
6784     Inst = TmpInst;
6785     return true;
6786   }
6787
6788   case ARM::VST2LNdWB_register_Asm_8:
6789   case ARM::VST2LNdWB_register_Asm_16:
6790   case ARM::VST2LNdWB_register_Asm_32:
6791   case ARM::VST2LNqWB_register_Asm_16:
6792   case ARM::VST2LNqWB_register_Asm_32: {
6793     MCInst TmpInst;
6794     // Shuffle the operands around so the lane index operand is in the
6795     // right place.
6796     unsigned Spacing;
6797     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6798     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6799     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6800     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6801     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6802     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6803     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6804                                             Spacing));
6805     TmpInst.addOperand(Inst.getOperand(1)); // lane
6806     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6807     TmpInst.addOperand(Inst.getOperand(6));
6808     Inst = TmpInst;
6809     return true;
6810   }
6811
6812   case ARM::VST3LNdWB_register_Asm_8:
6813   case ARM::VST3LNdWB_register_Asm_16:
6814   case ARM::VST3LNdWB_register_Asm_32:
6815   case ARM::VST3LNqWB_register_Asm_16:
6816   case ARM::VST3LNqWB_register_Asm_32: {
6817     MCInst TmpInst;
6818     // Shuffle the operands around so the lane index operand is in the
6819     // right place.
6820     unsigned Spacing;
6821     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6822     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6823     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6824     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6825     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6826     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6827     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6828                                             Spacing));
6829     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6830                                             Spacing * 2));
6831     TmpInst.addOperand(Inst.getOperand(1)); // lane
6832     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6833     TmpInst.addOperand(Inst.getOperand(6));
6834     Inst = TmpInst;
6835     return true;
6836   }
6837
6838   case ARM::VST4LNdWB_register_Asm_8:
6839   case ARM::VST4LNdWB_register_Asm_16:
6840   case ARM::VST4LNdWB_register_Asm_32:
6841   case ARM::VST4LNqWB_register_Asm_16:
6842   case ARM::VST4LNqWB_register_Asm_32: {
6843     MCInst TmpInst;
6844     // Shuffle the operands around so the lane index operand is in the
6845     // right place.
6846     unsigned Spacing;
6847     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6848     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6849     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6850     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6851     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6852     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6853     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6854                                             Spacing));
6855     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6856                                             Spacing * 2));
6857     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6858                                             Spacing * 3));
6859     TmpInst.addOperand(Inst.getOperand(1)); // lane
6860     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6861     TmpInst.addOperand(Inst.getOperand(6));
6862     Inst = TmpInst;
6863     return true;
6864   }
6865
6866   case ARM::VST1LNdWB_fixed_Asm_8:
6867   case ARM::VST1LNdWB_fixed_Asm_16:
6868   case ARM::VST1LNdWB_fixed_Asm_32: {
6869     MCInst TmpInst;
6870     // Shuffle the operands around so the lane index operand is in the
6871     // right place.
6872     unsigned Spacing;
6873     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6874     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6875     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6876     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6877     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6878     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6879     TmpInst.addOperand(Inst.getOperand(1)); // lane
6880     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6881     TmpInst.addOperand(Inst.getOperand(5));
6882     Inst = TmpInst;
6883     return true;
6884   }
6885
6886   case ARM::VST2LNdWB_fixed_Asm_8:
6887   case ARM::VST2LNdWB_fixed_Asm_16:
6888   case ARM::VST2LNdWB_fixed_Asm_32:
6889   case ARM::VST2LNqWB_fixed_Asm_16:
6890   case ARM::VST2LNqWB_fixed_Asm_32: {
6891     MCInst TmpInst;
6892     // Shuffle the operands around so the lane index operand is in the
6893     // right place.
6894     unsigned Spacing;
6895     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6896     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6897     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6898     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6899     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6900     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6901     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6902                                             Spacing));
6903     TmpInst.addOperand(Inst.getOperand(1)); // lane
6904     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6905     TmpInst.addOperand(Inst.getOperand(5));
6906     Inst = TmpInst;
6907     return true;
6908   }
6909
6910   case ARM::VST3LNdWB_fixed_Asm_8:
6911   case ARM::VST3LNdWB_fixed_Asm_16:
6912   case ARM::VST3LNdWB_fixed_Asm_32:
6913   case ARM::VST3LNqWB_fixed_Asm_16:
6914   case ARM::VST3LNqWB_fixed_Asm_32: {
6915     MCInst TmpInst;
6916     // Shuffle the operands around so the lane index operand is in the
6917     // right place.
6918     unsigned Spacing;
6919     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6920     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6921     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6922     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6923     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6924     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6925     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6926                                             Spacing));
6927     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6928                                             Spacing * 2));
6929     TmpInst.addOperand(Inst.getOperand(1)); // lane
6930     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6931     TmpInst.addOperand(Inst.getOperand(5));
6932     Inst = TmpInst;
6933     return true;
6934   }
6935
6936   case ARM::VST4LNdWB_fixed_Asm_8:
6937   case ARM::VST4LNdWB_fixed_Asm_16:
6938   case ARM::VST4LNdWB_fixed_Asm_32:
6939   case ARM::VST4LNqWB_fixed_Asm_16:
6940   case ARM::VST4LNqWB_fixed_Asm_32: {
6941     MCInst TmpInst;
6942     // Shuffle the operands around so the lane index operand is in the
6943     // right place.
6944     unsigned Spacing;
6945     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6946     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6947     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6948     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6949     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
6950     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6951     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6952                                             Spacing));
6953     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6954                                             Spacing * 2));
6955     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6956                                             Spacing * 3));
6957     TmpInst.addOperand(Inst.getOperand(1)); // lane
6958     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6959     TmpInst.addOperand(Inst.getOperand(5));
6960     Inst = TmpInst;
6961     return true;
6962   }
6963
6964   case ARM::VST1LNdAsm_8:
6965   case ARM::VST1LNdAsm_16:
6966   case ARM::VST1LNdAsm_32: {
6967     MCInst TmpInst;
6968     // Shuffle the operands around so the lane index operand is in the
6969     // right place.
6970     unsigned Spacing;
6971     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6972     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6973     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6974     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6975     TmpInst.addOperand(Inst.getOperand(1)); // lane
6976     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6977     TmpInst.addOperand(Inst.getOperand(5));
6978     Inst = TmpInst;
6979     return true;
6980   }
6981
6982   case ARM::VST2LNdAsm_8:
6983   case ARM::VST2LNdAsm_16:
6984   case ARM::VST2LNdAsm_32:
6985   case ARM::VST2LNqAsm_16:
6986   case ARM::VST2LNqAsm_32: {
6987     MCInst TmpInst;
6988     // Shuffle the operands around so the lane index operand is in the
6989     // right place.
6990     unsigned Spacing;
6991     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6992     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6993     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6994     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6995     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
6996                                             Spacing));
6997     TmpInst.addOperand(Inst.getOperand(1)); // lane
6998     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6999     TmpInst.addOperand(Inst.getOperand(5));
7000     Inst = TmpInst;
7001     return true;
7002   }
7003
7004   case ARM::VST3LNdAsm_8:
7005   case ARM::VST3LNdAsm_16:
7006   case ARM::VST3LNdAsm_32:
7007   case ARM::VST3LNqAsm_16:
7008   case ARM::VST3LNqAsm_32: {
7009     MCInst TmpInst;
7010     // Shuffle the operands around so the lane index operand is in the
7011     // right place.
7012     unsigned Spacing;
7013     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7014     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7015     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7016     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7017     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7018                                             Spacing));
7019     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7020                                             Spacing * 2));
7021     TmpInst.addOperand(Inst.getOperand(1)); // lane
7022     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7023     TmpInst.addOperand(Inst.getOperand(5));
7024     Inst = TmpInst;
7025     return true;
7026   }
7027
7028   case ARM::VST4LNdAsm_8:
7029   case ARM::VST4LNdAsm_16:
7030   case ARM::VST4LNdAsm_32:
7031   case ARM::VST4LNqAsm_16:
7032   case ARM::VST4LNqAsm_32: {
7033     MCInst TmpInst;
7034     // Shuffle the operands around so the lane index operand is in the
7035     // right place.
7036     unsigned Spacing;
7037     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7038     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7039     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7040     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7041     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7042                                             Spacing));
7043     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7044                                             Spacing * 2));
7045     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7046                                             Spacing * 3));
7047     TmpInst.addOperand(Inst.getOperand(1)); // lane
7048     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7049     TmpInst.addOperand(Inst.getOperand(5));
7050     Inst = TmpInst;
7051     return true;
7052   }
7053
7054   // Handle NEON VLD complex aliases.
7055   case ARM::VLD1LNdWB_register_Asm_8:
7056   case ARM::VLD1LNdWB_register_Asm_16:
7057   case ARM::VLD1LNdWB_register_Asm_32: {
7058     MCInst TmpInst;
7059     // Shuffle the operands around so the lane index operand is in the
7060     // right place.
7061     unsigned Spacing;
7062     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7063     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7064     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7065     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7066     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7067     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7068     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7069     TmpInst.addOperand(Inst.getOperand(1)); // lane
7070     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7071     TmpInst.addOperand(Inst.getOperand(6));
7072     Inst = TmpInst;
7073     return true;
7074   }
7075
7076   case ARM::VLD2LNdWB_register_Asm_8:
7077   case ARM::VLD2LNdWB_register_Asm_16:
7078   case ARM::VLD2LNdWB_register_Asm_32:
7079   case ARM::VLD2LNqWB_register_Asm_16:
7080   case ARM::VLD2LNqWB_register_Asm_32: {
7081     MCInst TmpInst;
7082     // Shuffle the operands around so the lane index operand is in the
7083     // right place.
7084     unsigned Spacing;
7085     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7086     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7087     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7088                                             Spacing));
7089     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7090     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7091     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7092     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7093     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7094     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7095                                             Spacing));
7096     TmpInst.addOperand(Inst.getOperand(1)); // lane
7097     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7098     TmpInst.addOperand(Inst.getOperand(6));
7099     Inst = TmpInst;
7100     return true;
7101   }
7102
7103   case ARM::VLD3LNdWB_register_Asm_8:
7104   case ARM::VLD3LNdWB_register_Asm_16:
7105   case ARM::VLD3LNdWB_register_Asm_32:
7106   case ARM::VLD3LNqWB_register_Asm_16:
7107   case ARM::VLD3LNqWB_register_Asm_32: {
7108     MCInst TmpInst;
7109     // Shuffle the operands around so the lane index operand is in the
7110     // right place.
7111     unsigned Spacing;
7112     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7113     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7114     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7115                                             Spacing));
7116     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7117                                             Spacing * 2));
7118     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7119     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7120     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7121     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7122     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7123     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7124                                             Spacing));
7125     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7126                                             Spacing * 2));
7127     TmpInst.addOperand(Inst.getOperand(1)); // lane
7128     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7129     TmpInst.addOperand(Inst.getOperand(6));
7130     Inst = TmpInst;
7131     return true;
7132   }
7133
7134   case ARM::VLD4LNdWB_register_Asm_8:
7135   case ARM::VLD4LNdWB_register_Asm_16:
7136   case ARM::VLD4LNdWB_register_Asm_32:
7137   case ARM::VLD4LNqWB_register_Asm_16:
7138   case ARM::VLD4LNqWB_register_Asm_32: {
7139     MCInst TmpInst;
7140     // Shuffle the operands around so the lane index operand is in the
7141     // right place.
7142     unsigned Spacing;
7143     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7144     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7145     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7146                                             Spacing));
7147     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7148                                             Spacing * 2));
7149     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7150                                             Spacing * 3));
7151     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7152     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7153     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7154     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7155     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7156     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7157                                             Spacing));
7158     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7159                                             Spacing * 2));
7160     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7161                                             Spacing * 3));
7162     TmpInst.addOperand(Inst.getOperand(1)); // lane
7163     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7164     TmpInst.addOperand(Inst.getOperand(6));
7165     Inst = TmpInst;
7166     return true;
7167   }
7168
7169   case ARM::VLD1LNdWB_fixed_Asm_8:
7170   case ARM::VLD1LNdWB_fixed_Asm_16:
7171   case ARM::VLD1LNdWB_fixed_Asm_32: {
7172     MCInst TmpInst;
7173     // Shuffle the operands around so the lane index operand is in the
7174     // right place.
7175     unsigned Spacing;
7176     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7177     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7178     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7179     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7180     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7181     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7182     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7183     TmpInst.addOperand(Inst.getOperand(1)); // lane
7184     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7185     TmpInst.addOperand(Inst.getOperand(5));
7186     Inst = TmpInst;
7187     return true;
7188   }
7189
7190   case ARM::VLD2LNdWB_fixed_Asm_8:
7191   case ARM::VLD2LNdWB_fixed_Asm_16:
7192   case ARM::VLD2LNdWB_fixed_Asm_32:
7193   case ARM::VLD2LNqWB_fixed_Asm_16:
7194   case ARM::VLD2LNqWB_fixed_Asm_32: {
7195     MCInst TmpInst;
7196     // Shuffle the operands around so the lane index operand is in the
7197     // right place.
7198     unsigned Spacing;
7199     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7200     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7201     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7202                                             Spacing));
7203     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7204     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7205     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7206     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7207     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7208     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7209                                             Spacing));
7210     TmpInst.addOperand(Inst.getOperand(1)); // lane
7211     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7212     TmpInst.addOperand(Inst.getOperand(5));
7213     Inst = TmpInst;
7214     return true;
7215   }
7216
7217   case ARM::VLD3LNdWB_fixed_Asm_8:
7218   case ARM::VLD3LNdWB_fixed_Asm_16:
7219   case ARM::VLD3LNdWB_fixed_Asm_32:
7220   case ARM::VLD3LNqWB_fixed_Asm_16:
7221   case ARM::VLD3LNqWB_fixed_Asm_32: {
7222     MCInst TmpInst;
7223     // Shuffle the operands around so the lane index operand is in the
7224     // right place.
7225     unsigned Spacing;
7226     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7227     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7228     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7229                                             Spacing));
7230     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7231                                             Spacing * 2));
7232     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7233     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7234     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7235     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7236     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7237     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7238                                             Spacing));
7239     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7240                                             Spacing * 2));
7241     TmpInst.addOperand(Inst.getOperand(1)); // lane
7242     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7243     TmpInst.addOperand(Inst.getOperand(5));
7244     Inst = TmpInst;
7245     return true;
7246   }
7247
7248   case ARM::VLD4LNdWB_fixed_Asm_8:
7249   case ARM::VLD4LNdWB_fixed_Asm_16:
7250   case ARM::VLD4LNdWB_fixed_Asm_32:
7251   case ARM::VLD4LNqWB_fixed_Asm_16:
7252   case ARM::VLD4LNqWB_fixed_Asm_32: {
7253     MCInst TmpInst;
7254     // Shuffle the operands around so the lane index operand is in the
7255     // right place.
7256     unsigned Spacing;
7257     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7258     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7259     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7260                                             Spacing));
7261     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7262                                             Spacing * 2));
7263     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7264                                             Spacing * 3));
7265     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7266     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7267     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7268     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7269     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7270     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7271                                             Spacing));
7272     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7273                                             Spacing * 2));
7274     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7275                                             Spacing * 3));
7276     TmpInst.addOperand(Inst.getOperand(1)); // lane
7277     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7278     TmpInst.addOperand(Inst.getOperand(5));
7279     Inst = TmpInst;
7280     return true;
7281   }
7282
7283   case ARM::VLD1LNdAsm_8:
7284   case ARM::VLD1LNdAsm_16:
7285   case ARM::VLD1LNdAsm_32: {
7286     MCInst TmpInst;
7287     // Shuffle the operands around so the lane index operand is in the
7288     // right place.
7289     unsigned Spacing;
7290     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7291     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7292     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7293     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7294     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7295     TmpInst.addOperand(Inst.getOperand(1)); // lane
7296     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7297     TmpInst.addOperand(Inst.getOperand(5));
7298     Inst = TmpInst;
7299     return true;
7300   }
7301
7302   case ARM::VLD2LNdAsm_8:
7303   case ARM::VLD2LNdAsm_16:
7304   case ARM::VLD2LNdAsm_32:
7305   case ARM::VLD2LNqAsm_16:
7306   case ARM::VLD2LNqAsm_32: {
7307     MCInst TmpInst;
7308     // Shuffle the operands around so the lane index operand is in the
7309     // right place.
7310     unsigned Spacing;
7311     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7312     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7313     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7314                                             Spacing));
7315     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7316     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7317     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7318     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7319                                             Spacing));
7320     TmpInst.addOperand(Inst.getOperand(1)); // lane
7321     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7322     TmpInst.addOperand(Inst.getOperand(5));
7323     Inst = TmpInst;
7324     return true;
7325   }
7326
7327   case ARM::VLD3LNdAsm_8:
7328   case ARM::VLD3LNdAsm_16:
7329   case ARM::VLD3LNdAsm_32:
7330   case ARM::VLD3LNqAsm_16:
7331   case ARM::VLD3LNqAsm_32: {
7332     MCInst TmpInst;
7333     // Shuffle the operands around so the lane index operand is in the
7334     // right place.
7335     unsigned Spacing;
7336     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7337     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7338     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7339                                             Spacing));
7340     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7341                                             Spacing * 2));
7342     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7343     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7344     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7345     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7346                                             Spacing));
7347     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7348                                             Spacing * 2));
7349     TmpInst.addOperand(Inst.getOperand(1)); // lane
7350     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7351     TmpInst.addOperand(Inst.getOperand(5));
7352     Inst = TmpInst;
7353     return true;
7354   }
7355
7356   case ARM::VLD4LNdAsm_8:
7357   case ARM::VLD4LNdAsm_16:
7358   case ARM::VLD4LNdAsm_32:
7359   case ARM::VLD4LNqAsm_16:
7360   case ARM::VLD4LNqAsm_32: {
7361     MCInst TmpInst;
7362     // Shuffle the operands around so the lane index operand is in the
7363     // right place.
7364     unsigned Spacing;
7365     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7366     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7367     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7368                                             Spacing));
7369     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7370                                             Spacing * 2));
7371     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7372                                             Spacing * 3));
7373     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7374     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7375     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7376     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7377                                             Spacing));
7378     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7379                                             Spacing * 2));
7380     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7381                                             Spacing * 3));
7382     TmpInst.addOperand(Inst.getOperand(1)); // lane
7383     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7384     TmpInst.addOperand(Inst.getOperand(5));
7385     Inst = TmpInst;
7386     return true;
7387   }
7388
7389   // VLD3DUP single 3-element structure to all lanes instructions.
7390   case ARM::VLD3DUPdAsm_8:
7391   case ARM::VLD3DUPdAsm_16:
7392   case ARM::VLD3DUPdAsm_32:
7393   case ARM::VLD3DUPqAsm_8:
7394   case ARM::VLD3DUPqAsm_16:
7395   case ARM::VLD3DUPqAsm_32: {
7396     MCInst TmpInst;
7397     unsigned Spacing;
7398     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7399     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7400     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7401                                             Spacing));
7402     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7403                                             Spacing * 2));
7404     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7405     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7406     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7407     TmpInst.addOperand(Inst.getOperand(4));
7408     Inst = TmpInst;
7409     return true;
7410   }
7411
7412   case ARM::VLD3DUPdWB_fixed_Asm_8:
7413   case ARM::VLD3DUPdWB_fixed_Asm_16:
7414   case ARM::VLD3DUPdWB_fixed_Asm_32:
7415   case ARM::VLD3DUPqWB_fixed_Asm_8:
7416   case ARM::VLD3DUPqWB_fixed_Asm_16:
7417   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7418     MCInst TmpInst;
7419     unsigned Spacing;
7420     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7421     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7422     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7423                                             Spacing));
7424     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7425                                             Spacing * 2));
7426     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7427     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7428     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7429     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7430     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7431     TmpInst.addOperand(Inst.getOperand(4));
7432     Inst = TmpInst;
7433     return true;
7434   }
7435
7436   case ARM::VLD3DUPdWB_register_Asm_8:
7437   case ARM::VLD3DUPdWB_register_Asm_16:
7438   case ARM::VLD3DUPdWB_register_Asm_32:
7439   case ARM::VLD3DUPqWB_register_Asm_8:
7440   case ARM::VLD3DUPqWB_register_Asm_16:
7441   case ARM::VLD3DUPqWB_register_Asm_32: {
7442     MCInst TmpInst;
7443     unsigned Spacing;
7444     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7445     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7446     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7447                                             Spacing));
7448     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7449                                             Spacing * 2));
7450     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7451     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7452     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7453     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7454     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7455     TmpInst.addOperand(Inst.getOperand(5));
7456     Inst = TmpInst;
7457     return true;
7458   }
7459
7460   // VLD3 multiple 3-element structure instructions.
7461   case ARM::VLD3dAsm_8:
7462   case ARM::VLD3dAsm_16:
7463   case ARM::VLD3dAsm_32:
7464   case ARM::VLD3qAsm_8:
7465   case ARM::VLD3qAsm_16:
7466   case ARM::VLD3qAsm_32: {
7467     MCInst TmpInst;
7468     unsigned Spacing;
7469     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7470     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7471     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7472                                             Spacing));
7473     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7474                                             Spacing * 2));
7475     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7476     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7477     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7478     TmpInst.addOperand(Inst.getOperand(4));
7479     Inst = TmpInst;
7480     return true;
7481   }
7482
7483   case ARM::VLD3dWB_fixed_Asm_8:
7484   case ARM::VLD3dWB_fixed_Asm_16:
7485   case ARM::VLD3dWB_fixed_Asm_32:
7486   case ARM::VLD3qWB_fixed_Asm_8:
7487   case ARM::VLD3qWB_fixed_Asm_16:
7488   case ARM::VLD3qWB_fixed_Asm_32: {
7489     MCInst TmpInst;
7490     unsigned Spacing;
7491     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7492     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7493     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7494                                             Spacing));
7495     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7496                                             Spacing * 2));
7497     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7498     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7499     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7500     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7501     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7502     TmpInst.addOperand(Inst.getOperand(4));
7503     Inst = TmpInst;
7504     return true;
7505   }
7506
7507   case ARM::VLD3dWB_register_Asm_8:
7508   case ARM::VLD3dWB_register_Asm_16:
7509   case ARM::VLD3dWB_register_Asm_32:
7510   case ARM::VLD3qWB_register_Asm_8:
7511   case ARM::VLD3qWB_register_Asm_16:
7512   case ARM::VLD3qWB_register_Asm_32: {
7513     MCInst TmpInst;
7514     unsigned Spacing;
7515     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7516     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7517     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7518                                             Spacing));
7519     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7520                                             Spacing * 2));
7521     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7522     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7523     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7524     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7525     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7526     TmpInst.addOperand(Inst.getOperand(5));
7527     Inst = TmpInst;
7528     return true;
7529   }
7530
7531   // VLD4DUP single 3-element structure to all lanes instructions.
7532   case ARM::VLD4DUPdAsm_8:
7533   case ARM::VLD4DUPdAsm_16:
7534   case ARM::VLD4DUPdAsm_32:
7535   case ARM::VLD4DUPqAsm_8:
7536   case ARM::VLD4DUPqAsm_16:
7537   case ARM::VLD4DUPqAsm_32: {
7538     MCInst TmpInst;
7539     unsigned Spacing;
7540     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7541     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7542     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7543                                             Spacing));
7544     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7545                                             Spacing * 2));
7546     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7547                                             Spacing * 3));
7548     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7549     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7550     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7551     TmpInst.addOperand(Inst.getOperand(4));
7552     Inst = TmpInst;
7553     return true;
7554   }
7555
7556   case ARM::VLD4DUPdWB_fixed_Asm_8:
7557   case ARM::VLD4DUPdWB_fixed_Asm_16:
7558   case ARM::VLD4DUPdWB_fixed_Asm_32:
7559   case ARM::VLD4DUPqWB_fixed_Asm_8:
7560   case ARM::VLD4DUPqWB_fixed_Asm_16:
7561   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7562     MCInst TmpInst;
7563     unsigned Spacing;
7564     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7565     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7566     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7567                                             Spacing));
7568     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7569                                             Spacing * 2));
7570     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7571                                             Spacing * 3));
7572     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7573     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7574     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7575     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7576     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7577     TmpInst.addOperand(Inst.getOperand(4));
7578     Inst = TmpInst;
7579     return true;
7580   }
7581
7582   case ARM::VLD4DUPdWB_register_Asm_8:
7583   case ARM::VLD4DUPdWB_register_Asm_16:
7584   case ARM::VLD4DUPdWB_register_Asm_32:
7585   case ARM::VLD4DUPqWB_register_Asm_8:
7586   case ARM::VLD4DUPqWB_register_Asm_16:
7587   case ARM::VLD4DUPqWB_register_Asm_32: {
7588     MCInst TmpInst;
7589     unsigned Spacing;
7590     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7591     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7592     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7593                                             Spacing));
7594     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7595                                             Spacing * 2));
7596     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7597                                             Spacing * 3));
7598     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7599     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7600     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7601     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7602     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7603     TmpInst.addOperand(Inst.getOperand(5));
7604     Inst = TmpInst;
7605     return true;
7606   }
7607
7608   // VLD4 multiple 4-element structure instructions.
7609   case ARM::VLD4dAsm_8:
7610   case ARM::VLD4dAsm_16:
7611   case ARM::VLD4dAsm_32:
7612   case ARM::VLD4qAsm_8:
7613   case ARM::VLD4qAsm_16:
7614   case ARM::VLD4qAsm_32: {
7615     MCInst TmpInst;
7616     unsigned Spacing;
7617     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7618     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7619     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7620                                             Spacing));
7621     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7622                                             Spacing * 2));
7623     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7624                                             Spacing * 3));
7625     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7626     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7627     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7628     TmpInst.addOperand(Inst.getOperand(4));
7629     Inst = TmpInst;
7630     return true;
7631   }
7632
7633   case ARM::VLD4dWB_fixed_Asm_8:
7634   case ARM::VLD4dWB_fixed_Asm_16:
7635   case ARM::VLD4dWB_fixed_Asm_32:
7636   case ARM::VLD4qWB_fixed_Asm_8:
7637   case ARM::VLD4qWB_fixed_Asm_16:
7638   case ARM::VLD4qWB_fixed_Asm_32: {
7639     MCInst TmpInst;
7640     unsigned Spacing;
7641     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7642     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7643     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7644                                             Spacing));
7645     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7646                                             Spacing * 2));
7647     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7648                                             Spacing * 3));
7649     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7650     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7651     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7652     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7653     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7654     TmpInst.addOperand(Inst.getOperand(4));
7655     Inst = TmpInst;
7656     return true;
7657   }
7658
7659   case ARM::VLD4dWB_register_Asm_8:
7660   case ARM::VLD4dWB_register_Asm_16:
7661   case ARM::VLD4dWB_register_Asm_32:
7662   case ARM::VLD4qWB_register_Asm_8:
7663   case ARM::VLD4qWB_register_Asm_16:
7664   case ARM::VLD4qWB_register_Asm_32: {
7665     MCInst TmpInst;
7666     unsigned Spacing;
7667     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7668     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7669     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7670                                             Spacing));
7671     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7672                                             Spacing * 2));
7673     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7674                                             Spacing * 3));
7675     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7676     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7677     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7678     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7679     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7680     TmpInst.addOperand(Inst.getOperand(5));
7681     Inst = TmpInst;
7682     return true;
7683   }
7684
7685   // VST3 multiple 3-element structure instructions.
7686   case ARM::VST3dAsm_8:
7687   case ARM::VST3dAsm_16:
7688   case ARM::VST3dAsm_32:
7689   case ARM::VST3qAsm_8:
7690   case ARM::VST3qAsm_16:
7691   case ARM::VST3qAsm_32: {
7692     MCInst TmpInst;
7693     unsigned Spacing;
7694     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7695     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7696     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7697     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7698     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7699                                             Spacing));
7700     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7701                                             Spacing * 2));
7702     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7703     TmpInst.addOperand(Inst.getOperand(4));
7704     Inst = TmpInst;
7705     return true;
7706   }
7707
7708   case ARM::VST3dWB_fixed_Asm_8:
7709   case ARM::VST3dWB_fixed_Asm_16:
7710   case ARM::VST3dWB_fixed_Asm_32:
7711   case ARM::VST3qWB_fixed_Asm_8:
7712   case ARM::VST3qWB_fixed_Asm_16:
7713   case ARM::VST3qWB_fixed_Asm_32: {
7714     MCInst TmpInst;
7715     unsigned Spacing;
7716     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7717     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7718     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7719     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7720     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7721     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7722     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7723                                             Spacing));
7724     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7725                                             Spacing * 2));
7726     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7727     TmpInst.addOperand(Inst.getOperand(4));
7728     Inst = TmpInst;
7729     return true;
7730   }
7731
7732   case ARM::VST3dWB_register_Asm_8:
7733   case ARM::VST3dWB_register_Asm_16:
7734   case ARM::VST3dWB_register_Asm_32:
7735   case ARM::VST3qWB_register_Asm_8:
7736   case ARM::VST3qWB_register_Asm_16:
7737   case ARM::VST3qWB_register_Asm_32: {
7738     MCInst TmpInst;
7739     unsigned Spacing;
7740     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7741     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7742     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7743     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7744     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7745     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7746     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7747                                             Spacing));
7748     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7749                                             Spacing * 2));
7750     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7751     TmpInst.addOperand(Inst.getOperand(5));
7752     Inst = TmpInst;
7753     return true;
7754   }
7755
7756   // VST4 multiple 3-element structure instructions.
7757   case ARM::VST4dAsm_8:
7758   case ARM::VST4dAsm_16:
7759   case ARM::VST4dAsm_32:
7760   case ARM::VST4qAsm_8:
7761   case ARM::VST4qAsm_16:
7762   case ARM::VST4qAsm_32: {
7763     MCInst TmpInst;
7764     unsigned Spacing;
7765     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7766     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7767     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7768     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7769     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7770                                             Spacing));
7771     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7772                                             Spacing * 2));
7773     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7774                                             Spacing * 3));
7775     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7776     TmpInst.addOperand(Inst.getOperand(4));
7777     Inst = TmpInst;
7778     return true;
7779   }
7780
7781   case ARM::VST4dWB_fixed_Asm_8:
7782   case ARM::VST4dWB_fixed_Asm_16:
7783   case ARM::VST4dWB_fixed_Asm_32:
7784   case ARM::VST4qWB_fixed_Asm_8:
7785   case ARM::VST4qWB_fixed_Asm_16:
7786   case ARM::VST4qWB_fixed_Asm_32: {
7787     MCInst TmpInst;
7788     unsigned Spacing;
7789     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7790     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7791     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7792     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7793     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7794     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7795     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7796                                             Spacing));
7797     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7798                                             Spacing * 2));
7799     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7800                                             Spacing * 3));
7801     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7802     TmpInst.addOperand(Inst.getOperand(4));
7803     Inst = TmpInst;
7804     return true;
7805   }
7806
7807   case ARM::VST4dWB_register_Asm_8:
7808   case ARM::VST4dWB_register_Asm_16:
7809   case ARM::VST4dWB_register_Asm_32:
7810   case ARM::VST4qWB_register_Asm_8:
7811   case ARM::VST4qWB_register_Asm_16:
7812   case ARM::VST4qWB_register_Asm_32: {
7813     MCInst TmpInst;
7814     unsigned Spacing;
7815     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7816     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7817     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7818     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7819     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7820     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7821     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7822                                             Spacing));
7823     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7824                                             Spacing * 2));
7825     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7826                                             Spacing * 3));
7827     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7828     TmpInst.addOperand(Inst.getOperand(5));
7829     Inst = TmpInst;
7830     return true;
7831   }
7832
7833   // Handle encoding choice for the shift-immediate instructions.
7834   case ARM::t2LSLri:
7835   case ARM::t2LSRri:
7836   case ARM::t2ASRri: {
7837     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7838         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7839         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
7840         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7841           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
7842       unsigned NewOpc;
7843       switch (Inst.getOpcode()) {
7844       default: llvm_unreachable("unexpected opcode");
7845       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
7846       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
7847       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
7848       }
7849       // The Thumb1 operands aren't in the same order. Awesome, eh?
7850       MCInst TmpInst;
7851       TmpInst.setOpcode(NewOpc);
7852       TmpInst.addOperand(Inst.getOperand(0));
7853       TmpInst.addOperand(Inst.getOperand(5));
7854       TmpInst.addOperand(Inst.getOperand(1));
7855       TmpInst.addOperand(Inst.getOperand(2));
7856       TmpInst.addOperand(Inst.getOperand(3));
7857       TmpInst.addOperand(Inst.getOperand(4));
7858       Inst = TmpInst;
7859       return true;
7860     }
7861     return false;
7862   }
7863
7864   // Handle the Thumb2 mode MOV complex aliases.
7865   case ARM::t2MOVsr:
7866   case ARM::t2MOVSsr: {
7867     // Which instruction to expand to depends on the CCOut operand and
7868     // whether we're in an IT block if the register operands are low
7869     // registers.
7870     bool isNarrow = false;
7871     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7872         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7873         isARMLowRegister(Inst.getOperand(2).getReg()) &&
7874         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7875         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
7876       isNarrow = true;
7877     MCInst TmpInst;
7878     unsigned newOpc;
7879     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
7880     default: llvm_unreachable("unexpected opcode!");
7881     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
7882     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
7883     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
7884     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
7885     }
7886     TmpInst.setOpcode(newOpc);
7887     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7888     if (isNarrow)
7889       TmpInst.addOperand(MCOperand::createReg(
7890           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7891     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7892     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7893     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7894     TmpInst.addOperand(Inst.getOperand(5));
7895     if (!isNarrow)
7896       TmpInst.addOperand(MCOperand::createReg(
7897           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7898     Inst = TmpInst;
7899     return true;
7900   }
7901   case ARM::t2MOVsi:
7902   case ARM::t2MOVSsi: {
7903     // Which instruction to expand to depends on the CCOut operand and
7904     // whether we're in an IT block if the register operands are low
7905     // registers.
7906     bool isNarrow = false;
7907     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7908         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7909         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
7910       isNarrow = true;
7911     MCInst TmpInst;
7912     unsigned newOpc;
7913     switch(ARM_AM::getSORegShOp(Inst.getOperand(2).getImm())) {
7914     default: llvm_unreachable("unexpected opcode!");
7915     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
7916     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
7917     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
7918     case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
7919     case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
7920     }
7921     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
7922     if (Amount == 32) Amount = 0;
7923     TmpInst.setOpcode(newOpc);
7924     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7925     if (isNarrow)
7926       TmpInst.addOperand(MCOperand::createReg(
7927           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7928     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7929     if (newOpc != ARM::t2RRX)
7930       TmpInst.addOperand(MCOperand::createImm(Amount));
7931     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7932     TmpInst.addOperand(Inst.getOperand(4));
7933     if (!isNarrow)
7934       TmpInst.addOperand(MCOperand::createReg(
7935           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7936     Inst = TmpInst;
7937     return true;
7938   }
7939   // Handle the ARM mode MOV complex aliases.
7940   case ARM::ASRr:
7941   case ARM::LSRr:
7942   case ARM::LSLr:
7943   case ARM::RORr: {
7944     ARM_AM::ShiftOpc ShiftTy;
7945     switch(Inst.getOpcode()) {
7946     default: llvm_unreachable("unexpected opcode!");
7947     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
7948     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
7949     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
7950     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
7951     }
7952     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
7953     MCInst TmpInst;
7954     TmpInst.setOpcode(ARM::MOVsr);
7955     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7956     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7957     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7958     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7959     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7960     TmpInst.addOperand(Inst.getOperand(4));
7961     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7962     Inst = TmpInst;
7963     return true;
7964   }
7965   case ARM::ASRi:
7966   case ARM::LSRi:
7967   case ARM::LSLi:
7968   case ARM::RORi: {
7969     ARM_AM::ShiftOpc ShiftTy;
7970     switch(Inst.getOpcode()) {
7971     default: llvm_unreachable("unexpected opcode!");
7972     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
7973     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
7974     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
7975     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
7976     }
7977     // A shift by zero is a plain MOVr, not a MOVsi.
7978     unsigned Amt = Inst.getOperand(2).getImm();
7979     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
7980     // A shift by 32 should be encoded as 0 when permitted
7981     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
7982       Amt = 0;
7983     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
7984     MCInst TmpInst;
7985     TmpInst.setOpcode(Opc);
7986     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7987     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7988     if (Opc == ARM::MOVsi)
7989       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
7990     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7991     TmpInst.addOperand(Inst.getOperand(4));
7992     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7993     Inst = TmpInst;
7994     return true;
7995   }
7996   case ARM::RRXi: {
7997     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
7998     MCInst TmpInst;
7999     TmpInst.setOpcode(ARM::MOVsi);
8000     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8001     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8002     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8003     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8004     TmpInst.addOperand(Inst.getOperand(3));
8005     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8006     Inst = TmpInst;
8007     return true;
8008   }
8009   case ARM::t2LDMIA_UPD: {
8010     // If this is a load of a single register, then we should use
8011     // a post-indexed LDR instruction instead, per the ARM ARM.
8012     if (Inst.getNumOperands() != 5)
8013       return false;
8014     MCInst TmpInst;
8015     TmpInst.setOpcode(ARM::t2LDR_POST);
8016     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8017     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8018     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8019     TmpInst.addOperand(MCOperand::createImm(4));
8020     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8021     TmpInst.addOperand(Inst.getOperand(3));
8022     Inst = TmpInst;
8023     return true;
8024   }
8025   case ARM::t2STMDB_UPD: {
8026     // If this is a store of a single register, then we should use
8027     // a pre-indexed STR instruction instead, per the ARM ARM.
8028     if (Inst.getNumOperands() != 5)
8029       return false;
8030     MCInst TmpInst;
8031     TmpInst.setOpcode(ARM::t2STR_PRE);
8032     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8033     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8034     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8035     TmpInst.addOperand(MCOperand::createImm(-4));
8036     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8037     TmpInst.addOperand(Inst.getOperand(3));
8038     Inst = TmpInst;
8039     return true;
8040   }
8041   case ARM::LDMIA_UPD:
8042     // If this is a load of a single register via a 'pop', then we should use
8043     // a post-indexed LDR instruction instead, per the ARM ARM.
8044     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8045         Inst.getNumOperands() == 5) {
8046       MCInst TmpInst;
8047       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8048       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8049       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8050       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8051       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8052       TmpInst.addOperand(MCOperand::createImm(4));
8053       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8054       TmpInst.addOperand(Inst.getOperand(3));
8055       Inst = TmpInst;
8056       return true;
8057     }
8058     break;
8059   case ARM::STMDB_UPD:
8060     // If this is a store of a single register via a 'push', then we should use
8061     // a pre-indexed STR instruction instead, per the ARM ARM.
8062     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8063         Inst.getNumOperands() == 5) {
8064       MCInst TmpInst;
8065       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8066       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8067       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8068       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8069       TmpInst.addOperand(MCOperand::createImm(-4));
8070       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8071       TmpInst.addOperand(Inst.getOperand(3));
8072       Inst = TmpInst;
8073     }
8074     break;
8075   case ARM::t2ADDri12:
8076     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8077     // mnemonic was used (not "addw"), encoding T3 is preferred.
8078     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8079         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8080       break;
8081     Inst.setOpcode(ARM::t2ADDri);
8082     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8083     break;
8084   case ARM::t2SUBri12:
8085     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8086     // mnemonic was used (not "subw"), encoding T3 is preferred.
8087     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8088         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8089       break;
8090     Inst.setOpcode(ARM::t2SUBri);
8091     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8092     break;
8093   case ARM::tADDi8:
8094     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8095     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8096     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8097     // to encoding T1 if <Rd> is omitted."
8098     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8099       Inst.setOpcode(ARM::tADDi3);
8100       return true;
8101     }
8102     break;
8103   case ARM::tSUBi8:
8104     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8105     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8106     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8107     // to encoding T1 if <Rd> is omitted."
8108     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8109       Inst.setOpcode(ARM::tSUBi3);
8110       return true;
8111     }
8112     break;
8113   case ARM::t2ADDri:
8114   case ARM::t2SUBri: {
8115     // If the destination and first source operand are the same, and
8116     // the flags are compatible with the current IT status, use encoding T2
8117     // instead of T3. For compatibility with the system 'as'. Make sure the
8118     // wide encoding wasn't explicit.
8119     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8120         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8121         (unsigned)Inst.getOperand(2).getImm() > 255 ||
8122         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
8123          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
8124         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8125          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8126       break;
8127     MCInst TmpInst;
8128     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8129                       ARM::tADDi8 : ARM::tSUBi8);
8130     TmpInst.addOperand(Inst.getOperand(0));
8131     TmpInst.addOperand(Inst.getOperand(5));
8132     TmpInst.addOperand(Inst.getOperand(0));
8133     TmpInst.addOperand(Inst.getOperand(2));
8134     TmpInst.addOperand(Inst.getOperand(3));
8135     TmpInst.addOperand(Inst.getOperand(4));
8136     Inst = TmpInst;
8137     return true;
8138   }
8139   case ARM::t2ADDrr: {
8140     // If the destination and first source operand are the same, and
8141     // there's no setting of the flags, use encoding T2 instead of T3.
8142     // Note that this is only for ADD, not SUB. This mirrors the system
8143     // 'as' behaviour.  Also take advantage of ADD being commutative.
8144     // Make sure the wide encoding wasn't explicit.
8145     bool Swap = false;
8146     auto DestReg = Inst.getOperand(0).getReg();
8147     bool Transform = DestReg == Inst.getOperand(1).getReg();
8148     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8149       Transform = true;
8150       Swap = true;
8151     }
8152     if (!Transform ||
8153         Inst.getOperand(5).getReg() != 0 ||
8154         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8155          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8156       break;
8157     MCInst TmpInst;
8158     TmpInst.setOpcode(ARM::tADDhirr);
8159     TmpInst.addOperand(Inst.getOperand(0));
8160     TmpInst.addOperand(Inst.getOperand(0));
8161     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8162     TmpInst.addOperand(Inst.getOperand(3));
8163     TmpInst.addOperand(Inst.getOperand(4));
8164     Inst = TmpInst;
8165     return true;
8166   }
8167   case ARM::tADDrSP: {
8168     // If the non-SP source operand and the destination operand are not the
8169     // same, we need to use the 32-bit encoding if it's available.
8170     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8171       Inst.setOpcode(ARM::t2ADDrr);
8172       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8173       return true;
8174     }
8175     break;
8176   }
8177   case ARM::tB:
8178     // A Thumb conditional branch outside of an IT block is a tBcc.
8179     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8180       Inst.setOpcode(ARM::tBcc);
8181       return true;
8182     }
8183     break;
8184   case ARM::t2B:
8185     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8186     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8187       Inst.setOpcode(ARM::t2Bcc);
8188       return true;
8189     }
8190     break;
8191   case ARM::t2Bcc:
8192     // If the conditional is AL or we're in an IT block, we really want t2B.
8193     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8194       Inst.setOpcode(ARM::t2B);
8195       return true;
8196     }
8197     break;
8198   case ARM::tBcc:
8199     // If the conditional is AL, we really want tB.
8200     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8201       Inst.setOpcode(ARM::tB);
8202       return true;
8203     }
8204     break;
8205   case ARM::tLDMIA: {
8206     // If the register list contains any high registers, or if the writeback
8207     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8208     // instead if we're in Thumb2. Otherwise, this should have generated
8209     // an error in validateInstruction().
8210     unsigned Rn = Inst.getOperand(0).getReg();
8211     bool hasWritebackToken =
8212         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8213          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8214     bool listContainsBase;
8215     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8216         (!listContainsBase && !hasWritebackToken) ||
8217         (listContainsBase && hasWritebackToken)) {
8218       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8219       assert (isThumbTwo());
8220       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8221       // If we're switching to the updating version, we need to insert
8222       // the writeback tied operand.
8223       if (hasWritebackToken)
8224         Inst.insert(Inst.begin(),
8225                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8226       return true;
8227     }
8228     break;
8229   }
8230   case ARM::tSTMIA_UPD: {
8231     // If the register list contains any high registers, we need to use
8232     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8233     // should have generated an error in validateInstruction().
8234     unsigned Rn = Inst.getOperand(0).getReg();
8235     bool listContainsBase;
8236     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8237       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8238       assert (isThumbTwo());
8239       Inst.setOpcode(ARM::t2STMIA_UPD);
8240       return true;
8241     }
8242     break;
8243   }
8244   case ARM::tPOP: {
8245     bool listContainsBase;
8246     // If the register list contains any high registers, we need to use
8247     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8248     // should have generated an error in validateInstruction().
8249     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8250       return false;
8251     assert (isThumbTwo());
8252     Inst.setOpcode(ARM::t2LDMIA_UPD);
8253     // Add the base register and writeback operands.
8254     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8255     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8256     return true;
8257   }
8258   case ARM::tPUSH: {
8259     bool listContainsBase;
8260     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8261       return false;
8262     assert (isThumbTwo());
8263     Inst.setOpcode(ARM::t2STMDB_UPD);
8264     // Add the base register and writeback operands.
8265     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8266     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8267     return true;
8268   }
8269   case ARM::t2MOVi: {
8270     // If we can use the 16-bit encoding and the user didn't explicitly
8271     // request the 32-bit variant, transform it here.
8272     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8273         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8274         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8275           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8276          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8277         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8278          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8279       // The operands aren't in the same order for tMOVi8...
8280       MCInst TmpInst;
8281       TmpInst.setOpcode(ARM::tMOVi8);
8282       TmpInst.addOperand(Inst.getOperand(0));
8283       TmpInst.addOperand(Inst.getOperand(4));
8284       TmpInst.addOperand(Inst.getOperand(1));
8285       TmpInst.addOperand(Inst.getOperand(2));
8286       TmpInst.addOperand(Inst.getOperand(3));
8287       Inst = TmpInst;
8288       return true;
8289     }
8290     break;
8291   }
8292   case ARM::t2MOVr: {
8293     // If we can use the 16-bit encoding and the user didn't explicitly
8294     // request the 32-bit variant, transform it here.
8295     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8296         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8297         Inst.getOperand(2).getImm() == ARMCC::AL &&
8298         Inst.getOperand(4).getReg() == ARM::CPSR &&
8299         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8300          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8301       // The operands aren't the same for tMOV[S]r... (no cc_out)
8302       MCInst TmpInst;
8303       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8304       TmpInst.addOperand(Inst.getOperand(0));
8305       TmpInst.addOperand(Inst.getOperand(1));
8306       TmpInst.addOperand(Inst.getOperand(2));
8307       TmpInst.addOperand(Inst.getOperand(3));
8308       Inst = TmpInst;
8309       return true;
8310     }
8311     break;
8312   }
8313   case ARM::t2SXTH:
8314   case ARM::t2SXTB:
8315   case ARM::t2UXTH:
8316   case ARM::t2UXTB: {
8317     // If we can use the 16-bit encoding and the user didn't explicitly
8318     // request the 32-bit variant, transform it here.
8319     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8320         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8321         Inst.getOperand(2).getImm() == 0 &&
8322         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8323          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8324       unsigned NewOpc;
8325       switch (Inst.getOpcode()) {
8326       default: llvm_unreachable("Illegal opcode!");
8327       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8328       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8329       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8330       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8331       }
8332       // The operands aren't the same for thumb1 (no rotate operand).
8333       MCInst TmpInst;
8334       TmpInst.setOpcode(NewOpc);
8335       TmpInst.addOperand(Inst.getOperand(0));
8336       TmpInst.addOperand(Inst.getOperand(1));
8337       TmpInst.addOperand(Inst.getOperand(3));
8338       TmpInst.addOperand(Inst.getOperand(4));
8339       Inst = TmpInst;
8340       return true;
8341     }
8342     break;
8343   }
8344   case ARM::MOVsi: {
8345     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8346     // rrx shifts and asr/lsr of #32 is encoded as 0
8347     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr) 
8348       return false;
8349     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8350       // Shifting by zero is accepted as a vanilla 'MOVr'
8351       MCInst TmpInst;
8352       TmpInst.setOpcode(ARM::MOVr);
8353       TmpInst.addOperand(Inst.getOperand(0));
8354       TmpInst.addOperand(Inst.getOperand(1));
8355       TmpInst.addOperand(Inst.getOperand(3));
8356       TmpInst.addOperand(Inst.getOperand(4));
8357       TmpInst.addOperand(Inst.getOperand(5));
8358       Inst = TmpInst;
8359       return true;
8360     }
8361     return false;
8362   }
8363   case ARM::ANDrsi:
8364   case ARM::ORRrsi:
8365   case ARM::EORrsi:
8366   case ARM::BICrsi:
8367   case ARM::SUBrsi:
8368   case ARM::ADDrsi: {
8369     unsigned newOpc;
8370     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8371     if (SOpc == ARM_AM::rrx) return false;
8372     switch (Inst.getOpcode()) {
8373     default: llvm_unreachable("unexpected opcode!");
8374     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8375     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8376     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8377     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8378     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8379     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8380     }
8381     // If the shift is by zero, use the non-shifted instruction definition.
8382     // The exception is for right shifts, where 0 == 32
8383     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8384         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8385       MCInst TmpInst;
8386       TmpInst.setOpcode(newOpc);
8387       TmpInst.addOperand(Inst.getOperand(0));
8388       TmpInst.addOperand(Inst.getOperand(1));
8389       TmpInst.addOperand(Inst.getOperand(2));
8390       TmpInst.addOperand(Inst.getOperand(4));
8391       TmpInst.addOperand(Inst.getOperand(5));
8392       TmpInst.addOperand(Inst.getOperand(6));
8393       Inst = TmpInst;
8394       return true;
8395     }
8396     return false;
8397   }
8398   case ARM::ITasm:
8399   case ARM::t2IT: {
8400     // The mask bits for all but the first condition are represented as
8401     // the low bit of the condition code value implies 't'. We currently
8402     // always have 1 implies 't', so XOR toggle the bits if the low bit
8403     // of the condition code is zero. 
8404     MCOperand &MO = Inst.getOperand(1);
8405     unsigned Mask = MO.getImm();
8406     unsigned OrigMask = Mask;
8407     unsigned TZ = countTrailingZeros(Mask);
8408     if ((Inst.getOperand(0).getImm() & 1) == 0) {
8409       assert(Mask && TZ <= 3 && "illegal IT mask value!");
8410       Mask ^= (0xE << TZ) & 0xF;
8411     }
8412     MO.setImm(Mask);
8413
8414     // Set up the IT block state according to the IT instruction we just
8415     // matched.
8416     assert(!inITBlock() && "nested IT blocks?!");
8417     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8418     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
8419     ITState.CurPosition = 0;
8420     ITState.FirstCond = true;
8421     break;
8422   }
8423   case ARM::t2LSLrr:
8424   case ARM::t2LSRrr:
8425   case ARM::t2ASRrr:
8426   case ARM::t2SBCrr:
8427   case ARM::t2RORrr:
8428   case ARM::t2BICrr:
8429   {
8430     // Assemblers should use the narrow encodings of these instructions when permissible.
8431     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8432          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8433         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8434         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8435          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8436         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8437          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8438              ".w"))) {
8439       unsigned NewOpc;
8440       switch (Inst.getOpcode()) {
8441         default: llvm_unreachable("unexpected opcode");
8442         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8443         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8444         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8445         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8446         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8447         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8448       }
8449       MCInst TmpInst;
8450       TmpInst.setOpcode(NewOpc);
8451       TmpInst.addOperand(Inst.getOperand(0));
8452       TmpInst.addOperand(Inst.getOperand(5));
8453       TmpInst.addOperand(Inst.getOperand(1));
8454       TmpInst.addOperand(Inst.getOperand(2));
8455       TmpInst.addOperand(Inst.getOperand(3));
8456       TmpInst.addOperand(Inst.getOperand(4));
8457       Inst = TmpInst;
8458       return true;
8459     }
8460     return false;
8461   }
8462   case ARM::t2ANDrr:
8463   case ARM::t2EORrr:
8464   case ARM::t2ADCrr:
8465   case ARM::t2ORRrr:
8466   {
8467     // Assemblers should use the narrow encodings of these instructions when permissible.
8468     // These instructions are special in that they are commutable, so shorter encodings
8469     // are available more often.
8470     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8471          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8472         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8473          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8474         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8475          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8476         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8477          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8478              ".w"))) {
8479       unsigned NewOpc;
8480       switch (Inst.getOpcode()) {
8481         default: llvm_unreachable("unexpected opcode");
8482         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8483         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8484         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8485         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8486       }
8487       MCInst TmpInst;
8488       TmpInst.setOpcode(NewOpc);
8489       TmpInst.addOperand(Inst.getOperand(0));
8490       TmpInst.addOperand(Inst.getOperand(5));
8491       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8492         TmpInst.addOperand(Inst.getOperand(1));
8493         TmpInst.addOperand(Inst.getOperand(2));
8494       } else {
8495         TmpInst.addOperand(Inst.getOperand(2));
8496         TmpInst.addOperand(Inst.getOperand(1));
8497       }
8498       TmpInst.addOperand(Inst.getOperand(3));
8499       TmpInst.addOperand(Inst.getOperand(4));
8500       Inst = TmpInst;
8501       return true;
8502     }
8503     return false;
8504   }
8505   }
8506   return false;
8507 }
8508
8509 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8510   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8511   // suffix depending on whether they're in an IT block or not.
8512   unsigned Opc = Inst.getOpcode();
8513   const MCInstrDesc &MCID = MII.get(Opc);
8514   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8515     assert(MCID.hasOptionalDef() &&
8516            "optionally flag setting instruction missing optional def operand");
8517     assert(MCID.NumOperands == Inst.getNumOperands() &&
8518            "operand count mismatch!");
8519     // Find the optional-def operand (cc_out).
8520     unsigned OpNo;
8521     for (OpNo = 0;
8522          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8523          ++OpNo)
8524       ;
8525     // If we're parsing Thumb1, reject it completely.
8526     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8527       return Match_MnemonicFail;
8528     // If we're parsing Thumb2, which form is legal depends on whether we're
8529     // in an IT block.
8530     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8531         !inITBlock())
8532       return Match_RequiresITBlock;
8533     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8534         inITBlock())
8535       return Match_RequiresNotITBlock;
8536   } else if (isThumbOne()) {
8537     // Some high-register supporting Thumb1 encodings only allow both registers
8538     // to be from r0-r7 when in Thumb2.
8539     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8540         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8541         isARMLowRegister(Inst.getOperand(2).getReg()))
8542       return Match_RequiresThumb2;
8543     // Others only require ARMv6 or later.
8544     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8545              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8546              isARMLowRegister(Inst.getOperand(1).getReg()))
8547       return Match_RequiresV6;
8548   }
8549
8550   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8551     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8552       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8553       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8554         return Match_RequiresV8;
8555       else if (Inst.getOperand(I).getReg() == ARM::PC)
8556         return Match_InvalidOperand;
8557     }
8558
8559   return Match_Success;
8560 }
8561
8562 namespace llvm {
8563 template <> inline bool IsCPSRDead<MCInst>(MCInst *Instr) {
8564   return true; // In an assembly source, no need to second-guess
8565 }
8566 }
8567
8568 static const char *getSubtargetFeatureName(uint64_t Val);
8569 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8570                                            OperandVector &Operands,
8571                                            MCStreamer &Out, uint64_t &ErrorInfo,
8572                                            bool MatchingInlineAsm) {
8573   MCInst Inst;
8574   unsigned MatchResult;
8575
8576   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
8577                                      MatchingInlineAsm);
8578   switch (MatchResult) {
8579   case Match_Success:
8580     // Context sensitive operand constraints aren't handled by the matcher,
8581     // so check them here.
8582     if (validateInstruction(Inst, Operands)) {
8583       // Still progress the IT block, otherwise one wrong condition causes
8584       // nasty cascading errors.
8585       forwardITPosition();
8586       return true;
8587     }
8588
8589     { // processInstruction() updates inITBlock state, we need to save it away
8590       bool wasInITBlock = inITBlock();
8591
8592       // Some instructions need post-processing to, for example, tweak which
8593       // encoding is selected. Loop on it while changes happen so the
8594       // individual transformations can chain off each other. E.g.,
8595       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
8596       while (processInstruction(Inst, Operands, Out))
8597         ;
8598
8599       // Only after the instruction is fully processed, we can validate it
8600       if (wasInITBlock && hasV8Ops() && isThumb() &&
8601           !isV8EligibleForIT(&Inst)) {
8602         Warning(IDLoc, "deprecated instruction in IT block");
8603       }
8604     }
8605
8606     // Only move forward at the very end so that everything in validate
8607     // and process gets a consistent answer about whether we're in an IT
8608     // block.
8609     forwardITPosition();
8610
8611     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
8612     // doesn't actually encode.
8613     if (Inst.getOpcode() == ARM::ITasm)
8614       return false;
8615
8616     Inst.setLoc(IDLoc);
8617     Out.EmitInstruction(Inst, getSTI());
8618     return false;
8619   case Match_MissingFeature: {
8620     assert(ErrorInfo && "Unknown missing feature!");
8621     // Special case the error message for the very common case where only
8622     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
8623     std::string Msg = "instruction requires:";
8624     uint64_t Mask = 1;
8625     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
8626       if (ErrorInfo & Mask) {
8627         Msg += " ";
8628         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
8629       }
8630       Mask <<= 1;
8631     }
8632     return Error(IDLoc, Msg);
8633   }
8634   case Match_InvalidOperand: {
8635     SMLoc ErrorLoc = IDLoc;
8636     if (ErrorInfo != ~0ULL) {
8637       if (ErrorInfo >= Operands.size())
8638         return Error(IDLoc, "too few operands for instruction");
8639
8640       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8641       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8642     }
8643
8644     return Error(ErrorLoc, "invalid operand for instruction");
8645   }
8646   case Match_MnemonicFail:
8647     return Error(IDLoc, "invalid instruction",
8648                  ((ARMOperand &)*Operands[0]).getLocRange());
8649   case Match_RequiresNotITBlock:
8650     return Error(IDLoc, "flag setting instruction only valid outside IT block");
8651   case Match_RequiresITBlock:
8652     return Error(IDLoc, "instruction only valid inside IT block");
8653   case Match_RequiresV6:
8654     return Error(IDLoc, "instruction variant requires ARMv6 or later");
8655   case Match_RequiresThumb2:
8656     return Error(IDLoc, "instruction variant requires Thumb2");
8657   case Match_RequiresV8:
8658     return Error(IDLoc, "instruction variant requires ARMv8 or later");
8659   case Match_ImmRange0_15: {
8660     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8661     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8662     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
8663   }
8664   case Match_ImmRange0_239: {
8665     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8666     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8667     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
8668   }
8669   case Match_AlignedMemoryRequiresNone:
8670   case Match_DupAlignedMemoryRequiresNone:
8671   case Match_AlignedMemoryRequires16:
8672   case Match_DupAlignedMemoryRequires16:
8673   case Match_AlignedMemoryRequires32:
8674   case Match_DupAlignedMemoryRequires32:
8675   case Match_AlignedMemoryRequires64:
8676   case Match_DupAlignedMemoryRequires64:
8677   case Match_AlignedMemoryRequires64or128:
8678   case Match_DupAlignedMemoryRequires64or128:
8679   case Match_AlignedMemoryRequires64or128or256:
8680   {
8681     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
8682     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8683     switch (MatchResult) {
8684       default:
8685         llvm_unreachable("Missing Match_Aligned type");
8686       case Match_AlignedMemoryRequiresNone:
8687       case Match_DupAlignedMemoryRequiresNone:
8688         return Error(ErrorLoc, "alignment must be omitted");
8689       case Match_AlignedMemoryRequires16:
8690       case Match_DupAlignedMemoryRequires16:
8691         return Error(ErrorLoc, "alignment must be 16 or omitted");
8692       case Match_AlignedMemoryRequires32:
8693       case Match_DupAlignedMemoryRequires32:
8694         return Error(ErrorLoc, "alignment must be 32 or omitted");
8695       case Match_AlignedMemoryRequires64:
8696       case Match_DupAlignedMemoryRequires64:
8697         return Error(ErrorLoc, "alignment must be 64 or omitted");
8698       case Match_AlignedMemoryRequires64or128:
8699       case Match_DupAlignedMemoryRequires64or128:
8700         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
8701       case Match_AlignedMemoryRequires64or128or256:
8702         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
8703     }
8704   }
8705   }
8706
8707   llvm_unreachable("Implement any new match types added!");
8708 }
8709
8710 /// parseDirective parses the arm specific directives
8711 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
8712   const MCObjectFileInfo::Environment Format =
8713     getContext().getObjectFileInfo()->getObjectFileType();
8714   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8715   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
8716
8717   StringRef IDVal = DirectiveID.getIdentifier();
8718   if (IDVal == ".word")
8719     return parseLiteralValues(4, DirectiveID.getLoc());
8720   else if (IDVal == ".short" || IDVal == ".hword")
8721     return parseLiteralValues(2, DirectiveID.getLoc());
8722   else if (IDVal == ".thumb")
8723     return parseDirectiveThumb(DirectiveID.getLoc());
8724   else if (IDVal == ".arm")
8725     return parseDirectiveARM(DirectiveID.getLoc());
8726   else if (IDVal == ".thumb_func")
8727     return parseDirectiveThumbFunc(DirectiveID.getLoc());
8728   else if (IDVal == ".code")
8729     return parseDirectiveCode(DirectiveID.getLoc());
8730   else if (IDVal == ".syntax")
8731     return parseDirectiveSyntax(DirectiveID.getLoc());
8732   else if (IDVal == ".unreq")
8733     return parseDirectiveUnreq(DirectiveID.getLoc());
8734   else if (IDVal == ".fnend")
8735     return parseDirectiveFnEnd(DirectiveID.getLoc());
8736   else if (IDVal == ".cantunwind")
8737     return parseDirectiveCantUnwind(DirectiveID.getLoc());
8738   else if (IDVal == ".personality")
8739     return parseDirectivePersonality(DirectiveID.getLoc());
8740   else if (IDVal == ".handlerdata")
8741     return parseDirectiveHandlerData(DirectiveID.getLoc());
8742   else if (IDVal == ".setfp")
8743     return parseDirectiveSetFP(DirectiveID.getLoc());
8744   else if (IDVal == ".pad")
8745     return parseDirectivePad(DirectiveID.getLoc());
8746   else if (IDVal == ".save")
8747     return parseDirectiveRegSave(DirectiveID.getLoc(), false);
8748   else if (IDVal == ".vsave")
8749     return parseDirectiveRegSave(DirectiveID.getLoc(), true);
8750   else if (IDVal == ".ltorg" || IDVal == ".pool")
8751     return parseDirectiveLtorg(DirectiveID.getLoc());
8752   else if (IDVal == ".even")
8753     return parseDirectiveEven(DirectiveID.getLoc());
8754   else if (IDVal == ".personalityindex")
8755     return parseDirectivePersonalityIndex(DirectiveID.getLoc());
8756   else if (IDVal == ".unwind_raw")
8757     return parseDirectiveUnwindRaw(DirectiveID.getLoc());
8758   else if (IDVal == ".movsp")
8759     return parseDirectiveMovSP(DirectiveID.getLoc());
8760   else if (IDVal == ".arch_extension")
8761     return parseDirectiveArchExtension(DirectiveID.getLoc());
8762   else if (IDVal == ".align")
8763     return parseDirectiveAlign(DirectiveID.getLoc());
8764   else if (IDVal == ".thumb_set")
8765     return parseDirectiveThumbSet(DirectiveID.getLoc());
8766
8767   if (!IsMachO && !IsCOFF) {
8768     if (IDVal == ".arch")
8769       return parseDirectiveArch(DirectiveID.getLoc());
8770     else if (IDVal == ".cpu")
8771       return parseDirectiveCPU(DirectiveID.getLoc());
8772     else if (IDVal == ".eabi_attribute")
8773       return parseDirectiveEabiAttr(DirectiveID.getLoc());
8774     else if (IDVal == ".fpu")
8775       return parseDirectiveFPU(DirectiveID.getLoc());
8776     else if (IDVal == ".fnstart")
8777       return parseDirectiveFnStart(DirectiveID.getLoc());
8778     else if (IDVal == ".inst")
8779       return parseDirectiveInst(DirectiveID.getLoc());
8780     else if (IDVal == ".inst.n")
8781       return parseDirectiveInst(DirectiveID.getLoc(), 'n');
8782     else if (IDVal == ".inst.w")
8783       return parseDirectiveInst(DirectiveID.getLoc(), 'w');
8784     else if (IDVal == ".object_arch")
8785       return parseDirectiveObjectArch(DirectiveID.getLoc());
8786     else if (IDVal == ".tlsdescseq")
8787       return parseDirectiveTLSDescSeq(DirectiveID.getLoc());
8788   }
8789
8790   return true;
8791 }
8792
8793 /// parseLiteralValues
8794 ///  ::= .hword expression [, expression]*
8795 ///  ::= .short expression [, expression]*
8796 ///  ::= .word expression [, expression]*
8797 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
8798   MCAsmParser &Parser = getParser();
8799   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8800     for (;;) {
8801       const MCExpr *Value;
8802       if (getParser().parseExpression(Value)) {
8803         Parser.eatToEndOfStatement();
8804         return false;
8805       }
8806
8807       getParser().getStreamer().EmitValue(Value, Size, L);
8808
8809       if (getLexer().is(AsmToken::EndOfStatement))
8810         break;
8811
8812       // FIXME: Improve diagnostic.
8813       if (getLexer().isNot(AsmToken::Comma)) {
8814         Error(L, "unexpected token in directive");
8815         return false;
8816       }
8817       Parser.Lex();
8818     }
8819   }
8820
8821   Parser.Lex();
8822   return false;
8823 }
8824
8825 /// parseDirectiveThumb
8826 ///  ::= .thumb
8827 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
8828   MCAsmParser &Parser = getParser();
8829   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8830     Error(L, "unexpected token in directive");
8831     return false;
8832   }
8833   Parser.Lex();
8834
8835   if (!hasThumb()) {
8836     Error(L, "target does not support Thumb mode");
8837     return false;
8838   }
8839
8840   if (!isThumb())
8841     SwitchMode();
8842
8843   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8844   return false;
8845 }
8846
8847 /// parseDirectiveARM
8848 ///  ::= .arm
8849 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
8850   MCAsmParser &Parser = getParser();
8851   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8852     Error(L, "unexpected token in directive");
8853     return false;
8854   }
8855   Parser.Lex();
8856
8857   if (!hasARM()) {
8858     Error(L, "target does not support ARM mode");
8859     return false;
8860   }
8861
8862   if (isThumb())
8863     SwitchMode();
8864
8865   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8866   return false;
8867 }
8868
8869 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
8870   if (NextSymbolIsThumb) {
8871     getParser().getStreamer().EmitThumbFunc(Symbol);
8872     NextSymbolIsThumb = false;
8873   }
8874 }
8875
8876 /// parseDirectiveThumbFunc
8877 ///  ::= .thumbfunc symbol_name
8878 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
8879   MCAsmParser &Parser = getParser();
8880   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
8881   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8882
8883   // Darwin asm has (optionally) function name after .thumb_func direction
8884   // ELF doesn't
8885   if (IsMachO) {
8886     const AsmToken &Tok = Parser.getTok();
8887     if (Tok.isNot(AsmToken::EndOfStatement)) {
8888       if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String)) {
8889         Error(L, "unexpected token in .thumb_func directive");
8890         return false;
8891       }
8892
8893       MCSymbol *Func =
8894           getParser().getContext().getOrCreateSymbol(Tok.getIdentifier());
8895       getParser().getStreamer().EmitThumbFunc(Func);
8896       Parser.Lex(); // Consume the identifier token.
8897       return false;
8898     }
8899   }
8900
8901   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8902     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8903     Parser.eatToEndOfStatement();
8904     return false;
8905   }
8906
8907   NextSymbolIsThumb = true;
8908   return false;
8909 }
8910
8911 /// parseDirectiveSyntax
8912 ///  ::= .syntax unified | divided
8913 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
8914   MCAsmParser &Parser = getParser();
8915   const AsmToken &Tok = Parser.getTok();
8916   if (Tok.isNot(AsmToken::Identifier)) {
8917     Error(L, "unexpected token in .syntax directive");
8918     return false;
8919   }
8920
8921   StringRef Mode = Tok.getString();
8922   if (Mode == "unified" || Mode == "UNIFIED") {
8923     Parser.Lex();
8924   } else if (Mode == "divided" || Mode == "DIVIDED") {
8925     Error(L, "'.syntax divided' arm asssembly not supported");
8926     return false;
8927   } else {
8928     Error(L, "unrecognized syntax mode in .syntax directive");
8929     return false;
8930   }
8931
8932   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8933     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8934     return false;
8935   }
8936   Parser.Lex();
8937
8938   // TODO tell the MC streamer the mode
8939   // getParser().getStreamer().Emit???();
8940   return false;
8941 }
8942
8943 /// parseDirectiveCode
8944 ///  ::= .code 16 | 32
8945 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
8946   MCAsmParser &Parser = getParser();
8947   const AsmToken &Tok = Parser.getTok();
8948   if (Tok.isNot(AsmToken::Integer)) {
8949     Error(L, "unexpected token in .code directive");
8950     return false;
8951   }
8952   int64_t Val = Parser.getTok().getIntVal();
8953   if (Val != 16 && Val != 32) {
8954     Error(L, "invalid operand to .code directive");
8955     return false;
8956   }
8957   Parser.Lex();
8958
8959   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8960     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8961     return false;
8962   }
8963   Parser.Lex();
8964
8965   if (Val == 16) {
8966     if (!hasThumb()) {
8967       Error(L, "target does not support Thumb mode");
8968       return false;
8969     }
8970
8971     if (!isThumb())
8972       SwitchMode();
8973     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8974   } else {
8975     if (!hasARM()) {
8976       Error(L, "target does not support ARM mode");
8977       return false;
8978     }
8979
8980     if (isThumb())
8981       SwitchMode();
8982     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8983   }
8984
8985   return false;
8986 }
8987
8988 /// parseDirectiveReq
8989 ///  ::= name .req registername
8990 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
8991   MCAsmParser &Parser = getParser();
8992   Parser.Lex(); // Eat the '.req' token.
8993   unsigned Reg;
8994   SMLoc SRegLoc, ERegLoc;
8995   if (ParseRegister(Reg, SRegLoc, ERegLoc)) {
8996     Parser.eatToEndOfStatement();
8997     Error(SRegLoc, "register name expected");
8998     return false;
8999   }
9000
9001   // Shouldn't be anything else.
9002   if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
9003     Parser.eatToEndOfStatement();
9004     Error(Parser.getTok().getLoc(), "unexpected input in .req directive.");
9005     return false;
9006   }
9007
9008   Parser.Lex(); // Consume the EndOfStatement
9009
9010   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg) {
9011     Error(SRegLoc, "redefinition of '" + Name + "' does not match original.");
9012     return false;
9013   }
9014
9015   return false;
9016 }
9017
9018 /// parseDirectiveUneq
9019 ///  ::= .unreq registername
9020 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9021   MCAsmParser &Parser = getParser();
9022   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9023     Parser.eatToEndOfStatement();
9024     Error(L, "unexpected input in .unreq directive.");
9025     return false;
9026   }
9027   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9028   Parser.Lex(); // Eat the identifier.
9029   return false;
9030 }
9031
9032 /// parseDirectiveArch
9033 ///  ::= .arch token
9034 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9035   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9036
9037   unsigned ID = ARM::parseArch(Arch);
9038
9039   if (ID == ARM::AK_INVALID) {
9040     Error(L, "Unknown arch name");
9041     return false;
9042   }
9043
9044   Triple T;
9045   MCSubtargetInfo &STI = copySTI();
9046   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9047   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9048
9049   getTargetStreamer().emitArch(ID);
9050   return false;
9051 }
9052
9053 /// parseDirectiveEabiAttr
9054 ///  ::= .eabi_attribute int, int [, "str"]
9055 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9056 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9057   MCAsmParser &Parser = getParser();
9058   int64_t Tag;
9059   SMLoc TagLoc;
9060   TagLoc = Parser.getTok().getLoc();
9061   if (Parser.getTok().is(AsmToken::Identifier)) {
9062     StringRef Name = Parser.getTok().getIdentifier();
9063     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9064     if (Tag == -1) {
9065       Error(TagLoc, "attribute name not recognised: " + Name);
9066       Parser.eatToEndOfStatement();
9067       return false;
9068     }
9069     Parser.Lex();
9070   } else {
9071     const MCExpr *AttrExpr;
9072
9073     TagLoc = Parser.getTok().getLoc();
9074     if (Parser.parseExpression(AttrExpr)) {
9075       Parser.eatToEndOfStatement();
9076       return false;
9077     }
9078
9079     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9080     if (!CE) {
9081       Error(TagLoc, "expected numeric constant");
9082       Parser.eatToEndOfStatement();
9083       return false;
9084     }
9085
9086     Tag = CE->getValue();
9087   }
9088
9089   if (Parser.getTok().isNot(AsmToken::Comma)) {
9090     Error(Parser.getTok().getLoc(), "comma expected");
9091     Parser.eatToEndOfStatement();
9092     return false;
9093   }
9094   Parser.Lex(); // skip comma
9095
9096   StringRef StringValue = "";
9097   bool IsStringValue = false;
9098
9099   int64_t IntegerValue = 0;
9100   bool IsIntegerValue = false;
9101
9102   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9103     IsStringValue = true;
9104   else if (Tag == ARMBuildAttrs::compatibility) {
9105     IsStringValue = true;
9106     IsIntegerValue = true;
9107   } else if (Tag < 32 || Tag % 2 == 0)
9108     IsIntegerValue = true;
9109   else if (Tag % 2 == 1)
9110     IsStringValue = true;
9111   else
9112     llvm_unreachable("invalid tag type");
9113
9114   if (IsIntegerValue) {
9115     const MCExpr *ValueExpr;
9116     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9117     if (Parser.parseExpression(ValueExpr)) {
9118       Parser.eatToEndOfStatement();
9119       return false;
9120     }
9121
9122     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9123     if (!CE) {
9124       Error(ValueExprLoc, "expected numeric constant");
9125       Parser.eatToEndOfStatement();
9126       return false;
9127     }
9128
9129     IntegerValue = CE->getValue();
9130   }
9131
9132   if (Tag == ARMBuildAttrs::compatibility) {
9133     if (Parser.getTok().isNot(AsmToken::Comma))
9134       IsStringValue = false;
9135     if (Parser.getTok().isNot(AsmToken::Comma)) {
9136       Error(Parser.getTok().getLoc(), "comma expected");
9137       Parser.eatToEndOfStatement();
9138       return false;
9139     } else {
9140        Parser.Lex();
9141     }
9142   }
9143
9144   if (IsStringValue) {
9145     if (Parser.getTok().isNot(AsmToken::String)) {
9146       Error(Parser.getTok().getLoc(), "bad string constant");
9147       Parser.eatToEndOfStatement();
9148       return false;
9149     }
9150
9151     StringValue = Parser.getTok().getStringContents();
9152     Parser.Lex();
9153   }
9154
9155   if (IsIntegerValue && IsStringValue) {
9156     assert(Tag == ARMBuildAttrs::compatibility);
9157     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9158   } else if (IsIntegerValue)
9159     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9160   else if (IsStringValue)
9161     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9162   return false;
9163 }
9164
9165 /// parseDirectiveCPU
9166 ///  ::= .cpu str
9167 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9168   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9169   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9170
9171   // FIXME: This is using table-gen data, but should be moved to
9172   // ARMTargetParser once that is table-gen'd.
9173   if (!getSTI().isCPUStringValid(CPU)) {
9174     Error(L, "Unknown CPU name");
9175     return false;
9176   }
9177
9178   MCSubtargetInfo &STI = copySTI();
9179   STI.setDefaultFeatures(CPU, "");
9180   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9181
9182   return false;
9183 }
9184 /// parseDirectiveFPU
9185 ///  ::= .fpu str
9186 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9187   SMLoc FPUNameLoc = getTok().getLoc();
9188   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9189
9190   unsigned ID = ARM::parseFPU(FPU);
9191   std::vector<const char *> Features;
9192   if (!ARM::getFPUFeatures(ID, Features)) {
9193     Error(FPUNameLoc, "Unknown FPU name");
9194     return false;
9195   }
9196
9197   MCSubtargetInfo &STI = copySTI();
9198   for (auto Feature : Features)
9199     STI.ApplyFeatureFlag(Feature);
9200   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9201
9202   getTargetStreamer().emitFPU(ID);
9203   return false;
9204 }
9205
9206 /// parseDirectiveFnStart
9207 ///  ::= .fnstart
9208 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9209   if (UC.hasFnStart()) {
9210     Error(L, ".fnstart starts before the end of previous one");
9211     UC.emitFnStartLocNotes();
9212     return false;
9213   }
9214
9215   // Reset the unwind directives parser state
9216   UC.reset();
9217
9218   getTargetStreamer().emitFnStart();
9219
9220   UC.recordFnStart(L);
9221   return false;
9222 }
9223
9224 /// parseDirectiveFnEnd
9225 ///  ::= .fnend
9226 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9227   // Check the ordering of unwind directives
9228   if (!UC.hasFnStart()) {
9229     Error(L, ".fnstart must precede .fnend directive");
9230     return false;
9231   }
9232
9233   // Reset the unwind directives parser state
9234   getTargetStreamer().emitFnEnd();
9235
9236   UC.reset();
9237   return false;
9238 }
9239
9240 /// parseDirectiveCantUnwind
9241 ///  ::= .cantunwind
9242 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9243   UC.recordCantUnwind(L);
9244
9245   // Check the ordering of unwind directives
9246   if (!UC.hasFnStart()) {
9247     Error(L, ".fnstart must precede .cantunwind directive");
9248     return false;
9249   }
9250   if (UC.hasHandlerData()) {
9251     Error(L, ".cantunwind can't be used with .handlerdata directive");
9252     UC.emitHandlerDataLocNotes();
9253     return false;
9254   }
9255   if (UC.hasPersonality()) {
9256     Error(L, ".cantunwind can't be used with .personality directive");
9257     UC.emitPersonalityLocNotes();
9258     return false;
9259   }
9260
9261   getTargetStreamer().emitCantUnwind();
9262   return false;
9263 }
9264
9265 /// parseDirectivePersonality
9266 ///  ::= .personality name
9267 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9268   MCAsmParser &Parser = getParser();
9269   bool HasExistingPersonality = UC.hasPersonality();
9270
9271   UC.recordPersonality(L);
9272
9273   // Check the ordering of unwind directives
9274   if (!UC.hasFnStart()) {
9275     Error(L, ".fnstart must precede .personality directive");
9276     return false;
9277   }
9278   if (UC.cantUnwind()) {
9279     Error(L, ".personality can't be used with .cantunwind directive");
9280     UC.emitCantUnwindLocNotes();
9281     return false;
9282   }
9283   if (UC.hasHandlerData()) {
9284     Error(L, ".personality must precede .handlerdata directive");
9285     UC.emitHandlerDataLocNotes();
9286     return false;
9287   }
9288   if (HasExistingPersonality) {
9289     Parser.eatToEndOfStatement();
9290     Error(L, "multiple personality directives");
9291     UC.emitPersonalityLocNotes();
9292     return false;
9293   }
9294
9295   // Parse the name of the personality routine
9296   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9297     Parser.eatToEndOfStatement();
9298     Error(L, "unexpected input in .personality directive.");
9299     return false;
9300   }
9301   StringRef Name(Parser.getTok().getIdentifier());
9302   Parser.Lex();
9303
9304   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9305   getTargetStreamer().emitPersonality(PR);
9306   return false;
9307 }
9308
9309 /// parseDirectiveHandlerData
9310 ///  ::= .handlerdata
9311 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9312   UC.recordHandlerData(L);
9313
9314   // Check the ordering of unwind directives
9315   if (!UC.hasFnStart()) {
9316     Error(L, ".fnstart must precede .personality directive");
9317     return false;
9318   }
9319   if (UC.cantUnwind()) {
9320     Error(L, ".handlerdata can't be used with .cantunwind directive");
9321     UC.emitCantUnwindLocNotes();
9322     return false;
9323   }
9324
9325   getTargetStreamer().emitHandlerData();
9326   return false;
9327 }
9328
9329 /// parseDirectiveSetFP
9330 ///  ::= .setfp fpreg, spreg [, offset]
9331 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9332   MCAsmParser &Parser = getParser();
9333   // Check the ordering of unwind directives
9334   if (!UC.hasFnStart()) {
9335     Error(L, ".fnstart must precede .setfp directive");
9336     return false;
9337   }
9338   if (UC.hasHandlerData()) {
9339     Error(L, ".setfp must precede .handlerdata directive");
9340     return false;
9341   }
9342
9343   // Parse fpreg
9344   SMLoc FPRegLoc = Parser.getTok().getLoc();
9345   int FPReg = tryParseRegister();
9346   if (FPReg == -1) {
9347     Error(FPRegLoc, "frame pointer register expected");
9348     return false;
9349   }
9350
9351   // Consume comma
9352   if (Parser.getTok().isNot(AsmToken::Comma)) {
9353     Error(Parser.getTok().getLoc(), "comma expected");
9354     return false;
9355   }
9356   Parser.Lex(); // skip comma
9357
9358   // Parse spreg
9359   SMLoc SPRegLoc = Parser.getTok().getLoc();
9360   int SPReg = tryParseRegister();
9361   if (SPReg == -1) {
9362     Error(SPRegLoc, "stack pointer register expected");
9363     return false;
9364   }
9365
9366   if (SPReg != ARM::SP && SPReg != UC.getFPReg()) {
9367     Error(SPRegLoc, "register should be either $sp or the latest fp register");
9368     return false;
9369   }
9370
9371   // Update the frame pointer register
9372   UC.saveFPReg(FPReg);
9373
9374   // Parse offset
9375   int64_t Offset = 0;
9376   if (Parser.getTok().is(AsmToken::Comma)) {
9377     Parser.Lex(); // skip comma
9378
9379     if (Parser.getTok().isNot(AsmToken::Hash) &&
9380         Parser.getTok().isNot(AsmToken::Dollar)) {
9381       Error(Parser.getTok().getLoc(), "'#' expected");
9382       return false;
9383     }
9384     Parser.Lex(); // skip hash token.
9385
9386     const MCExpr *OffsetExpr;
9387     SMLoc ExLoc = Parser.getTok().getLoc();
9388     SMLoc EndLoc;
9389     if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9390       Error(ExLoc, "malformed setfp offset");
9391       return false;
9392     }
9393     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9394     if (!CE) {
9395       Error(ExLoc, "setfp offset must be an immediate");
9396       return false;
9397     }
9398
9399     Offset = CE->getValue();
9400   }
9401
9402   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9403                                 static_cast<unsigned>(SPReg), Offset);
9404   return false;
9405 }
9406
9407 /// parseDirective
9408 ///  ::= .pad offset
9409 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9410   MCAsmParser &Parser = getParser();
9411   // Check the ordering of unwind directives
9412   if (!UC.hasFnStart()) {
9413     Error(L, ".fnstart must precede .pad directive");
9414     return false;
9415   }
9416   if (UC.hasHandlerData()) {
9417     Error(L, ".pad must precede .handlerdata directive");
9418     return false;
9419   }
9420
9421   // Parse the offset
9422   if (Parser.getTok().isNot(AsmToken::Hash) &&
9423       Parser.getTok().isNot(AsmToken::Dollar)) {
9424     Error(Parser.getTok().getLoc(), "'#' expected");
9425     return false;
9426   }
9427   Parser.Lex(); // skip hash token.
9428
9429   const MCExpr *OffsetExpr;
9430   SMLoc ExLoc = Parser.getTok().getLoc();
9431   SMLoc EndLoc;
9432   if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9433     Error(ExLoc, "malformed pad offset");
9434     return false;
9435   }
9436   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9437   if (!CE) {
9438     Error(ExLoc, "pad offset must be an immediate");
9439     return false;
9440   }
9441
9442   getTargetStreamer().emitPad(CE->getValue());
9443   return false;
9444 }
9445
9446 /// parseDirectiveRegSave
9447 ///  ::= .save  { registers }
9448 ///  ::= .vsave { registers }
9449 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9450   // Check the ordering of unwind directives
9451   if (!UC.hasFnStart()) {
9452     Error(L, ".fnstart must precede .save or .vsave directives");
9453     return false;
9454   }
9455   if (UC.hasHandlerData()) {
9456     Error(L, ".save or .vsave must precede .handlerdata directive");
9457     return false;
9458   }
9459
9460   // RAII object to make sure parsed operands are deleted.
9461   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9462
9463   // Parse the register list
9464   if (parseRegisterList(Operands))
9465     return false;
9466   ARMOperand &Op = (ARMOperand &)*Operands[0];
9467   if (!IsVector && !Op.isRegList()) {
9468     Error(L, ".save expects GPR registers");
9469     return false;
9470   }
9471   if (IsVector && !Op.isDPRRegList()) {
9472     Error(L, ".vsave expects DPR registers");
9473     return false;
9474   }
9475
9476   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9477   return false;
9478 }
9479
9480 /// parseDirectiveInst
9481 ///  ::= .inst opcode [, ...]
9482 ///  ::= .inst.n opcode [, ...]
9483 ///  ::= .inst.w opcode [, ...]
9484 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9485   MCAsmParser &Parser = getParser();
9486   int Width;
9487
9488   if (isThumb()) {
9489     switch (Suffix) {
9490     case 'n':
9491       Width = 2;
9492       break;
9493     case 'w':
9494       Width = 4;
9495       break;
9496     default:
9497       Parser.eatToEndOfStatement();
9498       Error(Loc, "cannot determine Thumb instruction size, "
9499                  "use inst.n/inst.w instead");
9500       return false;
9501     }
9502   } else {
9503     if (Suffix) {
9504       Parser.eatToEndOfStatement();
9505       Error(Loc, "width suffixes are invalid in ARM mode");
9506       return false;
9507     }
9508     Width = 4;
9509   }
9510
9511   if (getLexer().is(AsmToken::EndOfStatement)) {
9512     Parser.eatToEndOfStatement();
9513     Error(Loc, "expected expression following directive");
9514     return false;
9515   }
9516
9517   for (;;) {
9518     const MCExpr *Expr;
9519
9520     if (getParser().parseExpression(Expr)) {
9521       Error(Loc, "expected expression");
9522       return false;
9523     }
9524
9525     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9526     if (!Value) {
9527       Error(Loc, "expected constant expression");
9528       return false;
9529     }
9530
9531     switch (Width) {
9532     case 2:
9533       if (Value->getValue() > 0xffff) {
9534         Error(Loc, "inst.n operand is too big, use inst.w instead");
9535         return false;
9536       }
9537       break;
9538     case 4:
9539       if (Value->getValue() > 0xffffffff) {
9540         Error(Loc,
9541               StringRef(Suffix ? "inst.w" : "inst") + " operand is too big");
9542         return false;
9543       }
9544       break;
9545     default:
9546       llvm_unreachable("only supported widths are 2 and 4");
9547     }
9548
9549     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9550
9551     if (getLexer().is(AsmToken::EndOfStatement))
9552       break;
9553
9554     if (getLexer().isNot(AsmToken::Comma)) {
9555       Error(Loc, "unexpected token in directive");
9556       return false;
9557     }
9558
9559     Parser.Lex();
9560   }
9561
9562   Parser.Lex();
9563   return false;
9564 }
9565
9566 /// parseDirectiveLtorg
9567 ///  ::= .ltorg | .pool
9568 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9569   getTargetStreamer().emitCurrentConstantPool();
9570   return false;
9571 }
9572
9573 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9574   const MCSection *Section = getStreamer().getCurrentSection().first;
9575
9576   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9577     TokError("unexpected token in directive");
9578     return false;
9579   }
9580
9581   if (!Section) {
9582     getStreamer().InitSections(false);
9583     Section = getStreamer().getCurrentSection().first;
9584   }
9585
9586   assert(Section && "must have section to emit alignment");
9587   if (Section->UseCodeAlign())
9588     getStreamer().EmitCodeAlignment(2);
9589   else
9590     getStreamer().EmitValueToAlignment(2);
9591
9592   return false;
9593 }
9594
9595 /// parseDirectivePersonalityIndex
9596 ///   ::= .personalityindex index
9597 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9598   MCAsmParser &Parser = getParser();
9599   bool HasExistingPersonality = UC.hasPersonality();
9600
9601   UC.recordPersonalityIndex(L);
9602
9603   if (!UC.hasFnStart()) {
9604     Parser.eatToEndOfStatement();
9605     Error(L, ".fnstart must precede .personalityindex directive");
9606     return false;
9607   }
9608   if (UC.cantUnwind()) {
9609     Parser.eatToEndOfStatement();
9610     Error(L, ".personalityindex cannot be used with .cantunwind");
9611     UC.emitCantUnwindLocNotes();
9612     return false;
9613   }
9614   if (UC.hasHandlerData()) {
9615     Parser.eatToEndOfStatement();
9616     Error(L, ".personalityindex must precede .handlerdata directive");
9617     UC.emitHandlerDataLocNotes();
9618     return false;
9619   }
9620   if (HasExistingPersonality) {
9621     Parser.eatToEndOfStatement();
9622     Error(L, "multiple personality directives");
9623     UC.emitPersonalityLocNotes();
9624     return false;
9625   }
9626
9627   const MCExpr *IndexExpression;
9628   SMLoc IndexLoc = Parser.getTok().getLoc();
9629   if (Parser.parseExpression(IndexExpression)) {
9630     Parser.eatToEndOfStatement();
9631     return false;
9632   }
9633
9634   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9635   if (!CE) {
9636     Parser.eatToEndOfStatement();
9637     Error(IndexLoc, "index must be a constant number");
9638     return false;
9639   }
9640   if (CE->getValue() < 0 ||
9641       CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX) {
9642     Parser.eatToEndOfStatement();
9643     Error(IndexLoc, "personality routine index should be in range [0-3]");
9644     return false;
9645   }
9646
9647   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9648   return false;
9649 }
9650
9651 /// parseDirectiveUnwindRaw
9652 ///   ::= .unwind_raw offset, opcode [, opcode...]
9653 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9654   MCAsmParser &Parser = getParser();
9655   if (!UC.hasFnStart()) {
9656     Parser.eatToEndOfStatement();
9657     Error(L, ".fnstart must precede .unwind_raw directives");
9658     return false;
9659   }
9660
9661   int64_t StackOffset;
9662
9663   const MCExpr *OffsetExpr;
9664   SMLoc OffsetLoc = getLexer().getLoc();
9665   if (getLexer().is(AsmToken::EndOfStatement) ||
9666       getParser().parseExpression(OffsetExpr)) {
9667     Error(OffsetLoc, "expected expression");
9668     Parser.eatToEndOfStatement();
9669     return false;
9670   }
9671
9672   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9673   if (!CE) {
9674     Error(OffsetLoc, "offset must be a constant");
9675     Parser.eatToEndOfStatement();
9676     return false;
9677   }
9678
9679   StackOffset = CE->getValue();
9680
9681   if (getLexer().isNot(AsmToken::Comma)) {
9682     Error(getLexer().getLoc(), "expected comma");
9683     Parser.eatToEndOfStatement();
9684     return false;
9685   }
9686   Parser.Lex();
9687
9688   SmallVector<uint8_t, 16> Opcodes;
9689   for (;;) {
9690     const MCExpr *OE;
9691
9692     SMLoc OpcodeLoc = getLexer().getLoc();
9693     if (getLexer().is(AsmToken::EndOfStatement) || Parser.parseExpression(OE)) {
9694       Error(OpcodeLoc, "expected opcode expression");
9695       Parser.eatToEndOfStatement();
9696       return false;
9697     }
9698
9699     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9700     if (!OC) {
9701       Error(OpcodeLoc, "opcode value must be a constant");
9702       Parser.eatToEndOfStatement();
9703       return false;
9704     }
9705
9706     const int64_t Opcode = OC->getValue();
9707     if (Opcode & ~0xff) {
9708       Error(OpcodeLoc, "invalid opcode");
9709       Parser.eatToEndOfStatement();
9710       return false;
9711     }
9712
9713     Opcodes.push_back(uint8_t(Opcode));
9714
9715     if (getLexer().is(AsmToken::EndOfStatement))
9716       break;
9717
9718     if (getLexer().isNot(AsmToken::Comma)) {
9719       Error(getLexer().getLoc(), "unexpected token in directive");
9720       Parser.eatToEndOfStatement();
9721       return false;
9722     }
9723
9724     Parser.Lex();
9725   }
9726
9727   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9728
9729   Parser.Lex();
9730   return false;
9731 }
9732
9733 /// parseDirectiveTLSDescSeq
9734 ///   ::= .tlsdescseq tls-variable
9735 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9736   MCAsmParser &Parser = getParser();
9737
9738   if (getLexer().isNot(AsmToken::Identifier)) {
9739     TokError("expected variable after '.tlsdescseq' directive");
9740     Parser.eatToEndOfStatement();
9741     return false;
9742   }
9743
9744   const MCSymbolRefExpr *SRE =
9745     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
9746                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9747   Lex();
9748
9749   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9750     Error(Parser.getTok().getLoc(), "unexpected token");
9751     Parser.eatToEndOfStatement();
9752     return false;
9753   }
9754
9755   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9756   return false;
9757 }
9758
9759 /// parseDirectiveMovSP
9760 ///  ::= .movsp reg [, #offset]
9761 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
9762   MCAsmParser &Parser = getParser();
9763   if (!UC.hasFnStart()) {
9764     Parser.eatToEndOfStatement();
9765     Error(L, ".fnstart must precede .movsp directives");
9766     return false;
9767   }
9768   if (UC.getFPReg() != ARM::SP) {
9769     Parser.eatToEndOfStatement();
9770     Error(L, "unexpected .movsp directive");
9771     return false;
9772   }
9773
9774   SMLoc SPRegLoc = Parser.getTok().getLoc();
9775   int SPReg = tryParseRegister();
9776   if (SPReg == -1) {
9777     Parser.eatToEndOfStatement();
9778     Error(SPRegLoc, "register expected");
9779     return false;
9780   }
9781
9782   if (SPReg == ARM::SP || SPReg == ARM::PC) {
9783     Parser.eatToEndOfStatement();
9784     Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
9785     return false;
9786   }
9787
9788   int64_t Offset = 0;
9789   if (Parser.getTok().is(AsmToken::Comma)) {
9790     Parser.Lex();
9791
9792     if (Parser.getTok().isNot(AsmToken::Hash)) {
9793       Error(Parser.getTok().getLoc(), "expected #constant");
9794       Parser.eatToEndOfStatement();
9795       return false;
9796     }
9797     Parser.Lex();
9798
9799     const MCExpr *OffsetExpr;
9800     SMLoc OffsetLoc = Parser.getTok().getLoc();
9801     if (Parser.parseExpression(OffsetExpr)) {
9802       Parser.eatToEndOfStatement();
9803       Error(OffsetLoc, "malformed offset expression");
9804       return false;
9805     }
9806
9807     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9808     if (!CE) {
9809       Parser.eatToEndOfStatement();
9810       Error(OffsetLoc, "offset must be an immediate constant");
9811       return false;
9812     }
9813
9814     Offset = CE->getValue();
9815   }
9816
9817   getTargetStreamer().emitMovSP(SPReg, Offset);
9818   UC.saveFPReg(SPReg);
9819
9820   return false;
9821 }
9822
9823 /// parseDirectiveObjectArch
9824 ///   ::= .object_arch name
9825 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
9826   MCAsmParser &Parser = getParser();
9827   if (getLexer().isNot(AsmToken::Identifier)) {
9828     Error(getLexer().getLoc(), "unexpected token");
9829     Parser.eatToEndOfStatement();
9830     return false;
9831   }
9832
9833   StringRef Arch = Parser.getTok().getString();
9834   SMLoc ArchLoc = Parser.getTok().getLoc();
9835   getLexer().Lex();
9836
9837   unsigned ID = ARM::parseArch(Arch);
9838
9839   if (ID == ARM::AK_INVALID) {
9840     Error(ArchLoc, "unknown architecture '" + Arch + "'");
9841     Parser.eatToEndOfStatement();
9842     return false;
9843   }
9844
9845   getTargetStreamer().emitObjectArch(ID);
9846
9847   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9848     Error(getLexer().getLoc(), "unexpected token");
9849     Parser.eatToEndOfStatement();
9850   }
9851
9852   return false;
9853 }
9854
9855 /// parseDirectiveAlign
9856 ///   ::= .align
9857 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
9858   // NOTE: if this is not the end of the statement, fall back to the target
9859   // agnostic handling for this directive which will correctly handle this.
9860   if (getLexer().isNot(AsmToken::EndOfStatement))
9861     return true;
9862
9863   // '.align' is target specifically handled to mean 2**2 byte alignment.
9864   if (getStreamer().getCurrentSection().first->UseCodeAlign())
9865     getStreamer().EmitCodeAlignment(4, 0);
9866   else
9867     getStreamer().EmitValueToAlignment(4, 0, 1, 0);
9868
9869   return false;
9870 }
9871
9872 /// parseDirectiveThumbSet
9873 ///  ::= .thumb_set name, value
9874 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
9875   MCAsmParser &Parser = getParser();
9876
9877   StringRef Name;
9878   if (Parser.parseIdentifier(Name)) {
9879     TokError("expected identifier after '.thumb_set'");
9880     Parser.eatToEndOfStatement();
9881     return false;
9882   }
9883
9884   if (getLexer().isNot(AsmToken::Comma)) {
9885     TokError("expected comma after name '" + Name + "'");
9886     Parser.eatToEndOfStatement();
9887     return false;
9888   }
9889   Lex();
9890
9891   MCSymbol *Sym;
9892   const MCExpr *Value;
9893   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
9894                                                Parser, Sym, Value))
9895     return true;
9896
9897   getTargetStreamer().emitThumbSet(Sym, Value);
9898   return false;
9899 }
9900
9901 /// Force static initialization.
9902 extern "C" void LLVMInitializeARMAsmParser() {
9903   RegisterMCAsmParser<ARMAsmParser> X(TheARMLETarget);
9904   RegisterMCAsmParser<ARMAsmParser> Y(TheARMBETarget);
9905   RegisterMCAsmParser<ARMAsmParser> A(TheThumbLETarget);
9906   RegisterMCAsmParser<ARMAsmParser> B(TheThumbBETarget);
9907 }
9908
9909 #define GET_REGISTER_MATCHER
9910 #define GET_SUBTARGET_FEATURE_NAME
9911 #define GET_MATCHER_IMPLEMENTATION
9912 #include "ARMGenAsmMatcher.inc"
9913
9914 // FIXME: This structure should be moved inside ARMTargetParser
9915 // when we start to table-generate them, and we can use the ARM
9916 // flags below, that were generated by table-gen.
9917 static const struct {
9918   const unsigned Kind;
9919   const uint64_t ArchCheck;
9920   const FeatureBitset Features;
9921 } Extensions[] = {
9922   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
9923   { ARM::AEK_CRYPTO,  Feature_HasV8,
9924     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
9925   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
9926   { (ARM::AEK_HWDIV | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
9927     {ARM::FeatureHWDiv, ARM::FeatureHWDivARM} },
9928   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
9929   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
9930   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
9931   // FIXME: Only available in A-class, isel not predicated
9932   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
9933   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
9934   // FIXME: Unsupported extensions.
9935   { ARM::AEK_OS, Feature_None, {} },
9936   { ARM::AEK_IWMMXT, Feature_None, {} },
9937   { ARM::AEK_IWMMXT2, Feature_None, {} },
9938   { ARM::AEK_MAVERICK, Feature_None, {} },
9939   { ARM::AEK_XSCALE, Feature_None, {} },
9940 };
9941
9942 /// parseDirectiveArchExtension
9943 ///   ::= .arch_extension [no]feature
9944 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
9945   MCAsmParser &Parser = getParser();
9946
9947   if (getLexer().isNot(AsmToken::Identifier)) {
9948     Error(getLexer().getLoc(), "unexpected token");
9949     Parser.eatToEndOfStatement();
9950     return false;
9951   }
9952
9953   StringRef Name = Parser.getTok().getString();
9954   SMLoc ExtLoc = Parser.getTok().getLoc();
9955   getLexer().Lex();
9956
9957   bool EnableFeature = true;
9958   if (Name.startswith_lower("no")) {
9959     EnableFeature = false;
9960     Name = Name.substr(2);
9961   }
9962   unsigned FeatureKind = ARM::parseArchExt(Name);
9963   if (FeatureKind == ARM::AEK_INVALID)
9964     Error(ExtLoc, "unknown architectural extension: " + Name);
9965
9966   for (const auto &Extension : Extensions) {
9967     if (Extension.Kind != FeatureKind)
9968       continue;
9969
9970     if (Extension.Features.none())
9971       report_fatal_error("unsupported architectural extension: " + Name);
9972
9973     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck) {
9974       Error(ExtLoc, "architectural extension '" + Name + "' is not "
9975             "allowed for the current base architecture");
9976       return false;
9977     }
9978
9979     MCSubtargetInfo &STI = copySTI();
9980     FeatureBitset ToggleFeatures = EnableFeature
9981       ? (~STI.getFeatureBits() & Extension.Features)
9982       : ( STI.getFeatureBits() & Extension.Features);
9983
9984     uint64_t Features =
9985         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
9986     setAvailableFeatures(Features);
9987     return false;
9988   }
9989
9990   Error(ExtLoc, "unknown architectural extension: " + Name);
9991   Parser.eatToEndOfStatement();
9992   return false;
9993 }
9994
9995 // Define this matcher function after the auto-generated include so we
9996 // have the match class enum definitions.
9997 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
9998                                                   unsigned Kind) {
9999   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10000   // If the kind is a token for a literal immediate, check if our asm
10001   // operand matches. This is for InstAliases which have a fixed-value
10002   // immediate in the syntax.
10003   switch (Kind) {
10004   default: break;
10005   case MCK__35_0:
10006     if (Op.isImm())
10007       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10008         if (CE->getValue() == 0)
10009           return Match_Success;
10010     break;
10011   case MCK_ModImm:
10012     if (Op.isImm()) {
10013       const MCExpr *SOExpr = Op.getImm();
10014       int64_t Value;
10015       if (!SOExpr->evaluateAsAbsolute(Value))
10016         return Match_Success;
10017       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
10018              "expression value must be representable in 32 bits");
10019     }
10020     break;
10021   case MCK_rGPR:
10022     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10023       return Match_Success;
10024     break;
10025   case MCK_GPRPair:
10026     if (Op.isReg() &&
10027         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10028       return Match_Success;
10029     break;
10030   }
10031   return Match_InvalidOperand;
10032 }