ARM assembly parsing and encoding for VMOV/VMVN/VORR/VBIC.i16.
[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/StringExtras.h"
34 #include "llvm/ADT/StringSwitch.h"
35 #include "llvm/ADT/Twine.h"
36
37 using namespace llvm;
38
39 namespace {
40
41 class ARMOperand;
42
43 class ARMAsmParser : public MCTargetAsmParser {
44   MCSubtargetInfo &STI;
45   MCAsmParser &Parser;
46
47   struct {
48     ARMCC::CondCodes Cond;    // Condition for IT block.
49     unsigned Mask:4;          // Condition mask for instructions.
50                               // Starting at first 1 (from lsb).
51                               //   '1'  condition as indicated in IT.
52                               //   '0'  inverse of condition (else).
53                               // Count of instructions in IT block is
54                               // 4 - trailingzeroes(mask)
55
56     bool FirstCond;           // Explicit flag for when we're parsing the
57                               // First instruction in the IT block. It's
58                               // implied in the mask, so needs special
59                               // handling.
60
61     unsigned CurPosition;     // Current position in parsing of IT
62                               // block. In range [0,3]. Initialized
63                               // according to count of instructions in block.
64                               // ~0U if no active IT block.
65   } ITState;
66   bool inITBlock() { return ITState.CurPosition != ~0U;}
67   void forwardITPosition() {
68     if (!inITBlock()) return;
69     // Move to the next instruction in the IT block, if there is one. If not,
70     // mark the block as done.
71     unsigned TZ = CountTrailingZeros_32(ITState.Mask);
72     if (++ITState.CurPosition == 5 - TZ)
73       ITState.CurPosition = ~0U; // Done with the IT block after this.
74   }
75
76
77   MCAsmParser &getParser() const { return Parser; }
78   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
79
80   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
81   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
82
83   int tryParseRegister();
84   bool tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
85   int tryParseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
86   bool parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
87   bool parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
88   bool parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
89   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
90   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
91                               unsigned &ShiftAmount);
92   bool parseDirectiveWord(unsigned Size, SMLoc L);
93   bool parseDirectiveThumb(SMLoc L);
94   bool parseDirectiveThumbFunc(SMLoc L);
95   bool parseDirectiveCode(SMLoc L);
96   bool parseDirectiveSyntax(SMLoc L);
97
98   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
99                           bool &CarrySetting, unsigned &ProcessorIMod,
100                           StringRef &ITMask);
101   void getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
102                              bool &CanAcceptPredicationCode);
103
104   bool isThumb() const {
105     // FIXME: Can tablegen auto-generate this?
106     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
107   }
108   bool isThumbOne() const {
109     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
110   }
111   bool isThumbTwo() const {
112     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2);
113   }
114   bool hasV6Ops() const {
115     return STI.getFeatureBits() & ARM::HasV6Ops;
116   }
117   bool hasV7Ops() const {
118     return STI.getFeatureBits() & ARM::HasV7Ops;
119   }
120   void SwitchMode() {
121     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
122     setAvailableFeatures(FB);
123   }
124   bool isMClass() const {
125     return STI.getFeatureBits() & ARM::FeatureMClass;
126   }
127
128   /// @name Auto-generated Match Functions
129   /// {
130
131 #define GET_ASSEMBLER_HEADER
132 #include "ARMGenAsmMatcher.inc"
133
134   /// }
135
136   OperandMatchResultTy parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*>&);
137   OperandMatchResultTy parseCoprocNumOperand(
138     SmallVectorImpl<MCParsedAsmOperand*>&);
139   OperandMatchResultTy parseCoprocRegOperand(
140     SmallVectorImpl<MCParsedAsmOperand*>&);
141   OperandMatchResultTy parseCoprocOptionOperand(
142     SmallVectorImpl<MCParsedAsmOperand*>&);
143   OperandMatchResultTy parseMemBarrierOptOperand(
144     SmallVectorImpl<MCParsedAsmOperand*>&);
145   OperandMatchResultTy parseProcIFlagsOperand(
146     SmallVectorImpl<MCParsedAsmOperand*>&);
147   OperandMatchResultTy parseMSRMaskOperand(
148     SmallVectorImpl<MCParsedAsmOperand*>&);
149   OperandMatchResultTy parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &O,
150                                    StringRef Op, int Low, int High);
151   OperandMatchResultTy parsePKHLSLImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
152     return parsePKHImm(O, "lsl", 0, 31);
153   }
154   OperandMatchResultTy parsePKHASRImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
155     return parsePKHImm(O, "asr", 1, 32);
156   }
157   OperandMatchResultTy parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*>&);
158   OperandMatchResultTy parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*>&);
159   OperandMatchResultTy parseRotImm(SmallVectorImpl<MCParsedAsmOperand*>&);
160   OperandMatchResultTy parseBitfield(SmallVectorImpl<MCParsedAsmOperand*>&);
161   OperandMatchResultTy parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*>&);
162   OperandMatchResultTy parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*>&);
163   OperandMatchResultTy parseFPImm(SmallVectorImpl<MCParsedAsmOperand*>&);
164
165   // Asm Match Converter Methods
166   bool cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
167                     const SmallVectorImpl<MCParsedAsmOperand*> &);
168   bool cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
169                     const SmallVectorImpl<MCParsedAsmOperand*> &);
170   bool cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
171                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
172   bool cvtStWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
173                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
174   bool cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
175                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
176   bool cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
177                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
178   bool cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
179                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
180   bool cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
181                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
182   bool cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
183                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
184   bool cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
185                              const SmallVectorImpl<MCParsedAsmOperand*> &);
186   bool cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
187                              const SmallVectorImpl<MCParsedAsmOperand*> &);
188   bool cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
189                              const SmallVectorImpl<MCParsedAsmOperand*> &);
190   bool cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
191                              const SmallVectorImpl<MCParsedAsmOperand*> &);
192   bool cvtLdrdPre(MCInst &Inst, unsigned Opcode,
193                   const SmallVectorImpl<MCParsedAsmOperand*> &);
194   bool cvtStrdPre(MCInst &Inst, unsigned Opcode,
195                   const SmallVectorImpl<MCParsedAsmOperand*> &);
196   bool cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
197                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
198   bool cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
199                         const SmallVectorImpl<MCParsedAsmOperand*> &);
200
201   bool validateInstruction(MCInst &Inst,
202                            const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
203   void processInstruction(MCInst &Inst,
204                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
205   bool shouldOmitCCOutOperand(StringRef Mnemonic,
206                               SmallVectorImpl<MCParsedAsmOperand*> &Operands);
207
208 public:
209   enum ARMMatchResultTy {
210     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
211     Match_RequiresNotITBlock,
212     Match_RequiresV6,
213     Match_RequiresThumb2
214   };
215
216   ARMAsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser)
217     : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
218     MCAsmParserExtension::Initialize(_Parser);
219
220     // Initialize the set of available features.
221     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
222
223     // Not in an ITBlock to start with.
224     ITState.CurPosition = ~0U;
225   }
226
227   // Implementation of the MCTargetAsmParser interface:
228   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
229   bool ParseInstruction(StringRef Name, SMLoc NameLoc,
230                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
231   bool ParseDirective(AsmToken DirectiveID);
232
233   unsigned checkTargetMatchPredicate(MCInst &Inst);
234
235   bool MatchAndEmitInstruction(SMLoc IDLoc,
236                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
237                                MCStreamer &Out);
238 };
239 } // end anonymous namespace
240
241 namespace {
242
243 /// ARMOperand - Instances of this class represent a parsed ARM machine
244 /// instruction.
245 class ARMOperand : public MCParsedAsmOperand {
246   enum KindTy {
247     k_CondCode,
248     k_CCOut,
249     k_ITCondMask,
250     k_CoprocNum,
251     k_CoprocReg,
252     k_CoprocOption,
253     k_Immediate,
254     k_FPImmediate,
255     k_MemBarrierOpt,
256     k_Memory,
257     k_PostIndexRegister,
258     k_MSRMask,
259     k_ProcIFlags,
260     k_VectorIndex,
261     k_Register,
262     k_RegisterList,
263     k_DPRRegisterList,
264     k_SPRRegisterList,
265     k_ShiftedRegister,
266     k_ShiftedImmediate,
267     k_ShifterImmediate,
268     k_RotateImmediate,
269     k_BitfieldDescriptor,
270     k_Token
271   } Kind;
272
273   SMLoc StartLoc, EndLoc;
274   SmallVector<unsigned, 8> Registers;
275
276   union {
277     struct {
278       ARMCC::CondCodes Val;
279     } CC;
280
281     struct {
282       unsigned Val;
283     } Cop;
284
285     struct {
286       unsigned Val;
287     } CoprocOption;
288
289     struct {
290       unsigned Mask:4;
291     } ITMask;
292
293     struct {
294       ARM_MB::MemBOpt Val;
295     } MBOpt;
296
297     struct {
298       ARM_PROC::IFlags Val;
299     } IFlags;
300
301     struct {
302       unsigned Val;
303     } MMask;
304
305     struct {
306       const char *Data;
307       unsigned Length;
308     } Tok;
309
310     struct {
311       unsigned RegNum;
312     } Reg;
313
314     struct {
315       unsigned Val;
316     } VectorIndex;
317
318     struct {
319       const MCExpr *Val;
320     } Imm;
321
322     struct {
323       unsigned Val;       // encoded 8-bit representation
324     } FPImm;
325
326     /// Combined record for all forms of ARM address expressions.
327     struct {
328       unsigned BaseRegNum;
329       // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
330       // was specified.
331       const MCConstantExpr *OffsetImm;  // Offset immediate value
332       unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
333       ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
334       unsigned ShiftImm;        // shift for OffsetReg.
335       unsigned Alignment;       // 0 = no alignment specified
336                                 // n = alignment in bytes (8, 16, or 32)
337       unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
338     } Memory;
339
340     struct {
341       unsigned RegNum;
342       bool isAdd;
343       ARM_AM::ShiftOpc ShiftTy;
344       unsigned ShiftImm;
345     } PostIdxReg;
346
347     struct {
348       bool isASR;
349       unsigned Imm;
350     } ShifterImm;
351     struct {
352       ARM_AM::ShiftOpc ShiftTy;
353       unsigned SrcReg;
354       unsigned ShiftReg;
355       unsigned ShiftImm;
356     } RegShiftedReg;
357     struct {
358       ARM_AM::ShiftOpc ShiftTy;
359       unsigned SrcReg;
360       unsigned ShiftImm;
361     } RegShiftedImm;
362     struct {
363       unsigned Imm;
364     } RotImm;
365     struct {
366       unsigned LSB;
367       unsigned Width;
368     } Bitfield;
369   };
370
371   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
372 public:
373   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
374     Kind = o.Kind;
375     StartLoc = o.StartLoc;
376     EndLoc = o.EndLoc;
377     switch (Kind) {
378     case k_CondCode:
379       CC = o.CC;
380       break;
381     case k_ITCondMask:
382       ITMask = o.ITMask;
383       break;
384     case k_Token:
385       Tok = o.Tok;
386       break;
387     case k_CCOut:
388     case k_Register:
389       Reg = o.Reg;
390       break;
391     case k_RegisterList:
392     case k_DPRRegisterList:
393     case k_SPRRegisterList:
394       Registers = o.Registers;
395       break;
396     case k_CoprocNum:
397     case k_CoprocReg:
398       Cop = o.Cop;
399       break;
400     case k_CoprocOption:
401       CoprocOption = o.CoprocOption;
402       break;
403     case k_Immediate:
404       Imm = o.Imm;
405       break;
406     case k_FPImmediate:
407       FPImm = o.FPImm;
408       break;
409     case k_MemBarrierOpt:
410       MBOpt = o.MBOpt;
411       break;
412     case k_Memory:
413       Memory = o.Memory;
414       break;
415     case k_PostIndexRegister:
416       PostIdxReg = o.PostIdxReg;
417       break;
418     case k_MSRMask:
419       MMask = o.MMask;
420       break;
421     case k_ProcIFlags:
422       IFlags = o.IFlags;
423       break;
424     case k_ShifterImmediate:
425       ShifterImm = o.ShifterImm;
426       break;
427     case k_ShiftedRegister:
428       RegShiftedReg = o.RegShiftedReg;
429       break;
430     case k_ShiftedImmediate:
431       RegShiftedImm = o.RegShiftedImm;
432       break;
433     case k_RotateImmediate:
434       RotImm = o.RotImm;
435       break;
436     case k_BitfieldDescriptor:
437       Bitfield = o.Bitfield;
438       break;
439     case k_VectorIndex:
440       VectorIndex = o.VectorIndex;
441       break;
442     }
443   }
444
445   /// getStartLoc - Get the location of the first token of this operand.
446   SMLoc getStartLoc() const { return StartLoc; }
447   /// getEndLoc - Get the location of the last token of this operand.
448   SMLoc getEndLoc() const { return EndLoc; }
449
450   ARMCC::CondCodes getCondCode() const {
451     assert(Kind == k_CondCode && "Invalid access!");
452     return CC.Val;
453   }
454
455   unsigned getCoproc() const {
456     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
457     return Cop.Val;
458   }
459
460   StringRef getToken() const {
461     assert(Kind == k_Token && "Invalid access!");
462     return StringRef(Tok.Data, Tok.Length);
463   }
464
465   unsigned getReg() const {
466     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
467     return Reg.RegNum;
468   }
469
470   const SmallVectorImpl<unsigned> &getRegList() const {
471     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
472             Kind == k_SPRRegisterList) && "Invalid access!");
473     return Registers;
474   }
475
476   const MCExpr *getImm() const {
477     assert(Kind == k_Immediate && "Invalid access!");
478     return Imm.Val;
479   }
480
481   unsigned getFPImm() const {
482     assert(Kind == k_FPImmediate && "Invalid access!");
483     return FPImm.Val;
484   }
485
486   unsigned getVectorIndex() const {
487     assert(Kind == k_VectorIndex && "Invalid access!");
488     return VectorIndex.Val;
489   }
490
491   ARM_MB::MemBOpt getMemBarrierOpt() const {
492     assert(Kind == k_MemBarrierOpt && "Invalid access!");
493     return MBOpt.Val;
494   }
495
496   ARM_PROC::IFlags getProcIFlags() const {
497     assert(Kind == k_ProcIFlags && "Invalid access!");
498     return IFlags.Val;
499   }
500
501   unsigned getMSRMask() const {
502     assert(Kind == k_MSRMask && "Invalid access!");
503     return MMask.Val;
504   }
505
506   bool isCoprocNum() const { return Kind == k_CoprocNum; }
507   bool isCoprocReg() const { return Kind == k_CoprocReg; }
508   bool isCoprocOption() const { return Kind == k_CoprocOption; }
509   bool isCondCode() const { return Kind == k_CondCode; }
510   bool isCCOut() const { return Kind == k_CCOut; }
511   bool isITMask() const { return Kind == k_ITCondMask; }
512   bool isITCondCode() const { return Kind == k_CondCode; }
513   bool isImm() const { return Kind == k_Immediate; }
514   bool isFPImm() const { return Kind == k_FPImmediate; }
515   bool isImm8s4() const {
516     if (Kind != k_Immediate)
517       return false;
518     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
519     if (!CE) return false;
520     int64_t Value = CE->getValue();
521     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
522   }
523   bool isImm0_1020s4() const {
524     if (Kind != k_Immediate)
525       return false;
526     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
527     if (!CE) return false;
528     int64_t Value = CE->getValue();
529     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
530   }
531   bool isImm0_508s4() const {
532     if (Kind != k_Immediate)
533       return false;
534     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
535     if (!CE) return false;
536     int64_t Value = CE->getValue();
537     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
538   }
539   bool isImm0_255() const {
540     if (Kind != k_Immediate)
541       return false;
542     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
543     if (!CE) return false;
544     int64_t Value = CE->getValue();
545     return Value >= 0 && Value < 256;
546   }
547   bool isImm0_7() const {
548     if (Kind != k_Immediate)
549       return false;
550     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
551     if (!CE) return false;
552     int64_t Value = CE->getValue();
553     return Value >= 0 && Value < 8;
554   }
555   bool isImm0_15() const {
556     if (Kind != k_Immediate)
557       return false;
558     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
559     if (!CE) return false;
560     int64_t Value = CE->getValue();
561     return Value >= 0 && Value < 16;
562   }
563   bool isImm0_31() const {
564     if (Kind != k_Immediate)
565       return false;
566     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
567     if (!CE) return false;
568     int64_t Value = CE->getValue();
569     return Value >= 0 && Value < 32;
570   }
571   bool isImm1_16() const {
572     if (Kind != k_Immediate)
573       return false;
574     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
575     if (!CE) return false;
576     int64_t Value = CE->getValue();
577     return Value > 0 && Value < 17;
578   }
579   bool isImm1_32() const {
580     if (Kind != k_Immediate)
581       return false;
582     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
583     if (!CE) return false;
584     int64_t Value = CE->getValue();
585     return Value > 0 && Value < 33;
586   }
587   bool isImm0_65535() const {
588     if (Kind != k_Immediate)
589       return false;
590     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
591     if (!CE) return false;
592     int64_t Value = CE->getValue();
593     return Value >= 0 && Value < 65536;
594   }
595   bool isImm0_65535Expr() const {
596     if (Kind != k_Immediate)
597       return false;
598     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
599     // If it's not a constant expression, it'll generate a fixup and be
600     // handled later.
601     if (!CE) return true;
602     int64_t Value = CE->getValue();
603     return Value >= 0 && Value < 65536;
604   }
605   bool isImm24bit() const {
606     if (Kind != k_Immediate)
607       return false;
608     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
609     if (!CE) return false;
610     int64_t Value = CE->getValue();
611     return Value >= 0 && Value <= 0xffffff;
612   }
613   bool isImmThumbSR() const {
614     if (Kind != k_Immediate)
615       return false;
616     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
617     if (!CE) return false;
618     int64_t Value = CE->getValue();
619     return Value > 0 && Value < 33;
620   }
621   bool isPKHLSLImm() const {
622     if (Kind != k_Immediate)
623       return false;
624     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
625     if (!CE) return false;
626     int64_t Value = CE->getValue();
627     return Value >= 0 && Value < 32;
628   }
629   bool isPKHASRImm() const {
630     if (Kind != k_Immediate)
631       return false;
632     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
633     if (!CE) return false;
634     int64_t Value = CE->getValue();
635     return Value > 0 && Value <= 32;
636   }
637   bool isARMSOImm() const {
638     if (Kind != k_Immediate)
639       return false;
640     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
641     if (!CE) return false;
642     int64_t Value = CE->getValue();
643     return ARM_AM::getSOImmVal(Value) != -1;
644   }
645   bool isT2SOImm() const {
646     if (Kind != k_Immediate)
647       return false;
648     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
649     if (!CE) return false;
650     int64_t Value = CE->getValue();
651     return ARM_AM::getT2SOImmVal(Value) != -1;
652   }
653   bool isSetEndImm() const {
654     if (Kind != k_Immediate)
655       return false;
656     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
657     if (!CE) return false;
658     int64_t Value = CE->getValue();
659     return Value == 1 || Value == 0;
660   }
661   bool isReg() const { return Kind == k_Register; }
662   bool isRegList() const { return Kind == k_RegisterList; }
663   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
664   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
665   bool isToken() const { return Kind == k_Token; }
666   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
667   bool isMemory() const { return Kind == k_Memory; }
668   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
669   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
670   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
671   bool isRotImm() const { return Kind == k_RotateImmediate; }
672   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
673   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
674   bool isPostIdxReg() const {
675     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy == ARM_AM::no_shift;
676   }
677   bool isMemNoOffset(bool alignOK = false) const {
678     if (!isMemory())
679       return false;
680     // No offset of any kind.
681     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == 0 &&
682      (alignOK || Memory.Alignment == 0);
683   }
684   bool isAlignedMemory() const {
685     return isMemNoOffset(true);
686   }
687   bool isAddrMode2() const {
688     if (!isMemory() || Memory.Alignment != 0) return false;
689     // Check for register offset.
690     if (Memory.OffsetRegNum) return true;
691     // Immediate offset in range [-4095, 4095].
692     if (!Memory.OffsetImm) return true;
693     int64_t Val = Memory.OffsetImm->getValue();
694     return Val > -4096 && Val < 4096;
695   }
696   bool isAM2OffsetImm() const {
697     if (Kind != k_Immediate)
698       return false;
699     // Immediate offset in range [-4095, 4095].
700     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
701     if (!CE) return false;
702     int64_t Val = CE->getValue();
703     return Val > -4096 && Val < 4096;
704   }
705   bool isAddrMode3() const {
706     if (!isMemory() || Memory.Alignment != 0) return false;
707     // No shifts are legal for AM3.
708     if (Memory.ShiftType != ARM_AM::no_shift) return false;
709     // Check for register offset.
710     if (Memory.OffsetRegNum) return true;
711     // Immediate offset in range [-255, 255].
712     if (!Memory.OffsetImm) return true;
713     int64_t Val = Memory.OffsetImm->getValue();
714     return Val > -256 && Val < 256;
715   }
716   bool isAM3Offset() const {
717     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
718       return false;
719     if (Kind == k_PostIndexRegister)
720       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
721     // Immediate offset in range [-255, 255].
722     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
723     if (!CE) return false;
724     int64_t Val = CE->getValue();
725     // Special case, #-0 is INT32_MIN.
726     return (Val > -256 && Val < 256) || Val == INT32_MIN;
727   }
728   bool isAddrMode5() const {
729     if (!isMemory() || Memory.Alignment != 0) return false;
730     // Check for register offset.
731     if (Memory.OffsetRegNum) return false;
732     // Immediate offset in range [-1020, 1020] and a multiple of 4.
733     if (!Memory.OffsetImm) return true;
734     int64_t Val = Memory.OffsetImm->getValue();
735     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
736            Val == INT32_MIN;
737   }
738   bool isMemTBB() const {
739     if (!isMemory() || !Memory.OffsetRegNum || Memory.isNegative ||
740         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
741       return false;
742     return true;
743   }
744   bool isMemTBH() const {
745     if (!isMemory() || !Memory.OffsetRegNum || Memory.isNegative ||
746         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
747         Memory.Alignment != 0 )
748       return false;
749     return true;
750   }
751   bool isMemRegOffset() const {
752     if (!isMemory() || !Memory.OffsetRegNum || Memory.Alignment != 0)
753       return false;
754     return true;
755   }
756   bool isT2MemRegOffset() const {
757     if (!isMemory() || !Memory.OffsetRegNum || Memory.isNegative ||
758         Memory.Alignment != 0)
759       return false;
760     // Only lsl #{0, 1, 2, 3} allowed.
761     if (Memory.ShiftType == ARM_AM::no_shift)
762       return true;
763     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
764       return false;
765     return true;
766   }
767   bool isMemThumbRR() const {
768     // Thumb reg+reg addressing is simple. Just two registers, a base and
769     // an offset. No shifts, negations or any other complicating factors.
770     if (!isMemory() || !Memory.OffsetRegNum || Memory.isNegative ||
771         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
772       return false;
773     return isARMLowRegister(Memory.BaseRegNum) &&
774       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
775   }
776   bool isMemThumbRIs4() const {
777     if (!isMemory() || Memory.OffsetRegNum != 0 ||
778         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
779       return false;
780     // Immediate offset, multiple of 4 in range [0, 124].
781     if (!Memory.OffsetImm) return true;
782     int64_t Val = Memory.OffsetImm->getValue();
783     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
784   }
785   bool isMemThumbRIs2() const {
786     if (!isMemory() || Memory.OffsetRegNum != 0 ||
787         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
788       return false;
789     // Immediate offset, multiple of 4 in range [0, 62].
790     if (!Memory.OffsetImm) return true;
791     int64_t Val = Memory.OffsetImm->getValue();
792     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
793   }
794   bool isMemThumbRIs1() const {
795     if (!isMemory() || Memory.OffsetRegNum != 0 ||
796         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
797       return false;
798     // Immediate offset in range [0, 31].
799     if (!Memory.OffsetImm) return true;
800     int64_t Val = Memory.OffsetImm->getValue();
801     return Val >= 0 && Val <= 31;
802   }
803   bool isMemThumbSPI() const {
804     if (!isMemory() || Memory.OffsetRegNum != 0 ||
805         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
806       return false;
807     // Immediate offset, multiple of 4 in range [0, 1020].
808     if (!Memory.OffsetImm) return true;
809     int64_t Val = Memory.OffsetImm->getValue();
810     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
811   }
812   bool isMemImm8s4Offset() const {
813     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
814       return false;
815     // Immediate offset a multiple of 4 in range [-1020, 1020].
816     if (!Memory.OffsetImm) return true;
817     int64_t Val = Memory.OffsetImm->getValue();
818     return Val >= -1020 && Val <= 1020 && (Val & 3) == 0;
819   }
820   bool isMemImm0_1020s4Offset() const {
821     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
822       return false;
823     // Immediate offset a multiple of 4 in range [0, 1020].
824     if (!Memory.OffsetImm) return true;
825     int64_t Val = Memory.OffsetImm->getValue();
826     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
827   }
828   bool isMemImm8Offset() const {
829     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
830       return false;
831     // Immediate offset in range [-255, 255].
832     if (!Memory.OffsetImm) return true;
833     int64_t Val = Memory.OffsetImm->getValue();
834     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
835   }
836   bool isMemPosImm8Offset() const {
837     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
838       return false;
839     // Immediate offset in range [0, 255].
840     if (!Memory.OffsetImm) return true;
841     int64_t Val = Memory.OffsetImm->getValue();
842     return Val >= 0 && Val < 256;
843   }
844   bool isMemNegImm8Offset() const {
845     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
846       return false;
847     // Immediate offset in range [-255, -1].
848     if (!Memory.OffsetImm) return true;
849     int64_t Val = Memory.OffsetImm->getValue();
850     return Val > -256 && Val < 0;
851   }
852   bool isMemUImm12Offset() const {
853     // If we have an immediate that's not a constant, treat it as a label
854     // reference needing a fixup. If it is a constant, it's something else
855     // and we reject it.
856     if (Kind == k_Immediate && !isa<MCConstantExpr>(getImm()))
857       return true;
858
859     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
860       return false;
861     // Immediate offset in range [0, 4095].
862     if (!Memory.OffsetImm) return true;
863     int64_t Val = Memory.OffsetImm->getValue();
864     return (Val >= 0 && Val < 4096);
865   }
866   bool isMemImm12Offset() const {
867     // If we have an immediate that's not a constant, treat it as a label
868     // reference needing a fixup. If it is a constant, it's something else
869     // and we reject it.
870     if (Kind == k_Immediate && !isa<MCConstantExpr>(getImm()))
871       return true;
872
873     if (!isMemory() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
874       return false;
875     // Immediate offset in range [-4095, 4095].
876     if (!Memory.OffsetImm) return true;
877     int64_t Val = Memory.OffsetImm->getValue();
878     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
879   }
880   bool isPostIdxImm8() const {
881     if (Kind != k_Immediate)
882       return false;
883     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
884     if (!CE) return false;
885     int64_t Val = CE->getValue();
886     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
887   }
888   bool isPostIdxImm8s4() const {
889     if (Kind != k_Immediate)
890       return false;
891     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
892     if (!CE) return false;
893     int64_t Val = CE->getValue();
894     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
895       (Val == INT32_MIN);
896   }
897
898   bool isMSRMask() const { return Kind == k_MSRMask; }
899   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
900
901   // NEON operands.
902   bool isVectorIndex8() const {
903     if (Kind != k_VectorIndex) return false;
904     return VectorIndex.Val < 8;
905   }
906   bool isVectorIndex16() const {
907     if (Kind != k_VectorIndex) return false;
908     return VectorIndex.Val < 4;
909   }
910   bool isVectorIndex32() const {
911     if (Kind != k_VectorIndex) return false;
912     return VectorIndex.Val < 2;
913   }
914
915   bool isNEONi8splat() const {
916     if (Kind != k_Immediate)
917       return false;
918     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
919     // Must be a constant.
920     if (!CE) return false;
921     int64_t Value = CE->getValue();
922     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
923     // value.
924     return Value >= 0 && Value < 256;
925   }
926
927   bool isNEONi16splat() const {
928     if (Kind != k_Immediate)
929       return false;
930     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
931     // Must be a constant.
932     if (!CE) return false;
933     int64_t Value = CE->getValue();
934     // i16 value in the range [0,255] or [0x0100, 0xff00]
935     return (Value >= 0 && Value < 256) || (Value >= 0x0100 && Value <= 0xff00);
936   }
937
938   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
939     // Add as immediates when possible.  Null MCExpr = 0.
940     if (Expr == 0)
941       Inst.addOperand(MCOperand::CreateImm(0));
942     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
943       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
944     else
945       Inst.addOperand(MCOperand::CreateExpr(Expr));
946   }
947
948   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
949     assert(N == 2 && "Invalid number of operands!");
950     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
951     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
952     Inst.addOperand(MCOperand::CreateReg(RegNum));
953   }
954
955   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
956     assert(N == 1 && "Invalid number of operands!");
957     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
958   }
959
960   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
961     assert(N == 1 && "Invalid number of operands!");
962     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
963   }
964
965   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
966     assert(N == 1 && "Invalid number of operands!");
967     Inst.addOperand(MCOperand::CreateImm(CoprocOption.Val));
968   }
969
970   void addITMaskOperands(MCInst &Inst, unsigned N) const {
971     assert(N == 1 && "Invalid number of operands!");
972     Inst.addOperand(MCOperand::CreateImm(ITMask.Mask));
973   }
974
975   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
976     assert(N == 1 && "Invalid number of operands!");
977     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
978   }
979
980   void addCCOutOperands(MCInst &Inst, unsigned N) const {
981     assert(N == 1 && "Invalid number of operands!");
982     Inst.addOperand(MCOperand::CreateReg(getReg()));
983   }
984
985   void addRegOperands(MCInst &Inst, unsigned N) const {
986     assert(N == 1 && "Invalid number of operands!");
987     Inst.addOperand(MCOperand::CreateReg(getReg()));
988   }
989
990   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
991     assert(N == 3 && "Invalid number of operands!");
992     assert(isRegShiftedReg() && "addRegShiftedRegOperands() on non RegShiftedReg!");
993     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
994     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
995     Inst.addOperand(MCOperand::CreateImm(
996       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
997   }
998
999   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1000     assert(N == 2 && "Invalid number of operands!");
1001     assert(isRegShiftedImm() && "addRegShiftedImmOperands() on non RegShiftedImm!");
1002     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
1003     Inst.addOperand(MCOperand::CreateImm(
1004       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, RegShiftedImm.ShiftImm)));
1005   }
1006
1007   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1008     assert(N == 1 && "Invalid number of operands!");
1009     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
1010                                          ShifterImm.Imm));
1011   }
1012
1013   void addRegListOperands(MCInst &Inst, unsigned N) const {
1014     assert(N == 1 && "Invalid number of operands!");
1015     const SmallVectorImpl<unsigned> &RegList = getRegList();
1016     for (SmallVectorImpl<unsigned>::const_iterator
1017            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1018       Inst.addOperand(MCOperand::CreateReg(*I));
1019   }
1020
1021   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1022     addRegListOperands(Inst, N);
1023   }
1024
1025   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1026     addRegListOperands(Inst, N);
1027   }
1028
1029   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1030     assert(N == 1 && "Invalid number of operands!");
1031     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1032     Inst.addOperand(MCOperand::CreateImm(RotImm.Imm >> 3));
1033   }
1034
1035   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1036     assert(N == 1 && "Invalid number of operands!");
1037     // Munge the lsb/width into a bitfield mask.
1038     unsigned lsb = Bitfield.LSB;
1039     unsigned width = Bitfield.Width;
1040     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1041     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1042                       (32 - (lsb + width)));
1043     Inst.addOperand(MCOperand::CreateImm(Mask));
1044   }
1045
1046   void addImmOperands(MCInst &Inst, unsigned N) const {
1047     assert(N == 1 && "Invalid number of operands!");
1048     addExpr(Inst, getImm());
1049   }
1050
1051   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1052     assert(N == 1 && "Invalid number of operands!");
1053     Inst.addOperand(MCOperand::CreateImm(getFPImm()));
1054   }
1055
1056   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1057     assert(N == 1 && "Invalid number of operands!");
1058     // FIXME: We really want to scale the value here, but the LDRD/STRD
1059     // instruction don't encode operands that way yet.
1060     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1061     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1062   }
1063
1064   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1065     assert(N == 1 && "Invalid number of operands!");
1066     // The immediate is scaled by four in the encoding and is stored
1067     // in the MCInst as such. Lop off the low two bits here.
1068     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1069     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
1070   }
1071
1072   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1073     assert(N == 1 && "Invalid number of operands!");
1074     // The immediate is scaled by four in the encoding and is stored
1075     // in the MCInst as such. Lop off the low two bits here.
1076     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1077     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
1078   }
1079
1080   void addImm0_255Operands(MCInst &Inst, unsigned N) const {
1081     assert(N == 1 && "Invalid number of operands!");
1082     addExpr(Inst, getImm());
1083   }
1084
1085   void addImm0_7Operands(MCInst &Inst, unsigned N) const {
1086     assert(N == 1 && "Invalid number of operands!");
1087     addExpr(Inst, getImm());
1088   }
1089
1090   void addImm0_15Operands(MCInst &Inst, unsigned N) const {
1091     assert(N == 1 && "Invalid number of operands!");
1092     addExpr(Inst, getImm());
1093   }
1094
1095   void addImm0_31Operands(MCInst &Inst, unsigned N) const {
1096     assert(N == 1 && "Invalid number of operands!");
1097     addExpr(Inst, getImm());
1098   }
1099
1100   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1101     assert(N == 1 && "Invalid number of operands!");
1102     // The constant encodes as the immediate-1, and we store in the instruction
1103     // the bits as encoded, so subtract off one here.
1104     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1105     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1106   }
1107
1108   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1109     assert(N == 1 && "Invalid number of operands!");
1110     // The constant encodes as the immediate-1, and we store in the instruction
1111     // the bits as encoded, so subtract off one here.
1112     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1113     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1114   }
1115
1116   void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
1117     assert(N == 1 && "Invalid number of operands!");
1118     addExpr(Inst, getImm());
1119   }
1120
1121   void addImm0_65535ExprOperands(MCInst &Inst, unsigned N) const {
1122     assert(N == 1 && "Invalid number of operands!");
1123     addExpr(Inst, getImm());
1124   }
1125
1126   void addImm24bitOperands(MCInst &Inst, unsigned N) const {
1127     assert(N == 1 && "Invalid number of operands!");
1128     addExpr(Inst, getImm());
1129   }
1130
1131   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1132     assert(N == 1 && "Invalid number of operands!");
1133     // The constant encodes as the immediate, except for 32, which encodes as
1134     // zero.
1135     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1136     unsigned Imm = CE->getValue();
1137     Inst.addOperand(MCOperand::CreateImm((Imm == 32 ? 0 : Imm)));
1138   }
1139
1140   void addPKHLSLImmOperands(MCInst &Inst, unsigned N) const {
1141     assert(N == 1 && "Invalid number of operands!");
1142     addExpr(Inst, getImm());
1143   }
1144
1145   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1146     assert(N == 1 && "Invalid number of operands!");
1147     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1148     // the instruction as well.
1149     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1150     int Val = CE->getValue();
1151     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
1152   }
1153
1154   void addARMSOImmOperands(MCInst &Inst, unsigned N) const {
1155     assert(N == 1 && "Invalid number of operands!");
1156     addExpr(Inst, getImm());
1157   }
1158
1159   void addT2SOImmOperands(MCInst &Inst, unsigned N) const {
1160     assert(N == 1 && "Invalid number of operands!");
1161     addExpr(Inst, getImm());
1162   }
1163
1164   void addSetEndImmOperands(MCInst &Inst, unsigned N) const {
1165     assert(N == 1 && "Invalid number of operands!");
1166     addExpr(Inst, getImm());
1167   }
1168
1169   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
1170     assert(N == 1 && "Invalid number of operands!");
1171     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
1172   }
1173
1174   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
1175     assert(N == 1 && "Invalid number of operands!");
1176     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1177   }
1178
1179   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
1180     assert(N == 2 && "Invalid number of operands!");
1181     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1182     Inst.addOperand(MCOperand::CreateImm(Memory.Alignment));
1183   }
1184
1185   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
1186     assert(N == 3 && "Invalid number of operands!");
1187     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1188     if (!Memory.OffsetRegNum) {
1189       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1190       // Special case for #-0
1191       if (Val == INT32_MIN) Val = 0;
1192       if (Val < 0) Val = -Val;
1193       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1194     } else {
1195       // For register offset, we encode the shift type and negation flag
1196       // here.
1197       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
1198                               Memory.ShiftImm, Memory.ShiftType);
1199     }
1200     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1201     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1202     Inst.addOperand(MCOperand::CreateImm(Val));
1203   }
1204
1205   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
1206     assert(N == 2 && "Invalid number of operands!");
1207     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1208     assert(CE && "non-constant AM2OffsetImm operand!");
1209     int32_t Val = CE->getValue();
1210     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1211     // Special case for #-0
1212     if (Val == INT32_MIN) Val = 0;
1213     if (Val < 0) Val = -Val;
1214     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1215     Inst.addOperand(MCOperand::CreateReg(0));
1216     Inst.addOperand(MCOperand::CreateImm(Val));
1217   }
1218
1219   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
1220     assert(N == 3 && "Invalid number of operands!");
1221     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1222     if (!Memory.OffsetRegNum) {
1223       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1224       // Special case for #-0
1225       if (Val == INT32_MIN) Val = 0;
1226       if (Val < 0) Val = -Val;
1227       Val = ARM_AM::getAM3Opc(AddSub, Val);
1228     } else {
1229       // For register offset, we encode the shift type and negation flag
1230       // here.
1231       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
1232     }
1233     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1234     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1235     Inst.addOperand(MCOperand::CreateImm(Val));
1236   }
1237
1238   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
1239     assert(N == 2 && "Invalid number of operands!");
1240     if (Kind == k_PostIndexRegister) {
1241       int32_t Val =
1242         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
1243       Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1244       Inst.addOperand(MCOperand::CreateImm(Val));
1245       return;
1246     }
1247
1248     // Constant offset.
1249     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
1250     int32_t Val = CE->getValue();
1251     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1252     // Special case for #-0
1253     if (Val == INT32_MIN) Val = 0;
1254     if (Val < 0) Val = -Val;
1255     Val = ARM_AM::getAM3Opc(AddSub, Val);
1256     Inst.addOperand(MCOperand::CreateReg(0));
1257     Inst.addOperand(MCOperand::CreateImm(Val));
1258   }
1259
1260   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
1261     assert(N == 2 && "Invalid number of operands!");
1262     // The lower two bits are always zero and as such are not encoded.
1263     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
1264     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1265     // Special case for #-0
1266     if (Val == INT32_MIN) Val = 0;
1267     if (Val < 0) Val = -Val;
1268     Val = ARM_AM::getAM5Opc(AddSub, Val);
1269     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1270     Inst.addOperand(MCOperand::CreateImm(Val));
1271   }
1272
1273   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
1274     assert(N == 2 && "Invalid number of operands!");
1275     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1276     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1277     Inst.addOperand(MCOperand::CreateImm(Val));
1278   }
1279
1280   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
1281     assert(N == 2 && "Invalid number of operands!");
1282     // The lower two bits are always zero and as such are not encoded.
1283     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
1284     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1285     Inst.addOperand(MCOperand::CreateImm(Val));
1286   }
1287
1288   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1289     assert(N == 2 && "Invalid number of operands!");
1290     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1291     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1292     Inst.addOperand(MCOperand::CreateImm(Val));
1293   }
1294
1295   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1296     addMemImm8OffsetOperands(Inst, N);
1297   }
1298
1299   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1300     addMemImm8OffsetOperands(Inst, N);
1301   }
1302
1303   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1304     assert(N == 2 && "Invalid number of operands!");
1305     // If this is an immediate, it's a label reference.
1306     if (Kind == k_Immediate) {
1307       addExpr(Inst, getImm());
1308       Inst.addOperand(MCOperand::CreateImm(0));
1309       return;
1310     }
1311
1312     // Otherwise, it's a normal memory reg+offset.
1313     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1314     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1315     Inst.addOperand(MCOperand::CreateImm(Val));
1316   }
1317
1318   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1319     assert(N == 2 && "Invalid number of operands!");
1320     // If this is an immediate, it's a label reference.
1321     if (Kind == k_Immediate) {
1322       addExpr(Inst, getImm());
1323       Inst.addOperand(MCOperand::CreateImm(0));
1324       return;
1325     }
1326
1327     // Otherwise, it's a normal memory reg+offset.
1328     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
1329     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1330     Inst.addOperand(MCOperand::CreateImm(Val));
1331   }
1332
1333   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
1334     assert(N == 2 && "Invalid number of operands!");
1335     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1336     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1337   }
1338
1339   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
1340     assert(N == 2 && "Invalid number of operands!");
1341     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1342     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1343   }
1344
1345   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1346     assert(N == 3 && "Invalid number of operands!");
1347     unsigned Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
1348                                      Memory.ShiftImm, Memory.ShiftType);
1349     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1350     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1351     Inst.addOperand(MCOperand::CreateImm(Val));
1352   }
1353
1354   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1355     assert(N == 3 && "Invalid number of operands!");
1356     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1357     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1358     Inst.addOperand(MCOperand::CreateImm(Memory.ShiftImm));
1359   }
1360
1361   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
1362     assert(N == 2 && "Invalid number of operands!");
1363     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1364     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
1365   }
1366
1367   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
1368     assert(N == 2 && "Invalid number of operands!");
1369     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
1370     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1371     Inst.addOperand(MCOperand::CreateImm(Val));
1372   }
1373
1374   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
1375     assert(N == 2 && "Invalid number of operands!");
1376     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
1377     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1378     Inst.addOperand(MCOperand::CreateImm(Val));
1379   }
1380
1381   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
1382     assert(N == 2 && "Invalid number of operands!");
1383     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
1384     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1385     Inst.addOperand(MCOperand::CreateImm(Val));
1386   }
1387
1388   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
1389     assert(N == 2 && "Invalid number of operands!");
1390     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
1391     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
1392     Inst.addOperand(MCOperand::CreateImm(Val));
1393   }
1394
1395   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
1396     assert(N == 1 && "Invalid number of operands!");
1397     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1398     assert(CE && "non-constant post-idx-imm8 operand!");
1399     int Imm = CE->getValue();
1400     bool isAdd = Imm >= 0;
1401     if (Imm == INT32_MIN) Imm = 0;
1402     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
1403     Inst.addOperand(MCOperand::CreateImm(Imm));
1404   }
1405
1406   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
1407     assert(N == 1 && "Invalid number of operands!");
1408     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1409     assert(CE && "non-constant post-idx-imm8s4 operand!");
1410     int Imm = CE->getValue();
1411     bool isAdd = Imm >= 0;
1412     if (Imm == INT32_MIN) Imm = 0;
1413     // Immediate is scaled by 4.
1414     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
1415     Inst.addOperand(MCOperand::CreateImm(Imm));
1416   }
1417
1418   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
1419     assert(N == 2 && "Invalid number of operands!");
1420     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1421     Inst.addOperand(MCOperand::CreateImm(PostIdxReg.isAdd));
1422   }
1423
1424   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
1425     assert(N == 2 && "Invalid number of operands!");
1426     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1427     // The sign, shift type, and shift amount are encoded in a single operand
1428     // using the AM2 encoding helpers.
1429     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
1430     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
1431                                      PostIdxReg.ShiftTy);
1432     Inst.addOperand(MCOperand::CreateImm(Imm));
1433   }
1434
1435   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
1436     assert(N == 1 && "Invalid number of operands!");
1437     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
1438   }
1439
1440   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
1441     assert(N == 1 && "Invalid number of operands!");
1442     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
1443   }
1444
1445   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
1446     assert(N == 1 && "Invalid number of operands!");
1447     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1448   }
1449
1450   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
1451     assert(N == 1 && "Invalid number of operands!");
1452     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1453   }
1454
1455   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
1456     assert(N == 1 && "Invalid number of operands!");
1457     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1458   }
1459
1460   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
1461     assert(N == 1 && "Invalid number of operands!");
1462     // The immediate encodes the type of constant as well as the value.
1463     // Mask in that this is an i8 splat.
1464     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1465     Inst.addOperand(MCOperand::CreateImm(CE->getValue() | 0xe00));
1466   }
1467
1468   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
1469     assert(N == 1 && "Invalid number of operands!");
1470     // The immediate encodes the type of constant as well as the value.
1471     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1472     unsigned Value = CE->getValue();
1473     if (Value >= 256)
1474       Value = (Value >> 8) | 0xa00;
1475     else
1476       Value |= 0x800;
1477     Inst.addOperand(MCOperand::CreateImm(Value));
1478   }
1479
1480   virtual void print(raw_ostream &OS) const;
1481
1482   static ARMOperand *CreateITMask(unsigned Mask, SMLoc S) {
1483     ARMOperand *Op = new ARMOperand(k_ITCondMask);
1484     Op->ITMask.Mask = Mask;
1485     Op->StartLoc = S;
1486     Op->EndLoc = S;
1487     return Op;
1488   }
1489
1490   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
1491     ARMOperand *Op = new ARMOperand(k_CondCode);
1492     Op->CC.Val = CC;
1493     Op->StartLoc = S;
1494     Op->EndLoc = S;
1495     return Op;
1496   }
1497
1498   static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
1499     ARMOperand *Op = new ARMOperand(k_CoprocNum);
1500     Op->Cop.Val = CopVal;
1501     Op->StartLoc = S;
1502     Op->EndLoc = S;
1503     return Op;
1504   }
1505
1506   static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
1507     ARMOperand *Op = new ARMOperand(k_CoprocReg);
1508     Op->Cop.Val = CopVal;
1509     Op->StartLoc = S;
1510     Op->EndLoc = S;
1511     return Op;
1512   }
1513
1514   static ARMOperand *CreateCoprocOption(unsigned Val, SMLoc S, SMLoc E) {
1515     ARMOperand *Op = new ARMOperand(k_CoprocOption);
1516     Op->Cop.Val = Val;
1517     Op->StartLoc = S;
1518     Op->EndLoc = E;
1519     return Op;
1520   }
1521
1522   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
1523     ARMOperand *Op = new ARMOperand(k_CCOut);
1524     Op->Reg.RegNum = RegNum;
1525     Op->StartLoc = S;
1526     Op->EndLoc = S;
1527     return Op;
1528   }
1529
1530   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
1531     ARMOperand *Op = new ARMOperand(k_Token);
1532     Op->Tok.Data = Str.data();
1533     Op->Tok.Length = Str.size();
1534     Op->StartLoc = S;
1535     Op->EndLoc = S;
1536     return Op;
1537   }
1538
1539   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
1540     ARMOperand *Op = new ARMOperand(k_Register);
1541     Op->Reg.RegNum = RegNum;
1542     Op->StartLoc = S;
1543     Op->EndLoc = E;
1544     return Op;
1545   }
1546
1547   static ARMOperand *CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,
1548                                            unsigned SrcReg,
1549                                            unsigned ShiftReg,
1550                                            unsigned ShiftImm,
1551                                            SMLoc S, SMLoc E) {
1552     ARMOperand *Op = new ARMOperand(k_ShiftedRegister);
1553     Op->RegShiftedReg.ShiftTy = ShTy;
1554     Op->RegShiftedReg.SrcReg = SrcReg;
1555     Op->RegShiftedReg.ShiftReg = ShiftReg;
1556     Op->RegShiftedReg.ShiftImm = ShiftImm;
1557     Op->StartLoc = S;
1558     Op->EndLoc = E;
1559     return Op;
1560   }
1561
1562   static ARMOperand *CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,
1563                                             unsigned SrcReg,
1564                                             unsigned ShiftImm,
1565                                             SMLoc S, SMLoc E) {
1566     ARMOperand *Op = new ARMOperand(k_ShiftedImmediate);
1567     Op->RegShiftedImm.ShiftTy = ShTy;
1568     Op->RegShiftedImm.SrcReg = SrcReg;
1569     Op->RegShiftedImm.ShiftImm = ShiftImm;
1570     Op->StartLoc = S;
1571     Op->EndLoc = E;
1572     return Op;
1573   }
1574
1575   static ARMOperand *CreateShifterImm(bool isASR, unsigned Imm,
1576                                    SMLoc S, SMLoc E) {
1577     ARMOperand *Op = new ARMOperand(k_ShifterImmediate);
1578     Op->ShifterImm.isASR = isASR;
1579     Op->ShifterImm.Imm = Imm;
1580     Op->StartLoc = S;
1581     Op->EndLoc = E;
1582     return Op;
1583   }
1584
1585   static ARMOperand *CreateRotImm(unsigned Imm, SMLoc S, SMLoc E) {
1586     ARMOperand *Op = new ARMOperand(k_RotateImmediate);
1587     Op->RotImm.Imm = Imm;
1588     Op->StartLoc = S;
1589     Op->EndLoc = E;
1590     return Op;
1591   }
1592
1593   static ARMOperand *CreateBitfield(unsigned LSB, unsigned Width,
1594                                     SMLoc S, SMLoc E) {
1595     ARMOperand *Op = new ARMOperand(k_BitfieldDescriptor);
1596     Op->Bitfield.LSB = LSB;
1597     Op->Bitfield.Width = Width;
1598     Op->StartLoc = S;
1599     Op->EndLoc = E;
1600     return Op;
1601   }
1602
1603   static ARMOperand *
1604   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
1605                 SMLoc StartLoc, SMLoc EndLoc) {
1606     KindTy Kind = k_RegisterList;
1607
1608     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().first))
1609       Kind = k_DPRRegisterList;
1610     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
1611              contains(Regs.front().first))
1612       Kind = k_SPRRegisterList;
1613
1614     ARMOperand *Op = new ARMOperand(Kind);
1615     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1616            I = Regs.begin(), E = Regs.end(); I != E; ++I)
1617       Op->Registers.push_back(I->first);
1618     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
1619     Op->StartLoc = StartLoc;
1620     Op->EndLoc = EndLoc;
1621     return Op;
1622   }
1623
1624   static ARMOperand *CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E,
1625                                        MCContext &Ctx) {
1626     ARMOperand *Op = new ARMOperand(k_VectorIndex);
1627     Op->VectorIndex.Val = Idx;
1628     Op->StartLoc = S;
1629     Op->EndLoc = E;
1630     return Op;
1631   }
1632
1633   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
1634     ARMOperand *Op = new ARMOperand(k_Immediate);
1635     Op->Imm.Val = Val;
1636     Op->StartLoc = S;
1637     Op->EndLoc = E;
1638     return Op;
1639   }
1640
1641   static ARMOperand *CreateFPImm(unsigned Val, SMLoc S, MCContext &Ctx) {
1642     ARMOperand *Op = new ARMOperand(k_FPImmediate);
1643     Op->FPImm.Val = Val;
1644     Op->StartLoc = S;
1645     Op->EndLoc = S;
1646     return Op;
1647   }
1648
1649   static ARMOperand *CreateMem(unsigned BaseRegNum,
1650                                const MCConstantExpr *OffsetImm,
1651                                unsigned OffsetRegNum,
1652                                ARM_AM::ShiftOpc ShiftType,
1653                                unsigned ShiftImm,
1654                                unsigned Alignment,
1655                                bool isNegative,
1656                                SMLoc S, SMLoc E) {
1657     ARMOperand *Op = new ARMOperand(k_Memory);
1658     Op->Memory.BaseRegNum = BaseRegNum;
1659     Op->Memory.OffsetImm = OffsetImm;
1660     Op->Memory.OffsetRegNum = OffsetRegNum;
1661     Op->Memory.ShiftType = ShiftType;
1662     Op->Memory.ShiftImm = ShiftImm;
1663     Op->Memory.Alignment = Alignment;
1664     Op->Memory.isNegative = isNegative;
1665     Op->StartLoc = S;
1666     Op->EndLoc = E;
1667     return Op;
1668   }
1669
1670   static ARMOperand *CreatePostIdxReg(unsigned RegNum, bool isAdd,
1671                                       ARM_AM::ShiftOpc ShiftTy,
1672                                       unsigned ShiftImm,
1673                                       SMLoc S, SMLoc E) {
1674     ARMOperand *Op = new ARMOperand(k_PostIndexRegister);
1675     Op->PostIdxReg.RegNum = RegNum;
1676     Op->PostIdxReg.isAdd = isAdd;
1677     Op->PostIdxReg.ShiftTy = ShiftTy;
1678     Op->PostIdxReg.ShiftImm = ShiftImm;
1679     Op->StartLoc = S;
1680     Op->EndLoc = E;
1681     return Op;
1682   }
1683
1684   static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
1685     ARMOperand *Op = new ARMOperand(k_MemBarrierOpt);
1686     Op->MBOpt.Val = Opt;
1687     Op->StartLoc = S;
1688     Op->EndLoc = S;
1689     return Op;
1690   }
1691
1692   static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
1693     ARMOperand *Op = new ARMOperand(k_ProcIFlags);
1694     Op->IFlags.Val = IFlags;
1695     Op->StartLoc = S;
1696     Op->EndLoc = S;
1697     return Op;
1698   }
1699
1700   static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
1701     ARMOperand *Op = new ARMOperand(k_MSRMask);
1702     Op->MMask.Val = MMask;
1703     Op->StartLoc = S;
1704     Op->EndLoc = S;
1705     return Op;
1706   }
1707 };
1708
1709 } // end anonymous namespace.
1710
1711 void ARMOperand::print(raw_ostream &OS) const {
1712   switch (Kind) {
1713   case k_FPImmediate:
1714     OS << "<fpimm " << getFPImm() << "(" << ARM_AM::getFPImmFloat(getFPImm())
1715        << ") >";
1716     break;
1717   case k_CondCode:
1718     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
1719     break;
1720   case k_CCOut:
1721     OS << "<ccout " << getReg() << ">";
1722     break;
1723   case k_ITCondMask: {
1724     static char MaskStr[][6] = { "()", "(t)", "(e)", "(tt)", "(et)", "(te)",
1725       "(ee)", "(ttt)", "(ett)", "(tet)", "(eet)", "(tte)", "(ete)",
1726       "(tee)", "(eee)" };
1727     assert((ITMask.Mask & 0xf) == ITMask.Mask);
1728     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
1729     break;
1730   }
1731   case k_CoprocNum:
1732     OS << "<coprocessor number: " << getCoproc() << ">";
1733     break;
1734   case k_CoprocReg:
1735     OS << "<coprocessor register: " << getCoproc() << ">";
1736     break;
1737   case k_CoprocOption:
1738     OS << "<coprocessor option: " << CoprocOption.Val << ">";
1739     break;
1740   case k_MSRMask:
1741     OS << "<mask: " << getMSRMask() << ">";
1742     break;
1743   case k_Immediate:
1744     getImm()->print(OS);
1745     break;
1746   case k_MemBarrierOpt:
1747     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
1748     break;
1749   case k_Memory:
1750     OS << "<memory "
1751        << " base:" << Memory.BaseRegNum;
1752     OS << ">";
1753     break;
1754   case k_PostIndexRegister:
1755     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
1756        << PostIdxReg.RegNum;
1757     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
1758       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
1759          << PostIdxReg.ShiftImm;
1760     OS << ">";
1761     break;
1762   case k_ProcIFlags: {
1763     OS << "<ARM_PROC::";
1764     unsigned IFlags = getProcIFlags();
1765     for (int i=2; i >= 0; --i)
1766       if (IFlags & (1 << i))
1767         OS << ARM_PROC::IFlagsToString(1 << i);
1768     OS << ">";
1769     break;
1770   }
1771   case k_Register:
1772     OS << "<register " << getReg() << ">";
1773     break;
1774   case k_ShifterImmediate:
1775     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
1776        << " #" << ShifterImm.Imm << ">";
1777     break;
1778   case k_ShiftedRegister:
1779     OS << "<so_reg_reg "
1780        << RegShiftedReg.SrcReg
1781        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedReg.ShiftImm))
1782        << ", " << RegShiftedReg.ShiftReg << ", "
1783        << ARM_AM::getSORegOffset(RegShiftedReg.ShiftImm)
1784        << ">";
1785     break;
1786   case k_ShiftedImmediate:
1787     OS << "<so_reg_imm "
1788        << RegShiftedImm.SrcReg
1789        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedImm.ShiftImm))
1790        << ", " << ARM_AM::getSORegOffset(RegShiftedImm.ShiftImm)
1791        << ">";
1792     break;
1793   case k_RotateImmediate:
1794     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
1795     break;
1796   case k_BitfieldDescriptor:
1797     OS << "<bitfield " << "lsb: " << Bitfield.LSB
1798        << ", width: " << Bitfield.Width << ">";
1799     break;
1800   case k_RegisterList:
1801   case k_DPRRegisterList:
1802   case k_SPRRegisterList: {
1803     OS << "<register_list ";
1804
1805     const SmallVectorImpl<unsigned> &RegList = getRegList();
1806     for (SmallVectorImpl<unsigned>::const_iterator
1807            I = RegList.begin(), E = RegList.end(); I != E; ) {
1808       OS << *I;
1809       if (++I < E) OS << ", ";
1810     }
1811
1812     OS << ">";
1813     break;
1814   }
1815   case k_Token:
1816     OS << "'" << getToken() << "'";
1817     break;
1818   case k_VectorIndex:
1819     OS << "<vectorindex " << getVectorIndex() << ">";
1820     break;
1821   }
1822 }
1823
1824 /// @name Auto-generated Match Functions
1825 /// {
1826
1827 static unsigned MatchRegisterName(StringRef Name);
1828
1829 /// }
1830
1831 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
1832                                  SMLoc &StartLoc, SMLoc &EndLoc) {
1833   RegNo = tryParseRegister();
1834
1835   return (RegNo == (unsigned)-1);
1836 }
1837
1838 /// Try to parse a register name.  The token must be an Identifier when called,
1839 /// and if it is a register name the token is eaten and the register number is
1840 /// returned.  Otherwise return -1.
1841 ///
1842 int ARMAsmParser::tryParseRegister() {
1843   const AsmToken &Tok = Parser.getTok();
1844   if (Tok.isNot(AsmToken::Identifier)) return -1;
1845
1846   // FIXME: Validate register for the current architecture; we have to do
1847   // validation later, so maybe there is no need for this here.
1848   std::string upperCase = Tok.getString().str();
1849   std::string lowerCase = LowercaseString(upperCase);
1850   unsigned RegNum = MatchRegisterName(lowerCase);
1851   if (!RegNum) {
1852     RegNum = StringSwitch<unsigned>(lowerCase)
1853       .Case("r13", ARM::SP)
1854       .Case("r14", ARM::LR)
1855       .Case("r15", ARM::PC)
1856       .Case("ip", ARM::R12)
1857       .Default(0);
1858   }
1859   if (!RegNum) return -1;
1860
1861   Parser.Lex(); // Eat identifier token.
1862
1863 #if 0
1864   // Also check for an index operand. This is only legal for vector registers,
1865   // but that'll get caught OK in operand matching, so we don't need to
1866   // explicitly filter everything else out here.
1867   if (Parser.getTok().is(AsmToken::LBrac)) {
1868     SMLoc SIdx = Parser.getTok().getLoc();
1869     Parser.Lex(); // Eat left bracket token.
1870
1871     const MCExpr *ImmVal;
1872     if (getParser().ParseExpression(ImmVal))
1873       return MatchOperand_ParseFail;
1874     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
1875     if (!MCE) {
1876       TokError("immediate value expected for vector index");
1877       return MatchOperand_ParseFail;
1878     }
1879
1880     SMLoc E = Parser.getTok().getLoc();
1881     if (Parser.getTok().isNot(AsmToken::RBrac)) {
1882       Error(E, "']' expected");
1883       return MatchOperand_ParseFail;
1884     }
1885
1886     Parser.Lex(); // Eat right bracket token.
1887
1888     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
1889                                                      SIdx, E,
1890                                                      getContext()));
1891   }
1892 #endif
1893
1894   return RegNum;
1895 }
1896
1897 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
1898 // If a recoverable error occurs, return 1. If an irrecoverable error
1899 // occurs, return -1. An irrecoverable error is one where tokens have been
1900 // consumed in the process of trying to parse the shifter (i.e., when it is
1901 // indeed a shifter operand, but malformed).
1902 int ARMAsmParser::tryParseShiftRegister(
1903                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1904   SMLoc S = Parser.getTok().getLoc();
1905   const AsmToken &Tok = Parser.getTok();
1906   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1907
1908   std::string upperCase = Tok.getString().str();
1909   std::string lowerCase = LowercaseString(upperCase);
1910   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
1911       .Case("lsl", ARM_AM::lsl)
1912       .Case("lsr", ARM_AM::lsr)
1913       .Case("asr", ARM_AM::asr)
1914       .Case("ror", ARM_AM::ror)
1915       .Case("rrx", ARM_AM::rrx)
1916       .Default(ARM_AM::no_shift);
1917
1918   if (ShiftTy == ARM_AM::no_shift)
1919     return 1;
1920
1921   Parser.Lex(); // Eat the operator.
1922
1923   // The source register for the shift has already been added to the
1924   // operand list, so we need to pop it off and combine it into the shifted
1925   // register operand instead.
1926   OwningPtr<ARMOperand> PrevOp((ARMOperand*)Operands.pop_back_val());
1927   if (!PrevOp->isReg())
1928     return Error(PrevOp->getStartLoc(), "shift must be of a register");
1929   int SrcReg = PrevOp->getReg();
1930   int64_t Imm = 0;
1931   int ShiftReg = 0;
1932   if (ShiftTy == ARM_AM::rrx) {
1933     // RRX Doesn't have an explicit shift amount. The encoder expects
1934     // the shift register to be the same as the source register. Seems odd,
1935     // but OK.
1936     ShiftReg = SrcReg;
1937   } else {
1938     // Figure out if this is shifted by a constant or a register (for non-RRX).
1939     if (Parser.getTok().is(AsmToken::Hash)) {
1940       Parser.Lex(); // Eat hash.
1941       SMLoc ImmLoc = Parser.getTok().getLoc();
1942       const MCExpr *ShiftExpr = 0;
1943       if (getParser().ParseExpression(ShiftExpr)) {
1944         Error(ImmLoc, "invalid immediate shift value");
1945         return -1;
1946       }
1947       // The expression must be evaluatable as an immediate.
1948       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
1949       if (!CE) {
1950         Error(ImmLoc, "invalid immediate shift value");
1951         return -1;
1952       }
1953       // Range check the immediate.
1954       // lsl, ror: 0 <= imm <= 31
1955       // lsr, asr: 0 <= imm <= 32
1956       Imm = CE->getValue();
1957       if (Imm < 0 ||
1958           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
1959           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
1960         Error(ImmLoc, "immediate shift value out of range");
1961         return -1;
1962       }
1963     } else if (Parser.getTok().is(AsmToken::Identifier)) {
1964       ShiftReg = tryParseRegister();
1965       SMLoc L = Parser.getTok().getLoc();
1966       if (ShiftReg == -1) {
1967         Error (L, "expected immediate or register in shift operand");
1968         return -1;
1969       }
1970     } else {
1971       Error (Parser.getTok().getLoc(),
1972                     "expected immediate or register in shift operand");
1973       return -1;
1974     }
1975   }
1976
1977   if (ShiftReg && ShiftTy != ARM_AM::rrx)
1978     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
1979                                                          ShiftReg, Imm,
1980                                                S, Parser.getTok().getLoc()));
1981   else
1982     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
1983                                                S, Parser.getTok().getLoc()));
1984
1985   return 0;
1986 }
1987
1988
1989 /// Try to parse a register name.  The token must be an Identifier when called.
1990 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
1991 /// if there is a "writeback". 'true' if it's not a register.
1992 ///
1993 /// TODO this is likely to change to allow different register types and or to
1994 /// parse for a specific register type.
1995 bool ARMAsmParser::
1996 tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1997   SMLoc S = Parser.getTok().getLoc();
1998   int RegNo = tryParseRegister();
1999   if (RegNo == -1)
2000     return true;
2001
2002   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
2003
2004   const AsmToken &ExclaimTok = Parser.getTok();
2005   if (ExclaimTok.is(AsmToken::Exclaim)) {
2006     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
2007                                                ExclaimTok.getLoc()));
2008     Parser.Lex(); // Eat exclaim token
2009     return false;
2010   }
2011
2012   // Also check for an index operand. This is only legal for vector registers,
2013   // but that'll get caught OK in operand matching, so we don't need to
2014   // explicitly filter everything else out here.
2015   if (Parser.getTok().is(AsmToken::LBrac)) {
2016     SMLoc SIdx = Parser.getTok().getLoc();
2017     Parser.Lex(); // Eat left bracket token.
2018
2019     const MCExpr *ImmVal;
2020     if (getParser().ParseExpression(ImmVal))
2021       return MatchOperand_ParseFail;
2022     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2023     if (!MCE) {
2024       TokError("immediate value expected for vector index");
2025       return MatchOperand_ParseFail;
2026     }
2027
2028     SMLoc E = Parser.getTok().getLoc();
2029     if (Parser.getTok().isNot(AsmToken::RBrac)) {
2030       Error(E, "']' expected");
2031       return MatchOperand_ParseFail;
2032     }
2033
2034     Parser.Lex(); // Eat right bracket token.
2035
2036     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
2037                                                      SIdx, E,
2038                                                      getContext()));
2039   }
2040
2041   return false;
2042 }
2043
2044 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
2045 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
2046 /// "c5", ...
2047 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
2048   // Use the same layout as the tablegen'erated register name matcher. Ugly,
2049   // but efficient.
2050   switch (Name.size()) {
2051   default: break;
2052   case 2:
2053     if (Name[0] != CoprocOp)
2054       return -1;
2055     switch (Name[1]) {
2056     default:  return -1;
2057     case '0': return 0;
2058     case '1': return 1;
2059     case '2': return 2;
2060     case '3': return 3;
2061     case '4': return 4;
2062     case '5': return 5;
2063     case '6': return 6;
2064     case '7': return 7;
2065     case '8': return 8;
2066     case '9': return 9;
2067     }
2068     break;
2069   case 3:
2070     if (Name[0] != CoprocOp || Name[1] != '1')
2071       return -1;
2072     switch (Name[2]) {
2073     default:  return -1;
2074     case '0': return 10;
2075     case '1': return 11;
2076     case '2': return 12;
2077     case '3': return 13;
2078     case '4': return 14;
2079     case '5': return 15;
2080     }
2081     break;
2082   }
2083
2084   return -1;
2085 }
2086
2087 /// parseITCondCode - Try to parse a condition code for an IT instruction.
2088 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2089 parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2090   SMLoc S = Parser.getTok().getLoc();
2091   const AsmToken &Tok = Parser.getTok();
2092   if (!Tok.is(AsmToken::Identifier))
2093     return MatchOperand_NoMatch;
2094   unsigned CC = StringSwitch<unsigned>(Tok.getString())
2095     .Case("eq", ARMCC::EQ)
2096     .Case("ne", ARMCC::NE)
2097     .Case("hs", ARMCC::HS)
2098     .Case("cs", ARMCC::HS)
2099     .Case("lo", ARMCC::LO)
2100     .Case("cc", ARMCC::LO)
2101     .Case("mi", ARMCC::MI)
2102     .Case("pl", ARMCC::PL)
2103     .Case("vs", ARMCC::VS)
2104     .Case("vc", ARMCC::VC)
2105     .Case("hi", ARMCC::HI)
2106     .Case("ls", ARMCC::LS)
2107     .Case("ge", ARMCC::GE)
2108     .Case("lt", ARMCC::LT)
2109     .Case("gt", ARMCC::GT)
2110     .Case("le", ARMCC::LE)
2111     .Case("al", ARMCC::AL)
2112     .Default(~0U);
2113   if (CC == ~0U)
2114     return MatchOperand_NoMatch;
2115   Parser.Lex(); // Eat the token.
2116
2117   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
2118
2119   return MatchOperand_Success;
2120 }
2121
2122 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
2123 /// token must be an Identifier when called, and if it is a coprocessor
2124 /// number, the token is eaten and the operand is added to the operand list.
2125 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2126 parseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2127   SMLoc S = Parser.getTok().getLoc();
2128   const AsmToken &Tok = Parser.getTok();
2129   if (Tok.isNot(AsmToken::Identifier))
2130     return MatchOperand_NoMatch;
2131
2132   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
2133   if (Num == -1)
2134     return MatchOperand_NoMatch;
2135
2136   Parser.Lex(); // Eat identifier token.
2137   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
2138   return MatchOperand_Success;
2139 }
2140
2141 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
2142 /// token must be an Identifier when called, and if it is a coprocessor
2143 /// number, the token is eaten and the operand is added to the operand list.
2144 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2145 parseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2146   SMLoc S = Parser.getTok().getLoc();
2147   const AsmToken &Tok = Parser.getTok();
2148   if (Tok.isNot(AsmToken::Identifier))
2149     return MatchOperand_NoMatch;
2150
2151   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
2152   if (Reg == -1)
2153     return MatchOperand_NoMatch;
2154
2155   Parser.Lex(); // Eat identifier token.
2156   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
2157   return MatchOperand_Success;
2158 }
2159
2160 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
2161 /// coproc_option : '{' imm0_255 '}'
2162 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2163 parseCoprocOptionOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2164   SMLoc S = Parser.getTok().getLoc();
2165
2166   // If this isn't a '{', this isn't a coprocessor immediate operand.
2167   if (Parser.getTok().isNot(AsmToken::LCurly))
2168     return MatchOperand_NoMatch;
2169   Parser.Lex(); // Eat the '{'
2170
2171   const MCExpr *Expr;
2172   SMLoc Loc = Parser.getTok().getLoc();
2173   if (getParser().ParseExpression(Expr)) {
2174     Error(Loc, "illegal expression");
2175     return MatchOperand_ParseFail;
2176   }
2177   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
2178   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
2179     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
2180     return MatchOperand_ParseFail;
2181   }
2182   int Val = CE->getValue();
2183
2184   // Check for and consume the closing '}'
2185   if (Parser.getTok().isNot(AsmToken::RCurly))
2186     return MatchOperand_ParseFail;
2187   SMLoc E = Parser.getTok().getLoc();
2188   Parser.Lex(); // Eat the '}'
2189
2190   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
2191   return MatchOperand_Success;
2192 }
2193
2194 // For register list parsing, we need to map from raw GPR register numbering
2195 // to the enumeration values. The enumeration values aren't sorted by
2196 // register number due to our using "sp", "lr" and "pc" as canonical names.
2197 static unsigned getNextRegister(unsigned Reg) {
2198   // If this is a GPR, we need to do it manually, otherwise we can rely
2199   // on the sort ordering of the enumeration since the other reg-classes
2200   // are sane.
2201   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
2202     return Reg + 1;
2203   switch(Reg) {
2204   default: assert(0 && "Invalid GPR number!");
2205   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
2206   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
2207   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
2208   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
2209   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
2210   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
2211   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
2212   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
2213   }
2214 }
2215
2216 /// Parse a register list.
2217 bool ARMAsmParser::
2218 parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2219   assert(Parser.getTok().is(AsmToken::LCurly) &&
2220          "Token is not a Left Curly Brace");
2221   SMLoc S = Parser.getTok().getLoc();
2222   Parser.Lex(); // Eat '{' token.
2223   SMLoc RegLoc = Parser.getTok().getLoc();
2224
2225   // Check the first register in the list to see what register class
2226   // this is a list of.
2227   int Reg = tryParseRegister();
2228   if (Reg == -1)
2229     return Error(RegLoc, "register expected");
2230
2231   MCRegisterClass *RC;
2232   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
2233     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
2234   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
2235     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
2236   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
2237     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
2238   else
2239     return Error(RegLoc, "invalid register in register list");
2240
2241   // The reglist instructions have at most 16 registers, so reserve
2242   // space for that many.
2243   SmallVector<std::pair<unsigned, SMLoc>, 16> Registers;
2244   // Store the first register.
2245   Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
2246
2247   // This starts immediately after the first register token in the list,
2248   // so we can see either a comma or a minus (range separator) as a legal
2249   // next token.
2250   while (Parser.getTok().is(AsmToken::Comma) ||
2251          Parser.getTok().is(AsmToken::Minus)) {
2252     if (Parser.getTok().is(AsmToken::Minus)) {
2253       Parser.Lex(); // Eat the comma.
2254       SMLoc EndLoc = Parser.getTok().getLoc();
2255       int EndReg = tryParseRegister();
2256       if (EndReg == -1)
2257         return Error(EndLoc, "register expected");
2258       // If the register is the same as the start reg, there's nothing
2259       // more to do.
2260       if (Reg == EndReg)
2261         continue;
2262       // The register must be in the same register class as the first.
2263       if (!RC->contains(EndReg))
2264         return Error(EndLoc, "invalid register in register list");
2265       // Ranges must go from low to high.
2266       if (getARMRegisterNumbering(Reg) > getARMRegisterNumbering(EndReg))
2267         return Error(EndLoc, "bad range in register list");
2268
2269       // Add all the registers in the range to the register list.
2270       while (Reg != EndReg) {
2271         Reg = getNextRegister(Reg);
2272         Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
2273       }
2274       continue;
2275     }
2276     Parser.Lex(); // Eat the comma.
2277     RegLoc = Parser.getTok().getLoc();
2278     int OldReg = Reg;
2279     Reg = tryParseRegister();
2280     if (Reg == -1)
2281       return Error(RegLoc, "register expected");
2282     // The register must be in the same register class as the first.
2283     if (!RC->contains(Reg))
2284       return Error(RegLoc, "invalid register in register list");
2285     // List must be monotonically increasing.
2286     if (getARMRegisterNumbering(Reg) <= getARMRegisterNumbering(OldReg))
2287       return Error(RegLoc, "register list not in ascending order");
2288     // VFP register lists must also be contiguous.
2289     // It's OK to use the enumeration values directly here rather, as the
2290     // VFP register classes have the enum sorted properly.
2291     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
2292         Reg != OldReg + 1)
2293       return Error(RegLoc, "non-contiguous register range");
2294     Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
2295   }
2296
2297   SMLoc E = Parser.getTok().getLoc();
2298   if (Parser.getTok().isNot(AsmToken::RCurly))
2299     return Error(E, "'}' expected");
2300   Parser.Lex(); // Eat '}' token.
2301
2302   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
2303   return false;
2304 }
2305
2306 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
2307 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2308 parseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2309   SMLoc S = Parser.getTok().getLoc();
2310   const AsmToken &Tok = Parser.getTok();
2311   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2312   StringRef OptStr = Tok.getString();
2313
2314   unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
2315     .Case("sy",    ARM_MB::SY)
2316     .Case("st",    ARM_MB::ST)
2317     .Case("sh",    ARM_MB::ISH)
2318     .Case("ish",   ARM_MB::ISH)
2319     .Case("shst",  ARM_MB::ISHST)
2320     .Case("ishst", ARM_MB::ISHST)
2321     .Case("nsh",   ARM_MB::NSH)
2322     .Case("un",    ARM_MB::NSH)
2323     .Case("nshst", ARM_MB::NSHST)
2324     .Case("unst",  ARM_MB::NSHST)
2325     .Case("osh",   ARM_MB::OSH)
2326     .Case("oshst", ARM_MB::OSHST)
2327     .Default(~0U);
2328
2329   if (Opt == ~0U)
2330     return MatchOperand_NoMatch;
2331
2332   Parser.Lex(); // Eat identifier token.
2333   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
2334   return MatchOperand_Success;
2335 }
2336
2337 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
2338 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2339 parseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2340   SMLoc S = Parser.getTok().getLoc();
2341   const AsmToken &Tok = Parser.getTok();
2342   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2343   StringRef IFlagsStr = Tok.getString();
2344
2345   // An iflags string of "none" is interpreted to mean that none of the AIF
2346   // bits are set.  Not a terribly useful instruction, but a valid encoding.
2347   unsigned IFlags = 0;
2348   if (IFlagsStr != "none") {
2349         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
2350       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
2351         .Case("a", ARM_PROC::A)
2352         .Case("i", ARM_PROC::I)
2353         .Case("f", ARM_PROC::F)
2354         .Default(~0U);
2355
2356       // If some specific iflag is already set, it means that some letter is
2357       // present more than once, this is not acceptable.
2358       if (Flag == ~0U || (IFlags & Flag))
2359         return MatchOperand_NoMatch;
2360
2361       IFlags |= Flag;
2362     }
2363   }
2364
2365   Parser.Lex(); // Eat identifier token.
2366   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
2367   return MatchOperand_Success;
2368 }
2369
2370 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
2371 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2372 parseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2373   SMLoc S = Parser.getTok().getLoc();
2374   const AsmToken &Tok = Parser.getTok();
2375   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2376   StringRef Mask = Tok.getString();
2377
2378   if (isMClass()) {
2379     // See ARMv6-M 10.1.1
2380     unsigned FlagsVal = StringSwitch<unsigned>(Mask)
2381       .Case("apsr", 0)
2382       .Case("iapsr", 1)
2383       .Case("eapsr", 2)
2384       .Case("xpsr", 3)
2385       .Case("ipsr", 5)
2386       .Case("epsr", 6)
2387       .Case("iepsr", 7)
2388       .Case("msp", 8)
2389       .Case("psp", 9)
2390       .Case("primask", 16)
2391       .Case("basepri", 17)
2392       .Case("basepri_max", 18)
2393       .Case("faultmask", 19)
2394       .Case("control", 20)
2395       .Default(~0U);
2396     
2397     if (FlagsVal == ~0U)
2398       return MatchOperand_NoMatch;
2399
2400     if (!hasV7Ops() && FlagsVal >= 17 && FlagsVal <= 19)
2401       // basepri, basepri_max and faultmask only valid for V7m.
2402       return MatchOperand_NoMatch;
2403     
2404     Parser.Lex(); // Eat identifier token.
2405     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
2406     return MatchOperand_Success;
2407   }
2408
2409   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
2410   size_t Start = 0, Next = Mask.find('_');
2411   StringRef Flags = "";
2412   std::string SpecReg = LowercaseString(Mask.slice(Start, Next));
2413   if (Next != StringRef::npos)
2414     Flags = Mask.slice(Next+1, Mask.size());
2415
2416   // FlagsVal contains the complete mask:
2417   // 3-0: Mask
2418   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
2419   unsigned FlagsVal = 0;
2420
2421   if (SpecReg == "apsr") {
2422     FlagsVal = StringSwitch<unsigned>(Flags)
2423     .Case("nzcvq",  0x8) // same as CPSR_f
2424     .Case("g",      0x4) // same as CPSR_s
2425     .Case("nzcvqg", 0xc) // same as CPSR_fs
2426     .Default(~0U);
2427
2428     if (FlagsVal == ~0U) {
2429       if (!Flags.empty())
2430         return MatchOperand_NoMatch;
2431       else
2432         FlagsVal = 8; // No flag
2433     }
2434   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
2435     if (Flags == "all") // cpsr_all is an alias for cpsr_fc
2436       Flags = "fc";
2437     for (int i = 0, e = Flags.size(); i != e; ++i) {
2438       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
2439       .Case("c", 1)
2440       .Case("x", 2)
2441       .Case("s", 4)
2442       .Case("f", 8)
2443       .Default(~0U);
2444
2445       // If some specific flag is already set, it means that some letter is
2446       // present more than once, this is not acceptable.
2447       if (FlagsVal == ~0U || (FlagsVal & Flag))
2448         return MatchOperand_NoMatch;
2449       FlagsVal |= Flag;
2450     }
2451   } else // No match for special register.
2452     return MatchOperand_NoMatch;
2453
2454   // Special register without flags are equivalent to "fc" flags.
2455   if (!FlagsVal)
2456     FlagsVal = 0x9;
2457
2458   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
2459   if (SpecReg == "spsr")
2460     FlagsVal |= 16;
2461
2462   Parser.Lex(); // Eat identifier token.
2463   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
2464   return MatchOperand_Success;
2465 }
2466
2467 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2468 parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands, StringRef Op,
2469             int Low, int High) {
2470   const AsmToken &Tok = Parser.getTok();
2471   if (Tok.isNot(AsmToken::Identifier)) {
2472     Error(Parser.getTok().getLoc(), Op + " operand expected.");
2473     return MatchOperand_ParseFail;
2474   }
2475   StringRef ShiftName = Tok.getString();
2476   std::string LowerOp = LowercaseString(Op);
2477   std::string UpperOp = UppercaseString(Op);
2478   if (ShiftName != LowerOp && ShiftName != UpperOp) {
2479     Error(Parser.getTok().getLoc(), Op + " operand expected.");
2480     return MatchOperand_ParseFail;
2481   }
2482   Parser.Lex(); // Eat shift type token.
2483
2484   // There must be a '#' and a shift amount.
2485   if (Parser.getTok().isNot(AsmToken::Hash)) {
2486     Error(Parser.getTok().getLoc(), "'#' expected");
2487     return MatchOperand_ParseFail;
2488   }
2489   Parser.Lex(); // Eat hash token.
2490
2491   const MCExpr *ShiftAmount;
2492   SMLoc Loc = Parser.getTok().getLoc();
2493   if (getParser().ParseExpression(ShiftAmount)) {
2494     Error(Loc, "illegal expression");
2495     return MatchOperand_ParseFail;
2496   }
2497   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2498   if (!CE) {
2499     Error(Loc, "constant expression expected");
2500     return MatchOperand_ParseFail;
2501   }
2502   int Val = CE->getValue();
2503   if (Val < Low || Val > High) {
2504     Error(Loc, "immediate value out of range");
2505     return MatchOperand_ParseFail;
2506   }
2507
2508   Operands.push_back(ARMOperand::CreateImm(CE, Loc, Parser.getTok().getLoc()));
2509
2510   return MatchOperand_Success;
2511 }
2512
2513 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2514 parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2515   const AsmToken &Tok = Parser.getTok();
2516   SMLoc S = Tok.getLoc();
2517   if (Tok.isNot(AsmToken::Identifier)) {
2518     Error(Tok.getLoc(), "'be' or 'le' operand expected");
2519     return MatchOperand_ParseFail;
2520   }
2521   int Val = StringSwitch<int>(Tok.getString())
2522     .Case("be", 1)
2523     .Case("le", 0)
2524     .Default(-1);
2525   Parser.Lex(); // Eat the token.
2526
2527   if (Val == -1) {
2528     Error(Tok.getLoc(), "'be' or 'le' operand expected");
2529     return MatchOperand_ParseFail;
2530   }
2531   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
2532                                                                   getContext()),
2533                                            S, Parser.getTok().getLoc()));
2534   return MatchOperand_Success;
2535 }
2536
2537 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
2538 /// instructions. Legal values are:
2539 ///     lsl #n  'n' in [0,31]
2540 ///     asr #n  'n' in [1,32]
2541 ///             n == 32 encoded as n == 0.
2542 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2543 parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2544   const AsmToken &Tok = Parser.getTok();
2545   SMLoc S = Tok.getLoc();
2546   if (Tok.isNot(AsmToken::Identifier)) {
2547     Error(S, "shift operator 'asr' or 'lsl' expected");
2548     return MatchOperand_ParseFail;
2549   }
2550   StringRef ShiftName = Tok.getString();
2551   bool isASR;
2552   if (ShiftName == "lsl" || ShiftName == "LSL")
2553     isASR = false;
2554   else if (ShiftName == "asr" || ShiftName == "ASR")
2555     isASR = true;
2556   else {
2557     Error(S, "shift operator 'asr' or 'lsl' expected");
2558     return MatchOperand_ParseFail;
2559   }
2560   Parser.Lex(); // Eat the operator.
2561
2562   // A '#' and a shift amount.
2563   if (Parser.getTok().isNot(AsmToken::Hash)) {
2564     Error(Parser.getTok().getLoc(), "'#' expected");
2565     return MatchOperand_ParseFail;
2566   }
2567   Parser.Lex(); // Eat hash token.
2568
2569   const MCExpr *ShiftAmount;
2570   SMLoc E = Parser.getTok().getLoc();
2571   if (getParser().ParseExpression(ShiftAmount)) {
2572     Error(E, "malformed shift expression");
2573     return MatchOperand_ParseFail;
2574   }
2575   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2576   if (!CE) {
2577     Error(E, "shift amount must be an immediate");
2578     return MatchOperand_ParseFail;
2579   }
2580
2581   int64_t Val = CE->getValue();
2582   if (isASR) {
2583     // Shift amount must be in [1,32]
2584     if (Val < 1 || Val > 32) {
2585       Error(E, "'asr' shift amount must be in range [1,32]");
2586       return MatchOperand_ParseFail;
2587     }
2588     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
2589     if (isThumb() && Val == 32) {
2590       Error(E, "'asr #32' shift amount not allowed in Thumb mode");
2591       return MatchOperand_ParseFail;
2592     }
2593     if (Val == 32) Val = 0;
2594   } else {
2595     // Shift amount must be in [1,32]
2596     if (Val < 0 || Val > 31) {
2597       Error(E, "'lsr' shift amount must be in range [0,31]");
2598       return MatchOperand_ParseFail;
2599     }
2600   }
2601
2602   E = Parser.getTok().getLoc();
2603   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, E));
2604
2605   return MatchOperand_Success;
2606 }
2607
2608 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
2609 /// of instructions. Legal values are:
2610 ///     ror #n  'n' in {0, 8, 16, 24}
2611 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2612 parseRotImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2613   const AsmToken &Tok = Parser.getTok();
2614   SMLoc S = Tok.getLoc();
2615   if (Tok.isNot(AsmToken::Identifier))
2616     return MatchOperand_NoMatch;
2617   StringRef ShiftName = Tok.getString();
2618   if (ShiftName != "ror" && ShiftName != "ROR")
2619     return MatchOperand_NoMatch;
2620   Parser.Lex(); // Eat the operator.
2621
2622   // A '#' and a rotate amount.
2623   if (Parser.getTok().isNot(AsmToken::Hash)) {
2624     Error(Parser.getTok().getLoc(), "'#' expected");
2625     return MatchOperand_ParseFail;
2626   }
2627   Parser.Lex(); // Eat hash token.
2628
2629   const MCExpr *ShiftAmount;
2630   SMLoc E = Parser.getTok().getLoc();
2631   if (getParser().ParseExpression(ShiftAmount)) {
2632     Error(E, "malformed rotate expression");
2633     return MatchOperand_ParseFail;
2634   }
2635   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2636   if (!CE) {
2637     Error(E, "rotate amount must be an immediate");
2638     return MatchOperand_ParseFail;
2639   }
2640
2641   int64_t Val = CE->getValue();
2642   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
2643   // normally, zero is represented in asm by omitting the rotate operand
2644   // entirely.
2645   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
2646     Error(E, "'ror' rotate amount must be 8, 16, or 24");
2647     return MatchOperand_ParseFail;
2648   }
2649
2650   E = Parser.getTok().getLoc();
2651   Operands.push_back(ARMOperand::CreateRotImm(Val, S, E));
2652
2653   return MatchOperand_Success;
2654 }
2655
2656 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2657 parseBitfield(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2658   SMLoc S = Parser.getTok().getLoc();
2659   // The bitfield descriptor is really two operands, the LSB and the width.
2660   if (Parser.getTok().isNot(AsmToken::Hash)) {
2661     Error(Parser.getTok().getLoc(), "'#' expected");
2662     return MatchOperand_ParseFail;
2663   }
2664   Parser.Lex(); // Eat hash token.
2665
2666   const MCExpr *LSBExpr;
2667   SMLoc E = Parser.getTok().getLoc();
2668   if (getParser().ParseExpression(LSBExpr)) {
2669     Error(E, "malformed immediate expression");
2670     return MatchOperand_ParseFail;
2671   }
2672   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
2673   if (!CE) {
2674     Error(E, "'lsb' operand must be an immediate");
2675     return MatchOperand_ParseFail;
2676   }
2677
2678   int64_t LSB = CE->getValue();
2679   // The LSB must be in the range [0,31]
2680   if (LSB < 0 || LSB > 31) {
2681     Error(E, "'lsb' operand must be in the range [0,31]");
2682     return MatchOperand_ParseFail;
2683   }
2684   E = Parser.getTok().getLoc();
2685
2686   // Expect another immediate operand.
2687   if (Parser.getTok().isNot(AsmToken::Comma)) {
2688     Error(Parser.getTok().getLoc(), "too few operands");
2689     return MatchOperand_ParseFail;
2690   }
2691   Parser.Lex(); // Eat hash token.
2692   if (Parser.getTok().isNot(AsmToken::Hash)) {
2693     Error(Parser.getTok().getLoc(), "'#' expected");
2694     return MatchOperand_ParseFail;
2695   }
2696   Parser.Lex(); // Eat hash token.
2697
2698   const MCExpr *WidthExpr;
2699   if (getParser().ParseExpression(WidthExpr)) {
2700     Error(E, "malformed immediate expression");
2701     return MatchOperand_ParseFail;
2702   }
2703   CE = dyn_cast<MCConstantExpr>(WidthExpr);
2704   if (!CE) {
2705     Error(E, "'width' operand must be an immediate");
2706     return MatchOperand_ParseFail;
2707   }
2708
2709   int64_t Width = CE->getValue();
2710   // The LSB must be in the range [1,32-lsb]
2711   if (Width < 1 || Width > 32 - LSB) {
2712     Error(E, "'width' operand must be in the range [1,32-lsb]");
2713     return MatchOperand_ParseFail;
2714   }
2715   E = Parser.getTok().getLoc();
2716
2717   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, E));
2718
2719   return MatchOperand_Success;
2720 }
2721
2722 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2723 parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2724   // Check for a post-index addressing register operand. Specifically:
2725   // postidx_reg := '+' register {, shift}
2726   //              | '-' register {, shift}
2727   //              | register {, shift}
2728
2729   // This method must return MatchOperand_NoMatch without consuming any tokens
2730   // in the case where there is no match, as other alternatives take other
2731   // parse methods.
2732   AsmToken Tok = Parser.getTok();
2733   SMLoc S = Tok.getLoc();
2734   bool haveEaten = false;
2735   bool isAdd = true;
2736   int Reg = -1;
2737   if (Tok.is(AsmToken::Plus)) {
2738     Parser.Lex(); // Eat the '+' token.
2739     haveEaten = true;
2740   } else if (Tok.is(AsmToken::Minus)) {
2741     Parser.Lex(); // Eat the '-' token.
2742     isAdd = false;
2743     haveEaten = true;
2744   }
2745   if (Parser.getTok().is(AsmToken::Identifier))
2746     Reg = tryParseRegister();
2747   if (Reg == -1) {
2748     if (!haveEaten)
2749       return MatchOperand_NoMatch;
2750     Error(Parser.getTok().getLoc(), "register expected");
2751     return MatchOperand_ParseFail;
2752   }
2753   SMLoc E = Parser.getTok().getLoc();
2754
2755   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
2756   unsigned ShiftImm = 0;
2757   if (Parser.getTok().is(AsmToken::Comma)) {
2758     Parser.Lex(); // Eat the ','.
2759     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
2760       return MatchOperand_ParseFail;
2761   }
2762
2763   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
2764                                                   ShiftImm, S, E));
2765
2766   return MatchOperand_Success;
2767 }
2768
2769 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2770 parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2771   // Check for a post-index addressing register operand. Specifically:
2772   // am3offset := '+' register
2773   //              | '-' register
2774   //              | register
2775   //              | # imm
2776   //              | # + imm
2777   //              | # - imm
2778
2779   // This method must return MatchOperand_NoMatch without consuming any tokens
2780   // in the case where there is no match, as other alternatives take other
2781   // parse methods.
2782   AsmToken Tok = Parser.getTok();
2783   SMLoc S = Tok.getLoc();
2784
2785   // Do immediates first, as we always parse those if we have a '#'.
2786   if (Parser.getTok().is(AsmToken::Hash)) {
2787     Parser.Lex(); // Eat the '#'.
2788     // Explicitly look for a '-', as we need to encode negative zero
2789     // differently.
2790     bool isNegative = Parser.getTok().is(AsmToken::Minus);
2791     const MCExpr *Offset;
2792     if (getParser().ParseExpression(Offset))
2793       return MatchOperand_ParseFail;
2794     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2795     if (!CE) {
2796       Error(S, "constant expression expected");
2797       return MatchOperand_ParseFail;
2798     }
2799     SMLoc E = Tok.getLoc();
2800     // Negative zero is encoded as the flag value INT32_MIN.
2801     int32_t Val = CE->getValue();
2802     if (isNegative && Val == 0)
2803       Val = INT32_MIN;
2804
2805     Operands.push_back(
2806       ARMOperand::CreateImm(MCConstantExpr::Create(Val, getContext()), S, E));
2807
2808     return MatchOperand_Success;
2809   }
2810
2811
2812   bool haveEaten = false;
2813   bool isAdd = true;
2814   int Reg = -1;
2815   if (Tok.is(AsmToken::Plus)) {
2816     Parser.Lex(); // Eat the '+' token.
2817     haveEaten = true;
2818   } else if (Tok.is(AsmToken::Minus)) {
2819     Parser.Lex(); // Eat the '-' token.
2820     isAdd = false;
2821     haveEaten = true;
2822   }
2823   if (Parser.getTok().is(AsmToken::Identifier))
2824     Reg = tryParseRegister();
2825   if (Reg == -1) {
2826     if (!haveEaten)
2827       return MatchOperand_NoMatch;
2828     Error(Parser.getTok().getLoc(), "register expected");
2829     return MatchOperand_ParseFail;
2830   }
2831   SMLoc E = Parser.getTok().getLoc();
2832
2833   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
2834                                                   0, S, E));
2835
2836   return MatchOperand_Success;
2837 }
2838
2839 /// cvtT2LdrdPre - Convert parsed operands to MCInst.
2840 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2841 /// when they refer multiple MIOperands inside a single one.
2842 bool ARMAsmParser::
2843 cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
2844              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2845   // Rt, Rt2
2846   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2847   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2848   // Create a writeback register dummy placeholder.
2849   Inst.addOperand(MCOperand::CreateReg(0));
2850   // addr
2851   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2852   // pred
2853   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2854   return true;
2855 }
2856
2857 /// cvtT2StrdPre - Convert parsed operands to MCInst.
2858 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2859 /// when they refer multiple MIOperands inside a single one.
2860 bool ARMAsmParser::
2861 cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
2862              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2863   // Create a writeback register dummy placeholder.
2864   Inst.addOperand(MCOperand::CreateReg(0));
2865   // Rt, Rt2
2866   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2867   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2868   // addr
2869   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2870   // pred
2871   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2872   return true;
2873 }
2874
2875 /// cvtLdWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
2876 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2877 /// when they refer multiple MIOperands inside a single one.
2878 bool ARMAsmParser::
2879 cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
2880                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2881   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2882
2883   // Create a writeback register dummy placeholder.
2884   Inst.addOperand(MCOperand::CreateImm(0));
2885
2886   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
2887   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2888   return true;
2889 }
2890
2891 /// cvtStWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
2892 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2893 /// when they refer multiple MIOperands inside a single one.
2894 bool ARMAsmParser::
2895 cvtStWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
2896                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2897   // Create a writeback register dummy placeholder.
2898   Inst.addOperand(MCOperand::CreateImm(0));
2899   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2900   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
2901   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2902   return true;
2903 }
2904
2905 /// cvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2906 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2907 /// when they refer multiple MIOperands inside a single one.
2908 bool ARMAsmParser::
2909 cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2910                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2911   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2912
2913   // Create a writeback register dummy placeholder.
2914   Inst.addOperand(MCOperand::CreateImm(0));
2915
2916   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2917   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2918   return true;
2919 }
2920
2921 /// cvtLdWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2922 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2923 /// when they refer multiple MIOperands inside a single one.
2924 bool ARMAsmParser::
2925 cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2926                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2927   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2928
2929   // Create a writeback register dummy placeholder.
2930   Inst.addOperand(MCOperand::CreateImm(0));
2931
2932   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2933   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2934   return true;
2935 }
2936
2937
2938 /// cvtStWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2939 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2940 /// when they refer multiple MIOperands inside a single one.
2941 bool ARMAsmParser::
2942 cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2943                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2944   // Create a writeback register dummy placeholder.
2945   Inst.addOperand(MCOperand::CreateImm(0));
2946   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2947   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2948   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2949   return true;
2950 }
2951
2952 /// cvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2953 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2954 /// when they refer multiple MIOperands inside a single one.
2955 bool ARMAsmParser::
2956 cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2957                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2958   // Create a writeback register dummy placeholder.
2959   Inst.addOperand(MCOperand::CreateImm(0));
2960   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2961   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2962   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2963   return true;
2964 }
2965
2966 /// cvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2967 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2968 /// when they refer multiple MIOperands inside a single one.
2969 bool ARMAsmParser::
2970 cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2971                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2972   // Create a writeback register dummy placeholder.
2973   Inst.addOperand(MCOperand::CreateImm(0));
2974   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2975   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2976   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2977   return true;
2978 }
2979
2980 /// cvtLdExtTWriteBackImm - Convert parsed operands to MCInst.
2981 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2982 /// when they refer multiple MIOperands inside a single one.
2983 bool ARMAsmParser::
2984 cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2985                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2986   // Rt
2987   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2988   // Create a writeback register dummy placeholder.
2989   Inst.addOperand(MCOperand::CreateImm(0));
2990   // addr
2991   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2992   // offset
2993   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2994   // pred
2995   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2996   return true;
2997 }
2998
2999 /// cvtLdExtTWriteBackReg - Convert parsed operands to MCInst.
3000 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3001 /// when they refer multiple MIOperands inside a single one.
3002 bool ARMAsmParser::
3003 cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
3004                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3005   // Rt
3006   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3007   // Create a writeback register dummy placeholder.
3008   Inst.addOperand(MCOperand::CreateImm(0));
3009   // addr
3010   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
3011   // offset
3012   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
3013   // pred
3014   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3015   return true;
3016 }
3017
3018 /// cvtStExtTWriteBackImm - Convert parsed operands to MCInst.
3019 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3020 /// when they refer multiple MIOperands inside a single one.
3021 bool ARMAsmParser::
3022 cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
3023                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3024   // Create a writeback register dummy placeholder.
3025   Inst.addOperand(MCOperand::CreateImm(0));
3026   // Rt
3027   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3028   // addr
3029   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
3030   // offset
3031   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
3032   // pred
3033   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3034   return true;
3035 }
3036
3037 /// cvtStExtTWriteBackReg - Convert parsed operands to MCInst.
3038 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3039 /// when they refer multiple MIOperands inside a single one.
3040 bool ARMAsmParser::
3041 cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
3042                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3043   // Create a writeback register dummy placeholder.
3044   Inst.addOperand(MCOperand::CreateImm(0));
3045   // Rt
3046   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3047   // addr
3048   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
3049   // offset
3050   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
3051   // pred
3052   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3053   return true;
3054 }
3055
3056 /// cvtLdrdPre - Convert parsed operands to MCInst.
3057 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3058 /// when they refer multiple MIOperands inside a single one.
3059 bool ARMAsmParser::
3060 cvtLdrdPre(MCInst &Inst, unsigned Opcode,
3061            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3062   // Rt, Rt2
3063   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3064   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
3065   // Create a writeback register dummy placeholder.
3066   Inst.addOperand(MCOperand::CreateImm(0));
3067   // addr
3068   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
3069   // pred
3070   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3071   return true;
3072 }
3073
3074 /// cvtStrdPre - Convert parsed operands to MCInst.
3075 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3076 /// when they refer multiple MIOperands inside a single one.
3077 bool ARMAsmParser::
3078 cvtStrdPre(MCInst &Inst, unsigned Opcode,
3079            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3080   // Create a writeback register dummy placeholder.
3081   Inst.addOperand(MCOperand::CreateImm(0));
3082   // Rt, Rt2
3083   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3084   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
3085   // addr
3086   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
3087   // pred
3088   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3089   return true;
3090 }
3091
3092 /// cvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
3093 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3094 /// when they refer multiple MIOperands inside a single one.
3095 bool ARMAsmParser::
3096 cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
3097                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3098   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
3099   // Create a writeback register dummy placeholder.
3100   Inst.addOperand(MCOperand::CreateImm(0));
3101   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
3102   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
3103   return true;
3104 }
3105
3106 /// cvtThumbMultiple- Convert parsed operands to MCInst.
3107 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
3108 /// when they refer multiple MIOperands inside a single one.
3109 bool ARMAsmParser::
3110 cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
3111            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3112   // The second source operand must be the same register as the destination
3113   // operand.
3114   if (Operands.size() == 6 &&
3115       (((ARMOperand*)Operands[3])->getReg() !=
3116        ((ARMOperand*)Operands[5])->getReg()) &&
3117       (((ARMOperand*)Operands[3])->getReg() !=
3118        ((ARMOperand*)Operands[4])->getReg())) {
3119     Error(Operands[3]->getStartLoc(),
3120           "destination register must match source register");
3121     return false;
3122   }
3123   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
3124   ((ARMOperand*)Operands[1])->addCCOutOperands(Inst, 1);
3125   ((ARMOperand*)Operands[4])->addRegOperands(Inst, 1);
3126   // If we have a three-operand form, use that, else the second source operand
3127   // is just the destination operand again.
3128   if (Operands.size() == 6)
3129     ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
3130   else
3131     Inst.addOperand(Inst.getOperand(0));
3132   ((ARMOperand*)Operands[2])->addCondCodeOperands(Inst, 2);
3133
3134   return true;
3135 }
3136
3137 /// Parse an ARM memory expression, return false if successful else return true
3138 /// or an error.  The first token must be a '[' when called.
3139 bool ARMAsmParser::
3140 parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3141   SMLoc S, E;
3142   assert(Parser.getTok().is(AsmToken::LBrac) &&
3143          "Token is not a Left Bracket");
3144   S = Parser.getTok().getLoc();
3145   Parser.Lex(); // Eat left bracket token.
3146
3147   const AsmToken &BaseRegTok = Parser.getTok();
3148   int BaseRegNum = tryParseRegister();
3149   if (BaseRegNum == -1)
3150     return Error(BaseRegTok.getLoc(), "register expected");
3151
3152   // The next token must either be a comma or a closing bracket.
3153   const AsmToken &Tok = Parser.getTok();
3154   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
3155     return Error(Tok.getLoc(), "malformed memory operand");
3156
3157   if (Tok.is(AsmToken::RBrac)) {
3158     E = Tok.getLoc();
3159     Parser.Lex(); // Eat right bracket token.
3160
3161     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, 0, ARM_AM::no_shift,
3162                                              0, 0, false, S, E));
3163
3164     // If there's a pre-indexing writeback marker, '!', just add it as a token
3165     // operand. It's rather odd, but syntactically valid.
3166     if (Parser.getTok().is(AsmToken::Exclaim)) {
3167       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
3168       Parser.Lex(); // Eat the '!'.
3169     }
3170
3171     return false;
3172   }
3173
3174   assert(Tok.is(AsmToken::Comma) && "Lost comma in memory operand?!");
3175   Parser.Lex(); // Eat the comma.
3176
3177   // If we have a ':', it's an alignment specifier.
3178   if (Parser.getTok().is(AsmToken::Colon)) {
3179     Parser.Lex(); // Eat the ':'.
3180     E = Parser.getTok().getLoc();
3181
3182     const MCExpr *Expr;
3183     if (getParser().ParseExpression(Expr))
3184      return true;
3185
3186     // The expression has to be a constant. Memory references with relocations
3187     // don't come through here, as they use the <label> forms of the relevant
3188     // instructions.
3189     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3190     if (!CE)
3191       return Error (E, "constant expression expected");
3192
3193     unsigned Align = 0;
3194     switch (CE->getValue()) {
3195     default:
3196       return Error(E, "alignment specifier must be 64, 128, or 256 bits");
3197     case 64:  Align = 8; break;
3198     case 128: Align = 16; break;
3199     case 256: Align = 32; break;
3200     }
3201
3202     // Now we should have the closing ']'
3203     E = Parser.getTok().getLoc();
3204     if (Parser.getTok().isNot(AsmToken::RBrac))
3205       return Error(E, "']' expected");
3206     Parser.Lex(); // Eat right bracket token.
3207
3208     // Don't worry about range checking the value here. That's handled by
3209     // the is*() predicates.
3210     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, 0,
3211                                              ARM_AM::no_shift, 0, Align,
3212                                              false, S, E));
3213
3214     // If there's a pre-indexing writeback marker, '!', just add it as a token
3215     // operand.
3216     if (Parser.getTok().is(AsmToken::Exclaim)) {
3217       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
3218       Parser.Lex(); // Eat the '!'.
3219     }
3220
3221     return false;
3222   }
3223
3224   // If we have a '#', it's an immediate offset, else assume it's a register
3225   // offset.
3226   if (Parser.getTok().is(AsmToken::Hash)) {
3227     Parser.Lex(); // Eat the '#'.
3228     E = Parser.getTok().getLoc();
3229
3230     bool isNegative = getParser().getTok().is(AsmToken::Minus);
3231     const MCExpr *Offset;
3232     if (getParser().ParseExpression(Offset))
3233      return true;
3234
3235     // The expression has to be a constant. Memory references with relocations
3236     // don't come through here, as they use the <label> forms of the relevant
3237     // instructions.
3238     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
3239     if (!CE)
3240       return Error (E, "constant expression expected");
3241
3242     // If the constant was #-0, represent it as INT32_MIN.
3243     int32_t Val = CE->getValue();
3244     if (isNegative && Val == 0)
3245       CE = MCConstantExpr::Create(INT32_MIN, getContext());
3246
3247     // Now we should have the closing ']'
3248     E = Parser.getTok().getLoc();
3249     if (Parser.getTok().isNot(AsmToken::RBrac))
3250       return Error(E, "']' expected");
3251     Parser.Lex(); // Eat right bracket token.
3252
3253     // Don't worry about range checking the value here. That's handled by
3254     // the is*() predicates.
3255     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
3256                                              ARM_AM::no_shift, 0, 0,
3257                                              false, S, E));
3258
3259     // If there's a pre-indexing writeback marker, '!', just add it as a token
3260     // operand.
3261     if (Parser.getTok().is(AsmToken::Exclaim)) {
3262       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
3263       Parser.Lex(); // Eat the '!'.
3264     }
3265
3266     return false;
3267   }
3268
3269   // The register offset is optionally preceded by a '+' or '-'
3270   bool isNegative = false;
3271   if (Parser.getTok().is(AsmToken::Minus)) {
3272     isNegative = true;
3273     Parser.Lex(); // Eat the '-'.
3274   } else if (Parser.getTok().is(AsmToken::Plus)) {
3275     // Nothing to do.
3276     Parser.Lex(); // Eat the '+'.
3277   }
3278
3279   E = Parser.getTok().getLoc();
3280   int OffsetRegNum = tryParseRegister();
3281   if (OffsetRegNum == -1)
3282     return Error(E, "register expected");
3283
3284   // If there's a shift operator, handle it.
3285   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
3286   unsigned ShiftImm = 0;
3287   if (Parser.getTok().is(AsmToken::Comma)) {
3288     Parser.Lex(); // Eat the ','.
3289     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
3290       return true;
3291   }
3292
3293   // Now we should have the closing ']'
3294   E = Parser.getTok().getLoc();
3295   if (Parser.getTok().isNot(AsmToken::RBrac))
3296     return Error(E, "']' expected");
3297   Parser.Lex(); // Eat right bracket token.
3298
3299   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, OffsetRegNum,
3300                                            ShiftType, ShiftImm, 0, isNegative,
3301                                            S, E));
3302
3303   // If there's a pre-indexing writeback marker, '!', just add it as a token
3304   // operand.
3305   if (Parser.getTok().is(AsmToken::Exclaim)) {
3306     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
3307     Parser.Lex(); // Eat the '!'.
3308   }
3309
3310   return false;
3311 }
3312
3313 /// parseMemRegOffsetShift - one of these two:
3314 ///   ( lsl | lsr | asr | ror ) , # shift_amount
3315 ///   rrx
3316 /// return true if it parses a shift otherwise it returns false.
3317 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
3318                                           unsigned &Amount) {
3319   SMLoc Loc = Parser.getTok().getLoc();
3320   const AsmToken &Tok = Parser.getTok();
3321   if (Tok.isNot(AsmToken::Identifier))
3322     return true;
3323   StringRef ShiftName = Tok.getString();
3324   if (ShiftName == "lsl" || ShiftName == "LSL")
3325     St = ARM_AM::lsl;
3326   else if (ShiftName == "lsr" || ShiftName == "LSR")
3327     St = ARM_AM::lsr;
3328   else if (ShiftName == "asr" || ShiftName == "ASR")
3329     St = ARM_AM::asr;
3330   else if (ShiftName == "ror" || ShiftName == "ROR")
3331     St = ARM_AM::ror;
3332   else if (ShiftName == "rrx" || ShiftName == "RRX")
3333     St = ARM_AM::rrx;
3334   else
3335     return Error(Loc, "illegal shift operator");
3336   Parser.Lex(); // Eat shift type token.
3337
3338   // rrx stands alone.
3339   Amount = 0;
3340   if (St != ARM_AM::rrx) {
3341     Loc = Parser.getTok().getLoc();
3342     // A '#' and a shift amount.
3343     const AsmToken &HashTok = Parser.getTok();
3344     if (HashTok.isNot(AsmToken::Hash))
3345       return Error(HashTok.getLoc(), "'#' expected");
3346     Parser.Lex(); // Eat hash token.
3347
3348     const MCExpr *Expr;
3349     if (getParser().ParseExpression(Expr))
3350       return true;
3351     // Range check the immediate.
3352     // lsl, ror: 0 <= imm <= 31
3353     // lsr, asr: 0 <= imm <= 32
3354     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3355     if (!CE)
3356       return Error(Loc, "shift amount must be an immediate");
3357     int64_t Imm = CE->getValue();
3358     if (Imm < 0 ||
3359         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
3360         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
3361       return Error(Loc, "immediate shift value out of range");
3362     Amount = Imm;
3363   }
3364
3365   return false;
3366 }
3367
3368 /// parseFPImm - A floating point immediate expression operand.
3369 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3370 parseFPImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3371   SMLoc S = Parser.getTok().getLoc();
3372
3373   if (Parser.getTok().isNot(AsmToken::Hash))
3374     return MatchOperand_NoMatch;
3375
3376   // Disambiguate the VMOV forms that can accept an FP immediate.
3377   // vmov.f32 <sreg>, #imm
3378   // vmov.f64 <dreg>, #imm
3379   // vmov.f32 <dreg>, #imm  @ vector f32x2
3380   // vmov.f32 <qreg>, #imm  @ vector f32x4
3381   //
3382   // There are also the NEON VMOV instructions which expect an
3383   // integer constant. Make sure we don't try to parse an FPImm
3384   // for these:
3385   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
3386   ARMOperand *TyOp = static_cast<ARMOperand*>(Operands[2]);
3387   if (!TyOp->isToken() || (TyOp->getToken() != ".f32" &&
3388                            TyOp->getToken() != ".f64"))
3389     return MatchOperand_NoMatch;
3390
3391   Parser.Lex(); // Eat the '#'.
3392
3393   // Handle negation, as that still comes through as a separate token.
3394   bool isNegative = false;
3395   if (Parser.getTok().is(AsmToken::Minus)) {
3396     isNegative = true;
3397     Parser.Lex();
3398   }
3399   const AsmToken &Tok = Parser.getTok();
3400   if (Tok.is(AsmToken::Real)) {
3401     APFloat RealVal(APFloat::IEEEdouble, Tok.getString());
3402     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
3403     // If we had a '-' in front, toggle the sign bit.
3404     IntVal ^= (uint64_t)isNegative << 63;
3405     int Val = ARM_AM::getFP64Imm(APInt(64, IntVal));
3406     Parser.Lex(); // Eat the token.
3407     if (Val == -1) {
3408       TokError("floating point value out of range");
3409       return MatchOperand_ParseFail;
3410     }
3411     Operands.push_back(ARMOperand::CreateFPImm(Val, S, getContext()));
3412     return MatchOperand_Success;
3413   }
3414   if (Tok.is(AsmToken::Integer)) {
3415     int64_t Val = Tok.getIntVal();
3416     Parser.Lex(); // Eat the token.
3417     if (Val > 255 || Val < 0) {
3418       TokError("encoded floating point value out of range");
3419       return MatchOperand_ParseFail;
3420     }
3421     Operands.push_back(ARMOperand::CreateFPImm(Val, S, getContext()));
3422     return MatchOperand_Success;
3423   }
3424
3425   TokError("invalid floating point immediate");
3426   return MatchOperand_ParseFail;
3427 }
3428 /// Parse a arm instruction operand.  For now this parses the operand regardless
3429 /// of the mnemonic.
3430 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
3431                                 StringRef Mnemonic) {
3432   SMLoc S, E;
3433
3434   // Check if the current operand has a custom associated parser, if so, try to
3435   // custom parse the operand, or fallback to the general approach.
3436   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
3437   if (ResTy == MatchOperand_Success)
3438     return false;
3439   // If there wasn't a custom match, try the generic matcher below. Otherwise,
3440   // there was a match, but an error occurred, in which case, just return that
3441   // the operand parsing failed.
3442   if (ResTy == MatchOperand_ParseFail)
3443     return true;
3444
3445   switch (getLexer().getKind()) {
3446   default:
3447     Error(Parser.getTok().getLoc(), "unexpected token in operand");
3448     return true;
3449   case AsmToken::Identifier: {
3450     // If this is VMRS, check for the apsr_nzcv operand.
3451     if (!tryParseRegisterWithWriteBack(Operands))
3452       return false;
3453     int Res = tryParseShiftRegister(Operands);
3454     if (Res == 0) // success
3455       return false;
3456     else if (Res == -1) // irrecoverable error
3457       return true;
3458     if (Mnemonic == "vmrs" && Parser.getTok().getString() == "apsr_nzcv") {
3459       S = Parser.getTok().getLoc();
3460       Parser.Lex();
3461       Operands.push_back(ARMOperand::CreateToken("apsr_nzcv", S));
3462       return false;
3463     }
3464
3465     // Fall though for the Identifier case that is not a register or a
3466     // special name.
3467   }
3468   case AsmToken::Integer: // things like 1f and 2b as a branch targets
3469   case AsmToken::Dot: {   // . as a branch target
3470     // This was not a register so parse other operands that start with an
3471     // identifier (like labels) as expressions and create them as immediates.
3472     const MCExpr *IdVal;
3473     S = Parser.getTok().getLoc();
3474     if (getParser().ParseExpression(IdVal))
3475       return true;
3476     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3477     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
3478     return false;
3479   }
3480   case AsmToken::LBrac:
3481     return parseMemory(Operands);
3482   case AsmToken::LCurly:
3483     return parseRegisterList(Operands);
3484   case AsmToken::Hash: {
3485     // #42 -> immediate.
3486     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
3487     S = Parser.getTok().getLoc();
3488     Parser.Lex();
3489     bool isNegative = Parser.getTok().is(AsmToken::Minus);
3490     const MCExpr *ImmVal;
3491     if (getParser().ParseExpression(ImmVal))
3492       return true;
3493     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
3494     if (!CE) {
3495       Error(S, "constant expression expected");
3496       return MatchOperand_ParseFail;
3497     }
3498     int32_t Val = CE->getValue();
3499     if (isNegative && Val == 0)
3500       ImmVal = MCConstantExpr::Create(INT32_MIN, getContext());
3501     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3502     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
3503     return false;
3504   }
3505   case AsmToken::Colon: {
3506     // ":lower16:" and ":upper16:" expression prefixes
3507     // FIXME: Check it's an expression prefix,
3508     // e.g. (FOO - :lower16:BAR) isn't legal.
3509     ARMMCExpr::VariantKind RefKind;
3510     if (parsePrefix(RefKind))
3511       return true;
3512
3513     const MCExpr *SubExprVal;
3514     if (getParser().ParseExpression(SubExprVal))
3515       return true;
3516
3517     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
3518                                                    getContext());
3519     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3520     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
3521     return false;
3522   }
3523   }
3524 }
3525
3526 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
3527 //  :lower16: and :upper16:.
3528 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
3529   RefKind = ARMMCExpr::VK_ARM_None;
3530
3531   // :lower16: and :upper16: modifiers
3532   assert(getLexer().is(AsmToken::Colon) && "expected a :");
3533   Parser.Lex(); // Eat ':'
3534
3535   if (getLexer().isNot(AsmToken::Identifier)) {
3536     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
3537     return true;
3538   }
3539
3540   StringRef IDVal = Parser.getTok().getIdentifier();
3541   if (IDVal == "lower16") {
3542     RefKind = ARMMCExpr::VK_ARM_LO16;
3543   } else if (IDVal == "upper16") {
3544     RefKind = ARMMCExpr::VK_ARM_HI16;
3545   } else {
3546     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
3547     return true;
3548   }
3549   Parser.Lex();
3550
3551   if (getLexer().isNot(AsmToken::Colon)) {
3552     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
3553     return true;
3554   }
3555   Parser.Lex(); // Eat the last ':'
3556   return false;
3557 }
3558
3559 /// \brief Given a mnemonic, split out possible predication code and carry
3560 /// setting letters to form a canonical mnemonic and flags.
3561 //
3562 // FIXME: Would be nice to autogen this.
3563 // FIXME: This is a bit of a maze of special cases.
3564 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
3565                                       unsigned &PredicationCode,
3566                                       bool &CarrySetting,
3567                                       unsigned &ProcessorIMod,
3568                                       StringRef &ITMask) {
3569   PredicationCode = ARMCC::AL;
3570   CarrySetting = false;
3571   ProcessorIMod = 0;
3572
3573   // Ignore some mnemonics we know aren't predicated forms.
3574   //
3575   // FIXME: Would be nice to autogen this.
3576   if ((Mnemonic == "movs" && isThumb()) ||
3577       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
3578       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
3579       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
3580       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
3581       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
3582       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
3583       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal")
3584     return Mnemonic;
3585
3586   // First, split out any predication code. Ignore mnemonics we know aren't
3587   // predicated but do have a carry-set and so weren't caught above.
3588   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
3589       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
3590       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
3591       Mnemonic != "sbcs" && Mnemonic != "rscs") {
3592     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
3593       .Case("eq", ARMCC::EQ)
3594       .Case("ne", ARMCC::NE)
3595       .Case("hs", ARMCC::HS)
3596       .Case("cs", ARMCC::HS)
3597       .Case("lo", ARMCC::LO)
3598       .Case("cc", ARMCC::LO)
3599       .Case("mi", ARMCC::MI)
3600       .Case("pl", ARMCC::PL)
3601       .Case("vs", ARMCC::VS)
3602       .Case("vc", ARMCC::VC)
3603       .Case("hi", ARMCC::HI)
3604       .Case("ls", ARMCC::LS)
3605       .Case("ge", ARMCC::GE)
3606       .Case("lt", ARMCC::LT)
3607       .Case("gt", ARMCC::GT)
3608       .Case("le", ARMCC::LE)
3609       .Case("al", ARMCC::AL)
3610       .Default(~0U);
3611     if (CC != ~0U) {
3612       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
3613       PredicationCode = CC;
3614     }
3615   }
3616
3617   // Next, determine if we have a carry setting bit. We explicitly ignore all
3618   // the instructions we know end in 's'.
3619   if (Mnemonic.endswith("s") &&
3620       !(Mnemonic == "cps" || Mnemonic == "mls" ||
3621         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
3622         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
3623         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
3624         Mnemonic == "vrsqrts" || Mnemonic == "srs" ||
3625         (Mnemonic == "movs" && isThumb()))) {
3626     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
3627     CarrySetting = true;
3628   }
3629
3630   // The "cps" instruction can have a interrupt mode operand which is glued into
3631   // the mnemonic. Check if this is the case, split it and parse the imod op
3632   if (Mnemonic.startswith("cps")) {
3633     // Split out any imod code.
3634     unsigned IMod =
3635       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
3636       .Case("ie", ARM_PROC::IE)
3637       .Case("id", ARM_PROC::ID)
3638       .Default(~0U);
3639     if (IMod != ~0U) {
3640       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
3641       ProcessorIMod = IMod;
3642     }
3643   }
3644
3645   // The "it" instruction has the condition mask on the end of the mnemonic.
3646   if (Mnemonic.startswith("it")) {
3647     ITMask = Mnemonic.slice(2, Mnemonic.size());
3648     Mnemonic = Mnemonic.slice(0, 2);
3649   }
3650
3651   return Mnemonic;
3652 }
3653
3654 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
3655 /// inclusion of carry set or predication code operands.
3656 //
3657 // FIXME: It would be nice to autogen this.
3658 void ARMAsmParser::
3659 getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
3660                       bool &CanAcceptPredicationCode) {
3661   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
3662       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
3663       Mnemonic == "add" || Mnemonic == "adc" ||
3664       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
3665       Mnemonic == "orr" || Mnemonic == "mvn" ||
3666       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
3667       Mnemonic == "sbc" || Mnemonic == "eor" || Mnemonic == "neg" ||
3668       (!isThumb() && (Mnemonic == "smull" || Mnemonic == "mov" ||
3669                       Mnemonic == "mla" || Mnemonic == "smlal" ||
3670                       Mnemonic == "umlal" || Mnemonic == "umull"))) {
3671     CanAcceptCarrySet = true;
3672   } else
3673     CanAcceptCarrySet = false;
3674
3675   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
3676       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
3677       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
3678       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
3679       Mnemonic == "dsb" || Mnemonic == "isb" || Mnemonic == "setend" ||
3680       (Mnemonic == "clrex" && !isThumb()) ||
3681       (Mnemonic == "nop" && isThumbOne()) ||
3682       ((Mnemonic == "pld" || Mnemonic == "pli" || Mnemonic == "pldw" ||
3683         Mnemonic == "ldc2" || Mnemonic == "ldc2l" ||
3684         Mnemonic == "stc2" || Mnemonic == "stc2l") && !isThumb()) ||
3685       ((Mnemonic.startswith("rfe") || Mnemonic.startswith("srs")) &&
3686        !isThumb()) ||
3687       Mnemonic.startswith("cps") || (Mnemonic == "movs" && isThumbOne())) {
3688     CanAcceptPredicationCode = false;
3689   } else
3690     CanAcceptPredicationCode = true;
3691
3692   if (isThumb()) {
3693     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
3694         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
3695       CanAcceptPredicationCode = false;
3696   }
3697 }
3698
3699 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
3700                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3701   // FIXME: This is all horribly hacky. We really need a better way to deal
3702   // with optional operands like this in the matcher table.
3703
3704   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
3705   // another does not. Specifically, the MOVW instruction does not. So we
3706   // special case it here and remove the defaulted (non-setting) cc_out
3707   // operand if that's the instruction we're trying to match.
3708   //
3709   // We do this as post-processing of the explicit operands rather than just
3710   // conditionally adding the cc_out in the first place because we need
3711   // to check the type of the parsed immediate operand.
3712   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
3713       !static_cast<ARMOperand*>(Operands[4])->isARMSOImm() &&
3714       static_cast<ARMOperand*>(Operands[4])->isImm0_65535Expr() &&
3715       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3716     return true;
3717
3718   // Register-register 'add' for thumb does not have a cc_out operand
3719   // when there are only two register operands.
3720   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
3721       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3722       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3723       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3724     return true;
3725   // Register-register 'add' for thumb does not have a cc_out operand
3726   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
3727   // have to check the immediate range here since Thumb2 has a variant
3728   // that can handle a different range and has a cc_out operand.
3729   if (((isThumb() && Mnemonic == "add") ||
3730        (isThumbTwo() && Mnemonic == "sub")) &&
3731       Operands.size() == 6 &&
3732       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3733       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3734       static_cast<ARMOperand*>(Operands[4])->getReg() == ARM::SP &&
3735       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3736       (static_cast<ARMOperand*>(Operands[5])->isReg() ||
3737        static_cast<ARMOperand*>(Operands[5])->isImm0_1020s4()))
3738     return true;
3739   // For Thumb2, add/sub immediate does not have a cc_out operand for the
3740   // imm0_4095 variant. That's the least-preferred variant when
3741   // selecting via the generic "add" mnemonic, so to know that we
3742   // should remove the cc_out operand, we have to explicitly check that
3743   // it's not one of the other variants. Ugh.
3744   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
3745       Operands.size() == 6 &&
3746       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3747       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3748       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3749     // Nest conditions rather than one big 'if' statement for readability.
3750     //
3751     // If either register is a high reg, it's either one of the SP
3752     // variants (handled above) or a 32-bit encoding, so we just
3753     // check against T3.
3754     if ((!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3755          !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg())) &&
3756         static_cast<ARMOperand*>(Operands[5])->isT2SOImm())
3757       return false;
3758     // If both registers are low, we're in an IT block, and the immediate is
3759     // in range, we should use encoding T1 instead, which has a cc_out.
3760     if (inITBlock() &&
3761         isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) &&
3762         isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) &&
3763         static_cast<ARMOperand*>(Operands[5])->isImm0_7())
3764       return false;
3765
3766     // Otherwise, we use encoding T4, which does not have a cc_out
3767     // operand.
3768     return true;
3769   }
3770
3771   // The thumb2 multiply instruction doesn't have a CCOut register, so
3772   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
3773   // use the 16-bit encoding or not.
3774   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
3775       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3776       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3777       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3778       static_cast<ARMOperand*>(Operands[5])->isReg() &&
3779       // If the registers aren't low regs, the destination reg isn't the
3780       // same as one of the source regs, or the cc_out operand is zero
3781       // outside of an IT block, we have to use the 32-bit encoding, so
3782       // remove the cc_out operand.
3783       (!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3784        !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) ||
3785        !inITBlock() ||
3786        (static_cast<ARMOperand*>(Operands[3])->getReg() !=
3787         static_cast<ARMOperand*>(Operands[5])->getReg() &&
3788         static_cast<ARMOperand*>(Operands[3])->getReg() !=
3789         static_cast<ARMOperand*>(Operands[4])->getReg())))
3790     return true;
3791
3792
3793
3794   // Register-register 'add/sub' for thumb does not have a cc_out operand
3795   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
3796   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
3797   // right, this will result in better diagnostics (which operand is off)
3798   // anyway.
3799   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
3800       (Operands.size() == 5 || Operands.size() == 6) &&
3801       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3802       static_cast<ARMOperand*>(Operands[3])->getReg() == ARM::SP &&
3803       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3804     return true;
3805
3806   return false;
3807 }
3808
3809 /// Parse an arm instruction mnemonic followed by its operands.
3810 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
3811                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3812   // Create the leading tokens for the mnemonic, split by '.' characters.
3813   size_t Start = 0, Next = Name.find('.');
3814   StringRef Mnemonic = Name.slice(Start, Next);
3815
3816   // Split out the predication code and carry setting flag from the mnemonic.
3817   unsigned PredicationCode;
3818   unsigned ProcessorIMod;
3819   bool CarrySetting;
3820   StringRef ITMask;
3821   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
3822                            ProcessorIMod, ITMask);
3823
3824   // In Thumb1, only the branch (B) instruction can be predicated.
3825   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
3826     Parser.EatToEndOfStatement();
3827     return Error(NameLoc, "conditional execution not supported in Thumb1");
3828   }
3829
3830   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
3831
3832   // Handle the IT instruction ITMask. Convert it to a bitmask. This
3833   // is the mask as it will be for the IT encoding if the conditional
3834   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
3835   // where the conditional bit0 is zero, the instruction post-processing
3836   // will adjust the mask accordingly.
3837   if (Mnemonic == "it") {
3838     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
3839     if (ITMask.size() > 3) {
3840       Parser.EatToEndOfStatement();
3841       return Error(Loc, "too many conditions on IT instruction");
3842     }
3843     unsigned Mask = 8;
3844     for (unsigned i = ITMask.size(); i != 0; --i) {
3845       char pos = ITMask[i - 1];
3846       if (pos != 't' && pos != 'e') {
3847         Parser.EatToEndOfStatement();
3848         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
3849       }
3850       Mask >>= 1;
3851       if (ITMask[i - 1] == 't')
3852         Mask |= 8;
3853     }
3854     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
3855   }
3856
3857   // FIXME: This is all a pretty gross hack. We should automatically handle
3858   // optional operands like this via tblgen.
3859
3860   // Next, add the CCOut and ConditionCode operands, if needed.
3861   //
3862   // For mnemonics which can ever incorporate a carry setting bit or predication
3863   // code, our matching model involves us always generating CCOut and
3864   // ConditionCode operands to match the mnemonic "as written" and then we let
3865   // the matcher deal with finding the right instruction or generating an
3866   // appropriate error.
3867   bool CanAcceptCarrySet, CanAcceptPredicationCode;
3868   getMnemonicAcceptInfo(Mnemonic, CanAcceptCarrySet, CanAcceptPredicationCode);
3869
3870   // If we had a carry-set on an instruction that can't do that, issue an
3871   // error.
3872   if (!CanAcceptCarrySet && CarrySetting) {
3873     Parser.EatToEndOfStatement();
3874     return Error(NameLoc, "instruction '" + Mnemonic +
3875                  "' can not set flags, but 's' suffix specified");
3876   }
3877   // If we had a predication code on an instruction that can't do that, issue an
3878   // error.
3879   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
3880     Parser.EatToEndOfStatement();
3881     return Error(NameLoc, "instruction '" + Mnemonic +
3882                  "' is not predicable, but condition code specified");
3883   }
3884
3885   // Add the carry setting operand, if necessary.
3886   if (CanAcceptCarrySet) {
3887     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
3888     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
3889                                                Loc));
3890   }
3891
3892   // Add the predication code operand, if necessary.
3893   if (CanAcceptPredicationCode) {
3894     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
3895                                       CarrySetting);
3896     Operands.push_back(ARMOperand::CreateCondCode(
3897                          ARMCC::CondCodes(PredicationCode), Loc));
3898   }
3899
3900   // Add the processor imod operand, if necessary.
3901   if (ProcessorIMod) {
3902     Operands.push_back(ARMOperand::CreateImm(
3903           MCConstantExpr::Create(ProcessorIMod, getContext()),
3904                                  NameLoc, NameLoc));
3905   }
3906
3907   // Add the remaining tokens in the mnemonic.
3908   while (Next != StringRef::npos) {
3909     Start = Next;
3910     Next = Name.find('.', Start + 1);
3911     StringRef ExtraToken = Name.slice(Start, Next);
3912
3913     // For now, we're only parsing Thumb1 (for the most part), so
3914     // just ignore ".n" qualifiers. We'll use them to restrict
3915     // matching when we do Thumb2.
3916     if (ExtraToken != ".n") {
3917       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
3918       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
3919     }
3920   }
3921
3922   // Read the remaining operands.
3923   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3924     // Read the first operand.
3925     if (parseOperand(Operands, Mnemonic)) {
3926       Parser.EatToEndOfStatement();
3927       return true;
3928     }
3929
3930     while (getLexer().is(AsmToken::Comma)) {
3931       Parser.Lex();  // Eat the comma.
3932
3933       // Parse and remember the operand.
3934       if (parseOperand(Operands, Mnemonic)) {
3935         Parser.EatToEndOfStatement();
3936         return true;
3937       }
3938     }
3939   }
3940
3941   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3942     SMLoc Loc = getLexer().getLoc();
3943     Parser.EatToEndOfStatement();
3944     return Error(Loc, "unexpected token in argument list");
3945   }
3946
3947   Parser.Lex(); // Consume the EndOfStatement
3948
3949   // Some instructions, mostly Thumb, have forms for the same mnemonic that
3950   // do and don't have a cc_out optional-def operand. With some spot-checks
3951   // of the operand list, we can figure out which variant we're trying to
3952   // parse and adjust accordingly before actually matching. We shouldn't ever
3953   // try to remove a cc_out operand that was explicitly set on the the
3954   // mnemonic, of course (CarrySetting == true). Reason number #317 the
3955   // table driven matcher doesn't fit well with the ARM instruction set.
3956   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands)) {
3957     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3958     Operands.erase(Operands.begin() + 1);
3959     delete Op;
3960   }
3961
3962   // ARM mode 'blx' need special handling, as the register operand version
3963   // is predicable, but the label operand version is not. So, we can't rely
3964   // on the Mnemonic based checking to correctly figure out when to put
3965   // a k_CondCode operand in the list. If we're trying to match the label
3966   // version, remove the k_CondCode operand here.
3967   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
3968       static_cast<ARMOperand*>(Operands[2])->isImm()) {
3969     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3970     Operands.erase(Operands.begin() + 1);
3971     delete Op;
3972   }
3973
3974   // The vector-compare-to-zero instructions have a literal token "#0" at
3975   // the end that comes to here as an immediate operand. Convert it to a
3976   // token to play nicely with the matcher.
3977   if ((Mnemonic == "vceq" || Mnemonic == "vcge" || Mnemonic == "vcgt" ||
3978       Mnemonic == "vcle" || Mnemonic == "vclt") && Operands.size() == 6 &&
3979       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3980     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
3981     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3982     if (CE && CE->getValue() == 0) {
3983       Operands.erase(Operands.begin() + 5);
3984       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3985       delete Op;
3986     }
3987   }
3988   // VCMP{E} does the same thing, but with a different operand count.
3989   if ((Mnemonic == "vcmp" || Mnemonic == "vcmpe") && Operands.size() == 5 &&
3990       static_cast<ARMOperand*>(Operands[4])->isImm()) {
3991     ARMOperand *Op = static_cast<ARMOperand*>(Operands[4]);
3992     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3993     if (CE && CE->getValue() == 0) {
3994       Operands.erase(Operands.begin() + 4);
3995       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3996       delete Op;
3997     }
3998   }
3999   // Similarly, the Thumb1 "RSB" instruction has a literal "#0" on the
4000   // end. Convert it to a token here.
4001   if (Mnemonic == "rsb" && isThumb() && Operands.size() == 6 &&
4002       static_cast<ARMOperand*>(Operands[5])->isImm()) {
4003     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
4004     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
4005     if (CE && CE->getValue() == 0) {
4006       Operands.erase(Operands.begin() + 5);
4007       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
4008       delete Op;
4009     }
4010   }
4011
4012   return false;
4013 }
4014
4015 // Validate context-sensitive operand constraints.
4016
4017 // return 'true' if register list contains non-low GPR registers,
4018 // 'false' otherwise. If Reg is in the register list or is HiReg, set
4019 // 'containsReg' to true.
4020 static bool checkLowRegisterList(MCInst Inst, unsigned OpNo, unsigned Reg,
4021                                  unsigned HiReg, bool &containsReg) {
4022   containsReg = false;
4023   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
4024     unsigned OpReg = Inst.getOperand(i).getReg();
4025     if (OpReg == Reg)
4026       containsReg = true;
4027     // Anything other than a low register isn't legal here.
4028     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
4029       return true;
4030   }
4031   return false;
4032 }
4033
4034 // Check if the specified regisgter is in the register list of the inst,
4035 // starting at the indicated operand number.
4036 static bool listContainsReg(MCInst &Inst, unsigned OpNo, unsigned Reg) {
4037   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
4038     unsigned OpReg = Inst.getOperand(i).getReg();
4039     if (OpReg == Reg)
4040       return true;
4041   }
4042   return false;
4043 }
4044
4045 // FIXME: We would really prefer to have MCInstrInfo (the wrapper around
4046 // the ARMInsts array) instead. Getting that here requires awkward
4047 // API changes, though. Better way?
4048 namespace llvm {
4049 extern MCInstrDesc ARMInsts[];
4050 }
4051 static MCInstrDesc &getInstDesc(unsigned Opcode) {
4052   return ARMInsts[Opcode];
4053 }
4054
4055 // FIXME: We would really like to be able to tablegen'erate this.
4056 bool ARMAsmParser::
4057 validateInstruction(MCInst &Inst,
4058                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
4059   MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
4060   SMLoc Loc = Operands[0]->getStartLoc();
4061   // Check the IT block state first.
4062   // NOTE: In Thumb mode, the BKPT instruction has the interesting property of
4063   // being allowed in IT blocks, but not being predicable.  It just always
4064   // executes.
4065   if (inITBlock() && Inst.getOpcode() != ARM::tBKPT) {
4066     unsigned bit = 1;
4067     if (ITState.FirstCond)
4068       ITState.FirstCond = false;
4069     else
4070       bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
4071     // The instruction must be predicable.
4072     if (!MCID.isPredicable())
4073       return Error(Loc, "instructions in IT block must be predicable");
4074     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
4075     unsigned ITCond = bit ? ITState.Cond :
4076       ARMCC::getOppositeCondition(ITState.Cond);
4077     if (Cond != ITCond) {
4078       // Find the condition code Operand to get its SMLoc information.
4079       SMLoc CondLoc;
4080       for (unsigned i = 1; i < Operands.size(); ++i)
4081         if (static_cast<ARMOperand*>(Operands[i])->isCondCode())
4082           CondLoc = Operands[i]->getStartLoc();
4083       return Error(CondLoc, "incorrect condition in IT block; got '" +
4084                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
4085                    "', but expected '" +
4086                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
4087     }
4088   // Check for non-'al' condition codes outside of the IT block.
4089   } else if (isThumbTwo() && MCID.isPredicable() &&
4090              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
4091              ARMCC::AL && Inst.getOpcode() != ARM::tB &&
4092              Inst.getOpcode() != ARM::t2B)
4093     return Error(Loc, "predicated instructions must be in IT block");
4094
4095   switch (Inst.getOpcode()) {
4096   case ARM::LDRD:
4097   case ARM::LDRD_PRE:
4098   case ARM::LDRD_POST:
4099   case ARM::LDREXD: {
4100     // Rt2 must be Rt + 1.
4101     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
4102     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
4103     if (Rt2 != Rt + 1)
4104       return Error(Operands[3]->getStartLoc(),
4105                    "destination operands must be sequential");
4106     return false;
4107   }
4108   case ARM::STRD: {
4109     // Rt2 must be Rt + 1.
4110     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
4111     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
4112     if (Rt2 != Rt + 1)
4113       return Error(Operands[3]->getStartLoc(),
4114                    "source operands must be sequential");
4115     return false;
4116   }
4117   case ARM::STRD_PRE:
4118   case ARM::STRD_POST:
4119   case ARM::STREXD: {
4120     // Rt2 must be Rt + 1.
4121     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(1).getReg());
4122     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(2).getReg());
4123     if (Rt2 != Rt + 1)
4124       return Error(Operands[3]->getStartLoc(),
4125                    "source operands must be sequential");
4126     return false;
4127   }
4128   case ARM::SBFX:
4129   case ARM::UBFX: {
4130     // width must be in range [1, 32-lsb]
4131     unsigned lsb = Inst.getOperand(2).getImm();
4132     unsigned widthm1 = Inst.getOperand(3).getImm();
4133     if (widthm1 >= 32 - lsb)
4134       return Error(Operands[5]->getStartLoc(),
4135                    "bitfield width must be in range [1,32-lsb]");
4136     return false;
4137   }
4138   case ARM::tLDMIA: {
4139     // If we're parsing Thumb2, the .w variant is available and handles
4140     // most cases that are normally illegal for a Thumb1 LDM
4141     // instruction. We'll make the transformation in processInstruction()
4142     // if necessary.
4143     //
4144     // Thumb LDM instructions are writeback iff the base register is not
4145     // in the register list.
4146     unsigned Rn = Inst.getOperand(0).getReg();
4147     bool hasWritebackToken =
4148       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
4149        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
4150     bool listContainsBase;
4151     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) && !isThumbTwo())
4152       return Error(Operands[3 + hasWritebackToken]->getStartLoc(),
4153                    "registers must be in range r0-r7");
4154     // If we should have writeback, then there should be a '!' token.
4155     if (!listContainsBase && !hasWritebackToken && !isThumbTwo())
4156       return Error(Operands[2]->getStartLoc(),
4157                    "writeback operator '!' expected");
4158     // If we should not have writeback, there must not be a '!'. This is
4159     // true even for the 32-bit wide encodings.
4160     if (listContainsBase && hasWritebackToken)
4161       return Error(Operands[3]->getStartLoc(),
4162                    "writeback operator '!' not allowed when base register "
4163                    "in register list");
4164
4165     break;
4166   }
4167   case ARM::t2LDMIA_UPD: {
4168     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
4169       return Error(Operands[4]->getStartLoc(),
4170                    "writeback operator '!' not allowed when base register "
4171                    "in register list");
4172     break;
4173   }
4174   case ARM::tPOP: {
4175     bool listContainsBase;
4176     if (checkLowRegisterList(Inst, 3, 0, ARM::PC, listContainsBase))
4177       return Error(Operands[2]->getStartLoc(),
4178                    "registers must be in range r0-r7 or pc");
4179     break;
4180   }
4181   case ARM::tPUSH: {
4182     bool listContainsBase;
4183     if (checkLowRegisterList(Inst, 3, 0, ARM::LR, listContainsBase))
4184       return Error(Operands[2]->getStartLoc(),
4185                    "registers must be in range r0-r7 or lr");
4186     break;
4187   }
4188   case ARM::tSTMIA_UPD: {
4189     bool listContainsBase;
4190     if (checkLowRegisterList(Inst, 4, 0, 0, listContainsBase) && !isThumbTwo())
4191       return Error(Operands[4]->getStartLoc(),
4192                    "registers must be in range r0-r7");
4193     break;
4194   }
4195   }
4196
4197   return false;
4198 }
4199
4200 void ARMAsmParser::
4201 processInstruction(MCInst &Inst,
4202                    const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
4203   switch (Inst.getOpcode()) {
4204   case ARM::LDMIA_UPD:
4205     // If this is a load of a single register via a 'pop', then we should use
4206     // a post-indexed LDR instruction instead, per the ARM ARM.
4207     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "pop" &&
4208         Inst.getNumOperands() == 5) {
4209       MCInst TmpInst;
4210       TmpInst.setOpcode(ARM::LDR_POST_IMM);
4211       TmpInst.addOperand(Inst.getOperand(4)); // Rt
4212       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
4213       TmpInst.addOperand(Inst.getOperand(1)); // Rn
4214       TmpInst.addOperand(MCOperand::CreateReg(0));  // am2offset
4215       TmpInst.addOperand(MCOperand::CreateImm(4));
4216       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
4217       TmpInst.addOperand(Inst.getOperand(3));
4218       Inst = TmpInst;
4219     }
4220     break;
4221   case ARM::STMDB_UPD:
4222     // If this is a store of a single register via a 'push', then we should use
4223     // a pre-indexed STR instruction instead, per the ARM ARM.
4224     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "push" &&
4225         Inst.getNumOperands() == 5) {
4226       MCInst TmpInst;
4227       TmpInst.setOpcode(ARM::STR_PRE_IMM);
4228       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
4229       TmpInst.addOperand(Inst.getOperand(4)); // Rt
4230       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
4231       TmpInst.addOperand(MCOperand::CreateImm(-4));
4232       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
4233       TmpInst.addOperand(Inst.getOperand(3));
4234       Inst = TmpInst;
4235     }
4236     break;
4237   case ARM::tADDi8:
4238     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
4239     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
4240     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
4241     // to encoding T1 if <Rd> is omitted."
4242     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6)
4243       Inst.setOpcode(ARM::tADDi3);
4244     break;
4245   case ARM::tSUBi8:
4246     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
4247     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
4248     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
4249     // to encoding T1 if <Rd> is omitted."
4250     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6)
4251       Inst.setOpcode(ARM::tSUBi3);
4252     break;
4253   case ARM::tB:
4254     // A Thumb conditional branch outside of an IT block is a tBcc.
4255     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
4256       Inst.setOpcode(ARM::tBcc);
4257     break;
4258   case ARM::t2B:
4259     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
4260     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
4261       Inst.setOpcode(ARM::t2Bcc);
4262     break;
4263   case ARM::t2Bcc:
4264     // If the conditional is AL or we're in an IT block, we really want t2B.
4265     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock())
4266       Inst.setOpcode(ARM::t2B);
4267     break;
4268   case ARM::tBcc:
4269     // If the conditional is AL, we really want tB.
4270     if (Inst.getOperand(1).getImm() == ARMCC::AL)
4271       Inst.setOpcode(ARM::tB);
4272     break;
4273   case ARM::tLDMIA: {
4274     // If the register list contains any high registers, or if the writeback
4275     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
4276     // instead if we're in Thumb2. Otherwise, this should have generated
4277     // an error in validateInstruction().
4278     unsigned Rn = Inst.getOperand(0).getReg();
4279     bool hasWritebackToken =
4280       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
4281        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
4282     bool listContainsBase;
4283     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
4284         (!listContainsBase && !hasWritebackToken) ||
4285         (listContainsBase && hasWritebackToken)) {
4286       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
4287       assert (isThumbTwo());
4288       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
4289       // If we're switching to the updating version, we need to insert
4290       // the writeback tied operand.
4291       if (hasWritebackToken)
4292         Inst.insert(Inst.begin(),
4293                     MCOperand::CreateReg(Inst.getOperand(0).getReg()));
4294     }
4295     break;
4296   }
4297   case ARM::tSTMIA_UPD: {
4298     // If the register list contains any high registers, we need to use
4299     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
4300     // should have generated an error in validateInstruction().
4301     unsigned Rn = Inst.getOperand(0).getReg();
4302     bool listContainsBase;
4303     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
4304       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
4305       assert (isThumbTwo());
4306       Inst.setOpcode(ARM::t2STMIA_UPD);
4307     }
4308     break;
4309   }
4310   case ARM::t2MOVi: {
4311     // If we can use the 16-bit encoding and the user didn't explicitly
4312     // request the 32-bit variant, transform it here.
4313     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
4314         Inst.getOperand(1).getImm() <= 255 &&
4315         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
4316          Inst.getOperand(4).getReg() == ARM::CPSR) ||
4317         (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
4318         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
4319          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
4320       // The operands aren't in the same order for tMOVi8...
4321       MCInst TmpInst;
4322       TmpInst.setOpcode(ARM::tMOVi8);
4323       TmpInst.addOperand(Inst.getOperand(0));
4324       TmpInst.addOperand(Inst.getOperand(4));
4325       TmpInst.addOperand(Inst.getOperand(1));
4326       TmpInst.addOperand(Inst.getOperand(2));
4327       TmpInst.addOperand(Inst.getOperand(3));
4328       Inst = TmpInst;
4329     }
4330     break;
4331   }
4332   case ARM::t2MOVr: {
4333     // If we can use the 16-bit encoding and the user didn't explicitly
4334     // request the 32-bit variant, transform it here.
4335     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
4336         isARMLowRegister(Inst.getOperand(1).getReg()) &&
4337         Inst.getOperand(2).getImm() == ARMCC::AL &&
4338         Inst.getOperand(4).getReg() == ARM::CPSR &&
4339         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
4340          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
4341       // The operands aren't the same for tMOV[S]r... (no cc_out)
4342       MCInst TmpInst;
4343       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
4344       TmpInst.addOperand(Inst.getOperand(0));
4345       TmpInst.addOperand(Inst.getOperand(1));
4346       TmpInst.addOperand(Inst.getOperand(2));
4347       TmpInst.addOperand(Inst.getOperand(3));
4348       Inst = TmpInst;
4349     }
4350     break;
4351   }
4352   case ARM::t2SXTH:
4353   case ARM::t2SXTB:
4354   case ARM::t2UXTH:
4355   case ARM::t2UXTB: {
4356     // If we can use the 16-bit encoding and the user didn't explicitly
4357     // request the 32-bit variant, transform it here.
4358     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
4359         isARMLowRegister(Inst.getOperand(1).getReg()) &&
4360         Inst.getOperand(2).getImm() == 0 &&
4361         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
4362          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
4363       unsigned NewOpc;
4364       switch (Inst.getOpcode()) {
4365       default: llvm_unreachable("Illegal opcode!");
4366       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
4367       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
4368       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
4369       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
4370       }
4371       // The operands aren't the same for thumb1 (no rotate operand).
4372       MCInst TmpInst;
4373       TmpInst.setOpcode(NewOpc);
4374       TmpInst.addOperand(Inst.getOperand(0));
4375       TmpInst.addOperand(Inst.getOperand(1));
4376       TmpInst.addOperand(Inst.getOperand(3));
4377       TmpInst.addOperand(Inst.getOperand(4));
4378       Inst = TmpInst;
4379     }
4380     break;
4381   }
4382   case ARM::t2IT: {
4383     // The mask bits for all but the first condition are represented as
4384     // the low bit of the condition code value implies 't'. We currently
4385     // always have 1 implies 't', so XOR toggle the bits if the low bit
4386     // of the condition code is zero. The encoding also expects the low
4387     // bit of the condition to be encoded as bit 4 of the mask operand,
4388     // so mask that in if needed
4389     MCOperand &MO = Inst.getOperand(1);
4390     unsigned Mask = MO.getImm();
4391     unsigned OrigMask = Mask;
4392     unsigned TZ = CountTrailingZeros_32(Mask);
4393     if ((Inst.getOperand(0).getImm() & 1) == 0) {
4394       assert(Mask && TZ <= 3 && "illegal IT mask value!");
4395       for (unsigned i = 3; i != TZ; --i)
4396         Mask ^= 1 << i;
4397     } else
4398       Mask |= 0x10;
4399     MO.setImm(Mask);
4400
4401     // Set up the IT block state according to the IT instruction we just
4402     // matched.
4403     assert(!inITBlock() && "nested IT blocks?!");
4404     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
4405     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
4406     ITState.CurPosition = 0;
4407     ITState.FirstCond = true;
4408     break;
4409   }
4410   }
4411 }
4412
4413 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
4414   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
4415   // suffix depending on whether they're in an IT block or not.
4416   unsigned Opc = Inst.getOpcode();
4417   MCInstrDesc &MCID = getInstDesc(Opc);
4418   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
4419     assert(MCID.hasOptionalDef() &&
4420            "optionally flag setting instruction missing optional def operand");
4421     assert(MCID.NumOperands == Inst.getNumOperands() &&
4422            "operand count mismatch!");
4423     // Find the optional-def operand (cc_out).
4424     unsigned OpNo;
4425     for (OpNo = 0;
4426          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
4427          ++OpNo)
4428       ;
4429     // If we're parsing Thumb1, reject it completely.
4430     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
4431       return Match_MnemonicFail;
4432     // If we're parsing Thumb2, which form is legal depends on whether we're
4433     // in an IT block.
4434     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
4435         !inITBlock())
4436       return Match_RequiresITBlock;
4437     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
4438         inITBlock())
4439       return Match_RequiresNotITBlock;
4440   }
4441   // Some high-register supporting Thumb1 encodings only allow both registers
4442   // to be from r0-r7 when in Thumb2.
4443   else if (Opc == ARM::tADDhirr && isThumbOne() &&
4444            isARMLowRegister(Inst.getOperand(1).getReg()) &&
4445            isARMLowRegister(Inst.getOperand(2).getReg()))
4446     return Match_RequiresThumb2;
4447   // Others only require ARMv6 or later.
4448   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
4449            isARMLowRegister(Inst.getOperand(0).getReg()) &&
4450            isARMLowRegister(Inst.getOperand(1).getReg()))
4451     return Match_RequiresV6;
4452   return Match_Success;
4453 }
4454
4455 bool ARMAsmParser::
4456 MatchAndEmitInstruction(SMLoc IDLoc,
4457                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
4458                         MCStreamer &Out) {
4459   MCInst Inst;
4460   unsigned ErrorInfo;
4461   unsigned MatchResult;
4462   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
4463   switch (MatchResult) {
4464   default: break;
4465   case Match_Success:
4466     // Context sensitive operand constraints aren't handled by the matcher,
4467     // so check them here.
4468     if (validateInstruction(Inst, Operands)) {
4469       // Still progress the IT block, otherwise one wrong condition causes
4470       // nasty cascading errors.
4471       forwardITPosition();
4472       return true;
4473     }
4474
4475     // Some instructions need post-processing to, for example, tweak which
4476     // encoding is selected.
4477     processInstruction(Inst, Operands);
4478
4479     // Only move forward at the very end so that everything in validate
4480     // and process gets a consistent answer about whether we're in an IT
4481     // block.
4482     forwardITPosition();
4483
4484     Out.EmitInstruction(Inst);
4485     return false;
4486   case Match_MissingFeature:
4487     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
4488     return true;
4489   case Match_InvalidOperand: {
4490     SMLoc ErrorLoc = IDLoc;
4491     if (ErrorInfo != ~0U) {
4492       if (ErrorInfo >= Operands.size())
4493         return Error(IDLoc, "too few operands for instruction");
4494
4495       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
4496       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
4497     }
4498
4499     return Error(ErrorLoc, "invalid operand for instruction");
4500   }
4501   case Match_MnemonicFail:
4502     return Error(IDLoc, "invalid instruction");
4503   case Match_ConversionFail:
4504     // The converter function will have already emited a diagnostic.
4505     return true;
4506   case Match_RequiresNotITBlock:
4507     return Error(IDLoc, "flag setting instruction only valid outside IT block");
4508   case Match_RequiresITBlock:
4509     return Error(IDLoc, "instruction only valid inside IT block");
4510   case Match_RequiresV6:
4511     return Error(IDLoc, "instruction variant requires ARMv6 or later");
4512   case Match_RequiresThumb2:
4513     return Error(IDLoc, "instruction variant requires Thumb2");
4514   }
4515
4516   llvm_unreachable("Implement any new match types added!");
4517   return true;
4518 }
4519
4520 /// parseDirective parses the arm specific directives
4521 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
4522   StringRef IDVal = DirectiveID.getIdentifier();
4523   if (IDVal == ".word")
4524     return parseDirectiveWord(4, DirectiveID.getLoc());
4525   else if (IDVal == ".thumb")
4526     return parseDirectiveThumb(DirectiveID.getLoc());
4527   else if (IDVal == ".thumb_func")
4528     return parseDirectiveThumbFunc(DirectiveID.getLoc());
4529   else if (IDVal == ".code")
4530     return parseDirectiveCode(DirectiveID.getLoc());
4531   else if (IDVal == ".syntax")
4532     return parseDirectiveSyntax(DirectiveID.getLoc());
4533   return true;
4534 }
4535
4536 /// parseDirectiveWord
4537 ///  ::= .word [ expression (, expression)* ]
4538 bool ARMAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
4539   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4540     for (;;) {
4541       const MCExpr *Value;
4542       if (getParser().ParseExpression(Value))
4543         return true;
4544
4545       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
4546
4547       if (getLexer().is(AsmToken::EndOfStatement))
4548         break;
4549
4550       // FIXME: Improve diagnostic.
4551       if (getLexer().isNot(AsmToken::Comma))
4552         return Error(L, "unexpected token in directive");
4553       Parser.Lex();
4554     }
4555   }
4556
4557   Parser.Lex();
4558   return false;
4559 }
4560
4561 /// parseDirectiveThumb
4562 ///  ::= .thumb
4563 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
4564   if (getLexer().isNot(AsmToken::EndOfStatement))
4565     return Error(L, "unexpected token in directive");
4566   Parser.Lex();
4567
4568   // TODO: set thumb mode
4569   // TODO: tell the MC streamer the mode
4570   // getParser().getStreamer().Emit???();
4571   return false;
4572 }
4573
4574 /// parseDirectiveThumbFunc
4575 ///  ::= .thumbfunc symbol_name
4576 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
4577   const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
4578   bool isMachO = MAI.hasSubsectionsViaSymbols();
4579   StringRef Name;
4580
4581   // Darwin asm has function name after .thumb_func direction
4582   // ELF doesn't
4583   if (isMachO) {
4584     const AsmToken &Tok = Parser.getTok();
4585     if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
4586       return Error(L, "unexpected token in .thumb_func directive");
4587     Name = Tok.getString();
4588     Parser.Lex(); // Consume the identifier token.
4589   }
4590
4591   if (getLexer().isNot(AsmToken::EndOfStatement))
4592     return Error(L, "unexpected token in directive");
4593   Parser.Lex();
4594
4595   // FIXME: assuming function name will be the line following .thumb_func
4596   if (!isMachO) {
4597     Name = Parser.getTok().getString();
4598   }
4599
4600   // Mark symbol as a thumb symbol.
4601   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
4602   getParser().getStreamer().EmitThumbFunc(Func);
4603   return false;
4604 }
4605
4606 /// parseDirectiveSyntax
4607 ///  ::= .syntax unified | divided
4608 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
4609   const AsmToken &Tok = Parser.getTok();
4610   if (Tok.isNot(AsmToken::Identifier))
4611     return Error(L, "unexpected token in .syntax directive");
4612   StringRef Mode = Tok.getString();
4613   if (Mode == "unified" || Mode == "UNIFIED")
4614     Parser.Lex();
4615   else if (Mode == "divided" || Mode == "DIVIDED")
4616     return Error(L, "'.syntax divided' arm asssembly not supported");
4617   else
4618     return Error(L, "unrecognized syntax mode in .syntax directive");
4619
4620   if (getLexer().isNot(AsmToken::EndOfStatement))
4621     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4622   Parser.Lex();
4623
4624   // TODO tell the MC streamer the mode
4625   // getParser().getStreamer().Emit???();
4626   return false;
4627 }
4628
4629 /// parseDirectiveCode
4630 ///  ::= .code 16 | 32
4631 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
4632   const AsmToken &Tok = Parser.getTok();
4633   if (Tok.isNot(AsmToken::Integer))
4634     return Error(L, "unexpected token in .code directive");
4635   int64_t Val = Parser.getTok().getIntVal();
4636   if (Val == 16)
4637     Parser.Lex();
4638   else if (Val == 32)
4639     Parser.Lex();
4640   else
4641     return Error(L, "invalid operand to .code directive");
4642
4643   if (getLexer().isNot(AsmToken::EndOfStatement))
4644     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4645   Parser.Lex();
4646
4647   if (Val == 16) {
4648     if (!isThumb())
4649       SwitchMode();
4650     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
4651   } else {
4652     if (isThumb())
4653       SwitchMode();
4654     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
4655   }
4656
4657   return false;
4658 }
4659
4660 extern "C" void LLVMInitializeARMAsmLexer();
4661
4662 /// Force static initialization.
4663 extern "C" void LLVMInitializeARMAsmParser() {
4664   RegisterMCAsmParser<ARMAsmParser> X(TheARMTarget);
4665   RegisterMCAsmParser<ARMAsmParser> Y(TheThumbTarget);
4666   LLVMInitializeARMAsmLexer();
4667 }
4668
4669 #define GET_REGISTER_MATCHER
4670 #define GET_MATCHER_IMPLEMENTATION
4671 #include "ARMGenAsmMatcher.inc"