NEON VLD3 lane-indexed assembly parsing and encoding.
[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 "MCTargetDesc/ARMBaseInfo.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMMCExpr.h"
13 #include "llvm/MC/MCParser/MCAsmLexer.h"
14 #include "llvm/MC/MCParser/MCAsmParser.h"
15 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCStreamer.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCInstrDesc.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCTargetAsmParser.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringSwitch.h"
34 #include "llvm/ADT/Twine.h"
35
36 using namespace llvm;
37
38 namespace {
39
40 class ARMOperand;
41
42 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
43
44 class ARMAsmParser : public MCTargetAsmParser {
45   MCSubtargetInfo &STI;
46   MCAsmParser &Parser;
47
48   // Map of register aliases registers via the .req directive.
49   StringMap<unsigned> RegisterReqs;
50
51   struct {
52     ARMCC::CondCodes Cond;    // Condition for IT block.
53     unsigned Mask:4;          // Condition mask for instructions.
54                               // Starting at first 1 (from lsb).
55                               //   '1'  condition as indicated in IT.
56                               //   '0'  inverse of condition (else).
57                               // Count of instructions in IT block is
58                               // 4 - trailingzeroes(mask)
59
60     bool FirstCond;           // Explicit flag for when we're parsing the
61                               // First instruction in the IT block. It's
62                               // implied in the mask, so needs special
63                               // handling.
64
65     unsigned CurPosition;     // Current position in parsing of IT
66                               // block. In range [0,3]. Initialized
67                               // according to count of instructions in block.
68                               // ~0U if no active IT block.
69   } ITState;
70   bool inITBlock() { return ITState.CurPosition != ~0U;}
71   void forwardITPosition() {
72     if (!inITBlock()) return;
73     // Move to the next instruction in the IT block, if there is one. If not,
74     // mark the block as done.
75     unsigned TZ = CountTrailingZeros_32(ITState.Mask);
76     if (++ITState.CurPosition == 5 - TZ)
77       ITState.CurPosition = ~0U; // Done with the IT block after this.
78   }
79
80
81   MCAsmParser &getParser() const { return Parser; }
82   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
83
84   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
85   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
86
87   int tryParseRegister();
88   bool tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
89   int tryParseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
90   bool parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
91   bool parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
92   bool parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
93   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
94   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
95                               unsigned &ShiftAmount);
96   bool parseDirectiveWord(unsigned Size, SMLoc L);
97   bool parseDirectiveThumb(SMLoc L);
98   bool parseDirectiveARM(SMLoc L);
99   bool parseDirectiveThumbFunc(SMLoc L);
100   bool parseDirectiveCode(SMLoc L);
101   bool parseDirectiveSyntax(SMLoc L);
102   bool parseDirectiveReq(StringRef Name, SMLoc L);
103   bool parseDirectiveUnreq(SMLoc L);
104   bool parseDirectiveArch(SMLoc L);
105   bool parseDirectiveEabiAttr(SMLoc L);
106
107   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
108                           bool &CarrySetting, unsigned &ProcessorIMod,
109                           StringRef &ITMask);
110   void getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
111                              bool &CanAcceptPredicationCode);
112
113   bool isThumb() const {
114     // FIXME: Can tablegen auto-generate this?
115     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
116   }
117   bool isThumbOne() const {
118     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
119   }
120   bool isThumbTwo() const {
121     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2);
122   }
123   bool hasV6Ops() const {
124     return STI.getFeatureBits() & ARM::HasV6Ops;
125   }
126   bool hasV7Ops() const {
127     return STI.getFeatureBits() & ARM::HasV7Ops;
128   }
129   void SwitchMode() {
130     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
131     setAvailableFeatures(FB);
132   }
133   bool isMClass() const {
134     return STI.getFeatureBits() & ARM::FeatureMClass;
135   }
136
137   /// @name Auto-generated Match Functions
138   /// {
139
140 #define GET_ASSEMBLER_HEADER
141 #include "ARMGenAsmMatcher.inc"
142
143   /// }
144
145   OperandMatchResultTy parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*>&);
146   OperandMatchResultTy parseCoprocNumOperand(
147     SmallVectorImpl<MCParsedAsmOperand*>&);
148   OperandMatchResultTy parseCoprocRegOperand(
149     SmallVectorImpl<MCParsedAsmOperand*>&);
150   OperandMatchResultTy parseCoprocOptionOperand(
151     SmallVectorImpl<MCParsedAsmOperand*>&);
152   OperandMatchResultTy parseMemBarrierOptOperand(
153     SmallVectorImpl<MCParsedAsmOperand*>&);
154   OperandMatchResultTy parseProcIFlagsOperand(
155     SmallVectorImpl<MCParsedAsmOperand*>&);
156   OperandMatchResultTy parseMSRMaskOperand(
157     SmallVectorImpl<MCParsedAsmOperand*>&);
158   OperandMatchResultTy parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &O,
159                                    StringRef Op, int Low, int High);
160   OperandMatchResultTy parsePKHLSLImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
161     return parsePKHImm(O, "lsl", 0, 31);
162   }
163   OperandMatchResultTy parsePKHASRImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
164     return parsePKHImm(O, "asr", 1, 32);
165   }
166   OperandMatchResultTy parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*>&);
167   OperandMatchResultTy parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*>&);
168   OperandMatchResultTy parseRotImm(SmallVectorImpl<MCParsedAsmOperand*>&);
169   OperandMatchResultTy parseBitfield(SmallVectorImpl<MCParsedAsmOperand*>&);
170   OperandMatchResultTy parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*>&);
171   OperandMatchResultTy parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*>&);
172   OperandMatchResultTy parseFPImm(SmallVectorImpl<MCParsedAsmOperand*>&);
173   OperandMatchResultTy parseVectorList(SmallVectorImpl<MCParsedAsmOperand*>&);
174   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index);
175
176   // Asm Match Converter Methods
177   bool cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
178                     const SmallVectorImpl<MCParsedAsmOperand*> &);
179   bool cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
180                     const SmallVectorImpl<MCParsedAsmOperand*> &);
181   bool cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
182                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
183   bool cvtStWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
184                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
185   bool cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
186                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
187   bool cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
188                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
189   bool cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
190                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
191   bool cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
192                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
193   bool cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
194                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
195   bool cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
196                              const SmallVectorImpl<MCParsedAsmOperand*> &);
197   bool cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
198                              const SmallVectorImpl<MCParsedAsmOperand*> &);
199   bool cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
200                              const SmallVectorImpl<MCParsedAsmOperand*> &);
201   bool cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
202                              const SmallVectorImpl<MCParsedAsmOperand*> &);
203   bool cvtLdrdPre(MCInst &Inst, unsigned Opcode,
204                   const SmallVectorImpl<MCParsedAsmOperand*> &);
205   bool cvtStrdPre(MCInst &Inst, unsigned Opcode,
206                   const SmallVectorImpl<MCParsedAsmOperand*> &);
207   bool cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
208                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
209   bool cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
210                         const SmallVectorImpl<MCParsedAsmOperand*> &);
211   bool cvtVLDwbFixed(MCInst &Inst, unsigned Opcode,
212                      const SmallVectorImpl<MCParsedAsmOperand*> &);
213   bool cvtVLDwbRegister(MCInst &Inst, unsigned Opcode,
214                         const SmallVectorImpl<MCParsedAsmOperand*> &);
215   bool cvtVSTwbFixed(MCInst &Inst, unsigned Opcode,
216                      const SmallVectorImpl<MCParsedAsmOperand*> &);
217   bool cvtVSTwbRegister(MCInst &Inst, unsigned Opcode,
218                         const SmallVectorImpl<MCParsedAsmOperand*> &);
219
220   bool validateInstruction(MCInst &Inst,
221                            const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
222   bool processInstruction(MCInst &Inst,
223                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
224   bool shouldOmitCCOutOperand(StringRef Mnemonic,
225                               SmallVectorImpl<MCParsedAsmOperand*> &Operands);
226
227 public:
228   enum ARMMatchResultTy {
229     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
230     Match_RequiresNotITBlock,
231     Match_RequiresV6,
232     Match_RequiresThumb2
233   };
234
235   ARMAsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser)
236     : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
237     MCAsmParserExtension::Initialize(_Parser);
238
239     // Initialize the set of available features.
240     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
241
242     // Not in an ITBlock to start with.
243     ITState.CurPosition = ~0U;
244   }
245
246   // Implementation of the MCTargetAsmParser interface:
247   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
248   bool ParseInstruction(StringRef Name, SMLoc NameLoc,
249                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
250   bool ParseDirective(AsmToken DirectiveID);
251
252   unsigned checkTargetMatchPredicate(MCInst &Inst);
253
254   bool MatchAndEmitInstruction(SMLoc IDLoc,
255                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
256                                MCStreamer &Out);
257 };
258 } // end anonymous namespace
259
260 namespace {
261
262 /// ARMOperand - Instances of this class represent a parsed ARM machine
263 /// instruction.
264 class ARMOperand : public MCParsedAsmOperand {
265   enum KindTy {
266     k_CondCode,
267     k_CCOut,
268     k_ITCondMask,
269     k_CoprocNum,
270     k_CoprocReg,
271     k_CoprocOption,
272     k_Immediate,
273     k_MemBarrierOpt,
274     k_Memory,
275     k_PostIndexRegister,
276     k_MSRMask,
277     k_ProcIFlags,
278     k_VectorIndex,
279     k_Register,
280     k_RegisterList,
281     k_DPRRegisterList,
282     k_SPRRegisterList,
283     k_VectorList,
284     k_VectorListAllLanes,
285     k_VectorListIndexed,
286     k_ShiftedRegister,
287     k_ShiftedImmediate,
288     k_ShifterImmediate,
289     k_RotateImmediate,
290     k_BitfieldDescriptor,
291     k_Token
292   } Kind;
293
294   SMLoc StartLoc, EndLoc;
295   SmallVector<unsigned, 8> Registers;
296
297   union {
298     struct {
299       ARMCC::CondCodes Val;
300     } CC;
301
302     struct {
303       unsigned Val;
304     } Cop;
305
306     struct {
307       unsigned Val;
308     } CoprocOption;
309
310     struct {
311       unsigned Mask:4;
312     } ITMask;
313
314     struct {
315       ARM_MB::MemBOpt Val;
316     } MBOpt;
317
318     struct {
319       ARM_PROC::IFlags Val;
320     } IFlags;
321
322     struct {
323       unsigned Val;
324     } MMask;
325
326     struct {
327       const char *Data;
328       unsigned Length;
329     } Tok;
330
331     struct {
332       unsigned RegNum;
333     } Reg;
334
335     // A vector register list is a sequential list of 1 to 4 registers.
336     struct {
337       unsigned RegNum;
338       unsigned Count;
339       unsigned LaneIndex;
340       bool isDoubleSpaced;
341     } VectorList;
342
343     struct {
344       unsigned Val;
345     } VectorIndex;
346
347     struct {
348       const MCExpr *Val;
349     } Imm;
350
351     /// Combined record for all forms of ARM address expressions.
352     struct {
353       unsigned BaseRegNum;
354       // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
355       // was specified.
356       const MCConstantExpr *OffsetImm;  // Offset immediate value
357       unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
358       ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
359       unsigned ShiftImm;        // shift for OffsetReg.
360       unsigned Alignment;       // 0 = no alignment specified
361                                 // n = alignment in bytes (2, 4, 8, 16, or 32)
362       unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
363     } Memory;
364
365     struct {
366       unsigned RegNum;
367       bool isAdd;
368       ARM_AM::ShiftOpc ShiftTy;
369       unsigned ShiftImm;
370     } PostIdxReg;
371
372     struct {
373       bool isASR;
374       unsigned Imm;
375     } ShifterImm;
376     struct {
377       ARM_AM::ShiftOpc ShiftTy;
378       unsigned SrcReg;
379       unsigned ShiftReg;
380       unsigned ShiftImm;
381     } RegShiftedReg;
382     struct {
383       ARM_AM::ShiftOpc ShiftTy;
384       unsigned SrcReg;
385       unsigned ShiftImm;
386     } RegShiftedImm;
387     struct {
388       unsigned Imm;
389     } RotImm;
390     struct {
391       unsigned LSB;
392       unsigned Width;
393     } Bitfield;
394   };
395
396   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
397 public:
398   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
399     Kind = o.Kind;
400     StartLoc = o.StartLoc;
401     EndLoc = o.EndLoc;
402     switch (Kind) {
403     case k_CondCode:
404       CC = o.CC;
405       break;
406     case k_ITCondMask:
407       ITMask = o.ITMask;
408       break;
409     case k_Token:
410       Tok = o.Tok;
411       break;
412     case k_CCOut:
413     case k_Register:
414       Reg = o.Reg;
415       break;
416     case k_RegisterList:
417     case k_DPRRegisterList:
418     case k_SPRRegisterList:
419       Registers = o.Registers;
420       break;
421     case k_VectorList:
422     case k_VectorListAllLanes:
423     case k_VectorListIndexed:
424       VectorList = o.VectorList;
425       break;
426     case k_CoprocNum:
427     case k_CoprocReg:
428       Cop = o.Cop;
429       break;
430     case k_CoprocOption:
431       CoprocOption = o.CoprocOption;
432       break;
433     case k_Immediate:
434       Imm = o.Imm;
435       break;
436     case k_MemBarrierOpt:
437       MBOpt = o.MBOpt;
438       break;
439     case k_Memory:
440       Memory = o.Memory;
441       break;
442     case k_PostIndexRegister:
443       PostIdxReg = o.PostIdxReg;
444       break;
445     case k_MSRMask:
446       MMask = o.MMask;
447       break;
448     case k_ProcIFlags:
449       IFlags = o.IFlags;
450       break;
451     case k_ShifterImmediate:
452       ShifterImm = o.ShifterImm;
453       break;
454     case k_ShiftedRegister:
455       RegShiftedReg = o.RegShiftedReg;
456       break;
457     case k_ShiftedImmediate:
458       RegShiftedImm = o.RegShiftedImm;
459       break;
460     case k_RotateImmediate:
461       RotImm = o.RotImm;
462       break;
463     case k_BitfieldDescriptor:
464       Bitfield = o.Bitfield;
465       break;
466     case k_VectorIndex:
467       VectorIndex = o.VectorIndex;
468       break;
469     }
470   }
471
472   /// getStartLoc - Get the location of the first token of this operand.
473   SMLoc getStartLoc() const { return StartLoc; }
474   /// getEndLoc - Get the location of the last token of this operand.
475   SMLoc getEndLoc() const { return EndLoc; }
476
477   ARMCC::CondCodes getCondCode() const {
478     assert(Kind == k_CondCode && "Invalid access!");
479     return CC.Val;
480   }
481
482   unsigned getCoproc() const {
483     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
484     return Cop.Val;
485   }
486
487   StringRef getToken() const {
488     assert(Kind == k_Token && "Invalid access!");
489     return StringRef(Tok.Data, Tok.Length);
490   }
491
492   unsigned getReg() const {
493     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
494     return Reg.RegNum;
495   }
496
497   const SmallVectorImpl<unsigned> &getRegList() const {
498     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
499             Kind == k_SPRRegisterList) && "Invalid access!");
500     return Registers;
501   }
502
503   const MCExpr *getImm() const {
504     assert(isImm() && "Invalid access!");
505     return Imm.Val;
506   }
507
508   unsigned getVectorIndex() const {
509     assert(Kind == k_VectorIndex && "Invalid access!");
510     return VectorIndex.Val;
511   }
512
513   ARM_MB::MemBOpt getMemBarrierOpt() const {
514     assert(Kind == k_MemBarrierOpt && "Invalid access!");
515     return MBOpt.Val;
516   }
517
518   ARM_PROC::IFlags getProcIFlags() const {
519     assert(Kind == k_ProcIFlags && "Invalid access!");
520     return IFlags.Val;
521   }
522
523   unsigned getMSRMask() const {
524     assert(Kind == k_MSRMask && "Invalid access!");
525     return MMask.Val;
526   }
527
528   bool isCoprocNum() const { return Kind == k_CoprocNum; }
529   bool isCoprocReg() const { return Kind == k_CoprocReg; }
530   bool isCoprocOption() const { return Kind == k_CoprocOption; }
531   bool isCondCode() const { return Kind == k_CondCode; }
532   bool isCCOut() const { return Kind == k_CCOut; }
533   bool isITMask() const { return Kind == k_ITCondMask; }
534   bool isITCondCode() const { return Kind == k_CondCode; }
535   bool isImm() const { return Kind == k_Immediate; }
536   bool isFPImm() const {
537     if (!isImm()) return false;
538     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
539     if (!CE) return false;
540     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
541     return Val != -1;
542   }
543   bool isFBits16() const {
544     if (!isImm()) return false;
545     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
546     if (!CE) return false;
547     int64_t Value = CE->getValue();
548     return Value >= 0 && Value <= 16;
549   }
550   bool isFBits32() const {
551     if (!isImm()) return false;
552     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
553     if (!CE) return false;
554     int64_t Value = CE->getValue();
555     return Value >= 1 && Value <= 32;
556   }
557   bool isImm8s4() const {
558     if (!isImm()) return false;
559     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
560     if (!CE) return false;
561     int64_t Value = CE->getValue();
562     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
563   }
564   bool isImm0_1020s4() const {
565     if (!isImm()) return false;
566     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
567     if (!CE) return false;
568     int64_t Value = CE->getValue();
569     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
570   }
571   bool isImm0_508s4() const {
572     if (!isImm()) return false;
573     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
574     if (!CE) return false;
575     int64_t Value = CE->getValue();
576     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
577   }
578   bool isImm0_255() const {
579     if (!isImm()) return false;
580     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
581     if (!CE) return false;
582     int64_t Value = CE->getValue();
583     return Value >= 0 && Value < 256;
584   }
585   bool isImm0_1() const {
586     if (!isImm()) return false;
587     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
588     if (!CE) return false;
589     int64_t Value = CE->getValue();
590     return Value >= 0 && Value < 2;
591   }
592   bool isImm0_3() const {
593     if (!isImm()) return false;
594     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
595     if (!CE) return false;
596     int64_t Value = CE->getValue();
597     return Value >= 0 && Value < 4;
598   }
599   bool isImm0_7() const {
600     if (!isImm()) return false;
601     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
602     if (!CE) return false;
603     int64_t Value = CE->getValue();
604     return Value >= 0 && Value < 8;
605   }
606   bool isImm0_15() const {
607     if (!isImm()) return false;
608     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
609     if (!CE) return false;
610     int64_t Value = CE->getValue();
611     return Value >= 0 && Value < 16;
612   }
613   bool isImm0_31() const {
614     if (!isImm()) return false;
615     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
616     if (!CE) return false;
617     int64_t Value = CE->getValue();
618     return Value >= 0 && Value < 32;
619   }
620   bool isImm0_63() const {
621     if (!isImm()) return false;
622     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
623     if (!CE) return false;
624     int64_t Value = CE->getValue();
625     return Value >= 0 && Value < 64;
626   }
627   bool isImm8() const {
628     if (!isImm()) return false;
629     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
630     if (!CE) return false;
631     int64_t Value = CE->getValue();
632     return Value == 8;
633   }
634   bool isImm16() const {
635     if (!isImm()) return false;
636     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
637     if (!CE) return false;
638     int64_t Value = CE->getValue();
639     return Value == 16;
640   }
641   bool isImm32() const {
642     if (!isImm()) return false;
643     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
644     if (!CE) return false;
645     int64_t Value = CE->getValue();
646     return Value == 32;
647   }
648   bool isShrImm8() const {
649     if (!isImm()) return false;
650     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
651     if (!CE) return false;
652     int64_t Value = CE->getValue();
653     return Value > 0 && Value <= 8;
654   }
655   bool isShrImm16() const {
656     if (!isImm()) return false;
657     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
658     if (!CE) return false;
659     int64_t Value = CE->getValue();
660     return Value > 0 && Value <= 16;
661   }
662   bool isShrImm32() const {
663     if (!isImm()) return false;
664     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
665     if (!CE) return false;
666     int64_t Value = CE->getValue();
667     return Value > 0 && Value <= 32;
668   }
669   bool isShrImm64() const {
670     if (!isImm()) return false;
671     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
672     if (!CE) return false;
673     int64_t Value = CE->getValue();
674     return Value > 0 && Value <= 64;
675   }
676   bool isImm1_7() const {
677     if (!isImm()) return false;
678     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
679     if (!CE) return false;
680     int64_t Value = CE->getValue();
681     return Value > 0 && Value < 8;
682   }
683   bool isImm1_15() const {
684     if (!isImm()) return false;
685     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
686     if (!CE) return false;
687     int64_t Value = CE->getValue();
688     return Value > 0 && Value < 16;
689   }
690   bool isImm1_31() const {
691     if (!isImm()) return false;
692     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
693     if (!CE) return false;
694     int64_t Value = CE->getValue();
695     return Value > 0 && Value < 32;
696   }
697   bool isImm1_16() const {
698     if (!isImm()) return false;
699     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
700     if (!CE) return false;
701     int64_t Value = CE->getValue();
702     return Value > 0 && Value < 17;
703   }
704   bool isImm1_32() const {
705     if (!isImm()) return false;
706     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
707     if (!CE) return false;
708     int64_t Value = CE->getValue();
709     return Value > 0 && Value < 33;
710   }
711   bool isImm0_32() const {
712     if (!isImm()) return false;
713     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
714     if (!CE) return false;
715     int64_t Value = CE->getValue();
716     return Value >= 0 && Value < 33;
717   }
718   bool isImm0_65535() const {
719     if (!isImm()) return false;
720     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
721     if (!CE) return false;
722     int64_t Value = CE->getValue();
723     return Value >= 0 && Value < 65536;
724   }
725   bool isImm0_65535Expr() const {
726     if (!isImm()) return false;
727     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
728     // If it's not a constant expression, it'll generate a fixup and be
729     // handled later.
730     if (!CE) return true;
731     int64_t Value = CE->getValue();
732     return Value >= 0 && Value < 65536;
733   }
734   bool isImm24bit() const {
735     if (!isImm()) return false;
736     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
737     if (!CE) return false;
738     int64_t Value = CE->getValue();
739     return Value >= 0 && Value <= 0xffffff;
740   }
741   bool isImmThumbSR() const {
742     if (!isImm()) return false;
743     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
744     if (!CE) return false;
745     int64_t Value = CE->getValue();
746     return Value > 0 && Value < 33;
747   }
748   bool isPKHLSLImm() const {
749     if (!isImm()) return false;
750     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
751     if (!CE) return false;
752     int64_t Value = CE->getValue();
753     return Value >= 0 && Value < 32;
754   }
755   bool isPKHASRImm() const {
756     if (!isImm()) return false;
757     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
758     if (!CE) return false;
759     int64_t Value = CE->getValue();
760     return Value > 0 && Value <= 32;
761   }
762   bool isARMSOImm() const {
763     if (!isImm()) return false;
764     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
765     if (!CE) return false;
766     int64_t Value = CE->getValue();
767     return ARM_AM::getSOImmVal(Value) != -1;
768   }
769   bool isARMSOImmNot() const {
770     if (!isImm()) return false;
771     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
772     if (!CE) return false;
773     int64_t Value = CE->getValue();
774     return ARM_AM::getSOImmVal(~Value) != -1;
775   }
776   bool isARMSOImmNeg() const {
777     if (!isImm()) return false;
778     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
779     if (!CE) return false;
780     int64_t Value = CE->getValue();
781     return ARM_AM::getSOImmVal(-Value) != -1;
782   }
783   bool isT2SOImm() const {
784     if (!isImm()) return false;
785     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
786     if (!CE) return false;
787     int64_t Value = CE->getValue();
788     return ARM_AM::getT2SOImmVal(Value) != -1;
789   }
790   bool isT2SOImmNot() const {
791     if (!isImm()) return false;
792     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
793     if (!CE) return false;
794     int64_t Value = CE->getValue();
795     return ARM_AM::getT2SOImmVal(~Value) != -1;
796   }
797   bool isT2SOImmNeg() const {
798     if (!isImm()) return false;
799     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
800     if (!CE) return false;
801     int64_t Value = CE->getValue();
802     return ARM_AM::getT2SOImmVal(-Value) != -1;
803   }
804   bool isSetEndImm() const {
805     if (!isImm()) return false;
806     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
807     if (!CE) return false;
808     int64_t Value = CE->getValue();
809     return Value == 1 || Value == 0;
810   }
811   bool isReg() const { return Kind == k_Register; }
812   bool isRegList() const { return Kind == k_RegisterList; }
813   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
814   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
815   bool isToken() const { return Kind == k_Token; }
816   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
817   bool isMemory() const { return Kind == k_Memory; }
818   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
819   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
820   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
821   bool isRotImm() const { return Kind == k_RotateImmediate; }
822   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
823   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
824   bool isPostIdxReg() const {
825     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
826   }
827   bool isMemNoOffset(bool alignOK = false) const {
828     if (!isMemory())
829       return false;
830     // No offset of any kind.
831     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == 0 &&
832      (alignOK || Memory.Alignment == 0);
833   }
834   bool isMemPCRelImm12() const {
835     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
836       return false;
837     // Base register must be PC.
838     if (Memory.BaseRegNum != ARM::PC)
839       return false;
840     // Immediate offset in range [-4095, 4095].
841     if (!Memory.OffsetImm) return true;
842     int64_t Val = Memory.OffsetImm->getValue();
843     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
844   }
845   bool isAlignedMemory() const {
846     return isMemNoOffset(true);
847   }
848   bool isAddrMode2() const {
849     if (!isMemory() || Memory.Alignment != 0) return false;
850     // Check for register offset.
851     if (Memory.OffsetRegNum) return true;
852     // Immediate offset in range [-4095, 4095].
853     if (!Memory.OffsetImm) return true;
854     int64_t Val = Memory.OffsetImm->getValue();
855     return Val > -4096 && Val < 4096;
856   }
857   bool isAM2OffsetImm() const {
858     if (!isImm()) return false;
859     // Immediate offset in range [-4095, 4095].
860     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
861     if (!CE) return false;
862     int64_t Val = CE->getValue();
863     return Val > -4096 && Val < 4096;
864   }
865   bool isAddrMode3() const {
866     // If we have an immediate that's not a constant, treat it as a label
867     // reference needing a fixup. If it is a constant, it's something else
868     // and we reject it.
869     if (isImm() && !isa<MCConstantExpr>(getImm()))
870       return true;
871     if (!isMemory() || Memory.Alignment != 0) return false;
872     // No shifts are legal for AM3.
873     if (Memory.ShiftType != ARM_AM::no_shift) return false;
874     // Check for register offset.
875     if (Memory.OffsetRegNum) return true;
876     // Immediate offset in range [-255, 255].
877     if (!Memory.OffsetImm) return true;
878     int64_t Val = Memory.OffsetImm->getValue();
879     return Val > -256 && Val < 256;
880   }
881   bool isAM3Offset() const {
882     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
883       return false;
884     if (Kind == k_PostIndexRegister)
885       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
886     // Immediate offset in range [-255, 255].
887     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
888     if (!CE) return false;
889     int64_t Val = CE->getValue();
890     // Special case, #-0 is INT32_MIN.
891     return (Val > -256 && Val < 256) || Val == INT32_MIN;
892   }
893   bool isAddrMode5() const {
894     // If we have an immediate that's not a constant, treat it as a label
895     // reference needing a fixup. If it is a constant, it's something else
896     // and we reject it.
897     if (isImm() && !isa<MCConstantExpr>(getImm()))
898       return true;
899     if (!isMemory() || Memory.Alignment != 0) return false;
900     // Check for register offset.
901     if (Memory.OffsetRegNum) return false;
902     // Immediate offset in range [-1020, 1020] and a multiple of 4.
903     if (!Memory.OffsetImm) return true;
904     int64_t Val = Memory.OffsetImm->getValue();
905     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
906       Val == INT32_MIN;
907   }
908   bool isMemTBB() const {
909     if (!isMemory() || !Memory.OffsetRegNum || Memory.isNegative ||
910         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
911       return false;
912     return true;
913   }
914   bool isMemTBH() const {
915     if (!isMemory() || !Memory.OffsetRegNum || Memory.isNegative ||
916         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
917         Memory.Alignment != 0 )
918       return false;
919     return true;
920   }
921   bool isMemRegOffset() const {
922     if (!isMemory() || !Memory.OffsetRegNum || Memory.Alignment != 0)
923       return false;
924     return true;
925   }
926   bool isT2MemRegOffset() const {
927     if (!isMemory() || !Memory.OffsetRegNum || Memory.isNegative ||
928         Memory.Alignment != 0)
929       return false;
930     // Only lsl #{0, 1, 2, 3} allowed.
931     if (Memory.ShiftType == ARM_AM::no_shift)
932       return true;
933     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
934       return false;
935     return true;
936   }
937   bool isMemThumbRR() const {
938     // Thumb reg+reg addressing is simple. Just two registers, a base and
939     // an offset. No shifts, negations or any other complicating factors.
940     if (!isMemory() || !Memory.OffsetRegNum || Memory.isNegative ||
941         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
942       return false;
943     return isARMLowRegister(Memory.BaseRegNum) &&
944       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
945   }
946   bool isMemThumbRIs4() const {
947     if (!isMemory() || Memory.OffsetRegNum != 0 ||
948         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
949       return false;
950     // Immediate offset, multiple of 4 in range [0, 124].
951     if (!Memory.OffsetImm) return true;
952     int64_t Val = Memory.OffsetImm->getValue();
953     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
954   }
955   bool isMemThumbRIs2() const {
956     if (!isMemory() || Memory.OffsetRegNum != 0 ||
957         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
958       return false;
959     // Immediate offset, multiple of 4 in range [0, 62].
960     if (!Memory.OffsetImm) return true;
961     int64_t Val = Memory.OffsetImm->getValue();
962     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
963   }
964   bool isMemThumbRIs1() const {
965     if (!isMemory() || Memory.OffsetRegNum != 0 ||
966         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
967       return false;
968     // Immediate offset in range [0, 31].
969     if (!Memory.OffsetImm) return true;
970     int64_t Val = Memory.OffsetImm->getValue();
971     return Val >= 0 && Val <= 31;
972   }
973   bool isMemThumbSPI() const {
974     if (!isMemory() || Memory.OffsetRegNum != 0 ||
975         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
976       return false;
977     // Immediate offset, multiple of 4 in range [0, 1020].
978     if (!Memory.OffsetImm) return true;
979     int64_t Val = Memory.OffsetImm->getValue();
980     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
981   }
982   bool isMemImm8s4Offset() const {
983     // If we have an immediate that's not a constant, treat it as a label
984     // reference needing a fixup. If it is a constant, it's something else
985     // and we reject it.
986     if (isImm() && !isa<MCConstantExpr>(getImm()))
987       return true;
988     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
989       return false;
990     // Immediate offset a multiple of 4 in range [-1020, 1020].
991     if (!Memory.OffsetImm) return true;
992     int64_t Val = Memory.OffsetImm->getValue();
993     return Val >= -1020 && Val <= 1020 && (Val & 3) == 0;
994   }
995   bool isMemImm0_1020s4Offset() const {
996     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
997       return false;
998     // Immediate offset a multiple of 4 in range [0, 1020].
999     if (!Memory.OffsetImm) return true;
1000     int64_t Val = Memory.OffsetImm->getValue();
1001     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1002   }
1003   bool isMemImm8Offset() const {
1004     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1005       return false;
1006     // Base reg of PC isn't allowed for these encodings.
1007     if (Memory.BaseRegNum == ARM::PC) return false;
1008     // Immediate offset in range [-255, 255].
1009     if (!Memory.OffsetImm) return true;
1010     int64_t Val = Memory.OffsetImm->getValue();
1011     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1012   }
1013   bool isMemPosImm8Offset() const {
1014     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1015       return false;
1016     // Immediate offset in range [0, 255].
1017     if (!Memory.OffsetImm) return true;
1018     int64_t Val = Memory.OffsetImm->getValue();
1019     return Val >= 0 && Val < 256;
1020   }
1021   bool isMemNegImm8Offset() const {
1022     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1023       return false;
1024     // Base reg of PC isn't allowed for these encodings.
1025     if (Memory.BaseRegNum == ARM::PC) return false;
1026     // Immediate offset in range [-255, -1].
1027     if (!Memory.OffsetImm) return false;
1028     int64_t Val = Memory.OffsetImm->getValue();
1029     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1030   }
1031   bool isMemUImm12Offset() const {
1032     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1033       return false;
1034     // Immediate offset in range [0, 4095].
1035     if (!Memory.OffsetImm) return true;
1036     int64_t Val = Memory.OffsetImm->getValue();
1037     return (Val >= 0 && Val < 4096);
1038   }
1039   bool isMemImm12Offset() const {
1040     // If we have an immediate that's not a constant, treat it as a label
1041     // reference needing a fixup. If it is a constant, it's something else
1042     // and we reject it.
1043     if (isImm() && !isa<MCConstantExpr>(getImm()))
1044       return true;
1045
1046     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1047       return false;
1048     // Immediate offset in range [-4095, 4095].
1049     if (!Memory.OffsetImm) return true;
1050     int64_t Val = Memory.OffsetImm->getValue();
1051     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1052   }
1053   bool isPostIdxImm8() const {
1054     if (!isImm()) return false;
1055     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1056     if (!CE) return false;
1057     int64_t Val = CE->getValue();
1058     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1059   }
1060   bool isPostIdxImm8s4() const {
1061     if (!isImm()) return false;
1062     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1063     if (!CE) return false;
1064     int64_t Val = CE->getValue();
1065     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1066       (Val == INT32_MIN);
1067   }
1068
1069   bool isMSRMask() const { return Kind == k_MSRMask; }
1070   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1071
1072   // NEON operands.
1073   bool isSingleSpacedVectorList() const {
1074     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1075   }
1076   bool isDoubleSpacedVectorList() const {
1077     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1078   }
1079   bool isVecListOneD() const {
1080     if (!isSingleSpacedVectorList()) return false;
1081     return VectorList.Count == 1;
1082   }
1083
1084   bool isVecListTwoD() const {
1085     if (!isSingleSpacedVectorList()) return false;
1086     return VectorList.Count == 2;
1087   }
1088
1089   bool isVecListThreeD() const {
1090     if (!isSingleSpacedVectorList()) return false;
1091     return VectorList.Count == 3;
1092   }
1093
1094   bool isVecListFourD() const {
1095     if (!isSingleSpacedVectorList()) return false;
1096     return VectorList.Count == 4;
1097   }
1098
1099   bool isVecListTwoQ() const {
1100     if (!isDoubleSpacedVectorList()) return false;
1101     return VectorList.Count == 2;
1102   }
1103
1104   bool isSingleSpacedVectorAllLanes() const {
1105     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1106   }
1107   bool isDoubleSpacedVectorAllLanes() const {
1108     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1109   }
1110   bool isVecListOneDAllLanes() const {
1111     if (!isSingleSpacedVectorAllLanes()) return false;
1112     return VectorList.Count == 1;
1113   }
1114
1115   bool isVecListTwoDAllLanes() const {
1116     if (!isSingleSpacedVectorAllLanes()) return false;
1117     return VectorList.Count == 2;
1118   }
1119
1120   bool isVecListTwoQAllLanes() const {
1121     if (!isDoubleSpacedVectorAllLanes()) return false;
1122     return VectorList.Count == 2;
1123   }
1124
1125   bool isSingleSpacedVectorIndexed() const {
1126     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1127   }
1128   bool isDoubleSpacedVectorIndexed() const {
1129     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1130   }
1131   bool isVecListOneDByteIndexed() const {
1132     if (!isSingleSpacedVectorIndexed()) return false;
1133     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1134   }
1135
1136   bool isVecListOneDHWordIndexed() const {
1137     if (!isSingleSpacedVectorIndexed()) return false;
1138     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1139   }
1140
1141   bool isVecListOneDWordIndexed() const {
1142     if (!isSingleSpacedVectorIndexed()) return false;
1143     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1144   }
1145
1146   bool isVecListTwoDByteIndexed() const {
1147     if (!isSingleSpacedVectorIndexed()) return false;
1148     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1149   }
1150
1151   bool isVecListTwoDHWordIndexed() const {
1152     if (!isSingleSpacedVectorIndexed()) return false;
1153     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1154   }
1155
1156   bool isVecListTwoQWordIndexed() const {
1157     if (!isDoubleSpacedVectorIndexed()) return false;
1158     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1159   }
1160
1161   bool isVecListTwoQHWordIndexed() const {
1162     if (!isDoubleSpacedVectorIndexed()) return false;
1163     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1164   }
1165
1166   bool isVecListTwoDWordIndexed() const {
1167     if (!isSingleSpacedVectorIndexed()) return false;
1168     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1169   }
1170
1171   bool isVecListThreeDByteIndexed() const {
1172     if (!isSingleSpacedVectorIndexed()) return false;
1173     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1174   }
1175
1176   bool isVecListThreeDHWordIndexed() const {
1177     if (!isSingleSpacedVectorIndexed()) return false;
1178     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1179   }
1180
1181   bool isVecListThreeQWordIndexed() const {
1182     if (!isDoubleSpacedVectorIndexed()) return false;
1183     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1184   }
1185
1186   bool isVecListThreeQHWordIndexed() const {
1187     if (!isDoubleSpacedVectorIndexed()) return false;
1188     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1189   }
1190
1191   bool isVecListThreeDWordIndexed() const {
1192     if (!isSingleSpacedVectorIndexed()) return false;
1193     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1194   }
1195
1196   bool isVectorIndex8() const {
1197     if (Kind != k_VectorIndex) return false;
1198     return VectorIndex.Val < 8;
1199   }
1200   bool isVectorIndex16() const {
1201     if (Kind != k_VectorIndex) return false;
1202     return VectorIndex.Val < 4;
1203   }
1204   bool isVectorIndex32() const {
1205     if (Kind != k_VectorIndex) return false;
1206     return VectorIndex.Val < 2;
1207   }
1208
1209   bool isNEONi8splat() const {
1210     if (!isImm()) return false;
1211     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1212     // Must be a constant.
1213     if (!CE) return false;
1214     int64_t Value = CE->getValue();
1215     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1216     // value.
1217     return Value >= 0 && Value < 256;
1218   }
1219
1220   bool isNEONi16splat() const {
1221     if (!isImm()) return false;
1222     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1223     // Must be a constant.
1224     if (!CE) return false;
1225     int64_t Value = CE->getValue();
1226     // i16 value in the range [0,255] or [0x0100, 0xff00]
1227     return (Value >= 0 && Value < 256) || (Value >= 0x0100 && Value <= 0xff00);
1228   }
1229
1230   bool isNEONi32splat() const {
1231     if (!isImm()) return false;
1232     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1233     // Must be a constant.
1234     if (!CE) return false;
1235     int64_t Value = CE->getValue();
1236     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X.
1237     return (Value >= 0 && Value < 256) ||
1238       (Value >= 0x0100 && Value <= 0xff00) ||
1239       (Value >= 0x010000 && Value <= 0xff0000) ||
1240       (Value >= 0x01000000 && Value <= 0xff000000);
1241   }
1242
1243   bool isNEONi32vmov() const {
1244     if (!isImm()) return false;
1245     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1246     // Must be a constant.
1247     if (!CE) return false;
1248     int64_t Value = CE->getValue();
1249     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1250     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1251     return (Value >= 0 && Value < 256) ||
1252       (Value >= 0x0100 && Value <= 0xff00) ||
1253       (Value >= 0x010000 && Value <= 0xff0000) ||
1254       (Value >= 0x01000000 && Value <= 0xff000000) ||
1255       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1256       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1257   }
1258   bool isNEONi32vmovNeg() const {
1259     if (!isImm()) return false;
1260     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1261     // Must be a constant.
1262     if (!CE) return false;
1263     int64_t Value = ~CE->getValue();
1264     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1265     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1266     return (Value >= 0 && Value < 256) ||
1267       (Value >= 0x0100 && Value <= 0xff00) ||
1268       (Value >= 0x010000 && Value <= 0xff0000) ||
1269       (Value >= 0x01000000 && Value <= 0xff000000) ||
1270       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1271       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1272   }
1273
1274   bool isNEONi64splat() const {
1275     if (!isImm()) return false;
1276     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1277     // Must be a constant.
1278     if (!CE) return false;
1279     uint64_t Value = CE->getValue();
1280     // i64 value with each byte being either 0 or 0xff.
1281     for (unsigned i = 0; i < 8; ++i)
1282       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1283     return true;
1284   }
1285
1286   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1287     // Add as immediates when possible.  Null MCExpr = 0.
1288     if (Expr == 0)
1289       Inst.addOperand(MCOperand::CreateImm(0));
1290     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1291       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1292     else
1293       Inst.addOperand(MCOperand::CreateExpr(Expr));
1294   }
1295
1296   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1297     assert(N == 2 && "Invalid number of operands!");
1298     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
1299     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1300     Inst.addOperand(MCOperand::CreateReg(RegNum));
1301   }
1302
1303   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1304     assert(N == 1 && "Invalid number of operands!");
1305     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
1306   }
1307
1308   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1309     assert(N == 1 && "Invalid number of operands!");
1310     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
1311   }
1312
1313   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1314     assert(N == 1 && "Invalid number of operands!");
1315     Inst.addOperand(MCOperand::CreateImm(CoprocOption.Val));
1316   }
1317
1318   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1319     assert(N == 1 && "Invalid number of operands!");
1320     Inst.addOperand(MCOperand::CreateImm(ITMask.Mask));
1321   }
1322
1323   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1324     assert(N == 1 && "Invalid number of operands!");
1325     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
1326   }
1327
1328   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1329     assert(N == 1 && "Invalid number of operands!");
1330     Inst.addOperand(MCOperand::CreateReg(getReg()));
1331   }
1332
1333   void addRegOperands(MCInst &Inst, unsigned N) const {
1334     assert(N == 1 && "Invalid number of operands!");
1335     Inst.addOperand(MCOperand::CreateReg(getReg()));
1336   }
1337
1338   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1339     assert(N == 3 && "Invalid number of operands!");
1340     assert(isRegShiftedReg() &&
1341            "addRegShiftedRegOperands() on non RegShiftedReg!");
1342     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
1343     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
1344     Inst.addOperand(MCOperand::CreateImm(
1345       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1346   }
1347
1348   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1349     assert(N == 2 && "Invalid number of operands!");
1350     assert(isRegShiftedImm() &&
1351            "addRegShiftedImmOperands() on non RegShiftedImm!");
1352     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
1353     Inst.addOperand(MCOperand::CreateImm(
1354       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, RegShiftedImm.ShiftImm)));
1355   }
1356
1357   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1358     assert(N == 1 && "Invalid number of operands!");
1359     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
1360                                          ShifterImm.Imm));
1361   }
1362
1363   void addRegListOperands(MCInst &Inst, unsigned N) const {
1364     assert(N == 1 && "Invalid number of operands!");
1365     const SmallVectorImpl<unsigned> &RegList = getRegList();
1366     for (SmallVectorImpl<unsigned>::const_iterator
1367            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1368       Inst.addOperand(MCOperand::CreateReg(*I));
1369   }
1370
1371   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1372     addRegListOperands(Inst, N);
1373   }
1374
1375   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1376     addRegListOperands(Inst, N);
1377   }
1378
1379   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1380     assert(N == 1 && "Invalid number of operands!");
1381     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1382     Inst.addOperand(MCOperand::CreateImm(RotImm.Imm >> 3));
1383   }
1384
1385   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1386     assert(N == 1 && "Invalid number of operands!");
1387     // Munge the lsb/width into a bitfield mask.
1388     unsigned lsb = Bitfield.LSB;
1389     unsigned width = Bitfield.Width;
1390     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1391     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1392                       (32 - (lsb + width)));
1393     Inst.addOperand(MCOperand::CreateImm(Mask));
1394   }
1395
1396   void addImmOperands(MCInst &Inst, unsigned N) const {
1397     assert(N == 1 && "Invalid number of operands!");
1398     addExpr(Inst, getImm());
1399   }
1400
1401   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1402     assert(N == 1 && "Invalid number of operands!");
1403     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1404     Inst.addOperand(MCOperand::CreateImm(16 - CE->getValue()));
1405   }
1406
1407   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1408     assert(N == 1 && "Invalid number of operands!");
1409     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1410     Inst.addOperand(MCOperand::CreateImm(32 - CE->getValue()));
1411   }
1412
1413   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1414     assert(N == 1 && "Invalid number of operands!");
1415     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1416     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1417     Inst.addOperand(MCOperand::CreateImm(Val));
1418   }
1419
1420   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1421     assert(N == 1 && "Invalid number of operands!");
1422     // FIXME: We really want to scale the value here, but the LDRD/STRD
1423     // instruction don't encode operands that way yet.
1424     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1425     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1426   }
1427
1428   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1429     assert(N == 1 && "Invalid number of operands!");
1430     // The immediate is scaled by four in the encoding and is stored
1431     // in the MCInst as such. Lop off the low two bits here.
1432     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1433     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
1434   }
1435
1436   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1437     assert(N == 1 && "Invalid number of operands!");
1438     // The immediate is scaled by four in the encoding and is stored
1439     // in the MCInst as such. Lop off the low two bits here.
1440     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1441     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
1442   }
1443
1444   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1445     assert(N == 1 && "Invalid number of operands!");
1446     // The constant encodes as the immediate-1, and we store in the instruction
1447     // the bits as encoded, so subtract off one here.
1448     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1449     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1450   }
1451
1452   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1453     assert(N == 1 && "Invalid number of operands!");
1454     // The constant encodes as the immediate-1, and we store in the instruction
1455     // the bits as encoded, so subtract off one here.
1456     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1457     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1458   }
1459
1460   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1461     assert(N == 1 && "Invalid number of operands!");
1462     // The constant encodes as the immediate, except for 32, which encodes as
1463     // zero.
1464     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1465     unsigned Imm = CE->getValue();
1466     Inst.addOperand(MCOperand::CreateImm((Imm == 32 ? 0 : Imm)));
1467   }
1468
1469   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1470     assert(N == 1 && "Invalid number of operands!");
1471     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1472     // the instruction as well.
1473     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1474     int Val = CE->getValue();
1475     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
1476   }
1477
1478   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
1479     assert(N == 1 && "Invalid number of operands!");
1480     // The operand is actually a t2_so_imm, but we have its bitwise
1481     // negation in the assembly source, so twiddle it here.
1482     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1483     Inst.addOperand(MCOperand::CreateImm(~CE->getValue()));
1484   }
1485
1486   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
1487     assert(N == 1 && "Invalid number of operands!");
1488     // The operand is actually a t2_so_imm, but we have its
1489     // negation in the assembly source, so twiddle it here.
1490     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1491     Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
1492   }
1493
1494   void addARMSOImmNotOperands(MCInst &Inst, unsigned N) const {
1495     assert(N == 1 && "Invalid number of operands!");
1496     // The operand is actually a so_imm, but we have its bitwise
1497     // negation in the assembly source, so twiddle it here.
1498     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1499     Inst.addOperand(MCOperand::CreateImm(~CE->getValue()));
1500   }
1501
1502   void addARMSOImmNegOperands(MCInst &Inst, unsigned N) const {
1503     assert(N == 1 && "Invalid number of operands!");
1504     // The operand is actually a so_imm, but we have its
1505     // negation in the assembly source, so twiddle it here.
1506     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1507     Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
1508   }
1509
1510   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
1511     assert(N == 1 && "Invalid number of operands!");
1512     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
1513   }
1514
1515   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
1516     assert(N == 1 && "Invalid number of operands!");
1517     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1518   }
1519
1520   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
1521     assert(N == 1 && "Invalid number of operands!");
1522     int32_t Imm = Memory.OffsetImm->getValue();
1523     // FIXME: Handle #-0
1524     if (Imm == INT32_MIN) Imm = 0;
1525     Inst.addOperand(MCOperand::CreateImm(Imm));
1526   }
1527
1528   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
1529     assert(N == 2 && "Invalid number of operands!");
1530     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1531     Inst.addOperand(MCOperand::CreateImm(Memory.Alignment));
1532   }
1533
1534   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
1535     assert(N == 3 && "Invalid number of operands!");
1536     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1537     if (!Memory.OffsetRegNum) {
1538       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1539       // Special case for #-0
1540       if (Val == INT32_MIN) Val = 0;
1541       if (Val < 0) Val = -Val;
1542       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1543     } else {
1544       // For register offset, we encode the shift type and negation flag
1545       // here.
1546       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
1547                               Memory.ShiftImm, Memory.ShiftType);
1548     }
1549     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1550     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1551     Inst.addOperand(MCOperand::CreateImm(Val));
1552   }
1553
1554   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
1555     assert(N == 2 && "Invalid number of operands!");
1556     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1557     assert(CE && "non-constant AM2OffsetImm operand!");
1558     int32_t Val = CE->getValue();
1559     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1560     // Special case for #-0
1561     if (Val == INT32_MIN) Val = 0;
1562     if (Val < 0) Val = -Val;
1563     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1564     Inst.addOperand(MCOperand::CreateReg(0));
1565     Inst.addOperand(MCOperand::CreateImm(Val));
1566   }
1567
1568   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
1569     assert(N == 3 && "Invalid number of operands!");
1570     // If we have an immediate that's not a constant, treat it as a label
1571     // reference needing a fixup. If it is a constant, it's something else
1572     // and we reject it.
1573     if (isImm()) {
1574       Inst.addOperand(MCOperand::CreateExpr(getImm()));
1575       Inst.addOperand(MCOperand::CreateReg(0));
1576       Inst.addOperand(MCOperand::CreateImm(0));
1577       return;
1578     }
1579
1580     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1581     if (!Memory.OffsetRegNum) {
1582       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1583       // Special case for #-0
1584       if (Val == INT32_MIN) Val = 0;
1585       if (Val < 0) Val = -Val;
1586       Val = ARM_AM::getAM3Opc(AddSub, Val);
1587     } else {
1588       // For register offset, we encode the shift type and negation flag
1589       // here.
1590       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
1591     }
1592     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1593     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1594     Inst.addOperand(MCOperand::CreateImm(Val));
1595   }
1596
1597   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
1598     assert(N == 2 && "Invalid number of operands!");
1599     if (Kind == k_PostIndexRegister) {
1600       int32_t Val =
1601         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
1602       Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1603       Inst.addOperand(MCOperand::CreateImm(Val));
1604       return;
1605     }
1606
1607     // Constant offset.
1608     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
1609     int32_t Val = CE->getValue();
1610     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1611     // Special case for #-0
1612     if (Val == INT32_MIN) Val = 0;
1613     if (Val < 0) Val = -Val;
1614     Val = ARM_AM::getAM3Opc(AddSub, Val);
1615     Inst.addOperand(MCOperand::CreateReg(0));
1616     Inst.addOperand(MCOperand::CreateImm(Val));
1617   }
1618
1619   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
1620     assert(N == 2 && "Invalid number of operands!");
1621     // If we have an immediate that's not a constant, treat it as a label
1622     // reference needing a fixup. If it is a constant, it's something else
1623     // and we reject it.
1624     if (isImm()) {
1625       Inst.addOperand(MCOperand::CreateExpr(getImm()));
1626       Inst.addOperand(MCOperand::CreateImm(0));
1627       return;
1628     }
1629
1630     // The lower two bits are always zero and as such are not encoded.
1631     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
1632     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1633     // Special case for #-0
1634     if (Val == INT32_MIN) Val = 0;
1635     if (Val < 0) Val = -Val;
1636     Val = ARM_AM::getAM5Opc(AddSub, Val);
1637     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1638     Inst.addOperand(MCOperand::CreateImm(Val));
1639   }
1640
1641   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
1642     assert(N == 2 && "Invalid number of operands!");
1643     // If we have an immediate that's not a constant, treat it as a label
1644     // reference needing a fixup. If it is a constant, it's something else
1645     // and we reject it.
1646     if (isImm()) {
1647       Inst.addOperand(MCOperand::CreateExpr(getImm()));
1648       Inst.addOperand(MCOperand::CreateImm(0));
1649       return;
1650     }
1651
1652     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1653     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1654     Inst.addOperand(MCOperand::CreateImm(Val));
1655   }
1656
1657   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
1658     assert(N == 2 && "Invalid number of operands!");
1659     // The lower two bits are always zero and as such are not encoded.
1660     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
1661     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1662     Inst.addOperand(MCOperand::CreateImm(Val));
1663   }
1664
1665   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1666     assert(N == 2 && "Invalid number of operands!");
1667     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1668     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1669     Inst.addOperand(MCOperand::CreateImm(Val));
1670   }
1671
1672   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1673     addMemImm8OffsetOperands(Inst, N);
1674   }
1675
1676   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1677     addMemImm8OffsetOperands(Inst, N);
1678   }
1679
1680   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1681     assert(N == 2 && "Invalid number of operands!");
1682     // If this is an immediate, it's a label reference.
1683     if (isImm()) {
1684       addExpr(Inst, getImm());
1685       Inst.addOperand(MCOperand::CreateImm(0));
1686       return;
1687     }
1688
1689     // Otherwise, it's a normal memory reg+offset.
1690     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1691     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1692     Inst.addOperand(MCOperand::CreateImm(Val));
1693   }
1694
1695   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1696     assert(N == 2 && "Invalid number of operands!");
1697     // If this is an immediate, it's a label reference.
1698     if (isImm()) {
1699       addExpr(Inst, getImm());
1700       Inst.addOperand(MCOperand::CreateImm(0));
1701       return;
1702     }
1703
1704     // Otherwise, it's a normal memory reg+offset.
1705     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1706     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1707     Inst.addOperand(MCOperand::CreateImm(Val));
1708   }
1709
1710   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
1711     assert(N == 2 && "Invalid number of operands!");
1712     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1713     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1714   }
1715
1716   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
1717     assert(N == 2 && "Invalid number of operands!");
1718     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1719     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1720   }
1721
1722   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1723     assert(N == 3 && "Invalid number of operands!");
1724     unsigned Val =
1725       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
1726                         Memory.ShiftImm, Memory.ShiftType);
1727     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1728     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1729     Inst.addOperand(MCOperand::CreateImm(Val));
1730   }
1731
1732   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1733     assert(N == 3 && "Invalid number of operands!");
1734     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1735     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1736     Inst.addOperand(MCOperand::CreateImm(Memory.ShiftImm));
1737   }
1738
1739   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
1740     assert(N == 2 && "Invalid number of operands!");
1741     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1742     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1743   }
1744
1745   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
1746     assert(N == 2 && "Invalid number of operands!");
1747     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
1748     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1749     Inst.addOperand(MCOperand::CreateImm(Val));
1750   }
1751
1752   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
1753     assert(N == 2 && "Invalid number of operands!");
1754     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
1755     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1756     Inst.addOperand(MCOperand::CreateImm(Val));
1757   }
1758
1759   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
1760     assert(N == 2 && "Invalid number of operands!");
1761     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
1762     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1763     Inst.addOperand(MCOperand::CreateImm(Val));
1764   }
1765
1766   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
1767     assert(N == 2 && "Invalid number of operands!");
1768     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
1769     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1770     Inst.addOperand(MCOperand::CreateImm(Val));
1771   }
1772
1773   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
1774     assert(N == 1 && "Invalid number of operands!");
1775     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1776     assert(CE && "non-constant post-idx-imm8 operand!");
1777     int Imm = CE->getValue();
1778     bool isAdd = Imm >= 0;
1779     if (Imm == INT32_MIN) Imm = 0;
1780     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
1781     Inst.addOperand(MCOperand::CreateImm(Imm));
1782   }
1783
1784   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
1785     assert(N == 1 && "Invalid number of operands!");
1786     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1787     assert(CE && "non-constant post-idx-imm8s4 operand!");
1788     int Imm = CE->getValue();
1789     bool isAdd = Imm >= 0;
1790     if (Imm == INT32_MIN) Imm = 0;
1791     // Immediate is scaled by 4.
1792     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
1793     Inst.addOperand(MCOperand::CreateImm(Imm));
1794   }
1795
1796   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
1797     assert(N == 2 && "Invalid number of operands!");
1798     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1799     Inst.addOperand(MCOperand::CreateImm(PostIdxReg.isAdd));
1800   }
1801
1802   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
1803     assert(N == 2 && "Invalid number of operands!");
1804     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1805     // The sign, shift type, and shift amount are encoded in a single operand
1806     // using the AM2 encoding helpers.
1807     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
1808     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
1809                                      PostIdxReg.ShiftTy);
1810     Inst.addOperand(MCOperand::CreateImm(Imm));
1811   }
1812
1813   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
1814     assert(N == 1 && "Invalid number of operands!");
1815     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
1816   }
1817
1818   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
1819     assert(N == 1 && "Invalid number of operands!");
1820     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
1821   }
1822
1823   void addVecListOperands(MCInst &Inst, unsigned N) const {
1824     assert(N == 1 && "Invalid number of operands!");
1825     Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
1826   }
1827
1828   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
1829     assert(N == 2 && "Invalid number of operands!");
1830     Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
1831     Inst.addOperand(MCOperand::CreateImm(VectorList.LaneIndex));
1832   }
1833
1834   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
1835     assert(N == 1 && "Invalid number of operands!");
1836     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1837   }
1838
1839   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
1840     assert(N == 1 && "Invalid number of operands!");
1841     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1842   }
1843
1844   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
1845     assert(N == 1 && "Invalid number of operands!");
1846     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1847   }
1848
1849   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
1850     assert(N == 1 && "Invalid number of operands!");
1851     // The immediate encodes the type of constant as well as the value.
1852     // Mask in that this is an i8 splat.
1853     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1854     Inst.addOperand(MCOperand::CreateImm(CE->getValue() | 0xe00));
1855   }
1856
1857   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
1858     assert(N == 1 && "Invalid number of operands!");
1859     // The immediate encodes the type of constant as well as the value.
1860     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1861     unsigned Value = CE->getValue();
1862     if (Value >= 256)
1863       Value = (Value >> 8) | 0xa00;
1864     else
1865       Value |= 0x800;
1866     Inst.addOperand(MCOperand::CreateImm(Value));
1867   }
1868
1869   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
1870     assert(N == 1 && "Invalid number of operands!");
1871     // The immediate encodes the type of constant as well as the value.
1872     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1873     unsigned Value = CE->getValue();
1874     if (Value >= 256 && Value <= 0xff00)
1875       Value = (Value >> 8) | 0x200;
1876     else if (Value > 0xffff && Value <= 0xff0000)
1877       Value = (Value >> 16) | 0x400;
1878     else if (Value > 0xffffff)
1879       Value = (Value >> 24) | 0x600;
1880     Inst.addOperand(MCOperand::CreateImm(Value));
1881   }
1882
1883   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
1884     assert(N == 1 && "Invalid number of operands!");
1885     // The immediate encodes the type of constant as well as the value.
1886     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1887     unsigned Value = CE->getValue();
1888     if (Value >= 256 && Value <= 0xffff)
1889       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
1890     else if (Value > 0xffff && Value <= 0xffffff)
1891       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
1892     else if (Value > 0xffffff)
1893       Value = (Value >> 24) | 0x600;
1894     Inst.addOperand(MCOperand::CreateImm(Value));
1895   }
1896
1897   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
1898     assert(N == 1 && "Invalid number of operands!");
1899     // The immediate encodes the type of constant as well as the value.
1900     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1901     unsigned Value = ~CE->getValue();
1902     if (Value >= 256 && Value <= 0xffff)
1903       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
1904     else if (Value > 0xffff && Value <= 0xffffff)
1905       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
1906     else if (Value > 0xffffff)
1907       Value = (Value >> 24) | 0x600;
1908     Inst.addOperand(MCOperand::CreateImm(Value));
1909   }
1910
1911   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
1912     assert(N == 1 && "Invalid number of operands!");
1913     // The immediate encodes the type of constant as well as the value.
1914     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1915     uint64_t Value = CE->getValue();
1916     unsigned Imm = 0;
1917     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
1918       Imm |= (Value & 1) << i;
1919     }
1920     Inst.addOperand(MCOperand::CreateImm(Imm | 0x1e00));
1921   }
1922
1923   virtual void print(raw_ostream &OS) const;
1924
1925   static ARMOperand *CreateITMask(unsigned Mask, SMLoc S) {
1926     ARMOperand *Op = new ARMOperand(k_ITCondMask);
1927     Op->ITMask.Mask = Mask;
1928     Op->StartLoc = S;
1929     Op->EndLoc = S;
1930     return Op;
1931   }
1932
1933   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
1934     ARMOperand *Op = new ARMOperand(k_CondCode);
1935     Op->CC.Val = CC;
1936     Op->StartLoc = S;
1937     Op->EndLoc = S;
1938     return Op;
1939   }
1940
1941   static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
1942     ARMOperand *Op = new ARMOperand(k_CoprocNum);
1943     Op->Cop.Val = CopVal;
1944     Op->StartLoc = S;
1945     Op->EndLoc = S;
1946     return Op;
1947   }
1948
1949   static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
1950     ARMOperand *Op = new ARMOperand(k_CoprocReg);
1951     Op->Cop.Val = CopVal;
1952     Op->StartLoc = S;
1953     Op->EndLoc = S;
1954     return Op;
1955   }
1956
1957   static ARMOperand *CreateCoprocOption(unsigned Val, SMLoc S, SMLoc E) {
1958     ARMOperand *Op = new ARMOperand(k_CoprocOption);
1959     Op->Cop.Val = Val;
1960     Op->StartLoc = S;
1961     Op->EndLoc = E;
1962     return Op;
1963   }
1964
1965   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
1966     ARMOperand *Op = new ARMOperand(k_CCOut);
1967     Op->Reg.RegNum = RegNum;
1968     Op->StartLoc = S;
1969     Op->EndLoc = S;
1970     return Op;
1971   }
1972
1973   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
1974     ARMOperand *Op = new ARMOperand(k_Token);
1975     Op->Tok.Data = Str.data();
1976     Op->Tok.Length = Str.size();
1977     Op->StartLoc = S;
1978     Op->EndLoc = S;
1979     return Op;
1980   }
1981
1982   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
1983     ARMOperand *Op = new ARMOperand(k_Register);
1984     Op->Reg.RegNum = RegNum;
1985     Op->StartLoc = S;
1986     Op->EndLoc = E;
1987     return Op;
1988   }
1989
1990   static ARMOperand *CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,
1991                                            unsigned SrcReg,
1992                                            unsigned ShiftReg,
1993                                            unsigned ShiftImm,
1994                                            SMLoc S, SMLoc E) {
1995     ARMOperand *Op = new ARMOperand(k_ShiftedRegister);
1996     Op->RegShiftedReg.ShiftTy = ShTy;
1997     Op->RegShiftedReg.SrcReg = SrcReg;
1998     Op->RegShiftedReg.ShiftReg = ShiftReg;
1999     Op->RegShiftedReg.ShiftImm = ShiftImm;
2000     Op->StartLoc = S;
2001     Op->EndLoc = E;
2002     return Op;
2003   }
2004
2005   static ARMOperand *CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,
2006                                             unsigned SrcReg,
2007                                             unsigned ShiftImm,
2008                                             SMLoc S, SMLoc E) {
2009     ARMOperand *Op = new ARMOperand(k_ShiftedImmediate);
2010     Op->RegShiftedImm.ShiftTy = ShTy;
2011     Op->RegShiftedImm.SrcReg = SrcReg;
2012     Op->RegShiftedImm.ShiftImm = ShiftImm;
2013     Op->StartLoc = S;
2014     Op->EndLoc = E;
2015     return Op;
2016   }
2017
2018   static ARMOperand *CreateShifterImm(bool isASR, unsigned Imm,
2019                                    SMLoc S, SMLoc E) {
2020     ARMOperand *Op = new ARMOperand(k_ShifterImmediate);
2021     Op->ShifterImm.isASR = isASR;
2022     Op->ShifterImm.Imm = Imm;
2023     Op->StartLoc = S;
2024     Op->EndLoc = E;
2025     return Op;
2026   }
2027
2028   static ARMOperand *CreateRotImm(unsigned Imm, SMLoc S, SMLoc E) {
2029     ARMOperand *Op = new ARMOperand(k_RotateImmediate);
2030     Op->RotImm.Imm = Imm;
2031     Op->StartLoc = S;
2032     Op->EndLoc = E;
2033     return Op;
2034   }
2035
2036   static ARMOperand *CreateBitfield(unsigned LSB, unsigned Width,
2037                                     SMLoc S, SMLoc E) {
2038     ARMOperand *Op = new ARMOperand(k_BitfieldDescriptor);
2039     Op->Bitfield.LSB = LSB;
2040     Op->Bitfield.Width = Width;
2041     Op->StartLoc = S;
2042     Op->EndLoc = E;
2043     return Op;
2044   }
2045
2046   static ARMOperand *
2047   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
2048                 SMLoc StartLoc, SMLoc EndLoc) {
2049     KindTy Kind = k_RegisterList;
2050
2051     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().first))
2052       Kind = k_DPRRegisterList;
2053     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2054              contains(Regs.front().first))
2055       Kind = k_SPRRegisterList;
2056
2057     ARMOperand *Op = new ARMOperand(Kind);
2058     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
2059            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2060       Op->Registers.push_back(I->first);
2061     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
2062     Op->StartLoc = StartLoc;
2063     Op->EndLoc = EndLoc;
2064     return Op;
2065   }
2066
2067   static ARMOperand *CreateVectorList(unsigned RegNum, unsigned Count,
2068                                       bool isDoubleSpaced, SMLoc S, SMLoc E) {
2069     ARMOperand *Op = new ARMOperand(k_VectorList);
2070     Op->VectorList.RegNum = RegNum;
2071     Op->VectorList.Count = Count;
2072     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2073     Op->StartLoc = S;
2074     Op->EndLoc = E;
2075     return Op;
2076   }
2077
2078   static ARMOperand *CreateVectorListAllLanes(unsigned RegNum, unsigned Count,
2079                                               bool isDoubleSpaced,
2080                                               SMLoc S, SMLoc E) {
2081     ARMOperand *Op = new ARMOperand(k_VectorListAllLanes);
2082     Op->VectorList.RegNum = RegNum;
2083     Op->VectorList.Count = Count;
2084     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2085     Op->StartLoc = S;
2086     Op->EndLoc = E;
2087     return Op;
2088   }
2089
2090   static ARMOperand *CreateVectorListIndexed(unsigned RegNum, unsigned Count,
2091                                              unsigned Index,
2092                                              bool isDoubleSpaced,
2093                                              SMLoc S, SMLoc E) {
2094     ARMOperand *Op = new ARMOperand(k_VectorListIndexed);
2095     Op->VectorList.RegNum = RegNum;
2096     Op->VectorList.Count = Count;
2097     Op->VectorList.LaneIndex = Index;
2098     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2099     Op->StartLoc = S;
2100     Op->EndLoc = E;
2101     return Op;
2102   }
2103
2104   static ARMOperand *CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E,
2105                                        MCContext &Ctx) {
2106     ARMOperand *Op = new ARMOperand(k_VectorIndex);
2107     Op->VectorIndex.Val = Idx;
2108     Op->StartLoc = S;
2109     Op->EndLoc = E;
2110     return Op;
2111   }
2112
2113   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2114     ARMOperand *Op = new ARMOperand(k_Immediate);
2115     Op->Imm.Val = Val;
2116     Op->StartLoc = S;
2117     Op->EndLoc = E;
2118     return Op;
2119   }
2120
2121   static ARMOperand *CreateMem(unsigned BaseRegNum,
2122                                const MCConstantExpr *OffsetImm,
2123                                unsigned OffsetRegNum,
2124                                ARM_AM::ShiftOpc ShiftType,
2125                                unsigned ShiftImm,
2126                                unsigned Alignment,
2127                                bool isNegative,
2128                                SMLoc S, SMLoc E) {
2129     ARMOperand *Op = new ARMOperand(k_Memory);
2130     Op->Memory.BaseRegNum = BaseRegNum;
2131     Op->Memory.OffsetImm = OffsetImm;
2132     Op->Memory.OffsetRegNum = OffsetRegNum;
2133     Op->Memory.ShiftType = ShiftType;
2134     Op->Memory.ShiftImm = ShiftImm;
2135     Op->Memory.Alignment = Alignment;
2136     Op->Memory.isNegative = isNegative;
2137     Op->StartLoc = S;
2138     Op->EndLoc = E;
2139     return Op;
2140   }
2141
2142   static ARMOperand *CreatePostIdxReg(unsigned RegNum, bool isAdd,
2143                                       ARM_AM::ShiftOpc ShiftTy,
2144                                       unsigned ShiftImm,
2145                                       SMLoc S, SMLoc E) {
2146     ARMOperand *Op = new ARMOperand(k_PostIndexRegister);
2147     Op->PostIdxReg.RegNum = RegNum;
2148     Op->PostIdxReg.isAdd = isAdd;
2149     Op->PostIdxReg.ShiftTy = ShiftTy;
2150     Op->PostIdxReg.ShiftImm = ShiftImm;
2151     Op->StartLoc = S;
2152     Op->EndLoc = E;
2153     return Op;
2154   }
2155
2156   static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
2157     ARMOperand *Op = new ARMOperand(k_MemBarrierOpt);
2158     Op->MBOpt.Val = Opt;
2159     Op->StartLoc = S;
2160     Op->EndLoc = S;
2161     return Op;
2162   }
2163
2164   static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
2165     ARMOperand *Op = new ARMOperand(k_ProcIFlags);
2166     Op->IFlags.Val = IFlags;
2167     Op->StartLoc = S;
2168     Op->EndLoc = S;
2169     return Op;
2170   }
2171
2172   static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
2173     ARMOperand *Op = new ARMOperand(k_MSRMask);
2174     Op->MMask.Val = MMask;
2175     Op->StartLoc = S;
2176     Op->EndLoc = S;
2177     return Op;
2178   }
2179 };
2180
2181 } // end anonymous namespace.
2182
2183 void ARMOperand::print(raw_ostream &OS) const {
2184   switch (Kind) {
2185   case k_CondCode:
2186     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2187     break;
2188   case k_CCOut:
2189     OS << "<ccout " << getReg() << ">";
2190     break;
2191   case k_ITCondMask: {
2192     static const char *MaskStr[] = {
2193       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2194       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2195     };
2196     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2197     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2198     break;
2199   }
2200   case k_CoprocNum:
2201     OS << "<coprocessor number: " << getCoproc() << ">";
2202     break;
2203   case k_CoprocReg:
2204     OS << "<coprocessor register: " << getCoproc() << ">";
2205     break;
2206   case k_CoprocOption:
2207     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2208     break;
2209   case k_MSRMask:
2210     OS << "<mask: " << getMSRMask() << ">";
2211     break;
2212   case k_Immediate:
2213     getImm()->print(OS);
2214     break;
2215   case k_MemBarrierOpt:
2216     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
2217     break;
2218   case k_Memory:
2219     OS << "<memory "
2220        << " base:" << Memory.BaseRegNum;
2221     OS << ">";
2222     break;
2223   case k_PostIndexRegister:
2224     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2225        << PostIdxReg.RegNum;
2226     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2227       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2228          << PostIdxReg.ShiftImm;
2229     OS << ">";
2230     break;
2231   case k_ProcIFlags: {
2232     OS << "<ARM_PROC::";
2233     unsigned IFlags = getProcIFlags();
2234     for (int i=2; i >= 0; --i)
2235       if (IFlags & (1 << i))
2236         OS << ARM_PROC::IFlagsToString(1 << i);
2237     OS << ">";
2238     break;
2239   }
2240   case k_Register:
2241     OS << "<register " << getReg() << ">";
2242     break;
2243   case k_ShifterImmediate:
2244     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2245        << " #" << ShifterImm.Imm << ">";
2246     break;
2247   case k_ShiftedRegister:
2248     OS << "<so_reg_reg "
2249        << RegShiftedReg.SrcReg << " "
2250        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2251        << " " << RegShiftedReg.ShiftReg << ">";
2252     break;
2253   case k_ShiftedImmediate:
2254     OS << "<so_reg_imm "
2255        << RegShiftedImm.SrcReg << " "
2256        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2257        << " #" << RegShiftedImm.ShiftImm << ">";
2258     break;
2259   case k_RotateImmediate:
2260     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2261     break;
2262   case k_BitfieldDescriptor:
2263     OS << "<bitfield " << "lsb: " << Bitfield.LSB
2264        << ", width: " << Bitfield.Width << ">";
2265     break;
2266   case k_RegisterList:
2267   case k_DPRRegisterList:
2268   case k_SPRRegisterList: {
2269     OS << "<register_list ";
2270
2271     const SmallVectorImpl<unsigned> &RegList = getRegList();
2272     for (SmallVectorImpl<unsigned>::const_iterator
2273            I = RegList.begin(), E = RegList.end(); I != E; ) {
2274       OS << *I;
2275       if (++I < E) OS << ", ";
2276     }
2277
2278     OS << ">";
2279     break;
2280   }
2281   case k_VectorList:
2282     OS << "<vector_list " << VectorList.Count << " * "
2283        << VectorList.RegNum << ">";
2284     break;
2285   case k_VectorListAllLanes:
2286     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
2287        << VectorList.RegNum << ">";
2288     break;
2289   case k_VectorListIndexed:
2290     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
2291        << VectorList.Count << " * " << VectorList.RegNum << ">";
2292     break;
2293   case k_Token:
2294     OS << "'" << getToken() << "'";
2295     break;
2296   case k_VectorIndex:
2297     OS << "<vectorindex " << getVectorIndex() << ">";
2298     break;
2299   }
2300 }
2301
2302 /// @name Auto-generated Match Functions
2303 /// {
2304
2305 static unsigned MatchRegisterName(StringRef Name);
2306
2307 /// }
2308
2309 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
2310                                  SMLoc &StartLoc, SMLoc &EndLoc) {
2311   StartLoc = Parser.getTok().getLoc();
2312   RegNo = tryParseRegister();
2313   EndLoc = Parser.getTok().getLoc();
2314
2315   return (RegNo == (unsigned)-1);
2316 }
2317
2318 /// Try to parse a register name.  The token must be an Identifier when called,
2319 /// and if it is a register name the token is eaten and the register number is
2320 /// returned.  Otherwise return -1.
2321 ///
2322 int ARMAsmParser::tryParseRegister() {
2323   const AsmToken &Tok = Parser.getTok();
2324   if (Tok.isNot(AsmToken::Identifier)) return -1;
2325
2326   std::string lowerCase = Tok.getString().lower();
2327   unsigned RegNum = MatchRegisterName(lowerCase);
2328   if (!RegNum) {
2329     RegNum = StringSwitch<unsigned>(lowerCase)
2330       .Case("r13", ARM::SP)
2331       .Case("r14", ARM::LR)
2332       .Case("r15", ARM::PC)
2333       .Case("ip", ARM::R12)
2334       // Additional register name aliases for 'gas' compatibility.
2335       .Case("a1", ARM::R0)
2336       .Case("a2", ARM::R1)
2337       .Case("a3", ARM::R2)
2338       .Case("a4", ARM::R3)
2339       .Case("v1", ARM::R4)
2340       .Case("v2", ARM::R5)
2341       .Case("v3", ARM::R6)
2342       .Case("v4", ARM::R7)
2343       .Case("v5", ARM::R8)
2344       .Case("v6", ARM::R9)
2345       .Case("v7", ARM::R10)
2346       .Case("v8", ARM::R11)
2347       .Case("sb", ARM::R9)
2348       .Case("sl", ARM::R10)
2349       .Case("fp", ARM::R11)
2350       .Default(0);
2351   }
2352   if (!RegNum) {
2353     // Check for aliases registered via .req. Canonicalize to lower case.
2354     // That's more consistent since register names are case insensitive, and
2355     // it's how the original entry was passed in from MC/MCParser/AsmParser.
2356     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
2357     // If no match, return failure.
2358     if (Entry == RegisterReqs.end())
2359       return -1;
2360     Parser.Lex(); // Eat identifier token.
2361     return Entry->getValue();
2362   }
2363
2364   Parser.Lex(); // Eat identifier token.
2365
2366   return RegNum;
2367 }
2368
2369 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
2370 // If a recoverable error occurs, return 1. If an irrecoverable error
2371 // occurs, return -1. An irrecoverable error is one where tokens have been
2372 // consumed in the process of trying to parse the shifter (i.e., when it is
2373 // indeed a shifter operand, but malformed).
2374 int ARMAsmParser::tryParseShiftRegister(
2375                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2376   SMLoc S = Parser.getTok().getLoc();
2377   const AsmToken &Tok = Parser.getTok();
2378   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2379
2380   std::string lowerCase = Tok.getString().lower();
2381   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
2382       .Case("asl", ARM_AM::lsl)
2383       .Case("lsl", ARM_AM::lsl)
2384       .Case("lsr", ARM_AM::lsr)
2385       .Case("asr", ARM_AM::asr)
2386       .Case("ror", ARM_AM::ror)
2387       .Case("rrx", ARM_AM::rrx)
2388       .Default(ARM_AM::no_shift);
2389
2390   if (ShiftTy == ARM_AM::no_shift)
2391     return 1;
2392
2393   Parser.Lex(); // Eat the operator.
2394
2395   // The source register for the shift has already been added to the
2396   // operand list, so we need to pop it off and combine it into the shifted
2397   // register operand instead.
2398   OwningPtr<ARMOperand> PrevOp((ARMOperand*)Operands.pop_back_val());
2399   if (!PrevOp->isReg())
2400     return Error(PrevOp->getStartLoc(), "shift must be of a register");
2401   int SrcReg = PrevOp->getReg();
2402   int64_t Imm = 0;
2403   int ShiftReg = 0;
2404   if (ShiftTy == ARM_AM::rrx) {
2405     // RRX Doesn't have an explicit shift amount. The encoder expects
2406     // the shift register to be the same as the source register. Seems odd,
2407     // but OK.
2408     ShiftReg = SrcReg;
2409   } else {
2410     // Figure out if this is shifted by a constant or a register (for non-RRX).
2411     if (Parser.getTok().is(AsmToken::Hash) ||
2412         Parser.getTok().is(AsmToken::Dollar)) {
2413       Parser.Lex(); // Eat hash.
2414       SMLoc ImmLoc = Parser.getTok().getLoc();
2415       const MCExpr *ShiftExpr = 0;
2416       if (getParser().ParseExpression(ShiftExpr)) {
2417         Error(ImmLoc, "invalid immediate shift value");
2418         return -1;
2419       }
2420       // The expression must be evaluatable as an immediate.
2421       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
2422       if (!CE) {
2423         Error(ImmLoc, "invalid immediate shift value");
2424         return -1;
2425       }
2426       // Range check the immediate.
2427       // lsl, ror: 0 <= imm <= 31
2428       // lsr, asr: 0 <= imm <= 32
2429       Imm = CE->getValue();
2430       if (Imm < 0 ||
2431           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
2432           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
2433         Error(ImmLoc, "immediate shift value out of range");
2434         return -1;
2435       }
2436       // shift by zero is a nop. Always send it through as lsl.
2437       // ('as' compatibility)
2438       if (Imm == 0)
2439         ShiftTy = ARM_AM::lsl;
2440     } else if (Parser.getTok().is(AsmToken::Identifier)) {
2441       ShiftReg = tryParseRegister();
2442       SMLoc L = Parser.getTok().getLoc();
2443       if (ShiftReg == -1) {
2444         Error (L, "expected immediate or register in shift operand");
2445         return -1;
2446       }
2447     } else {
2448       Error (Parser.getTok().getLoc(),
2449                     "expected immediate or register in shift operand");
2450       return -1;
2451     }
2452   }
2453
2454   if (ShiftReg && ShiftTy != ARM_AM::rrx)
2455     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
2456                                                          ShiftReg, Imm,
2457                                                S, Parser.getTok().getLoc()));
2458   else
2459     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
2460                                                S, Parser.getTok().getLoc()));
2461
2462   return 0;
2463 }
2464
2465
2466 /// Try to parse a register name.  The token must be an Identifier when called.
2467 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
2468 /// if there is a "writeback". 'true' if it's not a register.
2469 ///
2470 /// TODO this is likely to change to allow different register types and or to
2471 /// parse for a specific register type.
2472 bool ARMAsmParser::
2473 tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2474   SMLoc S = Parser.getTok().getLoc();
2475   int RegNo = tryParseRegister();
2476   if (RegNo == -1)
2477     return true;
2478
2479   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
2480
2481   const AsmToken &ExclaimTok = Parser.getTok();
2482   if (ExclaimTok.is(AsmToken::Exclaim)) {
2483     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
2484                                                ExclaimTok.getLoc()));
2485     Parser.Lex(); // Eat exclaim token
2486     return false;
2487   }
2488
2489   // Also check for an index operand. This is only legal for vector registers,
2490   // but that'll get caught OK in operand matching, so we don't need to
2491   // explicitly filter everything else out here.
2492   if (Parser.getTok().is(AsmToken::LBrac)) {
2493     SMLoc SIdx = Parser.getTok().getLoc();
2494     Parser.Lex(); // Eat left bracket token.
2495
2496     const MCExpr *ImmVal;
2497     if (getParser().ParseExpression(ImmVal))
2498       return MatchOperand_ParseFail;
2499     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2500     if (!MCE) {
2501       TokError("immediate value expected for vector index");
2502       return MatchOperand_ParseFail;
2503     }
2504
2505     SMLoc E = Parser.getTok().getLoc();
2506     if (Parser.getTok().isNot(AsmToken::RBrac)) {
2507       Error(E, "']' expected");
2508       return MatchOperand_ParseFail;
2509     }
2510
2511     Parser.Lex(); // Eat right bracket token.
2512
2513     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
2514                                                      SIdx, E,
2515                                                      getContext()));
2516   }
2517
2518   return false;
2519 }
2520
2521 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
2522 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
2523 /// "c5", ...
2524 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
2525   // Use the same layout as the tablegen'erated register name matcher. Ugly,
2526   // but efficient.
2527   switch (Name.size()) {
2528   default: return -1;
2529   case 2:
2530     if (Name[0] != CoprocOp)
2531       return -1;
2532     switch (Name[1]) {
2533     default:  return -1;
2534     case '0': return 0;
2535     case '1': return 1;
2536     case '2': return 2;
2537     case '3': return 3;
2538     case '4': return 4;
2539     case '5': return 5;
2540     case '6': return 6;
2541     case '7': return 7;
2542     case '8': return 8;
2543     case '9': return 9;
2544     }
2545   case 3:
2546     if (Name[0] != CoprocOp || Name[1] != '1')
2547       return -1;
2548     switch (Name[2]) {
2549     default:  return -1;
2550     case '0': return 10;
2551     case '1': return 11;
2552     case '2': return 12;
2553     case '3': return 13;
2554     case '4': return 14;
2555     case '5': return 15;
2556     }
2557   }
2558 }
2559
2560 /// parseITCondCode - Try to parse a condition code for an IT instruction.
2561 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2562 parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2563   SMLoc S = Parser.getTok().getLoc();
2564   const AsmToken &Tok = Parser.getTok();
2565   if (!Tok.is(AsmToken::Identifier))
2566     return MatchOperand_NoMatch;
2567   unsigned CC = StringSwitch<unsigned>(Tok.getString())
2568     .Case("eq", ARMCC::EQ)
2569     .Case("ne", ARMCC::NE)
2570     .Case("hs", ARMCC::HS)
2571     .Case("cs", ARMCC::HS)
2572     .Case("lo", ARMCC::LO)
2573     .Case("cc", ARMCC::LO)
2574     .Case("mi", ARMCC::MI)
2575     .Case("pl", ARMCC::PL)
2576     .Case("vs", ARMCC::VS)
2577     .Case("vc", ARMCC::VC)
2578     .Case("hi", ARMCC::HI)
2579     .Case("ls", ARMCC::LS)
2580     .Case("ge", ARMCC::GE)
2581     .Case("lt", ARMCC::LT)
2582     .Case("gt", ARMCC::GT)
2583     .Case("le", ARMCC::LE)
2584     .Case("al", ARMCC::AL)
2585     .Default(~0U);
2586   if (CC == ~0U)
2587     return MatchOperand_NoMatch;
2588   Parser.Lex(); // Eat the token.
2589
2590   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
2591
2592   return MatchOperand_Success;
2593 }
2594
2595 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
2596 /// token must be an Identifier when called, and if it is a coprocessor
2597 /// number, the token is eaten and the operand is added to the operand list.
2598 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2599 parseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2600   SMLoc S = Parser.getTok().getLoc();
2601   const AsmToken &Tok = Parser.getTok();
2602   if (Tok.isNot(AsmToken::Identifier))
2603     return MatchOperand_NoMatch;
2604
2605   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
2606   if (Num == -1)
2607     return MatchOperand_NoMatch;
2608
2609   Parser.Lex(); // Eat identifier token.
2610   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
2611   return MatchOperand_Success;
2612 }
2613
2614 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
2615 /// token must be an Identifier when called, and if it is a coprocessor
2616 /// number, the token is eaten and the operand is added to the operand list.
2617 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2618 parseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2619   SMLoc S = Parser.getTok().getLoc();
2620   const AsmToken &Tok = Parser.getTok();
2621   if (Tok.isNot(AsmToken::Identifier))
2622     return MatchOperand_NoMatch;
2623
2624   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
2625   if (Reg == -1)
2626     return MatchOperand_NoMatch;
2627
2628   Parser.Lex(); // Eat identifier token.
2629   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
2630   return MatchOperand_Success;
2631 }
2632
2633 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
2634 /// coproc_option : '{' imm0_255 '}'
2635 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2636 parseCoprocOptionOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2637   SMLoc S = Parser.getTok().getLoc();
2638
2639   // If this isn't a '{', this isn't a coprocessor immediate operand.
2640   if (Parser.getTok().isNot(AsmToken::LCurly))
2641     return MatchOperand_NoMatch;
2642   Parser.Lex(); // Eat the '{'
2643
2644   const MCExpr *Expr;
2645   SMLoc Loc = Parser.getTok().getLoc();
2646   if (getParser().ParseExpression(Expr)) {
2647     Error(Loc, "illegal expression");
2648     return MatchOperand_ParseFail;
2649   }
2650   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
2651   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
2652     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
2653     return MatchOperand_ParseFail;
2654   }
2655   int Val = CE->getValue();
2656
2657   // Check for and consume the closing '}'
2658   if (Parser.getTok().isNot(AsmToken::RCurly))
2659     return MatchOperand_ParseFail;
2660   SMLoc E = Parser.getTok().getLoc();
2661   Parser.Lex(); // Eat the '}'
2662
2663   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
2664   return MatchOperand_Success;
2665 }
2666
2667 // For register list parsing, we need to map from raw GPR register numbering
2668 // to the enumeration values. The enumeration values aren't sorted by
2669 // register number due to our using "sp", "lr" and "pc" as canonical names.
2670 static unsigned getNextRegister(unsigned Reg) {
2671   // If this is a GPR, we need to do it manually, otherwise we can rely
2672   // on the sort ordering of the enumeration since the other reg-classes
2673   // are sane.
2674   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
2675     return Reg + 1;
2676   switch(Reg) {
2677   default: assert(0 && "Invalid GPR number!");
2678   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
2679   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
2680   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
2681   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
2682   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
2683   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
2684   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
2685   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
2686   }
2687 }
2688
2689 // Return the low-subreg of a given Q register.
2690 static unsigned getDRegFromQReg(unsigned QReg) {
2691   switch (QReg) {
2692   default: llvm_unreachable("expected a Q register!");
2693   case ARM::Q0:  return ARM::D0;
2694   case ARM::Q1:  return ARM::D2;
2695   case ARM::Q2:  return ARM::D4;
2696   case ARM::Q3:  return ARM::D6;
2697   case ARM::Q4:  return ARM::D8;
2698   case ARM::Q5:  return ARM::D10;
2699   case ARM::Q6:  return ARM::D12;
2700   case ARM::Q7:  return ARM::D14;
2701   case ARM::Q8:  return ARM::D16;
2702   case ARM::Q9:  return ARM::D18;
2703   case ARM::Q10: return ARM::D20;
2704   case ARM::Q11: return ARM::D22;
2705   case ARM::Q12: return ARM::D24;
2706   case ARM::Q13: return ARM::D26;
2707   case ARM::Q14: return ARM::D28;
2708   case ARM::Q15: return ARM::D30;
2709   }
2710 }
2711
2712 /// Parse a register list.
2713 bool ARMAsmParser::
2714 parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2715   assert(Parser.getTok().is(AsmToken::LCurly) &&
2716          "Token is not a Left Curly Brace");
2717   SMLoc S = Parser.getTok().getLoc();
2718   Parser.Lex(); // Eat '{' token.
2719   SMLoc RegLoc = Parser.getTok().getLoc();
2720
2721   // Check the first register in the list to see what register class
2722   // this is a list of.
2723   int Reg = tryParseRegister();
2724   if (Reg == -1)
2725     return Error(RegLoc, "register expected");
2726
2727   // The reglist instructions have at most 16 registers, so reserve
2728   // space for that many.
2729   SmallVector<std::pair<unsigned, SMLoc>, 16> Registers;
2730
2731   // Allow Q regs and just interpret them as the two D sub-registers.
2732   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
2733     Reg = getDRegFromQReg(Reg);
2734     Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
2735     ++Reg;
2736   }
2737   const MCRegisterClass *RC;
2738   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
2739     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
2740   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
2741     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
2742   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
2743     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
2744   else
2745     return Error(RegLoc, "invalid register in register list");
2746
2747   // Store the register.
2748   Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
2749
2750   // This starts immediately after the first register token in the list,
2751   // so we can see either a comma or a minus (range separator) as a legal
2752   // next token.
2753   while (Parser.getTok().is(AsmToken::Comma) ||
2754          Parser.getTok().is(AsmToken::Minus)) {
2755     if (Parser.getTok().is(AsmToken::Minus)) {
2756       Parser.Lex(); // Eat the minus.
2757       SMLoc EndLoc = Parser.getTok().getLoc();
2758       int EndReg = tryParseRegister();
2759       if (EndReg == -1)
2760         return Error(EndLoc, "register expected");
2761       // Allow Q regs and just interpret them as the two D sub-registers.
2762       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
2763         EndReg = getDRegFromQReg(EndReg) + 1;
2764       // If the register is the same as the start reg, there's nothing
2765       // more to do.
2766       if (Reg == EndReg)
2767         continue;
2768       // The register must be in the same register class as the first.
2769       if (!RC->contains(EndReg))
2770         return Error(EndLoc, "invalid register in register list");
2771       // Ranges must go from low to high.
2772       if (getARMRegisterNumbering(Reg) > getARMRegisterNumbering(EndReg))
2773         return Error(EndLoc, "bad range in register list");
2774
2775       // Add all the registers in the range to the register list.
2776       while (Reg != EndReg) {
2777         Reg = getNextRegister(Reg);
2778         Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
2779       }
2780       continue;
2781     }
2782     Parser.Lex(); // Eat the comma.
2783     RegLoc = Parser.getTok().getLoc();
2784     int OldReg = Reg;
2785     const AsmToken RegTok = Parser.getTok();
2786     Reg = tryParseRegister();
2787     if (Reg == -1)
2788       return Error(RegLoc, "register expected");
2789     // Allow Q regs and just interpret them as the two D sub-registers.
2790     bool isQReg = false;
2791     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
2792       Reg = getDRegFromQReg(Reg);
2793       isQReg = true;
2794     }
2795     // The register must be in the same register class as the first.
2796     if (!RC->contains(Reg))
2797       return Error(RegLoc, "invalid register in register list");
2798     // List must be monotonically increasing.
2799     if (getARMRegisterNumbering(Reg) < getARMRegisterNumbering(OldReg))
2800       return Error(RegLoc, "register list not in ascending order");
2801     if (getARMRegisterNumbering(Reg) == getARMRegisterNumbering(OldReg)) {
2802       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
2803               ") in register list");
2804       continue;
2805     }
2806     // VFP register lists must also be contiguous.
2807     // It's OK to use the enumeration values directly here rather, as the
2808     // VFP register classes have the enum sorted properly.
2809     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
2810         Reg != OldReg + 1)
2811       return Error(RegLoc, "non-contiguous register range");
2812     Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
2813     if (isQReg)
2814       Registers.push_back(std::pair<unsigned, SMLoc>(++Reg, RegLoc));
2815   }
2816
2817   SMLoc E = Parser.getTok().getLoc();
2818   if (Parser.getTok().isNot(AsmToken::RCurly))
2819     return Error(E, "'}' expected");
2820   Parser.Lex(); // Eat '}' token.
2821
2822   // Push the register list operand.
2823   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
2824
2825   // The ARM system instruction variants for LDM/STM have a '^' token here.
2826   if (Parser.getTok().is(AsmToken::Caret)) {
2827     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
2828     Parser.Lex(); // Eat '^' token.
2829   }
2830
2831   return false;
2832 }
2833
2834 // Helper function to parse the lane index for vector lists.
2835 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2836 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index) {
2837   Index = 0; // Always return a defined index value.
2838   if (Parser.getTok().is(AsmToken::LBrac)) {
2839     Parser.Lex(); // Eat the '['.
2840     if (Parser.getTok().is(AsmToken::RBrac)) {
2841       // "Dn[]" is the 'all lanes' syntax.
2842       LaneKind = AllLanes;
2843       Parser.Lex(); // Eat the ']'.
2844       return MatchOperand_Success;
2845     }
2846     const MCExpr *LaneIndex;
2847     SMLoc Loc = Parser.getTok().getLoc();
2848     if (getParser().ParseExpression(LaneIndex)) {
2849       Error(Loc, "illegal expression");
2850       return MatchOperand_ParseFail;
2851     }
2852     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
2853     if (!CE) {
2854       Error(Loc, "lane index must be empty or an integer");
2855       return MatchOperand_ParseFail;
2856     }
2857     if (Parser.getTok().isNot(AsmToken::RBrac)) {
2858       Error(Parser.getTok().getLoc(), "']' expected");
2859       return MatchOperand_ParseFail;
2860     }
2861     Parser.Lex(); // Eat the ']'.
2862     int64_t Val = CE->getValue();
2863
2864     // FIXME: Make this range check context sensitive for .8, .16, .32.
2865     if (Val < 0 || Val > 7) {
2866       Error(Parser.getTok().getLoc(), "lane index out of range");
2867       return MatchOperand_ParseFail;
2868     }
2869     Index = Val;
2870     LaneKind = IndexedLane;
2871     return MatchOperand_Success;
2872   }
2873   LaneKind = NoLanes;
2874   return MatchOperand_Success;
2875 }
2876
2877 // parse a vector register list
2878 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2879 parseVectorList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2880   VectorLaneTy LaneKind;
2881   unsigned LaneIndex;
2882   SMLoc S = Parser.getTok().getLoc();
2883   // As an extension (to match gas), support a plain D register or Q register
2884   // (without encosing curly braces) as a single or double entry list,
2885   // respectively.
2886   if (Parser.getTok().is(AsmToken::Identifier)) {
2887     int Reg = tryParseRegister();
2888     if (Reg == -1)
2889       return MatchOperand_NoMatch;
2890     SMLoc E = Parser.getTok().getLoc();
2891     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
2892       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex);
2893       if (Res != MatchOperand_Success)
2894         return Res;
2895       switch (LaneKind) {
2896       case NoLanes:
2897         E = Parser.getTok().getLoc();
2898         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
2899         break;
2900       case AllLanes:
2901         E = Parser.getTok().getLoc();
2902         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
2903                                                                 S, E));
2904         break;
2905       case IndexedLane:
2906         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
2907                                                                LaneIndex,
2908                                                                false, S, E));
2909         break;
2910       }
2911       return MatchOperand_Success;
2912     }
2913     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
2914       Reg = getDRegFromQReg(Reg);
2915       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex);
2916       if (Res != MatchOperand_Success)
2917         return Res;
2918       switch (LaneKind) {
2919       case NoLanes:
2920         E = Parser.getTok().getLoc();
2921         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
2922         break;
2923       case AllLanes:
2924         E = Parser.getTok().getLoc();
2925         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
2926                                                                 S, E));
2927         break;
2928       case IndexedLane:
2929         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
2930                                                                LaneIndex,
2931                                                                false, S, E));
2932         break;
2933       }
2934       return MatchOperand_Success;
2935     }
2936     Error(S, "vector register expected");
2937     return MatchOperand_ParseFail;
2938   }
2939
2940   if (Parser.getTok().isNot(AsmToken::LCurly))
2941     return MatchOperand_NoMatch;
2942
2943   Parser.Lex(); // Eat '{' token.
2944   SMLoc RegLoc = Parser.getTok().getLoc();
2945
2946   int Reg = tryParseRegister();
2947   if (Reg == -1) {
2948     Error(RegLoc, "register expected");
2949     return MatchOperand_ParseFail;
2950   }
2951   unsigned Count = 1;
2952   int Spacing = 0;
2953   unsigned FirstReg = Reg;
2954   // The list is of D registers, but we also allow Q regs and just interpret
2955   // them as the two D sub-registers.
2956   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
2957     FirstReg = Reg = getDRegFromQReg(Reg);
2958     Spacing = 1; // double-spacing requires explicit D registers, otherwise
2959                  // it's ambiguous with four-register single spaced.
2960     ++Reg;
2961     ++Count;
2962   }
2963   if (parseVectorLane(LaneKind, LaneIndex) != MatchOperand_Success)
2964     return MatchOperand_ParseFail;
2965
2966   while (Parser.getTok().is(AsmToken::Comma) ||
2967          Parser.getTok().is(AsmToken::Minus)) {
2968     if (Parser.getTok().is(AsmToken::Minus)) {
2969       if (!Spacing)
2970         Spacing = 1; // Register range implies a single spaced list.
2971       else if (Spacing == 2) {
2972         Error(Parser.getTok().getLoc(),
2973               "sequential registers in double spaced list");
2974         return MatchOperand_ParseFail;
2975       }
2976       Parser.Lex(); // Eat the minus.
2977       SMLoc EndLoc = Parser.getTok().getLoc();
2978       int EndReg = tryParseRegister();
2979       if (EndReg == -1) {
2980         Error(EndLoc, "register expected");
2981         return MatchOperand_ParseFail;
2982       }
2983       // Allow Q regs and just interpret them as the two D sub-registers.
2984       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
2985         EndReg = getDRegFromQReg(EndReg) + 1;
2986       // If the register is the same as the start reg, there's nothing
2987       // more to do.
2988       if (Reg == EndReg)
2989         continue;
2990       // The register must be in the same register class as the first.
2991       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
2992         Error(EndLoc, "invalid register in register list");
2993         return MatchOperand_ParseFail;
2994       }
2995       // Ranges must go from low to high.
2996       if (Reg > EndReg) {
2997         Error(EndLoc, "bad range in register list");
2998         return MatchOperand_ParseFail;
2999       }
3000       // Parse the lane specifier if present.
3001       VectorLaneTy NextLaneKind;
3002       unsigned NextLaneIndex;
3003       if (parseVectorLane(NextLaneKind, NextLaneIndex) != MatchOperand_Success)
3004         return MatchOperand_ParseFail;
3005       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3006         Error(EndLoc, "mismatched lane index in register list");
3007         return MatchOperand_ParseFail;
3008       }
3009       EndLoc = Parser.getTok().getLoc();
3010
3011       // Add all the registers in the range to the register list.
3012       Count += EndReg - Reg;
3013       Reg = EndReg;
3014       continue;
3015     }
3016     Parser.Lex(); // Eat the comma.
3017     RegLoc = Parser.getTok().getLoc();
3018     int OldReg = Reg;
3019     Reg = tryParseRegister();
3020     if (Reg == -1) {
3021       Error(RegLoc, "register expected");
3022       return MatchOperand_ParseFail;
3023     }
3024     // vector register lists must be contiguous.
3025     // It's OK to use the enumeration values directly here rather, as the
3026     // VFP register classes have the enum sorted properly.
3027     //
3028     // The list is of D registers, but we also allow Q regs and just interpret
3029     // them as the two D sub-registers.
3030     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3031       if (!Spacing)
3032         Spacing = 1; // Register range implies a single spaced list.
3033       else if (Spacing == 2) {
3034         Error(RegLoc,
3035               "invalid register in double-spaced list (must be 'D' register')");
3036         return MatchOperand_ParseFail;
3037       }
3038       Reg = getDRegFromQReg(Reg);
3039       if (Reg != OldReg + 1) {
3040         Error(RegLoc, "non-contiguous register range");
3041         return MatchOperand_ParseFail;
3042       }
3043       ++Reg;
3044       Count += 2;
3045       // Parse the lane specifier if present.
3046       VectorLaneTy NextLaneKind;
3047       unsigned NextLaneIndex;
3048       SMLoc EndLoc = Parser.getTok().getLoc();
3049       if (parseVectorLane(NextLaneKind, NextLaneIndex) != MatchOperand_Success)
3050         return MatchOperand_ParseFail;
3051       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3052         Error(EndLoc, "mismatched lane index in register list");
3053         return MatchOperand_ParseFail;
3054       }
3055       continue;
3056     }
3057     // Normal D register.
3058     // Figure out the register spacing (single or double) of the list if
3059     // we don't know it already.
3060     if (!Spacing)
3061       Spacing = 1 + (Reg == OldReg + 2);
3062
3063     // Just check that it's contiguous and keep going.
3064     if (Reg != OldReg + Spacing) {
3065       Error(RegLoc, "non-contiguous register range");
3066       return MatchOperand_ParseFail;
3067     }
3068     ++Count;
3069     // Parse the lane specifier if present.
3070     VectorLaneTy NextLaneKind;
3071     unsigned NextLaneIndex;
3072     SMLoc EndLoc = Parser.getTok().getLoc();
3073     if (parseVectorLane(NextLaneKind, NextLaneIndex) != MatchOperand_Success)
3074       return MatchOperand_ParseFail;
3075     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3076       Error(EndLoc, "mismatched lane index in register list");
3077       return MatchOperand_ParseFail;
3078     }
3079   }
3080
3081   SMLoc E = Parser.getTok().getLoc();
3082   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3083     Error(E, "'}' expected");
3084     return MatchOperand_ParseFail;
3085   }
3086   Parser.Lex(); // Eat '}' token.
3087
3088   switch (LaneKind) {
3089   case NoLanes:
3090     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3091                                                     (Spacing == 2), S, E));
3092     break;
3093   case AllLanes:
3094     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3095                                                             (Spacing == 2),
3096                                                             S, E));
3097     break;
3098   case IndexedLane:
3099     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3100                                                            LaneIndex,
3101                                                            (Spacing == 2),
3102                                                            S, E));
3103     break;
3104   }
3105   return MatchOperand_Success;
3106 }
3107
3108 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3109 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3110 parseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3111   SMLoc S = Parser.getTok().getLoc();
3112   const AsmToken &Tok = Parser.getTok();
3113   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
3114   StringRef OptStr = Tok.getString();
3115
3116   unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
3117     .Case("sy",    ARM_MB::SY)
3118     .Case("st",    ARM_MB::ST)
3119     .Case("sh",    ARM_MB::ISH)
3120     .Case("ish",   ARM_MB::ISH)
3121     .Case("shst",  ARM_MB::ISHST)
3122     .Case("ishst", ARM_MB::ISHST)
3123     .Case("nsh",   ARM_MB::NSH)
3124     .Case("un",    ARM_MB::NSH)
3125     .Case("nshst", ARM_MB::NSHST)
3126     .Case("unst",  ARM_MB::NSHST)
3127     .Case("osh",   ARM_MB::OSH)
3128     .Case("oshst", ARM_MB::OSHST)
3129     .Default(~0U);
3130
3131   if (Opt == ~0U)
3132     return MatchOperand_NoMatch;
3133
3134   Parser.Lex(); // Eat identifier token.
3135   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3136   return MatchOperand_Success;
3137 }
3138
3139 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
3140 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3141 parseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3142   SMLoc S = Parser.getTok().getLoc();
3143   const AsmToken &Tok = Parser.getTok();
3144   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
3145   StringRef IFlagsStr = Tok.getString();
3146
3147   // An iflags string of "none" is interpreted to mean that none of the AIF
3148   // bits are set.  Not a terribly useful instruction, but a valid encoding.
3149   unsigned IFlags = 0;
3150   if (IFlagsStr != "none") {
3151         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
3152       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
3153         .Case("a", ARM_PROC::A)
3154         .Case("i", ARM_PROC::I)
3155         .Case("f", ARM_PROC::F)
3156         .Default(~0U);
3157
3158       // If some specific iflag is already set, it means that some letter is
3159       // present more than once, this is not acceptable.
3160       if (Flag == ~0U || (IFlags & Flag))
3161         return MatchOperand_NoMatch;
3162
3163       IFlags |= Flag;
3164     }
3165   }
3166
3167   Parser.Lex(); // Eat identifier token.
3168   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
3169   return MatchOperand_Success;
3170 }
3171
3172 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
3173 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3174 parseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3175   SMLoc S = Parser.getTok().getLoc();
3176   const AsmToken &Tok = Parser.getTok();
3177   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
3178   StringRef Mask = Tok.getString();
3179
3180   if (isMClass()) {
3181     // See ARMv6-M 10.1.1
3182     unsigned FlagsVal = StringSwitch<unsigned>(Mask)
3183       .Case("apsr", 0)
3184       .Case("iapsr", 1)
3185       .Case("eapsr", 2)
3186       .Case("xpsr", 3)
3187       .Case("ipsr", 5)
3188       .Case("epsr", 6)
3189       .Case("iepsr", 7)
3190       .Case("msp", 8)
3191       .Case("psp", 9)
3192       .Case("primask", 16)
3193       .Case("basepri", 17)
3194       .Case("basepri_max", 18)
3195       .Case("faultmask", 19)
3196       .Case("control", 20)
3197       .Default(~0U);
3198
3199     if (FlagsVal == ~0U)
3200       return MatchOperand_NoMatch;
3201
3202     if (!hasV7Ops() && FlagsVal >= 17 && FlagsVal <= 19)
3203       // basepri, basepri_max and faultmask only valid for V7m.
3204       return MatchOperand_NoMatch;
3205
3206     Parser.Lex(); // Eat identifier token.
3207     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
3208     return MatchOperand_Success;
3209   }
3210
3211   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
3212   size_t Start = 0, Next = Mask.find('_');
3213   StringRef Flags = "";
3214   std::string SpecReg = Mask.slice(Start, Next).lower();
3215   if (Next != StringRef::npos)
3216     Flags = Mask.slice(Next+1, Mask.size());
3217
3218   // FlagsVal contains the complete mask:
3219   // 3-0: Mask
3220   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
3221   unsigned FlagsVal = 0;
3222
3223   if (SpecReg == "apsr") {
3224     FlagsVal = StringSwitch<unsigned>(Flags)
3225     .Case("nzcvq",  0x8) // same as CPSR_f
3226     .Case("g",      0x4) // same as CPSR_s
3227     .Case("nzcvqg", 0xc) // same as CPSR_fs
3228     .Default(~0U);
3229
3230     if (FlagsVal == ~0U) {
3231       if (!Flags.empty())
3232         return MatchOperand_NoMatch;
3233       else
3234         FlagsVal = 8; // No flag
3235     }
3236   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
3237     if (Flags == "all") // cpsr_all is an alias for cpsr_fc
3238       Flags = "fc";
3239     for (int i = 0, e = Flags.size(); i != e; ++i) {
3240       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
3241       .Case("c", 1)
3242       .Case("x", 2)
3243       .Case("s", 4)
3244       .Case("f", 8)
3245       .Default(~0U);
3246
3247       // If some specific flag is already set, it means that some letter is
3248       // present more than once, this is not acceptable.
3249       if (FlagsVal == ~0U || (FlagsVal & Flag))
3250         return MatchOperand_NoMatch;
3251       FlagsVal |= Flag;
3252     }
3253   } else // No match for special register.
3254     return MatchOperand_NoMatch;
3255
3256   // Special register without flags is NOT equivalent to "fc" flags.
3257   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
3258   // two lines would enable gas compatibility at the expense of breaking
3259   // round-tripping.
3260   //
3261   // if (!FlagsVal)
3262   //  FlagsVal = 0x9;
3263
3264   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
3265   if (SpecReg == "spsr")
3266     FlagsVal |= 16;
3267
3268   Parser.Lex(); // Eat identifier token.
3269   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
3270   return MatchOperand_Success;
3271 }
3272
3273 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3274 parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands, StringRef Op,
3275             int Low, int High) {
3276   const AsmToken &Tok = Parser.getTok();
3277   if (Tok.isNot(AsmToken::Identifier)) {
3278     Error(Parser.getTok().getLoc(), Op + " operand expected.");
3279     return MatchOperand_ParseFail;
3280   }
3281   StringRef ShiftName = Tok.getString();
3282   std::string LowerOp = Op.lower();
3283   std::string UpperOp = Op.upper();
3284   if (ShiftName != LowerOp && ShiftName != UpperOp) {
3285     Error(Parser.getTok().getLoc(), Op + " operand expected.");
3286     return MatchOperand_ParseFail;
3287   }
3288   Parser.Lex(); // Eat shift type token.
3289
3290   // There must be a '#' and a shift amount.
3291   if (Parser.getTok().isNot(AsmToken::Hash) &&
3292       Parser.getTok().isNot(AsmToken::Dollar)) {
3293     Error(Parser.getTok().getLoc(), "'#' expected");
3294     return MatchOperand_ParseFail;
3295   }
3296   Parser.Lex(); // Eat hash token.
3297
3298   const MCExpr *ShiftAmount;
3299   SMLoc Loc = Parser.getTok().getLoc();
3300   if (getParser().ParseExpression(ShiftAmount)) {
3301     Error(Loc, "illegal expression");
3302     return MatchOperand_ParseFail;
3303   }
3304   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
3305   if (!CE) {
3306     Error(Loc, "constant expression expected");
3307     return MatchOperand_ParseFail;
3308   }
3309   int Val = CE->getValue();
3310   if (Val < Low || Val > High) {
3311     Error(Loc, "immediate value out of range");
3312     return MatchOperand_ParseFail;
3313   }
3314
3315   Operands.push_back(ARMOperand::CreateImm(CE, Loc, Parser.getTok().getLoc()));
3316
3317   return MatchOperand_Success;
3318 }
3319
3320 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3321 parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3322   const AsmToken &Tok = Parser.getTok();
3323   SMLoc S = Tok.getLoc();
3324   if (Tok.isNot(AsmToken::Identifier)) {
3325     Error(Tok.getLoc(), "'be' or 'le' operand expected");
3326     return MatchOperand_ParseFail;
3327   }
3328   int Val = StringSwitch<int>(Tok.getString())
3329     .Case("be", 1)
3330     .Case("le", 0)
3331     .Default(-1);
3332   Parser.Lex(); // Eat the token.
3333
3334   if (Val == -1) {
3335     Error(Tok.getLoc(), "'be' or 'le' operand expected");
3336     return MatchOperand_ParseFail;
3337   }
3338   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
3339                                                                   getContext()),
3340                                            S, Parser.getTok().getLoc()));
3341   return MatchOperand_Success;
3342 }
3343
3344 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
3345 /// instructions. Legal values are:
3346 ///     lsl #n  'n' in [0,31]
3347 ///     asr #n  'n' in [1,32]
3348 ///             n == 32 encoded as n == 0.
3349 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3350 parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3351   const AsmToken &Tok = Parser.getTok();
3352   SMLoc S = Tok.getLoc();
3353   if (Tok.isNot(AsmToken::Identifier)) {
3354     Error(S, "shift operator 'asr' or 'lsl' expected");
3355     return MatchOperand_ParseFail;
3356   }
3357   StringRef ShiftName = Tok.getString();
3358   bool isASR;
3359   if (ShiftName == "lsl" || ShiftName == "LSL")
3360     isASR = false;
3361   else if (ShiftName == "asr" || ShiftName == "ASR")
3362     isASR = true;
3363   else {
3364     Error(S, "shift operator 'asr' or 'lsl' expected");
3365     return MatchOperand_ParseFail;
3366   }
3367   Parser.Lex(); // Eat the operator.
3368
3369   // A '#' and a shift amount.
3370   if (Parser.getTok().isNot(AsmToken::Hash) &&
3371       Parser.getTok().isNot(AsmToken::Dollar)) {
3372     Error(Parser.getTok().getLoc(), "'#' expected");
3373     return MatchOperand_ParseFail;
3374   }
3375   Parser.Lex(); // Eat hash token.
3376
3377   const MCExpr *ShiftAmount;
3378   SMLoc E = Parser.getTok().getLoc();
3379   if (getParser().ParseExpression(ShiftAmount)) {
3380     Error(E, "malformed shift expression");
3381     return MatchOperand_ParseFail;
3382   }
3383   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
3384   if (!CE) {
3385     Error(E, "shift amount must be an immediate");
3386     return MatchOperand_ParseFail;
3387   }
3388
3389   int64_t Val = CE->getValue();
3390   if (isASR) {
3391     // Shift amount must be in [1,32]
3392     if (Val < 1 || Val > 32) {
3393       Error(E, "'asr' shift amount must be in range [1,32]");
3394       return MatchOperand_ParseFail;
3395     }
3396     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
3397     if (isThumb() && Val == 32) {
3398       Error(E, "'asr #32' shift amount not allowed in Thumb mode");
3399       return MatchOperand_ParseFail;
3400     }
3401     if (Val == 32) Val = 0;
3402   } else {
3403     // Shift amount must be in [1,32]
3404     if (Val < 0 || Val > 31) {
3405       Error(E, "'lsr' shift amount must be in range [0,31]");
3406       return MatchOperand_ParseFail;
3407     }
3408   }
3409
3410   E = Parser.getTok().getLoc();
3411   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, E));
3412
3413   return MatchOperand_Success;
3414 }
3415
3416 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
3417 /// of instructions. Legal values are:
3418 ///     ror #n  'n' in {0, 8, 16, 24}
3419 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3420 parseRotImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3421   const AsmToken &Tok = Parser.getTok();
3422   SMLoc S = Tok.getLoc();
3423   if (Tok.isNot(AsmToken::Identifier))
3424     return MatchOperand_NoMatch;
3425   StringRef ShiftName = Tok.getString();
3426   if (ShiftName != "ror" && ShiftName != "ROR")
3427     return MatchOperand_NoMatch;
3428   Parser.Lex(); // Eat the operator.
3429
3430   // A '#' and a rotate amount.
3431   if (Parser.getTok().isNot(AsmToken::Hash) &&
3432       Parser.getTok().isNot(AsmToken::Dollar)) {
3433     Error(Parser.getTok().getLoc(), "'#' expected");
3434     return MatchOperand_ParseFail;
3435   }
3436   Parser.Lex(); // Eat hash token.
3437
3438   const MCExpr *ShiftAmount;
3439   SMLoc E = Parser.getTok().getLoc();
3440   if (getParser().ParseExpression(ShiftAmount)) {
3441     Error(E, "malformed rotate expression");
3442     return MatchOperand_ParseFail;
3443   }
3444   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
3445   if (!CE) {
3446     Error(E, "rotate amount must be an immediate");
3447     return MatchOperand_ParseFail;
3448   }
3449
3450   int64_t Val = CE->getValue();
3451   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
3452   // normally, zero is represented in asm by omitting the rotate operand
3453   // entirely.
3454   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
3455     Error(E, "'ror' rotate amount must be 8, 16, or 24");
3456     return MatchOperand_ParseFail;
3457   }
3458
3459   E = Parser.getTok().getLoc();
3460   Operands.push_back(ARMOperand::CreateRotImm(Val, S, E));
3461
3462   return MatchOperand_Success;
3463 }
3464
3465 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3466 parseBitfield(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3467   SMLoc S = Parser.getTok().getLoc();
3468   // The bitfield descriptor is really two operands, the LSB and the width.
3469   if (Parser.getTok().isNot(AsmToken::Hash) &&
3470       Parser.getTok().isNot(AsmToken::Dollar)) {
3471     Error(Parser.getTok().getLoc(), "'#' expected");
3472     return MatchOperand_ParseFail;
3473   }
3474   Parser.Lex(); // Eat hash token.
3475
3476   const MCExpr *LSBExpr;
3477   SMLoc E = Parser.getTok().getLoc();
3478   if (getParser().ParseExpression(LSBExpr)) {
3479     Error(E, "malformed immediate expression");
3480     return MatchOperand_ParseFail;
3481   }
3482   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
3483   if (!CE) {
3484     Error(E, "'lsb' operand must be an immediate");
3485     return MatchOperand_ParseFail;
3486   }
3487
3488   int64_t LSB = CE->getValue();
3489   // The LSB must be in the range [0,31]
3490   if (LSB < 0 || LSB > 31) {
3491     Error(E, "'lsb' operand must be in the range [0,31]");
3492     return MatchOperand_ParseFail;
3493   }
3494   E = Parser.getTok().getLoc();
3495
3496   // Expect another immediate operand.
3497   if (Parser.getTok().isNot(AsmToken::Comma)) {
3498     Error(Parser.getTok().getLoc(), "too few operands");
3499     return MatchOperand_ParseFail;
3500   }
3501   Parser.Lex(); // Eat hash token.
3502   if (Parser.getTok().isNot(AsmToken::Hash) &&
3503       Parser.getTok().isNot(AsmToken::Dollar)) {
3504     Error(Parser.getTok().getLoc(), "'#' expected");
3505     return MatchOperand_ParseFail;
3506   }
3507   Parser.Lex(); // Eat hash token.
3508
3509   const MCExpr *WidthExpr;
3510   if (getParser().ParseExpression(WidthExpr)) {
3511     Error(E, "malformed immediate expression");
3512     return MatchOperand_ParseFail;
3513   }
3514   CE = dyn_cast<MCConstantExpr>(WidthExpr);
3515   if (!CE) {
3516     Error(E, "'width' operand must be an immediate");
3517     return MatchOperand_ParseFail;
3518   }
3519
3520   int64_t Width = CE->getValue();
3521   // The LSB must be in the range [1,32-lsb]
3522   if (Width < 1 || Width > 32 - LSB) {
3523     Error(E, "'width' operand must be in the range [1,32-lsb]");
3524     return MatchOperand_ParseFail;
3525   }
3526   E = Parser.getTok().getLoc();
3527
3528   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, E));
3529
3530   return MatchOperand_Success;
3531 }
3532
3533 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3534 parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3535   // Check for a post-index addressing register operand. Specifically:
3536   // postidx_reg := '+' register {, shift}
3537   //              | '-' register {, shift}
3538   //              | register {, shift}
3539
3540   // This method must return MatchOperand_NoMatch without consuming any tokens
3541   // in the case where there is no match, as other alternatives take other
3542   // parse methods.
3543   AsmToken Tok = Parser.getTok();
3544   SMLoc S = Tok.getLoc();
3545   bool haveEaten = false;
3546   bool isAdd = true;
3547   int Reg = -1;
3548   if (Tok.is(AsmToken::Plus)) {
3549     Parser.Lex(); // Eat the '+' token.
3550     haveEaten = true;
3551   } else if (Tok.is(AsmToken::Minus)) {
3552     Parser.Lex(); // Eat the '-' token.
3553     isAdd = false;
3554     haveEaten = true;
3555   }
3556   if (Parser.getTok().is(AsmToken::Identifier))
3557     Reg = tryParseRegister();
3558   if (Reg == -1) {
3559     if (!haveEaten)
3560       return MatchOperand_NoMatch;
3561     Error(Parser.getTok().getLoc(), "register expected");
3562     return MatchOperand_ParseFail;
3563   }
3564   SMLoc E = Parser.getTok().getLoc();
3565
3566   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
3567   unsigned ShiftImm = 0;
3568   if (Parser.getTok().is(AsmToken::Comma)) {
3569     Parser.Lex(); // Eat the ','.
3570     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
3571       return MatchOperand_ParseFail;
3572   }
3573
3574   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
3575                                                   ShiftImm, S, E));
3576
3577   return MatchOperand_Success;
3578 }
3579
3580 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3581 parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3582   // Check for a post-index addressing register operand. Specifically:
3583   // am3offset := '+' register
3584   //              | '-' register
3585   //              | register
3586   //              | # imm
3587   //              | # + imm
3588   //              | # - imm
3589
3590   // This method must return MatchOperand_NoMatch without consuming any tokens
3591   // in the case where there is no match, as other alternatives take other
3592   // parse methods.
3593   AsmToken Tok = Parser.getTok();
3594   SMLoc S = Tok.getLoc();
3595
3596   // Do immediates first, as we always parse those if we have a '#'.
3597   if (Parser.getTok().is(AsmToken::Hash) ||
3598       Parser.getTok().is(AsmToken::Dollar)) {
3599     Parser.Lex(); // Eat the '#'.
3600     // Explicitly look for a '-', as we need to encode negative zero
3601     // differently.
3602     bool isNegative = Parser.getTok().is(AsmToken::Minus);
3603     const MCExpr *Offset;
3604     if (getParser().ParseExpression(Offset))
3605       return MatchOperand_ParseFail;
3606     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
3607     if (!CE) {
3608       Error(S, "constant expression expected");
3609       return MatchOperand_ParseFail;
3610     }
3611     SMLoc E = Tok.getLoc();
3612     // Negative zero is encoded as the flag value INT32_MIN.
3613     int32_t Val = CE->getValue();
3614     if (isNegative && Val == 0)
3615       Val = INT32_MIN;
3616
3617     Operands.push_back(
3618       ARMOperand::CreateImm(MCConstantExpr::Create(Val, getContext()), S, E));
3619
3620     return MatchOperand_Success;
3621   }
3622
3623
3624   bool haveEaten = false;
3625   bool isAdd = true;
3626   int Reg = -1;
3627   if (Tok.is(AsmToken::Plus)) {
3628     Parser.Lex(); // Eat the '+' token.
3629     haveEaten = true;
3630   } else if (Tok.is(AsmToken::Minus)) {
3631     Parser.Lex(); // Eat the '-' token.
3632     isAdd = false;
3633     haveEaten = true;
3634   }
3635   if (Parser.getTok().is(AsmToken::Identifier))
3636     Reg = tryParseRegister();
3637   if (Reg == -1) {
3638     if (!haveEaten)
3639       return MatchOperand_NoMatch;
3640     Error(Parser.getTok().getLoc(), "register expected");
3641     return MatchOperand_ParseFail;
3642   }
3643   SMLoc E = Parser.getTok().getLoc();
3644
3645   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
3646                                                   0, S, E));
3647
3648   return MatchOperand_Success;
3649 }
3650
3651 /// cvtT2LdrdPre - Convert parsed operands to MCInst.
3652 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3653 /// when they refer multiple MIOperands inside a single one.
3654 bool ARMAsmParser::
3655 cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
3656              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3657   // Rt, Rt2
3658   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3659   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
3660   // Create a writeback register dummy placeholder.
3661   Inst.addOperand(MCOperand::CreateReg(0));
3662   // addr
3663   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
3664   // pred
3665   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3666   return true;
3667 }
3668
3669 /// cvtT2StrdPre - Convert parsed operands to MCInst.
3670 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3671 /// when they refer multiple MIOperands inside a single one.
3672 bool ARMAsmParser::
3673 cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
3674              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3675   // Create a writeback register dummy placeholder.
3676   Inst.addOperand(MCOperand::CreateReg(0));
3677   // Rt, Rt2
3678   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3679   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
3680   // addr
3681   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
3682   // pred
3683   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3684   return true;
3685 }
3686
3687 /// cvtLdWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
3688 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3689 /// when they refer multiple MIOperands inside a single one.
3690 bool ARMAsmParser::
3691 cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
3692                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3693   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3694
3695   // Create a writeback register dummy placeholder.
3696   Inst.addOperand(MCOperand::CreateImm(0));
3697
3698   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
3699   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3700   return true;
3701 }
3702
3703 /// cvtStWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
3704 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3705 /// when they refer multiple MIOperands inside a single one.
3706 bool ARMAsmParser::
3707 cvtStWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
3708                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3709   // Create a writeback register dummy placeholder.
3710   Inst.addOperand(MCOperand::CreateImm(0));
3711   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3712   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
3713   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3714   return true;
3715 }
3716
3717 /// cvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
3718 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3719 /// when they refer multiple MIOperands inside a single one.
3720 bool ARMAsmParser::
3721 cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
3722                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3723   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3724
3725   // Create a writeback register dummy placeholder.
3726   Inst.addOperand(MCOperand::CreateImm(0));
3727
3728   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
3729   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3730   return true;
3731 }
3732
3733 /// cvtLdWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
3734 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3735 /// when they refer multiple MIOperands inside a single one.
3736 bool ARMAsmParser::
3737 cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
3738                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3739   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3740
3741   // Create a writeback register dummy placeholder.
3742   Inst.addOperand(MCOperand::CreateImm(0));
3743
3744   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
3745   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3746   return true;
3747 }
3748
3749
3750 /// cvtStWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
3751 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3752 /// when they refer multiple MIOperands inside a single one.
3753 bool ARMAsmParser::
3754 cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
3755                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3756   // Create a writeback register dummy placeholder.
3757   Inst.addOperand(MCOperand::CreateImm(0));
3758   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3759   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
3760   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3761   return true;
3762 }
3763
3764 /// cvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
3765 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3766 /// when they refer multiple MIOperands inside a single one.
3767 bool ARMAsmParser::
3768 cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
3769                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3770   // Create a writeback register dummy placeholder.
3771   Inst.addOperand(MCOperand::CreateImm(0));
3772   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3773   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
3774   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3775   return true;
3776 }
3777
3778 /// cvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
3779 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3780 /// when they refer multiple MIOperands inside a single one.
3781 bool ARMAsmParser::
3782 cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
3783                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3784   // Create a writeback register dummy placeholder.
3785   Inst.addOperand(MCOperand::CreateImm(0));
3786   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3787   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
3788   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3789   return true;
3790 }
3791
3792 /// cvtLdExtTWriteBackImm - Convert parsed operands to MCInst.
3793 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3794 /// when they refer multiple MIOperands inside a single one.
3795 bool ARMAsmParser::
3796 cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
3797                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3798   // Rt
3799   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3800   // Create a writeback register dummy placeholder.
3801   Inst.addOperand(MCOperand::CreateImm(0));
3802   // addr
3803   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
3804   // offset
3805   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
3806   // pred
3807   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3808   return true;
3809 }
3810
3811 /// cvtLdExtTWriteBackReg - Convert parsed operands to MCInst.
3812 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3813 /// when they refer multiple MIOperands inside a single one.
3814 bool ARMAsmParser::
3815 cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
3816                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3817   // Rt
3818   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3819   // Create a writeback register dummy placeholder.
3820   Inst.addOperand(MCOperand::CreateImm(0));
3821   // addr
3822   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
3823   // offset
3824   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
3825   // pred
3826   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3827   return true;
3828 }
3829
3830 /// cvtStExtTWriteBackImm - Convert parsed operands to MCInst.
3831 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3832 /// when they refer multiple MIOperands inside a single one.
3833 bool ARMAsmParser::
3834 cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
3835                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3836   // Create a writeback register dummy placeholder.
3837   Inst.addOperand(MCOperand::CreateImm(0));
3838   // Rt
3839   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3840   // addr
3841   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
3842   // offset
3843   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
3844   // pred
3845   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3846   return true;
3847 }
3848
3849 /// cvtStExtTWriteBackReg - Convert parsed operands to MCInst.
3850 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3851 /// when they refer multiple MIOperands inside a single one.
3852 bool ARMAsmParser::
3853 cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
3854                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3855   // Create a writeback register dummy placeholder.
3856   Inst.addOperand(MCOperand::CreateImm(0));
3857   // Rt
3858   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3859   // addr
3860   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
3861   // offset
3862   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
3863   // pred
3864   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3865   return true;
3866 }
3867
3868 /// cvtLdrdPre - Convert parsed operands to MCInst.
3869 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3870 /// when they refer multiple MIOperands inside a single one.
3871 bool ARMAsmParser::
3872 cvtLdrdPre(MCInst &Inst, unsigned Opcode,
3873            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3874   // Rt, Rt2
3875   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3876   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
3877   // Create a writeback register dummy placeholder.
3878   Inst.addOperand(MCOperand::CreateImm(0));
3879   // addr
3880   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
3881   // pred
3882   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3883   return true;
3884 }
3885
3886 /// cvtStrdPre - Convert parsed operands to MCInst.
3887 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3888 /// when they refer multiple MIOperands inside a single one.
3889 bool ARMAsmParser::
3890 cvtStrdPre(MCInst &Inst, unsigned Opcode,
3891            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3892   // Create a writeback register dummy placeholder.
3893   Inst.addOperand(MCOperand::CreateImm(0));
3894   // Rt, Rt2
3895   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3896   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
3897   // addr
3898   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
3899   // pred
3900   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3901   return true;
3902 }
3903
3904 /// cvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
3905 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3906 /// when they refer multiple MIOperands inside a single one.
3907 bool ARMAsmParser::
3908 cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
3909                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3910   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3911   // Create a writeback register dummy placeholder.
3912   Inst.addOperand(MCOperand::CreateImm(0));
3913   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
3914   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3915   return true;
3916 }
3917
3918 /// cvtThumbMultiple- Convert parsed operands to MCInst.
3919 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3920 /// when they refer multiple MIOperands inside a single one.
3921 bool ARMAsmParser::
3922 cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
3923            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3924   // The second source operand must be the same register as the destination
3925   // operand.
3926   if (Operands.size() == 6 &&
3927       (((ARMOperand*)Operands[3])->getReg() !=
3928        ((ARMOperand*)Operands[5])->getReg()) &&
3929       (((ARMOperand*)Operands[3])->getReg() !=
3930        ((ARMOperand*)Operands[4])->getReg())) {
3931     Error(Operands[3]->getStartLoc(),
3932           "destination register must match source register");
3933     return false;
3934   }
3935   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
3936   ((ARMOperand*)Operands[1])->addCCOutOperands(Inst, 1);
3937   // If we have a three-operand form, make sure to set Rn to be the operand
3938   // that isn't the same as Rd.
3939   unsigned RegOp = 4;
3940   if (Operands.size() == 6 &&
3941       ((ARMOperand*)Operands[4])->getReg() ==
3942         ((ARMOperand*)Operands[3])->getReg())
3943     RegOp = 5;
3944   ((ARMOperand*)Operands[RegOp])->addRegOperands(Inst, 1);
3945   Inst.addOperand(Inst.getOperand(0));
3946   ((ARMOperand*)Operands[2])->addCondCodeOperands(Inst, 2);
3947
3948   return true;
3949 }
3950
3951 bool ARMAsmParser::
3952 cvtVLDwbFixed(MCInst &Inst, unsigned Opcode,
3953               const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3954   // Vd
3955   ((ARMOperand*)Operands[3])->addVecListOperands(Inst, 1);
3956   // Create a writeback register dummy placeholder.
3957   Inst.addOperand(MCOperand::CreateImm(0));
3958   // Vn
3959   ((ARMOperand*)Operands[4])->addAlignedMemoryOperands(Inst, 2);
3960   // pred
3961   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3962   return true;
3963 }
3964
3965 bool ARMAsmParser::
3966 cvtVLDwbRegister(MCInst &Inst, unsigned Opcode,
3967                  const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3968   // Vd
3969   ((ARMOperand*)Operands[3])->addVecListOperands(Inst, 1);
3970   // Create a writeback register dummy placeholder.
3971   Inst.addOperand(MCOperand::CreateImm(0));
3972   // Vn
3973   ((ARMOperand*)Operands[4])->addAlignedMemoryOperands(Inst, 2);
3974   // Vm
3975   ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
3976   // pred
3977   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3978   return true;
3979 }
3980
3981 bool ARMAsmParser::
3982 cvtVSTwbFixed(MCInst &Inst, unsigned Opcode,
3983               const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3984   // Create a writeback register dummy placeholder.
3985   Inst.addOperand(MCOperand::CreateImm(0));
3986   // Vn
3987   ((ARMOperand*)Operands[4])->addAlignedMemoryOperands(Inst, 2);
3988   // Vt
3989   ((ARMOperand*)Operands[3])->addVecListOperands(Inst, 1);
3990   // pred
3991   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3992   return true;
3993 }
3994
3995 bool ARMAsmParser::
3996 cvtVSTwbRegister(MCInst &Inst, unsigned Opcode,
3997                  const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3998   // Create a writeback register dummy placeholder.
3999   Inst.addOperand(MCOperand::CreateImm(0));
4000   // Vn
4001   ((ARMOperand*)Operands[4])->addAlignedMemoryOperands(Inst, 2);
4002   // Vm
4003   ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
4004   // Vt
4005   ((ARMOperand*)Operands[3])->addVecListOperands(Inst, 1);
4006   // pred
4007   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
4008   return true;
4009 }
4010
4011 /// Parse an ARM memory expression, return false if successful else return true
4012 /// or an error.  The first token must be a '[' when called.
4013 bool ARMAsmParser::
4014 parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
4015   SMLoc S, E;
4016   assert(Parser.getTok().is(AsmToken::LBrac) &&
4017          "Token is not a Left Bracket");
4018   S = Parser.getTok().getLoc();
4019   Parser.Lex(); // Eat left bracket token.
4020
4021   const AsmToken &BaseRegTok = Parser.getTok();
4022   int BaseRegNum = tryParseRegister();
4023   if (BaseRegNum == -1)
4024     return Error(BaseRegTok.getLoc(), "register expected");
4025
4026   // The next token must either be a comma or a closing bracket.
4027   const AsmToken &Tok = Parser.getTok();
4028   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
4029     return Error(Tok.getLoc(), "malformed memory operand");
4030
4031   if (Tok.is(AsmToken::RBrac)) {
4032     E = Tok.getLoc();
4033     Parser.Lex(); // Eat right bracket token.
4034
4035     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, 0, ARM_AM::no_shift,
4036                                              0, 0, false, S, E));
4037
4038     // If there's a pre-indexing writeback marker, '!', just add it as a token
4039     // operand. It's rather odd, but syntactically valid.
4040     if (Parser.getTok().is(AsmToken::Exclaim)) {
4041       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4042       Parser.Lex(); // Eat the '!'.
4043     }
4044
4045     return false;
4046   }
4047
4048   assert(Tok.is(AsmToken::Comma) && "Lost comma in memory operand?!");
4049   Parser.Lex(); // Eat the comma.
4050
4051   // If we have a ':', it's an alignment specifier.
4052   if (Parser.getTok().is(AsmToken::Colon)) {
4053     Parser.Lex(); // Eat the ':'.
4054     E = Parser.getTok().getLoc();
4055
4056     const MCExpr *Expr;
4057     if (getParser().ParseExpression(Expr))
4058      return true;
4059
4060     // The expression has to be a constant. Memory references with relocations
4061     // don't come through here, as they use the <label> forms of the relevant
4062     // instructions.
4063     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4064     if (!CE)
4065       return Error (E, "constant expression expected");
4066
4067     unsigned Align = 0;
4068     switch (CE->getValue()) {
4069     default:
4070       return Error(E,
4071                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4072     case 16:  Align = 2; break;
4073     case 32:  Align = 4; break;
4074     case 64:  Align = 8; break;
4075     case 128: Align = 16; break;
4076     case 256: Align = 32; break;
4077     }
4078
4079     // Now we should have the closing ']'
4080     E = Parser.getTok().getLoc();
4081     if (Parser.getTok().isNot(AsmToken::RBrac))
4082       return Error(E, "']' expected");
4083     Parser.Lex(); // Eat right bracket token.
4084
4085     // Don't worry about range checking the value here. That's handled by
4086     // the is*() predicates.
4087     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, 0,
4088                                              ARM_AM::no_shift, 0, Align,
4089                                              false, S, E));
4090
4091     // If there's a pre-indexing writeback marker, '!', just add it as a token
4092     // operand.
4093     if (Parser.getTok().is(AsmToken::Exclaim)) {
4094       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4095       Parser.Lex(); // Eat the '!'.
4096     }
4097
4098     return false;
4099   }
4100
4101   // If we have a '#', it's an immediate offset, else assume it's a register
4102   // offset. Be friendly and also accept a plain integer (without a leading
4103   // hash) for gas compatibility.
4104   if (Parser.getTok().is(AsmToken::Hash) ||
4105       Parser.getTok().is(AsmToken::Dollar) ||
4106       Parser.getTok().is(AsmToken::Integer)) {
4107     if (Parser.getTok().isNot(AsmToken::Integer))
4108       Parser.Lex(); // Eat the '#'.
4109     E = Parser.getTok().getLoc();
4110
4111     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4112     const MCExpr *Offset;
4113     if (getParser().ParseExpression(Offset))
4114      return true;
4115
4116     // The expression has to be a constant. Memory references with relocations
4117     // don't come through here, as they use the <label> forms of the relevant
4118     // instructions.
4119     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4120     if (!CE)
4121       return Error (E, "constant expression expected");
4122
4123     // If the constant was #-0, represent it as INT32_MIN.
4124     int32_t Val = CE->getValue();
4125     if (isNegative && Val == 0)
4126       CE = MCConstantExpr::Create(INT32_MIN, getContext());
4127
4128     // Now we should have the closing ']'
4129     E = Parser.getTok().getLoc();
4130     if (Parser.getTok().isNot(AsmToken::RBrac))
4131       return Error(E, "']' expected");
4132     Parser.Lex(); // Eat right bracket token.
4133
4134     // Don't worry about range checking the value here. That's handled by
4135     // the is*() predicates.
4136     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4137                                              ARM_AM::no_shift, 0, 0,
4138                                              false, S, E));
4139
4140     // If there's a pre-indexing writeback marker, '!', just add it as a token
4141     // operand.
4142     if (Parser.getTok().is(AsmToken::Exclaim)) {
4143       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4144       Parser.Lex(); // Eat the '!'.
4145     }
4146
4147     return false;
4148   }
4149
4150   // The register offset is optionally preceded by a '+' or '-'
4151   bool isNegative = false;
4152   if (Parser.getTok().is(AsmToken::Minus)) {
4153     isNegative = true;
4154     Parser.Lex(); // Eat the '-'.
4155   } else if (Parser.getTok().is(AsmToken::Plus)) {
4156     // Nothing to do.
4157     Parser.Lex(); // Eat the '+'.
4158   }
4159
4160   E = Parser.getTok().getLoc();
4161   int OffsetRegNum = tryParseRegister();
4162   if (OffsetRegNum == -1)
4163     return Error(E, "register expected");
4164
4165   // If there's a shift operator, handle it.
4166   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4167   unsigned ShiftImm = 0;
4168   if (Parser.getTok().is(AsmToken::Comma)) {
4169     Parser.Lex(); // Eat the ','.
4170     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4171       return true;
4172   }
4173
4174   // Now we should have the closing ']'
4175   E = Parser.getTok().getLoc();
4176   if (Parser.getTok().isNot(AsmToken::RBrac))
4177     return Error(E, "']' expected");
4178   Parser.Lex(); // Eat right bracket token.
4179
4180   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, OffsetRegNum,
4181                                            ShiftType, ShiftImm, 0, isNegative,
4182                                            S, E));
4183
4184   // If there's a pre-indexing writeback marker, '!', just add it as a token
4185   // operand.
4186   if (Parser.getTok().is(AsmToken::Exclaim)) {
4187     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4188     Parser.Lex(); // Eat the '!'.
4189   }
4190
4191   return false;
4192 }
4193
4194 /// parseMemRegOffsetShift - one of these two:
4195 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4196 ///   rrx
4197 /// return true if it parses a shift otherwise it returns false.
4198 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4199                                           unsigned &Amount) {
4200   SMLoc Loc = Parser.getTok().getLoc();
4201   const AsmToken &Tok = Parser.getTok();
4202   if (Tok.isNot(AsmToken::Identifier))
4203     return true;
4204   StringRef ShiftName = Tok.getString();
4205   if (ShiftName == "lsl" || ShiftName == "LSL" ||
4206       ShiftName == "asl" || ShiftName == "ASL")
4207     St = ARM_AM::lsl;
4208   else if (ShiftName == "lsr" || ShiftName == "LSR")
4209     St = ARM_AM::lsr;
4210   else if (ShiftName == "asr" || ShiftName == "ASR")
4211     St = ARM_AM::asr;
4212   else if (ShiftName == "ror" || ShiftName == "ROR")
4213     St = ARM_AM::ror;
4214   else if (ShiftName == "rrx" || ShiftName == "RRX")
4215     St = ARM_AM::rrx;
4216   else
4217     return Error(Loc, "illegal shift operator");
4218   Parser.Lex(); // Eat shift type token.
4219
4220   // rrx stands alone.
4221   Amount = 0;
4222   if (St != ARM_AM::rrx) {
4223     Loc = Parser.getTok().getLoc();
4224     // A '#' and a shift amount.
4225     const AsmToken &HashTok = Parser.getTok();
4226     if (HashTok.isNot(AsmToken::Hash) &&
4227         HashTok.isNot(AsmToken::Dollar))
4228       return Error(HashTok.getLoc(), "'#' expected");
4229     Parser.Lex(); // Eat hash token.
4230
4231     const MCExpr *Expr;
4232     if (getParser().ParseExpression(Expr))
4233       return true;
4234     // Range check the immediate.
4235     // lsl, ror: 0 <= imm <= 31
4236     // lsr, asr: 0 <= imm <= 32
4237     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4238     if (!CE)
4239       return Error(Loc, "shift amount must be an immediate");
4240     int64_t Imm = CE->getValue();
4241     if (Imm < 0 ||
4242         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
4243         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
4244       return Error(Loc, "immediate shift value out of range");
4245     Amount = Imm;
4246   }
4247
4248   return false;
4249 }
4250
4251 /// parseFPImm - A floating point immediate expression operand.
4252 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
4253 parseFPImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
4254   // Anything that can accept a floating point constant as an operand
4255   // needs to go through here, as the regular ParseExpression is
4256   // integer only.
4257   //
4258   // This routine still creates a generic Immediate operand, containing
4259   // a bitcast of the 64-bit floating point value. The various operands
4260   // that accept floats can check whether the value is valid for them
4261   // via the standard is*() predicates.
4262
4263   SMLoc S = Parser.getTok().getLoc();
4264
4265   if (Parser.getTok().isNot(AsmToken::Hash) &&
4266       Parser.getTok().isNot(AsmToken::Dollar))
4267     return MatchOperand_NoMatch;
4268
4269   // Disambiguate the VMOV forms that can accept an FP immediate.
4270   // vmov.f32 <sreg>, #imm
4271   // vmov.f64 <dreg>, #imm
4272   // vmov.f32 <dreg>, #imm  @ vector f32x2
4273   // vmov.f32 <qreg>, #imm  @ vector f32x4
4274   //
4275   // There are also the NEON VMOV instructions which expect an
4276   // integer constant. Make sure we don't try to parse an FPImm
4277   // for these:
4278   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
4279   ARMOperand *TyOp = static_cast<ARMOperand*>(Operands[2]);
4280   if (!TyOp->isToken() || (TyOp->getToken() != ".f32" &&
4281                            TyOp->getToken() != ".f64"))
4282     return MatchOperand_NoMatch;
4283
4284   Parser.Lex(); // Eat the '#'.
4285
4286   // Handle negation, as that still comes through as a separate token.
4287   bool isNegative = false;
4288   if (Parser.getTok().is(AsmToken::Minus)) {
4289     isNegative = true;
4290     Parser.Lex();
4291   }
4292   const AsmToken &Tok = Parser.getTok();
4293   SMLoc Loc = Tok.getLoc();
4294   if (Tok.is(AsmToken::Real)) {
4295     APFloat RealVal(APFloat::IEEEsingle, Tok.getString());
4296     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
4297     // If we had a '-' in front, toggle the sign bit.
4298     IntVal ^= (uint64_t)isNegative << 31;
4299     Parser.Lex(); // Eat the token.
4300     Operands.push_back(ARMOperand::CreateImm(
4301           MCConstantExpr::Create(IntVal, getContext()),
4302           S, Parser.getTok().getLoc()));
4303     return MatchOperand_Success;
4304   }
4305   // Also handle plain integers. Instructions which allow floating point
4306   // immediates also allow a raw encoded 8-bit value.
4307   if (Tok.is(AsmToken::Integer)) {
4308     int64_t Val = Tok.getIntVal();
4309     Parser.Lex(); // Eat the token.
4310     if (Val > 255 || Val < 0) {
4311       Error(Loc, "encoded floating point value out of range");
4312       return MatchOperand_ParseFail;
4313     }
4314     double RealVal = ARM_AM::getFPImmFloat(Val);
4315     Val = APFloat(APFloat::IEEEdouble, RealVal).bitcastToAPInt().getZExtValue();
4316     Operands.push_back(ARMOperand::CreateImm(
4317         MCConstantExpr::Create(Val, getContext()), S,
4318         Parser.getTok().getLoc()));
4319     return MatchOperand_Success;
4320   }
4321
4322   Error(Loc, "invalid floating point immediate");
4323   return MatchOperand_ParseFail;
4324 }
4325
4326 /// Parse a arm instruction operand.  For now this parses the operand regardless
4327 /// of the mnemonic.
4328 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
4329                                 StringRef Mnemonic) {
4330   SMLoc S, E;
4331
4332   // Check if the current operand has a custom associated parser, if so, try to
4333   // custom parse the operand, or fallback to the general approach.
4334   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
4335   if (ResTy == MatchOperand_Success)
4336     return false;
4337   // If there wasn't a custom match, try the generic matcher below. Otherwise,
4338   // there was a match, but an error occurred, in which case, just return that
4339   // the operand parsing failed.
4340   if (ResTy == MatchOperand_ParseFail)
4341     return true;
4342
4343   switch (getLexer().getKind()) {
4344   default:
4345     Error(Parser.getTok().getLoc(), "unexpected token in operand");
4346     return true;
4347   case AsmToken::Identifier: {
4348     if (!tryParseRegisterWithWriteBack(Operands))
4349       return false;
4350     int Res = tryParseShiftRegister(Operands);
4351     if (Res == 0) // success
4352       return false;
4353     else if (Res == -1) // irrecoverable error
4354       return true;
4355     // If this is VMRS, check for the apsr_nzcv operand.
4356     if (Mnemonic == "vmrs" && Parser.getTok().getString() == "apsr_nzcv") {
4357       S = Parser.getTok().getLoc();
4358       Parser.Lex();
4359       Operands.push_back(ARMOperand::CreateToken("apsr_nzcv", S));
4360       return false;
4361     }
4362
4363     // Fall though for the Identifier case that is not a register or a
4364     // special name.
4365   }
4366   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
4367   case AsmToken::Integer: // things like 1f and 2b as a branch targets
4368   case AsmToken::String:  // quoted label names.
4369   case AsmToken::Dot: {   // . as a branch target
4370     // This was not a register so parse other operands that start with an
4371     // identifier (like labels) as expressions and create them as immediates.
4372     const MCExpr *IdVal;
4373     S = Parser.getTok().getLoc();
4374     if (getParser().ParseExpression(IdVal))
4375       return true;
4376     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4377     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
4378     return false;
4379   }
4380   case AsmToken::LBrac:
4381     return parseMemory(Operands);
4382   case AsmToken::LCurly:
4383     return parseRegisterList(Operands);
4384   case AsmToken::Dollar:
4385   case AsmToken::Hash: {
4386     // #42 -> immediate.
4387     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
4388     S = Parser.getTok().getLoc();
4389     Parser.Lex();
4390     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4391     const MCExpr *ImmVal;
4392     if (getParser().ParseExpression(ImmVal))
4393       return true;
4394     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
4395     if (CE) {
4396       int32_t Val = CE->getValue();
4397       if (isNegative && Val == 0)
4398         ImmVal = MCConstantExpr::Create(INT32_MIN, getContext());
4399     }
4400     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4401     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
4402     return false;
4403   }
4404   case AsmToken::Colon: {
4405     // ":lower16:" and ":upper16:" expression prefixes
4406     // FIXME: Check it's an expression prefix,
4407     // e.g. (FOO - :lower16:BAR) isn't legal.
4408     ARMMCExpr::VariantKind RefKind;
4409     if (parsePrefix(RefKind))
4410       return true;
4411
4412     const MCExpr *SubExprVal;
4413     if (getParser().ParseExpression(SubExprVal))
4414       return true;
4415
4416     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
4417                                                    getContext());
4418     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
4419     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
4420     return false;
4421   }
4422   }
4423 }
4424
4425 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
4426 //  :lower16: and :upper16:.
4427 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
4428   RefKind = ARMMCExpr::VK_ARM_None;
4429
4430   // :lower16: and :upper16: modifiers
4431   assert(getLexer().is(AsmToken::Colon) && "expected a :");
4432   Parser.Lex(); // Eat ':'
4433
4434   if (getLexer().isNot(AsmToken::Identifier)) {
4435     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
4436     return true;
4437   }
4438
4439   StringRef IDVal = Parser.getTok().getIdentifier();
4440   if (IDVal == "lower16") {
4441     RefKind = ARMMCExpr::VK_ARM_LO16;
4442   } else if (IDVal == "upper16") {
4443     RefKind = ARMMCExpr::VK_ARM_HI16;
4444   } else {
4445     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
4446     return true;
4447   }
4448   Parser.Lex();
4449
4450   if (getLexer().isNot(AsmToken::Colon)) {
4451     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
4452     return true;
4453   }
4454   Parser.Lex(); // Eat the last ':'
4455   return false;
4456 }
4457
4458 /// \brief Given a mnemonic, split out possible predication code and carry
4459 /// setting letters to form a canonical mnemonic and flags.
4460 //
4461 // FIXME: Would be nice to autogen this.
4462 // FIXME: This is a bit of a maze of special cases.
4463 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
4464                                       unsigned &PredicationCode,
4465                                       bool &CarrySetting,
4466                                       unsigned &ProcessorIMod,
4467                                       StringRef &ITMask) {
4468   PredicationCode = ARMCC::AL;
4469   CarrySetting = false;
4470   ProcessorIMod = 0;
4471
4472   // Ignore some mnemonics we know aren't predicated forms.
4473   //
4474   // FIXME: Would be nice to autogen this.
4475   if ((Mnemonic == "movs" && isThumb()) ||
4476       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
4477       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
4478       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
4479       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
4480       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
4481       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
4482       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
4483       Mnemonic == "fmuls")
4484     return Mnemonic;
4485
4486   // First, split out any predication code. Ignore mnemonics we know aren't
4487   // predicated but do have a carry-set and so weren't caught above.
4488   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
4489       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
4490       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
4491       Mnemonic != "sbcs" && Mnemonic != "rscs") {
4492     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
4493       .Case("eq", ARMCC::EQ)
4494       .Case("ne", ARMCC::NE)
4495       .Case("hs", ARMCC::HS)
4496       .Case("cs", ARMCC::HS)
4497       .Case("lo", ARMCC::LO)
4498       .Case("cc", ARMCC::LO)
4499       .Case("mi", ARMCC::MI)
4500       .Case("pl", ARMCC::PL)
4501       .Case("vs", ARMCC::VS)
4502       .Case("vc", ARMCC::VC)
4503       .Case("hi", ARMCC::HI)
4504       .Case("ls", ARMCC::LS)
4505       .Case("ge", ARMCC::GE)
4506       .Case("lt", ARMCC::LT)
4507       .Case("gt", ARMCC::GT)
4508       .Case("le", ARMCC::LE)
4509       .Case("al", ARMCC::AL)
4510       .Default(~0U);
4511     if (CC != ~0U) {
4512       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
4513       PredicationCode = CC;
4514     }
4515   }
4516
4517   // Next, determine if we have a carry setting bit. We explicitly ignore all
4518   // the instructions we know end in 's'.
4519   if (Mnemonic.endswith("s") &&
4520       !(Mnemonic == "cps" || Mnemonic == "mls" ||
4521         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
4522         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
4523         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
4524         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
4525         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
4526         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
4527         Mnemonic == "fmuls" || Mnemonic == "fcmps" ||
4528         (Mnemonic == "movs" && isThumb()))) {
4529     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
4530     CarrySetting = true;
4531   }
4532
4533   // The "cps" instruction can have a interrupt mode operand which is glued into
4534   // the mnemonic. Check if this is the case, split it and parse the imod op
4535   if (Mnemonic.startswith("cps")) {
4536     // Split out any imod code.
4537     unsigned IMod =
4538       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
4539       .Case("ie", ARM_PROC::IE)
4540       .Case("id", ARM_PROC::ID)
4541       .Default(~0U);
4542     if (IMod != ~0U) {
4543       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
4544       ProcessorIMod = IMod;
4545     }
4546   }
4547
4548   // The "it" instruction has the condition mask on the end of the mnemonic.
4549   if (Mnemonic.startswith("it")) {
4550     ITMask = Mnemonic.slice(2, Mnemonic.size());
4551     Mnemonic = Mnemonic.slice(0, 2);
4552   }
4553
4554   return Mnemonic;
4555 }
4556
4557 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
4558 /// inclusion of carry set or predication code operands.
4559 //
4560 // FIXME: It would be nice to autogen this.
4561 void ARMAsmParser::
4562 getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
4563                       bool &CanAcceptPredicationCode) {
4564   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
4565       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
4566       Mnemonic == "add" || Mnemonic == "adc" ||
4567       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
4568       Mnemonic == "orr" || Mnemonic == "mvn" ||
4569       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
4570       Mnemonic == "sbc" || Mnemonic == "eor" || Mnemonic == "neg" ||
4571       (!isThumb() && (Mnemonic == "smull" || Mnemonic == "mov" ||
4572                       Mnemonic == "mla" || Mnemonic == "smlal" ||
4573                       Mnemonic == "umlal" || Mnemonic == "umull"))) {
4574     CanAcceptCarrySet = true;
4575   } else
4576     CanAcceptCarrySet = false;
4577
4578   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
4579       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
4580       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
4581       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
4582       Mnemonic == "dsb" || Mnemonic == "isb" || Mnemonic == "setend" ||
4583       (Mnemonic == "clrex" && !isThumb()) ||
4584       (Mnemonic == "nop" && isThumbOne()) ||
4585       ((Mnemonic == "pld" || Mnemonic == "pli" || Mnemonic == "pldw" ||
4586         Mnemonic == "ldc2" || Mnemonic == "ldc2l" ||
4587         Mnemonic == "stc2" || Mnemonic == "stc2l") && !isThumb()) ||
4588       ((Mnemonic.startswith("rfe") || Mnemonic.startswith("srs")) &&
4589        !isThumb()) ||
4590       Mnemonic.startswith("cps") || (Mnemonic == "movs" && isThumbOne())) {
4591     CanAcceptPredicationCode = false;
4592   } else
4593     CanAcceptPredicationCode = true;
4594
4595   if (isThumb()) {
4596     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
4597         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
4598       CanAcceptPredicationCode = false;
4599   }
4600 }
4601
4602 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
4603                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
4604   // FIXME: This is all horribly hacky. We really need a better way to deal
4605   // with optional operands like this in the matcher table.
4606
4607   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
4608   // another does not. Specifically, the MOVW instruction does not. So we
4609   // special case it here and remove the defaulted (non-setting) cc_out
4610   // operand if that's the instruction we're trying to match.
4611   //
4612   // We do this as post-processing of the explicit operands rather than just
4613   // conditionally adding the cc_out in the first place because we need
4614   // to check the type of the parsed immediate operand.
4615   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
4616       !static_cast<ARMOperand*>(Operands[4])->isARMSOImm() &&
4617       static_cast<ARMOperand*>(Operands[4])->isImm0_65535Expr() &&
4618       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
4619     return true;
4620
4621   // Register-register 'add' for thumb does not have a cc_out operand
4622   // when there are only two register operands.
4623   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
4624       static_cast<ARMOperand*>(Operands[3])->isReg() &&
4625       static_cast<ARMOperand*>(Operands[4])->isReg() &&
4626       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
4627     return true;
4628   // Register-register 'add' for thumb does not have a cc_out operand
4629   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
4630   // have to check the immediate range here since Thumb2 has a variant
4631   // that can handle a different range and has a cc_out operand.
4632   if (((isThumb() && Mnemonic == "add") ||
4633        (isThumbTwo() && Mnemonic == "sub")) &&
4634       Operands.size() == 6 &&
4635       static_cast<ARMOperand*>(Operands[3])->isReg() &&
4636       static_cast<ARMOperand*>(Operands[4])->isReg() &&
4637       static_cast<ARMOperand*>(Operands[4])->getReg() == ARM::SP &&
4638       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
4639       (static_cast<ARMOperand*>(Operands[5])->isReg() ||
4640        static_cast<ARMOperand*>(Operands[5])->isImm0_1020s4()))
4641     return true;
4642   // For Thumb2, add/sub immediate does not have a cc_out operand for the
4643   // imm0_4095 variant. That's the least-preferred variant when
4644   // selecting via the generic "add" mnemonic, so to know that we
4645   // should remove the cc_out operand, we have to explicitly check that
4646   // it's not one of the other variants. Ugh.
4647   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
4648       Operands.size() == 6 &&
4649       static_cast<ARMOperand*>(Operands[3])->isReg() &&
4650       static_cast<ARMOperand*>(Operands[4])->isReg() &&
4651       static_cast<ARMOperand*>(Operands[5])->isImm()) {
4652     // Nest conditions rather than one big 'if' statement for readability.
4653     //
4654     // If either register is a high reg, it's either one of the SP
4655     // variants (handled above) or a 32-bit encoding, so we just
4656     // check against T3. If the second register is the PC, this is an
4657     // alternate form of ADR, which uses encoding T4, so check for that too.
4658     if ((!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
4659          !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg())) &&
4660         static_cast<ARMOperand*>(Operands[4])->getReg() != ARM::PC &&
4661         static_cast<ARMOperand*>(Operands[5])->isT2SOImm())
4662       return false;
4663     // If both registers are low, we're in an IT block, and the immediate is
4664     // in range, we should use encoding T1 instead, which has a cc_out.
4665     if (inITBlock() &&
4666         isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) &&
4667         isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) &&
4668         static_cast<ARMOperand*>(Operands[5])->isImm0_7())
4669       return false;
4670
4671     // Otherwise, we use encoding T4, which does not have a cc_out
4672     // operand.
4673     return true;
4674   }
4675
4676   // The thumb2 multiply instruction doesn't have a CCOut register, so
4677   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
4678   // use the 16-bit encoding or not.
4679   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
4680       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
4681       static_cast<ARMOperand*>(Operands[3])->isReg() &&
4682       static_cast<ARMOperand*>(Operands[4])->isReg() &&
4683       static_cast<ARMOperand*>(Operands[5])->isReg() &&
4684       // If the registers aren't low regs, the destination reg isn't the
4685       // same as one of the source regs, or the cc_out operand is zero
4686       // outside of an IT block, we have to use the 32-bit encoding, so
4687       // remove the cc_out operand.
4688       (!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
4689        !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) ||
4690        !isARMLowRegister(static_cast<ARMOperand*>(Operands[5])->getReg()) ||
4691        !inITBlock() ||
4692        (static_cast<ARMOperand*>(Operands[3])->getReg() !=
4693         static_cast<ARMOperand*>(Operands[5])->getReg() &&
4694         static_cast<ARMOperand*>(Operands[3])->getReg() !=
4695         static_cast<ARMOperand*>(Operands[4])->getReg())))
4696     return true;
4697
4698   // Also check the 'mul' syntax variant that doesn't specify an explicit
4699   // destination register.
4700   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
4701       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
4702       static_cast<ARMOperand*>(Operands[3])->isReg() &&
4703       static_cast<ARMOperand*>(Operands[4])->isReg() &&
4704       // If the registers aren't low regs  or the cc_out operand is zero
4705       // outside of an IT block, we have to use the 32-bit encoding, so
4706       // remove the cc_out operand.
4707       (!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
4708        !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) ||
4709        !inITBlock()))
4710     return true;
4711
4712
4713
4714   // Register-register 'add/sub' for thumb does not have a cc_out operand
4715   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
4716   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
4717   // right, this will result in better diagnostics (which operand is off)
4718   // anyway.
4719   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
4720       (Operands.size() == 5 || Operands.size() == 6) &&
4721       static_cast<ARMOperand*>(Operands[3])->isReg() &&
4722       static_cast<ARMOperand*>(Operands[3])->getReg() == ARM::SP &&
4723       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
4724     return true;
4725
4726   return false;
4727 }
4728
4729 static bool isDataTypeToken(StringRef Tok) {
4730   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
4731     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
4732     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
4733     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
4734     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
4735     Tok == ".f" || Tok == ".d";
4736 }
4737
4738 // FIXME: This bit should probably be handled via an explicit match class
4739 // in the .td files that matches the suffix instead of having it be
4740 // a literal string token the way it is now.
4741 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
4742   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
4743 }
4744
4745 static void applyMnemonicAliases(StringRef &Mnemonic, unsigned Features);
4746 /// Parse an arm instruction mnemonic followed by its operands.
4747 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
4748                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
4749   // Apply mnemonic aliases before doing anything else, as the destination
4750   // mnemnonic may include suffices and we want to handle them normally.
4751   // The generic tblgen'erated code does this later, at the start of
4752   // MatchInstructionImpl(), but that's too late for aliases that include
4753   // any sort of suffix.
4754   unsigned AvailableFeatures = getAvailableFeatures();
4755   applyMnemonicAliases(Name, AvailableFeatures);
4756
4757   // First check for the ARM-specific .req directive.
4758   if (Parser.getTok().is(AsmToken::Identifier) &&
4759       Parser.getTok().getIdentifier() == ".req") {
4760     parseDirectiveReq(Name, NameLoc);
4761     // We always return 'error' for this, as we're done with this
4762     // statement and don't need to match the 'instruction."
4763     return true;
4764   }
4765
4766   // Create the leading tokens for the mnemonic, split by '.' characters.
4767   size_t Start = 0, Next = Name.find('.');
4768   StringRef Mnemonic = Name.slice(Start, Next);
4769
4770   // Split out the predication code and carry setting flag from the mnemonic.
4771   unsigned PredicationCode;
4772   unsigned ProcessorIMod;
4773   bool CarrySetting;
4774   StringRef ITMask;
4775   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
4776                            ProcessorIMod, ITMask);
4777
4778   // In Thumb1, only the branch (B) instruction can be predicated.
4779   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
4780     Parser.EatToEndOfStatement();
4781     return Error(NameLoc, "conditional execution not supported in Thumb1");
4782   }
4783
4784   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
4785
4786   // Handle the IT instruction ITMask. Convert it to a bitmask. This
4787   // is the mask as it will be for the IT encoding if the conditional
4788   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
4789   // where the conditional bit0 is zero, the instruction post-processing
4790   // will adjust the mask accordingly.
4791   if (Mnemonic == "it") {
4792     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
4793     if (ITMask.size() > 3) {
4794       Parser.EatToEndOfStatement();
4795       return Error(Loc, "too many conditions on IT instruction");
4796     }
4797     unsigned Mask = 8;
4798     for (unsigned i = ITMask.size(); i != 0; --i) {
4799       char pos = ITMask[i - 1];
4800       if (pos != 't' && pos != 'e') {
4801         Parser.EatToEndOfStatement();
4802         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
4803       }
4804       Mask >>= 1;
4805       if (ITMask[i - 1] == 't')
4806         Mask |= 8;
4807     }
4808     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
4809   }
4810
4811   // FIXME: This is all a pretty gross hack. We should automatically handle
4812   // optional operands like this via tblgen.
4813
4814   // Next, add the CCOut and ConditionCode operands, if needed.
4815   //
4816   // For mnemonics which can ever incorporate a carry setting bit or predication
4817   // code, our matching model involves us always generating CCOut and
4818   // ConditionCode operands to match the mnemonic "as written" and then we let
4819   // the matcher deal with finding the right instruction or generating an
4820   // appropriate error.
4821   bool CanAcceptCarrySet, CanAcceptPredicationCode;
4822   getMnemonicAcceptInfo(Mnemonic, CanAcceptCarrySet, CanAcceptPredicationCode);
4823
4824   // If we had a carry-set on an instruction that can't do that, issue an
4825   // error.
4826   if (!CanAcceptCarrySet && CarrySetting) {
4827     Parser.EatToEndOfStatement();
4828     return Error(NameLoc, "instruction '" + Mnemonic +
4829                  "' can not set flags, but 's' suffix specified");
4830   }
4831   // If we had a predication code on an instruction that can't do that, issue an
4832   // error.
4833   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
4834     Parser.EatToEndOfStatement();
4835     return Error(NameLoc, "instruction '" + Mnemonic +
4836                  "' is not predicable, but condition code specified");
4837   }
4838
4839   // Add the carry setting operand, if necessary.
4840   if (CanAcceptCarrySet) {
4841     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
4842     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
4843                                                Loc));
4844   }
4845
4846   // Add the predication code operand, if necessary.
4847   if (CanAcceptPredicationCode) {
4848     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
4849                                       CarrySetting);
4850     Operands.push_back(ARMOperand::CreateCondCode(
4851                          ARMCC::CondCodes(PredicationCode), Loc));
4852   }
4853
4854   // Add the processor imod operand, if necessary.
4855   if (ProcessorIMod) {
4856     Operands.push_back(ARMOperand::CreateImm(
4857           MCConstantExpr::Create(ProcessorIMod, getContext()),
4858                                  NameLoc, NameLoc));
4859   }
4860
4861   // Add the remaining tokens in the mnemonic.
4862   while (Next != StringRef::npos) {
4863     Start = Next;
4864     Next = Name.find('.', Start + 1);
4865     StringRef ExtraToken = Name.slice(Start, Next);
4866
4867     // Some NEON instructions have an optional datatype suffix that is
4868     // completely ignored. Check for that.
4869     if (isDataTypeToken(ExtraToken) &&
4870         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
4871       continue;
4872
4873     if (ExtraToken != ".n") {
4874       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
4875       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
4876     }
4877   }
4878
4879   // Read the remaining operands.
4880   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4881     // Read the first operand.
4882     if (parseOperand(Operands, Mnemonic)) {
4883       Parser.EatToEndOfStatement();
4884       return true;
4885     }
4886
4887     while (getLexer().is(AsmToken::Comma)) {
4888       Parser.Lex();  // Eat the comma.
4889
4890       // Parse and remember the operand.
4891       if (parseOperand(Operands, Mnemonic)) {
4892         Parser.EatToEndOfStatement();
4893         return true;
4894       }
4895     }
4896   }
4897
4898   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4899     SMLoc Loc = getLexer().getLoc();
4900     Parser.EatToEndOfStatement();
4901     return Error(Loc, "unexpected token in argument list");
4902   }
4903
4904   Parser.Lex(); // Consume the EndOfStatement
4905
4906   // Some instructions, mostly Thumb, have forms for the same mnemonic that
4907   // do and don't have a cc_out optional-def operand. With some spot-checks
4908   // of the operand list, we can figure out which variant we're trying to
4909   // parse and adjust accordingly before actually matching. We shouldn't ever
4910   // try to remove a cc_out operand that was explicitly set on the the
4911   // mnemonic, of course (CarrySetting == true). Reason number #317 the
4912   // table driven matcher doesn't fit well with the ARM instruction set.
4913   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands)) {
4914     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
4915     Operands.erase(Operands.begin() + 1);
4916     delete Op;
4917   }
4918
4919   // ARM mode 'blx' need special handling, as the register operand version
4920   // is predicable, but the label operand version is not. So, we can't rely
4921   // on the Mnemonic based checking to correctly figure out when to put
4922   // a k_CondCode operand in the list. If we're trying to match the label
4923   // version, remove the k_CondCode operand here.
4924   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
4925       static_cast<ARMOperand*>(Operands[2])->isImm()) {
4926     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
4927     Operands.erase(Operands.begin() + 1);
4928     delete Op;
4929   }
4930
4931   // The vector-compare-to-zero instructions have a literal token "#0" at
4932   // the end that comes to here as an immediate operand. Convert it to a
4933   // token to play nicely with the matcher.
4934   if ((Mnemonic == "vceq" || Mnemonic == "vcge" || Mnemonic == "vcgt" ||
4935       Mnemonic == "vcle" || Mnemonic == "vclt") && Operands.size() == 6 &&
4936       static_cast<ARMOperand*>(Operands[5])->isImm()) {
4937     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
4938     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
4939     if (CE && CE->getValue() == 0) {
4940       Operands.erase(Operands.begin() + 5);
4941       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
4942       delete Op;
4943     }
4944   }
4945   // VCMP{E} does the same thing, but with a different operand count.
4946   if ((Mnemonic == "vcmp" || Mnemonic == "vcmpe") && Operands.size() == 5 &&
4947       static_cast<ARMOperand*>(Operands[4])->isImm()) {
4948     ARMOperand *Op = static_cast<ARMOperand*>(Operands[4]);
4949     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
4950     if (CE && CE->getValue() == 0) {
4951       Operands.erase(Operands.begin() + 4);
4952       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
4953       delete Op;
4954     }
4955   }
4956   // Similarly, the Thumb1 "RSB" instruction has a literal "#0" on the
4957   // end. Convert it to a token here. Take care not to convert those
4958   // that should hit the Thumb2 encoding.
4959   if (Mnemonic == "rsb" && isThumb() && Operands.size() == 6 &&
4960       static_cast<ARMOperand*>(Operands[3])->isReg() &&
4961       static_cast<ARMOperand*>(Operands[4])->isReg() &&
4962       static_cast<ARMOperand*>(Operands[5])->isImm()) {
4963     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
4964     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
4965     if (CE && CE->getValue() == 0 &&
4966         (isThumbOne() ||
4967          // The cc_out operand matches the IT block.
4968          ((inITBlock() != CarrySetting) &&
4969          // Neither register operand is a high register.
4970          (isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) &&
4971           isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()))))){
4972       Operands.erase(Operands.begin() + 5);
4973       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
4974       delete Op;
4975     }
4976   }
4977
4978   return false;
4979 }
4980
4981 // Validate context-sensitive operand constraints.
4982
4983 // return 'true' if register list contains non-low GPR registers,
4984 // 'false' otherwise. If Reg is in the register list or is HiReg, set
4985 // 'containsReg' to true.
4986 static bool checkLowRegisterList(MCInst Inst, unsigned OpNo, unsigned Reg,
4987                                  unsigned HiReg, bool &containsReg) {
4988   containsReg = false;
4989   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
4990     unsigned OpReg = Inst.getOperand(i).getReg();
4991     if (OpReg == Reg)
4992       containsReg = true;
4993     // Anything other than a low register isn't legal here.
4994     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
4995       return true;
4996   }
4997   return false;
4998 }
4999
5000 // Check if the specified regisgter is in the register list of the inst,
5001 // starting at the indicated operand number.
5002 static bool listContainsReg(MCInst &Inst, unsigned OpNo, unsigned Reg) {
5003   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
5004     unsigned OpReg = Inst.getOperand(i).getReg();
5005     if (OpReg == Reg)
5006       return true;
5007   }
5008   return false;
5009 }
5010
5011 // FIXME: We would really prefer to have MCInstrInfo (the wrapper around
5012 // the ARMInsts array) instead. Getting that here requires awkward
5013 // API changes, though. Better way?
5014 namespace llvm {
5015 extern const MCInstrDesc ARMInsts[];
5016 }
5017 static const MCInstrDesc &getInstDesc(unsigned Opcode) {
5018   return ARMInsts[Opcode];
5019 }
5020
5021 // FIXME: We would really like to be able to tablegen'erate this.
5022 bool ARMAsmParser::
5023 validateInstruction(MCInst &Inst,
5024                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
5025   const MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
5026   SMLoc Loc = Operands[0]->getStartLoc();
5027   // Check the IT block state first.
5028   // NOTE: In Thumb mode, the BKPT instruction has the interesting property of
5029   // being allowed in IT blocks, but not being predicable.  It just always
5030   // executes.
5031   if (inITBlock() && Inst.getOpcode() != ARM::tBKPT) {
5032     unsigned bit = 1;
5033     if (ITState.FirstCond)
5034       ITState.FirstCond = false;
5035     else
5036       bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
5037     // The instruction must be predicable.
5038     if (!MCID.isPredicable())
5039       return Error(Loc, "instructions in IT block must be predicable");
5040     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
5041     unsigned ITCond = bit ? ITState.Cond :
5042       ARMCC::getOppositeCondition(ITState.Cond);
5043     if (Cond != ITCond) {
5044       // Find the condition code Operand to get its SMLoc information.
5045       SMLoc CondLoc;
5046       for (unsigned i = 1; i < Operands.size(); ++i)
5047         if (static_cast<ARMOperand*>(Operands[i])->isCondCode())
5048           CondLoc = Operands[i]->getStartLoc();
5049       return Error(CondLoc, "incorrect condition in IT block; got '" +
5050                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
5051                    "', but expected '" +
5052                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
5053     }
5054   // Check for non-'al' condition codes outside of the IT block.
5055   } else if (isThumbTwo() && MCID.isPredicable() &&
5056              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
5057              ARMCC::AL && Inst.getOpcode() != ARM::tB &&
5058              Inst.getOpcode() != ARM::t2B)
5059     return Error(Loc, "predicated instructions must be in IT block");
5060
5061   switch (Inst.getOpcode()) {
5062   case ARM::LDRD:
5063   case ARM::LDRD_PRE:
5064   case ARM::LDRD_POST:
5065   case ARM::LDREXD: {
5066     // Rt2 must be Rt + 1.
5067     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
5068     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
5069     if (Rt2 != Rt + 1)
5070       return Error(Operands[3]->getStartLoc(),
5071                    "destination operands must be sequential");
5072     return false;
5073   }
5074   case ARM::STRD: {
5075     // Rt2 must be Rt + 1.
5076     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
5077     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
5078     if (Rt2 != Rt + 1)
5079       return Error(Operands[3]->getStartLoc(),
5080                    "source operands must be sequential");
5081     return false;
5082   }
5083   case ARM::STRD_PRE:
5084   case ARM::STRD_POST:
5085   case ARM::STREXD: {
5086     // Rt2 must be Rt + 1.
5087     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(1).getReg());
5088     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(2).getReg());
5089     if (Rt2 != Rt + 1)
5090       return Error(Operands[3]->getStartLoc(),
5091                    "source operands must be sequential");
5092     return false;
5093   }
5094   case ARM::SBFX:
5095   case ARM::UBFX: {
5096     // width must be in range [1, 32-lsb]
5097     unsigned lsb = Inst.getOperand(2).getImm();
5098     unsigned widthm1 = Inst.getOperand(3).getImm();
5099     if (widthm1 >= 32 - lsb)
5100       return Error(Operands[5]->getStartLoc(),
5101                    "bitfield width must be in range [1,32-lsb]");
5102     return false;
5103   }
5104   case ARM::tLDMIA: {
5105     // If we're parsing Thumb2, the .w variant is available and handles
5106     // most cases that are normally illegal for a Thumb1 LDM
5107     // instruction. We'll make the transformation in processInstruction()
5108     // if necessary.
5109     //
5110     // Thumb LDM instructions are writeback iff the base register is not
5111     // in the register list.
5112     unsigned Rn = Inst.getOperand(0).getReg();
5113     bool hasWritebackToken =
5114       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
5115        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
5116     bool listContainsBase;
5117     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) && !isThumbTwo())
5118       return Error(Operands[3 + hasWritebackToken]->getStartLoc(),
5119                    "registers must be in range r0-r7");
5120     // If we should have writeback, then there should be a '!' token.
5121     if (!listContainsBase && !hasWritebackToken && !isThumbTwo())
5122       return Error(Operands[2]->getStartLoc(),
5123                    "writeback operator '!' expected");
5124     // If we should not have writeback, there must not be a '!'. This is
5125     // true even for the 32-bit wide encodings.
5126     if (listContainsBase && hasWritebackToken)
5127       return Error(Operands[3]->getStartLoc(),
5128                    "writeback operator '!' not allowed when base register "
5129                    "in register list");
5130
5131     break;
5132   }
5133   case ARM::t2LDMIA_UPD: {
5134     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
5135       return Error(Operands[4]->getStartLoc(),
5136                    "writeback operator '!' not allowed when base register "
5137                    "in register list");
5138     break;
5139   }
5140   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
5141   // so only issue a diagnostic for thumb1. The instructions will be
5142   // switched to the t2 encodings in processInstruction() if necessary.
5143   case ARM::tPOP: {
5144     bool listContainsBase;
5145     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase) &&
5146         !isThumbTwo())
5147       return Error(Operands[2]->getStartLoc(),
5148                    "registers must be in range r0-r7 or pc");
5149     break;
5150   }
5151   case ARM::tPUSH: {
5152     bool listContainsBase;
5153     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase) &&
5154         !isThumbTwo())
5155       return Error(Operands[2]->getStartLoc(),
5156                    "registers must be in range r0-r7 or lr");
5157     break;
5158   }
5159   case ARM::tSTMIA_UPD: {
5160     bool listContainsBase;
5161     if (checkLowRegisterList(Inst, 4, 0, 0, listContainsBase) && !isThumbTwo())
5162       return Error(Operands[4]->getStartLoc(),
5163                    "registers must be in range r0-r7");
5164     break;
5165   }
5166   }
5167
5168   return false;
5169 }
5170
5171 static unsigned getRealVSTLNOpcode(unsigned Opc, unsigned &Spacing) {
5172   switch(Opc) {
5173   default: assert(0 && "unexpected opcode!");
5174   // VST1LN
5175   case ARM::VST1LNdWB_fixed_Asm_8:
5176     Spacing = 1;
5177     return ARM::VST1LNd8_UPD;
5178   case ARM::VST1LNdWB_fixed_Asm_16:
5179     Spacing = 1;
5180     return ARM::VST1LNd16_UPD;
5181   case ARM::VST1LNdWB_fixed_Asm_32:
5182     Spacing = 1;
5183     return ARM::VST1LNd32_UPD;
5184   case ARM::VST1LNdWB_register_Asm_8:
5185     Spacing = 1;
5186     return ARM::VST1LNd8_UPD;
5187   case ARM::VST1LNdWB_register_Asm_16:
5188     Spacing = 1;
5189     return ARM::VST1LNd16_UPD;
5190   case ARM::VST1LNdWB_register_Asm_32:
5191     Spacing = 1;
5192     return ARM::VST1LNd32_UPD;
5193   case ARM::VST1LNdAsm_8:
5194     Spacing = 1;
5195     return ARM::VST1LNd8;
5196   case ARM::VST1LNdAsm_16:
5197     Spacing = 1;
5198     return ARM::VST1LNd16;
5199   case ARM::VST1LNdAsm_32:
5200     Spacing = 1;
5201     return ARM::VST1LNd32;
5202
5203   // VST2LN
5204   case ARM::VST2LNdWB_fixed_Asm_8:
5205     Spacing = 1;
5206     return ARM::VST2LNd8_UPD;
5207   case ARM::VST2LNdWB_fixed_Asm_16:
5208     Spacing = 1;
5209     return ARM::VST2LNd16_UPD;
5210   case ARM::VST2LNdWB_fixed_Asm_32:
5211     Spacing = 1;
5212     return ARM::VST2LNd32_UPD;
5213   case ARM::VST2LNqWB_fixed_Asm_16:
5214     Spacing = 2;
5215     return ARM::VST2LNq16_UPD;
5216   case ARM::VST2LNqWB_fixed_Asm_32:
5217     Spacing = 2;
5218     return ARM::VST2LNq32_UPD;
5219
5220   case ARM::VST2LNdWB_register_Asm_8:
5221     Spacing = 1;
5222     return ARM::VST2LNd8_UPD;
5223   case ARM::VST2LNdWB_register_Asm_16:
5224     Spacing = 1;
5225     return ARM::VST2LNd16_UPD;
5226   case ARM::VST2LNdWB_register_Asm_32:
5227     Spacing = 1;
5228     return ARM::VST2LNd32_UPD;
5229   case ARM::VST2LNqWB_register_Asm_16:
5230     Spacing = 2;
5231     return ARM::VST2LNq16_UPD;
5232   case ARM::VST2LNqWB_register_Asm_32:
5233     Spacing = 2;
5234     return ARM::VST2LNq32_UPD;
5235
5236   case ARM::VST2LNdAsm_8:
5237     Spacing = 1;
5238     return ARM::VST2LNd8;
5239   case ARM::VST2LNdAsm_16:
5240     Spacing = 1;
5241     return ARM::VST2LNd16;
5242   case ARM::VST2LNdAsm_32:
5243     Spacing = 1;
5244     return ARM::VST2LNd32;
5245   case ARM::VST2LNqAsm_16:
5246     Spacing = 2;
5247     return ARM::VST2LNq16;
5248   case ARM::VST2LNqAsm_32:
5249     Spacing = 2;
5250     return ARM::VST2LNq32;
5251   }
5252 }
5253
5254 static unsigned getRealVLDLNOpcode(unsigned Opc, unsigned &Spacing) {
5255   switch(Opc) {
5256   default: assert(0 && "unexpected opcode!");
5257   // VLD1LN
5258   case ARM::VLD1LNdWB_fixed_Asm_8:
5259     Spacing = 1;
5260     return ARM::VLD1LNd8_UPD;
5261   case ARM::VLD1LNdWB_fixed_Asm_16:
5262     Spacing = 1;
5263     return ARM::VLD1LNd16_UPD;
5264   case ARM::VLD1LNdWB_fixed_Asm_32:
5265     Spacing = 1;
5266     return ARM::VLD1LNd32_UPD;
5267   case ARM::VLD1LNdWB_register_Asm_8:
5268     Spacing = 1;
5269     return ARM::VLD1LNd8_UPD;
5270   case ARM::VLD1LNdWB_register_Asm_16:
5271     Spacing = 1;
5272     return ARM::VLD1LNd16_UPD;
5273   case ARM::VLD1LNdWB_register_Asm_32:
5274     Spacing = 1;
5275     return ARM::VLD1LNd32_UPD;
5276   case ARM::VLD1LNdAsm_8:
5277     Spacing = 1;
5278     return ARM::VLD1LNd8;
5279   case ARM::VLD1LNdAsm_16:
5280     Spacing = 1;
5281     return ARM::VLD1LNd16;
5282   case ARM::VLD1LNdAsm_32:
5283     Spacing = 1;
5284     return ARM::VLD1LNd32;
5285
5286   // VLD2LN
5287   case ARM::VLD2LNdWB_fixed_Asm_8:
5288     Spacing = 1;
5289     return ARM::VLD2LNd8_UPD;
5290   case ARM::VLD2LNdWB_fixed_Asm_16:
5291     Spacing = 1;
5292     return ARM::VLD2LNd16_UPD;
5293   case ARM::VLD2LNdWB_fixed_Asm_32:
5294     Spacing = 1;
5295     return ARM::VLD2LNd32_UPD;
5296   case ARM::VLD2LNqWB_fixed_Asm_16:
5297     Spacing = 1;
5298     return ARM::VLD2LNq16_UPD;
5299   case ARM::VLD2LNqWB_fixed_Asm_32:
5300     Spacing = 2;
5301     return ARM::VLD2LNq32_UPD;
5302   case ARM::VLD2LNdWB_register_Asm_8:
5303     Spacing = 1;
5304     return ARM::VLD2LNd8_UPD;
5305   case ARM::VLD2LNdWB_register_Asm_16:
5306     Spacing = 1;
5307     return ARM::VLD2LNd16_UPD;
5308   case ARM::VLD2LNdWB_register_Asm_32:
5309     Spacing = 1;
5310     return ARM::VLD2LNd32_UPD;
5311   case ARM::VLD2LNqWB_register_Asm_16:
5312     Spacing = 2;
5313     return ARM::VLD2LNq16_UPD;
5314   case ARM::VLD2LNqWB_register_Asm_32:
5315     Spacing = 2;
5316     return ARM::VLD2LNq32_UPD;
5317   case ARM::VLD2LNdAsm_8:
5318     Spacing = 1;
5319     return ARM::VLD2LNd8;
5320   case ARM::VLD2LNdAsm_16:
5321     Spacing = 1;
5322     return ARM::VLD2LNd16;
5323   case ARM::VLD2LNdAsm_32:
5324     Spacing = 1;
5325     return ARM::VLD2LNd32;
5326   case ARM::VLD2LNqAsm_16:
5327     Spacing = 2;
5328     return ARM::VLD2LNq16;
5329   case ARM::VLD2LNqAsm_32:
5330     Spacing = 2;
5331     return ARM::VLD2LNq32;
5332
5333   // VLD3LN
5334   case ARM::VLD3LNdWB_fixed_Asm_8:
5335     Spacing = 1;
5336     return ARM::VLD3LNd8_UPD;
5337   case ARM::VLD3LNdWB_fixed_Asm_16:
5338     Spacing = 1;
5339     return ARM::VLD3LNd16_UPD;
5340   case ARM::VLD3LNdWB_fixed_Asm_32:
5341     Spacing = 1;
5342     return ARM::VLD3LNd32_UPD;
5343   case ARM::VLD3LNqWB_fixed_Asm_16:
5344     Spacing = 1;
5345     return ARM::VLD3LNq16_UPD;
5346   case ARM::VLD3LNqWB_fixed_Asm_32:
5347     Spacing = 2;
5348     return ARM::VLD3LNq32_UPD;
5349   case ARM::VLD3LNdWB_register_Asm_8:
5350     Spacing = 1;
5351     return ARM::VLD3LNd8_UPD;
5352   case ARM::VLD3LNdWB_register_Asm_16:
5353     Spacing = 1;
5354     return ARM::VLD3LNd16_UPD;
5355   case ARM::VLD3LNdWB_register_Asm_32:
5356     Spacing = 1;
5357     return ARM::VLD3LNd32_UPD;
5358   case ARM::VLD3LNqWB_register_Asm_16:
5359     Spacing = 2;
5360     return ARM::VLD3LNq16_UPD;
5361   case ARM::VLD3LNqWB_register_Asm_32:
5362     Spacing = 2;
5363     return ARM::VLD3LNq32_UPD;
5364   case ARM::VLD3LNdAsm_8:
5365     Spacing = 1;
5366     return ARM::VLD3LNd8;
5367   case ARM::VLD3LNdAsm_16:
5368     Spacing = 1;
5369     return ARM::VLD3LNd16;
5370   case ARM::VLD3LNdAsm_32:
5371     Spacing = 1;
5372     return ARM::VLD3LNd32;
5373   case ARM::VLD3LNqAsm_16:
5374     Spacing = 2;
5375     return ARM::VLD3LNq16;
5376   case ARM::VLD3LNqAsm_32:
5377     Spacing = 2;
5378     return ARM::VLD3LNq32;
5379   }
5380 }
5381
5382 bool ARMAsmParser::
5383 processInstruction(MCInst &Inst,
5384                    const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
5385   switch (Inst.getOpcode()) {
5386   // Aliases for alternate PC+imm syntax of LDR instructions.
5387   case ARM::t2LDRpcrel:
5388     Inst.setOpcode(ARM::t2LDRpci);
5389     return true;
5390   case ARM::t2LDRBpcrel:
5391     Inst.setOpcode(ARM::t2LDRBpci);
5392     return true;
5393   case ARM::t2LDRHpcrel:
5394     Inst.setOpcode(ARM::t2LDRHpci);
5395     return true;
5396   case ARM::t2LDRSBpcrel:
5397     Inst.setOpcode(ARM::t2LDRSBpci);
5398     return true;
5399   case ARM::t2LDRSHpcrel:
5400     Inst.setOpcode(ARM::t2LDRSHpci);
5401     return true;
5402   // Handle NEON VST complex aliases.
5403   case ARM::VST1LNdWB_register_Asm_8:
5404   case ARM::VST1LNdWB_register_Asm_16:
5405   case ARM::VST1LNdWB_register_Asm_32: {
5406     MCInst TmpInst;
5407     // Shuffle the operands around so the lane index operand is in the
5408     // right place.
5409     unsigned Spacing;
5410     TmpInst.setOpcode(getRealVSTLNOpcode(Inst.getOpcode(), Spacing));
5411     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5412     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5413     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5414     TmpInst.addOperand(Inst.getOperand(4)); // Rm
5415     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5416     TmpInst.addOperand(Inst.getOperand(1)); // lane
5417     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
5418     TmpInst.addOperand(Inst.getOperand(6));
5419     Inst = TmpInst;
5420     return true;
5421   }
5422
5423   case ARM::VST2LNdWB_register_Asm_8:
5424   case ARM::VST2LNdWB_register_Asm_16:
5425   case ARM::VST2LNdWB_register_Asm_32:
5426   case ARM::VST2LNqWB_register_Asm_16:
5427   case ARM::VST2LNqWB_register_Asm_32: {
5428     MCInst TmpInst;
5429     // Shuffle the operands around so the lane index operand is in the
5430     // right place.
5431     unsigned Spacing;
5432     TmpInst.setOpcode(getRealVSTLNOpcode(Inst.getOpcode(), Spacing));
5433     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5434     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5435     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5436     TmpInst.addOperand(Inst.getOperand(4)); // Rm
5437     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5438     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5439                                             Spacing));
5440     TmpInst.addOperand(Inst.getOperand(1)); // lane
5441     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
5442     TmpInst.addOperand(Inst.getOperand(6));
5443     Inst = TmpInst;
5444     return true;
5445   }
5446   case ARM::VST1LNdWB_fixed_Asm_8:
5447   case ARM::VST1LNdWB_fixed_Asm_16:
5448   case ARM::VST1LNdWB_fixed_Asm_32: {
5449     MCInst TmpInst;
5450     // Shuffle the operands around so the lane index operand is in the
5451     // right place.
5452     unsigned Spacing;
5453     TmpInst.setOpcode(getRealVSTLNOpcode(Inst.getOpcode(), Spacing));
5454     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5455     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5456     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5457     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
5458     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5459     TmpInst.addOperand(Inst.getOperand(1)); // lane
5460     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5461     TmpInst.addOperand(Inst.getOperand(5));
5462     Inst = TmpInst;
5463     return true;
5464   }
5465
5466   case ARM::VST2LNdWB_fixed_Asm_8:
5467   case ARM::VST2LNdWB_fixed_Asm_16:
5468   case ARM::VST2LNdWB_fixed_Asm_32:
5469   case ARM::VST2LNqWB_fixed_Asm_16:
5470   case ARM::VST2LNqWB_fixed_Asm_32: {
5471     MCInst TmpInst;
5472     // Shuffle the operands around so the lane index operand is in the
5473     // right place.
5474     unsigned Spacing;
5475     TmpInst.setOpcode(getRealVSTLNOpcode(Inst.getOpcode(), Spacing));
5476     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5477     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5478     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5479     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
5480     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5481     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5482                                             Spacing));
5483     TmpInst.addOperand(Inst.getOperand(1)); // lane
5484     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5485     TmpInst.addOperand(Inst.getOperand(5));
5486     Inst = TmpInst;
5487     return true;
5488   }
5489   case ARM::VST1LNdAsm_8:
5490   case ARM::VST1LNdAsm_16:
5491   case ARM::VST1LNdAsm_32: {
5492     MCInst TmpInst;
5493     // Shuffle the operands around so the lane index operand is in the
5494     // right place.
5495     unsigned Spacing;
5496     TmpInst.setOpcode(getRealVSTLNOpcode(Inst.getOpcode(), Spacing));
5497     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5498     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5499     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5500     TmpInst.addOperand(Inst.getOperand(1)); // lane
5501     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5502     TmpInst.addOperand(Inst.getOperand(5));
5503     Inst = TmpInst;
5504     return true;
5505   }
5506
5507   case ARM::VST2LNdAsm_8:
5508   case ARM::VST2LNdAsm_16:
5509   case ARM::VST2LNdAsm_32:
5510   case ARM::VST2LNqAsm_16:
5511   case ARM::VST2LNqAsm_32: {
5512     MCInst TmpInst;
5513     // Shuffle the operands around so the lane index operand is in the
5514     // right place.
5515     unsigned Spacing;
5516     TmpInst.setOpcode(getRealVSTLNOpcode(Inst.getOpcode(), Spacing));
5517     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5518     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5519     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5520     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5521                                             Spacing));
5522     TmpInst.addOperand(Inst.getOperand(1)); // lane
5523     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5524     TmpInst.addOperand(Inst.getOperand(5));
5525     Inst = TmpInst;
5526     return true;
5527   }
5528   // Handle NEON VLD complex aliases.
5529   case ARM::VLD1LNdWB_register_Asm_8:
5530   case ARM::VLD1LNdWB_register_Asm_16:
5531   case ARM::VLD1LNdWB_register_Asm_32: {
5532     MCInst TmpInst;
5533     // Shuffle the operands around so the lane index operand is in the
5534     // right place.
5535     unsigned Spacing;
5536     TmpInst.setOpcode(getRealVLDLNOpcode(Inst.getOpcode(), Spacing));
5537     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5538     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5539     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5540     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5541     TmpInst.addOperand(Inst.getOperand(4)); // Rm
5542     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
5543     TmpInst.addOperand(Inst.getOperand(1)); // lane
5544     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
5545     TmpInst.addOperand(Inst.getOperand(6));
5546     Inst = TmpInst;
5547     return true;
5548   }
5549
5550   case ARM::VLD2LNdWB_register_Asm_8:
5551   case ARM::VLD2LNdWB_register_Asm_16:
5552   case ARM::VLD2LNdWB_register_Asm_32:
5553   case ARM::VLD2LNqWB_register_Asm_16:
5554   case ARM::VLD2LNqWB_register_Asm_32: {
5555     MCInst TmpInst;
5556     // Shuffle the operands around so the lane index operand is in the
5557     // right place.
5558     unsigned Spacing;
5559     TmpInst.setOpcode(getRealVLDLNOpcode(Inst.getOpcode(), Spacing));
5560     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5561     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5562                                             Spacing));
5563     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5564     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5565     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5566     TmpInst.addOperand(Inst.getOperand(4)); // Rm
5567     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
5568     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5569                                             Spacing));
5570     TmpInst.addOperand(Inst.getOperand(1)); // lane
5571     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
5572     TmpInst.addOperand(Inst.getOperand(6));
5573     Inst = TmpInst;
5574     return true;
5575   }
5576
5577   case ARM::VLD3LNdWB_register_Asm_8:
5578   case ARM::VLD3LNdWB_register_Asm_16:
5579   case ARM::VLD3LNdWB_register_Asm_32:
5580   case ARM::VLD3LNqWB_register_Asm_16:
5581   case ARM::VLD3LNqWB_register_Asm_32: {
5582     MCInst TmpInst;
5583     // Shuffle the operands around so the lane index operand is in the
5584     // right place.
5585     unsigned Spacing;
5586     TmpInst.setOpcode(getRealVLDLNOpcode(Inst.getOpcode(), Spacing));
5587     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5588     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5589                                             Spacing));
5590     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5591                                             Spacing));
5592     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5593     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5594     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5595     TmpInst.addOperand(Inst.getOperand(4)); // Rm
5596     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
5597     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5598                                             Spacing));
5599     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5600                                             Spacing));
5601     TmpInst.addOperand(Inst.getOperand(1)); // lane
5602     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
5603     TmpInst.addOperand(Inst.getOperand(6));
5604     Inst = TmpInst;
5605     return true;
5606   }
5607
5608   case ARM::VLD1LNdWB_fixed_Asm_8:
5609   case ARM::VLD1LNdWB_fixed_Asm_16:
5610   case ARM::VLD1LNdWB_fixed_Asm_32: {
5611     MCInst TmpInst;
5612     // Shuffle the operands around so the lane index operand is in the
5613     // right place.
5614     unsigned Spacing;
5615     TmpInst.setOpcode(getRealVLDLNOpcode(Inst.getOpcode(), Spacing));
5616     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5617     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5618     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5619     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5620     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
5621     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
5622     TmpInst.addOperand(Inst.getOperand(1)); // lane
5623     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5624     TmpInst.addOperand(Inst.getOperand(5));
5625     Inst = TmpInst;
5626     return true;
5627   }
5628
5629   case ARM::VLD2LNdWB_fixed_Asm_8:
5630   case ARM::VLD2LNdWB_fixed_Asm_16:
5631   case ARM::VLD2LNdWB_fixed_Asm_32:
5632   case ARM::VLD2LNqWB_fixed_Asm_16:
5633   case ARM::VLD2LNqWB_fixed_Asm_32: {
5634     MCInst TmpInst;
5635     // Shuffle the operands around so the lane index operand is in the
5636     // right place.
5637     unsigned Spacing;
5638     TmpInst.setOpcode(getRealVLDLNOpcode(Inst.getOpcode(), Spacing));
5639     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5640     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5641                                             Spacing));
5642     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5643     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5644     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5645     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
5646     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
5647     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5648                                             Spacing));
5649     TmpInst.addOperand(Inst.getOperand(1)); // lane
5650     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5651     TmpInst.addOperand(Inst.getOperand(5));
5652     Inst = TmpInst;
5653     return true;
5654   }
5655
5656   case ARM::VLD3LNdWB_fixed_Asm_8:
5657   case ARM::VLD3LNdWB_fixed_Asm_16:
5658   case ARM::VLD3LNdWB_fixed_Asm_32:
5659   case ARM::VLD3LNqWB_fixed_Asm_16:
5660   case ARM::VLD3LNqWB_fixed_Asm_32: {
5661     MCInst TmpInst;
5662     // Shuffle the operands around so the lane index operand is in the
5663     // right place.
5664     unsigned Spacing;
5665     TmpInst.setOpcode(getRealVLDLNOpcode(Inst.getOpcode(), Spacing));
5666     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5667     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5668                                             Spacing));
5669     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5670                                             Spacing));
5671     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
5672     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5673     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5674     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
5675     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
5676     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5677                                             Spacing));
5678     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5679                                             Spacing));
5680     TmpInst.addOperand(Inst.getOperand(1)); // lane
5681     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5682     TmpInst.addOperand(Inst.getOperand(5));
5683     Inst = TmpInst;
5684     return true;
5685   }
5686
5687   case ARM::VLD1LNdAsm_8:
5688   case ARM::VLD1LNdAsm_16:
5689   case ARM::VLD1LNdAsm_32: {
5690     MCInst TmpInst;
5691     // Shuffle the operands around so the lane index operand is in the
5692     // right place.
5693     unsigned Spacing;
5694     TmpInst.setOpcode(getRealVLDLNOpcode(Inst.getOpcode(), Spacing));
5695     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5696     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5697     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5698     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
5699     TmpInst.addOperand(Inst.getOperand(1)); // lane
5700     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5701     TmpInst.addOperand(Inst.getOperand(5));
5702     Inst = TmpInst;
5703     return true;
5704   }
5705
5706   case ARM::VLD2LNdAsm_8:
5707   case ARM::VLD2LNdAsm_16:
5708   case ARM::VLD2LNdAsm_32:
5709   case ARM::VLD2LNqAsm_16:
5710   case ARM::VLD2LNqAsm_32: {
5711     MCInst TmpInst;
5712     // Shuffle the operands around so the lane index operand is in the
5713     // right place.
5714     unsigned Spacing;
5715     TmpInst.setOpcode(getRealVLDLNOpcode(Inst.getOpcode(), Spacing));
5716     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5717     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5718                                             Spacing));
5719     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5720     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5721     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
5722     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5723                                             Spacing));
5724     TmpInst.addOperand(Inst.getOperand(1)); // lane
5725     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5726     TmpInst.addOperand(Inst.getOperand(5));
5727     Inst = TmpInst;
5728     return true;
5729   }
5730
5731   case ARM::VLD3LNdAsm_8:
5732   case ARM::VLD3LNdAsm_16:
5733   case ARM::VLD3LNdAsm_32:
5734   case ARM::VLD3LNqAsm_16:
5735   case ARM::VLD3LNqAsm_32: {
5736     MCInst TmpInst;
5737     // Shuffle the operands around so the lane index operand is in the
5738     // right place.
5739     unsigned Spacing;
5740     TmpInst.setOpcode(getRealVLDLNOpcode(Inst.getOpcode(), Spacing));
5741     TmpInst.addOperand(Inst.getOperand(0)); // Vd
5742     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5743                                             Spacing));
5744     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5745                                             Spacing));
5746     TmpInst.addOperand(Inst.getOperand(2)); // Rn
5747     TmpInst.addOperand(Inst.getOperand(3)); // alignment
5748     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
5749     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5750                                             Spacing));
5751     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
5752                                             Spacing));
5753     TmpInst.addOperand(Inst.getOperand(1)); // lane
5754     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5755     TmpInst.addOperand(Inst.getOperand(5));
5756     Inst = TmpInst;
5757     return true;
5758   }
5759
5760   // Handle the Thumb2 mode MOV complex aliases.
5761   case ARM::t2MOVsr:
5762   case ARM::t2MOVSsr: {
5763     // Which instruction to expand to depends on the CCOut operand and
5764     // whether we're in an IT block if the register operands are low
5765     // registers.
5766     bool isNarrow = false;
5767     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
5768         isARMLowRegister(Inst.getOperand(1).getReg()) &&
5769         isARMLowRegister(Inst.getOperand(2).getReg()) &&
5770         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
5771         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
5772       isNarrow = true;
5773     MCInst TmpInst;
5774     unsigned newOpc;
5775     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
5776     default: llvm_unreachable("unexpected opcode!");
5777     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
5778     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
5779     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
5780     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
5781     }
5782     TmpInst.setOpcode(newOpc);
5783     TmpInst.addOperand(Inst.getOperand(0)); // Rd
5784     if (isNarrow)
5785       TmpInst.addOperand(MCOperand::CreateReg(
5786           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
5787     TmpInst.addOperand(Inst.getOperand(1)); // Rn
5788     TmpInst.addOperand(Inst.getOperand(2)); // Rm
5789     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
5790     TmpInst.addOperand(Inst.getOperand(5));
5791     if (!isNarrow)
5792       TmpInst.addOperand(MCOperand::CreateReg(
5793           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
5794     Inst = TmpInst;
5795     return true;
5796   }
5797   case ARM::t2MOVsi:
5798   case ARM::t2MOVSsi: {
5799     // Which instruction to expand to depends on the CCOut operand and
5800     // whether we're in an IT block if the register operands are low
5801     // registers.
5802     bool isNarrow = false;
5803     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
5804         isARMLowRegister(Inst.getOperand(1).getReg()) &&
5805         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
5806       isNarrow = true;
5807     MCInst TmpInst;
5808     unsigned newOpc;
5809     switch(ARM_AM::getSORegShOp(Inst.getOperand(2).getImm())) {
5810     default: llvm_unreachable("unexpected opcode!");
5811     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
5812     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
5813     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
5814     case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
5815     case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
5816     }
5817     unsigned Ammount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
5818     if (Ammount == 32) Ammount = 0;
5819     TmpInst.setOpcode(newOpc);
5820     TmpInst.addOperand(Inst.getOperand(0)); // Rd
5821     if (isNarrow)
5822       TmpInst.addOperand(MCOperand::CreateReg(
5823           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
5824     TmpInst.addOperand(Inst.getOperand(1)); // Rn
5825     if (newOpc != ARM::t2RRX)
5826       TmpInst.addOperand(MCOperand::CreateImm(Ammount));
5827     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
5828     TmpInst.addOperand(Inst.getOperand(4));
5829     if (!isNarrow)
5830       TmpInst.addOperand(MCOperand::CreateReg(
5831           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
5832     Inst = TmpInst;
5833     return true;
5834   }
5835   // Handle the ARM mode MOV complex aliases.
5836   case ARM::ASRr:
5837   case ARM::LSRr:
5838   case ARM::LSLr:
5839   case ARM::RORr: {
5840     ARM_AM::ShiftOpc ShiftTy;
5841     switch(Inst.getOpcode()) {
5842     default: llvm_unreachable("unexpected opcode!");
5843     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
5844     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
5845     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
5846     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
5847     }
5848     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
5849     MCInst TmpInst;
5850     TmpInst.setOpcode(ARM::MOVsr);
5851     TmpInst.addOperand(Inst.getOperand(0)); // Rd
5852     TmpInst.addOperand(Inst.getOperand(1)); // Rn
5853     TmpInst.addOperand(Inst.getOperand(2)); // Rm
5854     TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and ty
5855     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
5856     TmpInst.addOperand(Inst.getOperand(4));
5857     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
5858     Inst = TmpInst;
5859     return true;
5860   }
5861   case ARM::ASRi:
5862   case ARM::LSRi:
5863   case ARM::LSLi:
5864   case ARM::RORi: {
5865     ARM_AM::ShiftOpc ShiftTy;
5866     switch(Inst.getOpcode()) {
5867     default: llvm_unreachable("unexpected opcode!");
5868     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
5869     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
5870     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
5871     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
5872     }
5873     // A shift by zero is a plain MOVr, not a MOVsi.
5874     unsigned Amt = Inst.getOperand(2).getImm();
5875     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
5876     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
5877     MCInst TmpInst;
5878     TmpInst.setOpcode(Opc);
5879     TmpInst.addOperand(Inst.getOperand(0)); // Rd
5880     TmpInst.addOperand(Inst.getOperand(1)); // Rn
5881     if (Opc == ARM::MOVsi)
5882       TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and ty
5883     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
5884     TmpInst.addOperand(Inst.getOperand(4));
5885     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
5886     Inst = TmpInst;
5887     return true;
5888   }
5889   case ARM::RRXi: {
5890     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
5891     MCInst TmpInst;
5892     TmpInst.setOpcode(ARM::MOVsi);
5893     TmpInst.addOperand(Inst.getOperand(0)); // Rd
5894     TmpInst.addOperand(Inst.getOperand(1)); // Rn
5895     TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and ty
5896     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
5897     TmpInst.addOperand(Inst.getOperand(3));
5898     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
5899     Inst = TmpInst;
5900     return true;
5901   }
5902   case ARM::t2LDMIA_UPD: {
5903     // If this is a load of a single register, then we should use
5904     // a post-indexed LDR instruction instead, per the ARM ARM.
5905     if (Inst.getNumOperands() != 5)
5906       return false;
5907     MCInst TmpInst;
5908     TmpInst.setOpcode(ARM::t2LDR_POST);
5909     TmpInst.addOperand(Inst.getOperand(4)); // Rt
5910     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
5911     TmpInst.addOperand(Inst.getOperand(1)); // Rn
5912     TmpInst.addOperand(MCOperand::CreateImm(4));
5913     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
5914     TmpInst.addOperand(Inst.getOperand(3));
5915     Inst = TmpInst;
5916     return true;
5917   }
5918   case ARM::t2STMDB_UPD: {
5919     // If this is a store of a single register, then we should use
5920     // a pre-indexed STR instruction instead, per the ARM ARM.
5921     if (Inst.getNumOperands() != 5)
5922       return false;
5923     MCInst TmpInst;
5924     TmpInst.setOpcode(ARM::t2STR_PRE);
5925     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
5926     TmpInst.addOperand(Inst.getOperand(4)); // Rt
5927     TmpInst.addOperand(Inst.getOperand(1)); // Rn
5928     TmpInst.addOperand(MCOperand::CreateImm(-4));
5929     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
5930     TmpInst.addOperand(Inst.getOperand(3));
5931     Inst = TmpInst;
5932     return true;
5933   }
5934   case ARM::LDMIA_UPD:
5935     // If this is a load of a single register via a 'pop', then we should use
5936     // a post-indexed LDR instruction instead, per the ARM ARM.
5937     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "pop" &&
5938         Inst.getNumOperands() == 5) {
5939       MCInst TmpInst;
5940       TmpInst.setOpcode(ARM::LDR_POST_IMM);
5941       TmpInst.addOperand(Inst.getOperand(4)); // Rt
5942       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
5943       TmpInst.addOperand(Inst.getOperand(1)); // Rn
5944       TmpInst.addOperand(MCOperand::CreateReg(0));  // am2offset
5945       TmpInst.addOperand(MCOperand::CreateImm(4));
5946       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
5947       TmpInst.addOperand(Inst.getOperand(3));
5948       Inst = TmpInst;
5949       return true;
5950     }
5951     break;
5952   case ARM::STMDB_UPD:
5953     // If this is a store of a single register via a 'push', then we should use
5954     // a pre-indexed STR instruction instead, per the ARM ARM.
5955     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "push" &&
5956         Inst.getNumOperands() == 5) {
5957       MCInst TmpInst;
5958       TmpInst.setOpcode(ARM::STR_PRE_IMM);
5959       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
5960       TmpInst.addOperand(Inst.getOperand(4)); // Rt
5961       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
5962       TmpInst.addOperand(MCOperand::CreateImm(-4));
5963       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
5964       TmpInst.addOperand(Inst.getOperand(3));
5965       Inst = TmpInst;
5966     }
5967     break;
5968   case ARM::t2ADDri12:
5969     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
5970     // mnemonic was used (not "addw"), encoding T3 is preferred.
5971     if (static_cast<ARMOperand*>(Operands[0])->getToken() != "add" ||
5972         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
5973       break;
5974     Inst.setOpcode(ARM::t2ADDri);
5975     Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
5976     break;
5977   case ARM::t2SUBri12:
5978     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
5979     // mnemonic was used (not "subw"), encoding T3 is preferred.
5980     if (static_cast<ARMOperand*>(Operands[0])->getToken() != "sub" ||
5981         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
5982       break;
5983     Inst.setOpcode(ARM::t2SUBri);
5984     Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
5985     break;
5986   case ARM::tADDi8:
5987     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
5988     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
5989     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
5990     // to encoding T1 if <Rd> is omitted."
5991     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
5992       Inst.setOpcode(ARM::tADDi3);
5993       return true;
5994     }
5995     break;
5996   case ARM::tSUBi8:
5997     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
5998     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
5999     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
6000     // to encoding T1 if <Rd> is omitted."
6001     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
6002       Inst.setOpcode(ARM::tSUBi3);
6003       return true;
6004     }
6005     break;
6006   case ARM::t2ADDrr: {
6007     // If the destination and first source operand are the same, and
6008     // there's no setting of the flags, use encoding T2 instead of T3.
6009     // Note that this is only for ADD, not SUB. This mirrors the system
6010     // 'as' behaviour. Make sure the wide encoding wasn't explicit.
6011     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
6012         Inst.getOperand(5).getReg() != 0 ||
6013         (static_cast<ARMOperand*>(Operands[3])->isToken() &&
6014          static_cast<ARMOperand*>(Operands[3])->getToken() == ".w"))
6015       break;
6016     MCInst TmpInst;
6017     TmpInst.setOpcode(ARM::tADDhirr);
6018     TmpInst.addOperand(Inst.getOperand(0));
6019     TmpInst.addOperand(Inst.getOperand(0));
6020     TmpInst.addOperand(Inst.getOperand(2));
6021     TmpInst.addOperand(Inst.getOperand(3));
6022     TmpInst.addOperand(Inst.getOperand(4));
6023     Inst = TmpInst;
6024     return true;
6025   }
6026   case ARM::tB:
6027     // A Thumb conditional branch outside of an IT block is a tBcc.
6028     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
6029       Inst.setOpcode(ARM::tBcc);
6030       return true;
6031     }
6032     break;
6033   case ARM::t2B:
6034     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
6035     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
6036       Inst.setOpcode(ARM::t2Bcc);
6037       return true;
6038     }
6039     break;
6040   case ARM::t2Bcc:
6041     // If the conditional is AL or we're in an IT block, we really want t2B.
6042     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
6043       Inst.setOpcode(ARM::t2B);
6044       return true;
6045     }
6046     break;
6047   case ARM::tBcc:
6048     // If the conditional is AL, we really want tB.
6049     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
6050       Inst.setOpcode(ARM::tB);
6051       return true;
6052     }
6053     break;
6054   case ARM::tLDMIA: {
6055     // If the register list contains any high registers, or if the writeback
6056     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
6057     // instead if we're in Thumb2. Otherwise, this should have generated
6058     // an error in validateInstruction().
6059     unsigned Rn = Inst.getOperand(0).getReg();
6060     bool hasWritebackToken =
6061       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
6062        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
6063     bool listContainsBase;
6064     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
6065         (!listContainsBase && !hasWritebackToken) ||
6066         (listContainsBase && hasWritebackToken)) {
6067       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
6068       assert (isThumbTwo());
6069       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
6070       // If we're switching to the updating version, we need to insert
6071       // the writeback tied operand.
6072       if (hasWritebackToken)
6073         Inst.insert(Inst.begin(),
6074                     MCOperand::CreateReg(Inst.getOperand(0).getReg()));
6075       return true;
6076     }
6077     break;
6078   }
6079   case ARM::tSTMIA_UPD: {
6080     // If the register list contains any high registers, we need to use
6081     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
6082     // should have generated an error in validateInstruction().
6083     unsigned Rn = Inst.getOperand(0).getReg();
6084     bool listContainsBase;
6085     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
6086       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
6087       assert (isThumbTwo());
6088       Inst.setOpcode(ARM::t2STMIA_UPD);
6089       return true;
6090     }
6091     break;
6092   }
6093   case ARM::tPOP: {
6094     bool listContainsBase;
6095     // If the register list contains any high registers, we need to use
6096     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
6097     // should have generated an error in validateInstruction().
6098     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
6099       return false;
6100     assert (isThumbTwo());
6101     Inst.setOpcode(ARM::t2LDMIA_UPD);
6102     // Add the base register and writeback operands.
6103     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
6104     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
6105     return true;
6106   }
6107   case ARM::tPUSH: {
6108     bool listContainsBase;
6109     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
6110       return false;
6111     assert (isThumbTwo());
6112     Inst.setOpcode(ARM::t2STMDB_UPD);
6113     // Add the base register and writeback operands.
6114     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
6115     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
6116     return true;
6117   }
6118   case ARM::t2MOVi: {
6119     // If we can use the 16-bit encoding and the user didn't explicitly
6120     // request the 32-bit variant, transform it here.
6121     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
6122         Inst.getOperand(1).getImm() <= 255 &&
6123         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
6124          Inst.getOperand(4).getReg() == ARM::CPSR) ||
6125         (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
6126         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
6127          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
6128       // The operands aren't in the same order for tMOVi8...
6129       MCInst TmpInst;
6130       TmpInst.setOpcode(ARM::tMOVi8);
6131       TmpInst.addOperand(Inst.getOperand(0));
6132       TmpInst.addOperand(Inst.getOperand(4));
6133       TmpInst.addOperand(Inst.getOperand(1));
6134       TmpInst.addOperand(Inst.getOperand(2));
6135       TmpInst.addOperand(Inst.getOperand(3));
6136       Inst = TmpInst;
6137       return true;
6138     }
6139     break;
6140   }
6141   case ARM::t2MOVr: {
6142     // If we can use the 16-bit encoding and the user didn't explicitly
6143     // request the 32-bit variant, transform it here.
6144     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
6145         isARMLowRegister(Inst.getOperand(1).getReg()) &&
6146         Inst.getOperand(2).getImm() == ARMCC::AL &&
6147         Inst.getOperand(4).getReg() == ARM::CPSR &&
6148         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
6149          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
6150       // The operands aren't the same for tMOV[S]r... (no cc_out)
6151       MCInst TmpInst;
6152       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
6153       TmpInst.addOperand(Inst.getOperand(0));
6154       TmpInst.addOperand(Inst.getOperand(1));
6155       TmpInst.addOperand(Inst.getOperand(2));
6156       TmpInst.addOperand(Inst.getOperand(3));
6157       Inst = TmpInst;
6158       return true;
6159     }
6160     break;
6161   }
6162   case ARM::t2SXTH:
6163   case ARM::t2SXTB:
6164   case ARM::t2UXTH:
6165   case ARM::t2UXTB: {
6166     // If we can use the 16-bit encoding and the user didn't explicitly
6167     // request the 32-bit variant, transform it here.
6168     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
6169         isARMLowRegister(Inst.getOperand(1).getReg()) &&
6170         Inst.getOperand(2).getImm() == 0 &&
6171         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
6172          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
6173       unsigned NewOpc;
6174       switch (Inst.getOpcode()) {
6175       default: llvm_unreachable("Illegal opcode!");
6176       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
6177       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
6178       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
6179       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
6180       }
6181       // The operands aren't the same for thumb1 (no rotate operand).
6182       MCInst TmpInst;
6183       TmpInst.setOpcode(NewOpc);
6184       TmpInst.addOperand(Inst.getOperand(0));
6185       TmpInst.addOperand(Inst.getOperand(1));
6186       TmpInst.addOperand(Inst.getOperand(3));
6187       TmpInst.addOperand(Inst.getOperand(4));
6188       Inst = TmpInst;
6189       return true;
6190     }
6191     break;
6192   }
6193   case ARM::MOVsi: {
6194     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
6195     if (SOpc == ARM_AM::rrx) return false;
6196     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
6197       // Shifting by zero is accepted as a vanilla 'MOVr'
6198       MCInst TmpInst;
6199       TmpInst.setOpcode(ARM::MOVr);
6200       TmpInst.addOperand(Inst.getOperand(0));
6201       TmpInst.addOperand(Inst.getOperand(1));
6202       TmpInst.addOperand(Inst.getOperand(3));
6203       TmpInst.addOperand(Inst.getOperand(4));
6204       TmpInst.addOperand(Inst.getOperand(5));
6205       Inst = TmpInst;
6206       return true;
6207     }
6208     return false;
6209   }
6210   case ARM::ANDrsi:
6211   case ARM::ORRrsi:
6212   case ARM::EORrsi:
6213   case ARM::BICrsi:
6214   case ARM::SUBrsi:
6215   case ARM::ADDrsi: {
6216     unsigned newOpc;
6217     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
6218     if (SOpc == ARM_AM::rrx) return false;
6219     switch (Inst.getOpcode()) {
6220     default: assert(0 && "unexpected opcode!");
6221     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
6222     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
6223     case ARM::EORrsi: newOpc = ARM::EORrr; break;
6224     case ARM::BICrsi: newOpc = ARM::BICrr; break;
6225     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
6226     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
6227     }
6228     // If the shift is by zero, use the non-shifted instruction definition.
6229     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0) {
6230       MCInst TmpInst;
6231       TmpInst.setOpcode(newOpc);
6232       TmpInst.addOperand(Inst.getOperand(0));
6233       TmpInst.addOperand(Inst.getOperand(1));
6234       TmpInst.addOperand(Inst.getOperand(2));
6235       TmpInst.addOperand(Inst.getOperand(4));
6236       TmpInst.addOperand(Inst.getOperand(5));
6237       TmpInst.addOperand(Inst.getOperand(6));
6238       Inst = TmpInst;
6239       return true;
6240     }
6241     return false;
6242   }
6243   case ARM::t2IT: {
6244     // The mask bits for all but the first condition are represented as
6245     // the low bit of the condition code value implies 't'. We currently
6246     // always have 1 implies 't', so XOR toggle the bits if the low bit
6247     // of the condition code is zero. The encoding also expects the low
6248     // bit of the condition to be encoded as bit 4 of the mask operand,
6249     // so mask that in if needed
6250     MCOperand &MO = Inst.getOperand(1);
6251     unsigned Mask = MO.getImm();
6252     unsigned OrigMask = Mask;
6253     unsigned TZ = CountTrailingZeros_32(Mask);
6254     if ((Inst.getOperand(0).getImm() & 1) == 0) {
6255       assert(Mask && TZ <= 3 && "illegal IT mask value!");
6256       for (unsigned i = 3; i != TZ; --i)
6257         Mask ^= 1 << i;
6258     } else
6259       Mask |= 0x10;
6260     MO.setImm(Mask);
6261
6262     // Set up the IT block state according to the IT instruction we just
6263     // matched.
6264     assert(!inITBlock() && "nested IT blocks?!");
6265     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
6266     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
6267     ITState.CurPosition = 0;
6268     ITState.FirstCond = true;
6269     break;
6270   }
6271   }
6272   return false;
6273 }
6274
6275 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
6276   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
6277   // suffix depending on whether they're in an IT block or not.
6278   unsigned Opc = Inst.getOpcode();
6279   const MCInstrDesc &MCID = getInstDesc(Opc);
6280   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
6281     assert(MCID.hasOptionalDef() &&
6282            "optionally flag setting instruction missing optional def operand");
6283     assert(MCID.NumOperands == Inst.getNumOperands() &&
6284            "operand count mismatch!");
6285     // Find the optional-def operand (cc_out).
6286     unsigned OpNo;
6287     for (OpNo = 0;
6288          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
6289          ++OpNo)
6290       ;
6291     // If we're parsing Thumb1, reject it completely.
6292     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
6293       return Match_MnemonicFail;
6294     // If we're parsing Thumb2, which form is legal depends on whether we're
6295     // in an IT block.
6296     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
6297         !inITBlock())
6298       return Match_RequiresITBlock;
6299     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
6300         inITBlock())
6301       return Match_RequiresNotITBlock;
6302   }
6303   // Some high-register supporting Thumb1 encodings only allow both registers
6304   // to be from r0-r7 when in Thumb2.
6305   else if (Opc == ARM::tADDhirr && isThumbOne() &&
6306            isARMLowRegister(Inst.getOperand(1).getReg()) &&
6307            isARMLowRegister(Inst.getOperand(2).getReg()))
6308     return Match_RequiresThumb2;
6309   // Others only require ARMv6 or later.
6310   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
6311            isARMLowRegister(Inst.getOperand(0).getReg()) &&
6312            isARMLowRegister(Inst.getOperand(1).getReg()))
6313     return Match_RequiresV6;
6314   return Match_Success;
6315 }
6316
6317 bool ARMAsmParser::
6318 MatchAndEmitInstruction(SMLoc IDLoc,
6319                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
6320                         MCStreamer &Out) {
6321   MCInst Inst;
6322   unsigned ErrorInfo;
6323   unsigned MatchResult;
6324   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
6325   switch (MatchResult) {
6326   default: break;
6327   case Match_Success:
6328     // Context sensitive operand constraints aren't handled by the matcher,
6329     // so check them here.
6330     if (validateInstruction(Inst, Operands)) {
6331       // Still progress the IT block, otherwise one wrong condition causes
6332       // nasty cascading errors.
6333       forwardITPosition();
6334       return true;
6335     }
6336
6337     // Some instructions need post-processing to, for example, tweak which
6338     // encoding is selected. Loop on it while changes happen so the
6339     // individual transformations can chain off each other. E.g.,
6340     // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
6341     while (processInstruction(Inst, Operands))
6342       ;
6343
6344     // Only move forward at the very end so that everything in validate
6345     // and process gets a consistent answer about whether we're in an IT
6346     // block.
6347     forwardITPosition();
6348
6349     Out.EmitInstruction(Inst);
6350     return false;
6351   case Match_MissingFeature:
6352     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
6353     return true;
6354   case Match_InvalidOperand: {
6355     SMLoc ErrorLoc = IDLoc;
6356     if (ErrorInfo != ~0U) {
6357       if (ErrorInfo >= Operands.size())
6358         return Error(IDLoc, "too few operands for instruction");
6359
6360       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
6361       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
6362     }
6363
6364     return Error(ErrorLoc, "invalid operand for instruction");
6365   }
6366   case Match_MnemonicFail:
6367     return Error(IDLoc, "invalid instruction");
6368   case Match_ConversionFail:
6369     // The converter function will have already emited a diagnostic.
6370     return true;
6371   case Match_RequiresNotITBlock:
6372     return Error(IDLoc, "flag setting instruction only valid outside IT block");
6373   case Match_RequiresITBlock:
6374     return Error(IDLoc, "instruction only valid inside IT block");
6375   case Match_RequiresV6:
6376     return Error(IDLoc, "instruction variant requires ARMv6 or later");
6377   case Match_RequiresThumb2:
6378     return Error(IDLoc, "instruction variant requires Thumb2");
6379   }
6380
6381   llvm_unreachable("Implement any new match types added!");
6382 }
6383
6384 /// parseDirective parses the arm specific directives
6385 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
6386   StringRef IDVal = DirectiveID.getIdentifier();
6387   if (IDVal == ".word")
6388     return parseDirectiveWord(4, DirectiveID.getLoc());
6389   else if (IDVal == ".thumb")
6390     return parseDirectiveThumb(DirectiveID.getLoc());
6391   else if (IDVal == ".arm")
6392     return parseDirectiveARM(DirectiveID.getLoc());
6393   else if (IDVal == ".thumb_func")
6394     return parseDirectiveThumbFunc(DirectiveID.getLoc());
6395   else if (IDVal == ".code")
6396     return parseDirectiveCode(DirectiveID.getLoc());
6397   else if (IDVal == ".syntax")
6398     return parseDirectiveSyntax(DirectiveID.getLoc());
6399   else if (IDVal == ".unreq")
6400     return parseDirectiveUnreq(DirectiveID.getLoc());
6401   else if (IDVal == ".arch")
6402     return parseDirectiveArch(DirectiveID.getLoc());
6403   else if (IDVal == ".eabi_attribute")
6404     return parseDirectiveEabiAttr(DirectiveID.getLoc());
6405   return true;
6406 }
6407
6408 /// parseDirectiveWord
6409 ///  ::= .word [ expression (, expression)* ]
6410 bool ARMAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
6411   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6412     for (;;) {
6413       const MCExpr *Value;
6414       if (getParser().ParseExpression(Value))
6415         return true;
6416
6417       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
6418
6419       if (getLexer().is(AsmToken::EndOfStatement))
6420         break;
6421
6422       // FIXME: Improve diagnostic.
6423       if (getLexer().isNot(AsmToken::Comma))
6424         return Error(L, "unexpected token in directive");
6425       Parser.Lex();
6426     }
6427   }
6428
6429   Parser.Lex();
6430   return false;
6431 }
6432
6433 /// parseDirectiveThumb
6434 ///  ::= .thumb
6435 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
6436   if (getLexer().isNot(AsmToken::EndOfStatement))
6437     return Error(L, "unexpected token in directive");
6438   Parser.Lex();
6439
6440   if (!isThumb())
6441     SwitchMode();
6442   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
6443   return false;
6444 }
6445
6446 /// parseDirectiveARM
6447 ///  ::= .arm
6448 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
6449   if (getLexer().isNot(AsmToken::EndOfStatement))
6450     return Error(L, "unexpected token in directive");
6451   Parser.Lex();
6452
6453   if (isThumb())
6454     SwitchMode();
6455   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
6456   return false;
6457 }
6458
6459 /// parseDirectiveThumbFunc
6460 ///  ::= .thumbfunc symbol_name
6461 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
6462   const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
6463   bool isMachO = MAI.hasSubsectionsViaSymbols();
6464   StringRef Name;
6465   bool needFuncName = true;
6466
6467   // Darwin asm has (optionally) function name after .thumb_func direction
6468   // ELF doesn't
6469   if (isMachO) {
6470     const AsmToken &Tok = Parser.getTok();
6471     if (Tok.isNot(AsmToken::EndOfStatement)) {
6472       if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
6473         return Error(L, "unexpected token in .thumb_func directive");
6474       Name = Tok.getIdentifier();
6475       Parser.Lex(); // Consume the identifier token.
6476       needFuncName = false;
6477     }
6478   }
6479
6480   if (getLexer().isNot(AsmToken::EndOfStatement))
6481     return Error(L, "unexpected token in directive");
6482
6483   // Eat the end of statement and any blank lines that follow.
6484   while (getLexer().is(AsmToken::EndOfStatement))
6485     Parser.Lex();
6486
6487   // FIXME: assuming function name will be the line following .thumb_func
6488   // We really should be checking the next symbol definition even if there's
6489   // stuff in between.
6490   if (needFuncName) {
6491     Name = Parser.getTok().getIdentifier();
6492   }
6493
6494   // Mark symbol as a thumb symbol.
6495   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
6496   getParser().getStreamer().EmitThumbFunc(Func);
6497   return false;
6498 }
6499
6500 /// parseDirectiveSyntax
6501 ///  ::= .syntax unified | divided
6502 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
6503   const AsmToken &Tok = Parser.getTok();
6504   if (Tok.isNot(AsmToken::Identifier))
6505     return Error(L, "unexpected token in .syntax directive");
6506   StringRef Mode = Tok.getString();
6507   if (Mode == "unified" || Mode == "UNIFIED")
6508     Parser.Lex();
6509   else if (Mode == "divided" || Mode == "DIVIDED")
6510     return Error(L, "'.syntax divided' arm asssembly not supported");
6511   else
6512     return Error(L, "unrecognized syntax mode in .syntax directive");
6513
6514   if (getLexer().isNot(AsmToken::EndOfStatement))
6515     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
6516   Parser.Lex();
6517
6518   // TODO tell the MC streamer the mode
6519   // getParser().getStreamer().Emit???();
6520   return false;
6521 }
6522
6523 /// parseDirectiveCode
6524 ///  ::= .code 16 | 32
6525 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
6526   const AsmToken &Tok = Parser.getTok();
6527   if (Tok.isNot(AsmToken::Integer))
6528     return Error(L, "unexpected token in .code directive");
6529   int64_t Val = Parser.getTok().getIntVal();
6530   if (Val == 16)
6531     Parser.Lex();
6532   else if (Val == 32)
6533     Parser.Lex();
6534   else
6535     return Error(L, "invalid operand to .code directive");
6536
6537   if (getLexer().isNot(AsmToken::EndOfStatement))
6538     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
6539   Parser.Lex();
6540
6541   if (Val == 16) {
6542     if (!isThumb())
6543       SwitchMode();
6544     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
6545   } else {
6546     if (isThumb())
6547       SwitchMode();
6548     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
6549   }
6550
6551   return false;
6552 }
6553
6554 /// parseDirectiveReq
6555 ///  ::= name .req registername
6556 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
6557   Parser.Lex(); // Eat the '.req' token.
6558   unsigned Reg;
6559   SMLoc SRegLoc, ERegLoc;
6560   if (ParseRegister(Reg, SRegLoc, ERegLoc)) {
6561     Parser.EatToEndOfStatement();
6562     return Error(SRegLoc, "register name expected");
6563   }
6564
6565   // Shouldn't be anything else.
6566   if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
6567     Parser.EatToEndOfStatement();
6568     return Error(Parser.getTok().getLoc(),
6569                  "unexpected input in .req directive.");
6570   }
6571
6572   Parser.Lex(); // Consume the EndOfStatement
6573
6574   if (RegisterReqs.GetOrCreateValue(Name, Reg).getValue() != Reg)
6575     return Error(SRegLoc, "redefinition of '" + Name +
6576                           "' does not match original.");
6577
6578   return false;
6579 }
6580
6581 /// parseDirectiveUneq
6582 ///  ::= .unreq registername
6583 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
6584   if (Parser.getTok().isNot(AsmToken::Identifier)) {
6585     Parser.EatToEndOfStatement();
6586     return Error(L, "unexpected input in .unreq directive.");
6587   }
6588   RegisterReqs.erase(Parser.getTok().getIdentifier());
6589   Parser.Lex(); // Eat the identifier.
6590   return false;
6591 }
6592
6593 /// parseDirectiveArch
6594 ///  ::= .arch token
6595 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
6596   return true;
6597 }
6598
6599 /// parseDirectiveEabiAttr
6600 ///  ::= .eabi_attribute int, int
6601 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
6602   return true;
6603 }
6604
6605 extern "C" void LLVMInitializeARMAsmLexer();
6606
6607 /// Force static initialization.
6608 extern "C" void LLVMInitializeARMAsmParser() {
6609   RegisterMCAsmParser<ARMAsmParser> X(TheARMTarget);
6610   RegisterMCAsmParser<ARMAsmParser> Y(TheThumbTarget);
6611   LLVMInitializeARMAsmLexer();
6612 }
6613
6614 #define GET_REGISTER_MATCHER
6615 #define GET_MATCHER_IMPLEMENTATION
6616 #include "ARMGenAsmMatcher.inc"