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