a074bc5a7472be9efcdef53b3fc8cf7c95ee6672
[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/MCRegisterInfo.h"
22 #include "llvm/MC/MCSubtargetInfo.h"
23 #include "llvm/MC/MCTargetAsmParser.h"
24 #include "llvm/Target/TargetRegistry.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/ADT/OwningPtr.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33
34 using namespace llvm;
35
36 namespace {
37
38 class ARMOperand;
39
40 class ARMAsmParser : public MCTargetAsmParser {
41   MCSubtargetInfo &STI;
42   MCAsmParser &Parser;
43
44   MCAsmParser &getParser() const { return Parser; }
45   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
46
47   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
48   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
49
50   int tryParseRegister();
51   bool tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
52   int tryparseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
53   bool parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
54   bool parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &,
55                    ARMII::AddrMode AddrMode);
56   bool parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
57   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
58   const MCExpr *applyPrefixToExpr(const MCExpr *E,
59                                   MCSymbolRefExpr::VariantKind Variant);
60
61
62   bool parseMemoryOffsetReg(bool &Negative,
63                             bool &OffsetRegShifted,
64                             enum ARM_AM::ShiftOpc &ShiftType,
65                             const MCExpr *&ShiftAmount,
66                             const MCExpr *&Offset,
67                             bool &OffsetIsReg,
68                             int &OffsetRegNum,
69                             SMLoc &E);
70   bool parseShift(enum ARM_AM::ShiftOpc &St,
71                   const MCExpr *&ShiftAmount, SMLoc &E);
72   bool parseDirectiveWord(unsigned Size, SMLoc L);
73   bool parseDirectiveThumb(SMLoc L);
74   bool parseDirectiveThumbFunc(SMLoc L);
75   bool parseDirectiveCode(SMLoc L);
76   bool parseDirectiveSyntax(SMLoc L);
77
78   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
79                           bool &CarrySetting, unsigned &ProcessorIMod);
80   void getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
81                              bool &CanAcceptPredicationCode);
82
83   bool isThumb() const {
84     // FIXME: Can tablegen auto-generate this?
85     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
86   }
87   bool isThumbOne() const {
88     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
89   }
90   void SwitchMode() {
91     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
92     setAvailableFeatures(FB);
93   }
94
95   /// @name Auto-generated Match Functions
96   /// {
97
98 #define GET_ASSEMBLER_HEADER
99 #include "ARMGenAsmMatcher.inc"
100
101   /// }
102
103   OperandMatchResultTy parseCoprocNumOperand(
104     SmallVectorImpl<MCParsedAsmOperand*>&);
105   OperandMatchResultTy parseCoprocRegOperand(
106     SmallVectorImpl<MCParsedAsmOperand*>&);
107   OperandMatchResultTy parseMemBarrierOptOperand(
108     SmallVectorImpl<MCParsedAsmOperand*>&);
109   OperandMatchResultTy parseProcIFlagsOperand(
110     SmallVectorImpl<MCParsedAsmOperand*>&);
111   OperandMatchResultTy parseMSRMaskOperand(
112     SmallVectorImpl<MCParsedAsmOperand*>&);
113   OperandMatchResultTy parseMemMode2Operand(
114     SmallVectorImpl<MCParsedAsmOperand*>&);
115   OperandMatchResultTy parseMemMode3Operand(
116     SmallVectorImpl<MCParsedAsmOperand*>&);
117   OperandMatchResultTy parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &O,
118                                    StringRef Op, int Low, int High);
119   OperandMatchResultTy parsePKHLSLImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
120     return parsePKHImm(O, "lsl", 0, 31);
121   }
122   OperandMatchResultTy parsePKHASRImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
123     return parsePKHImm(O, "asr", 1, 32);
124   }
125   OperandMatchResultTy parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*>&);
126   OperandMatchResultTy parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*>&);
127
128   // Asm Match Converter Methods
129   bool cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
130                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
131   bool cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
132                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
133   bool cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
134                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
135   bool cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
136                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
137
138
139   bool validateInstruction(MCInst &Inst,
140                            const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
141
142 public:
143   ARMAsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser)
144     : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
145     MCAsmParserExtension::Initialize(_Parser);
146
147     // Initialize the set of available features.
148     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
149   }
150
151   // Implementation of the MCTargetAsmParser interface:
152   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
153   bool ParseInstruction(StringRef Name, SMLoc NameLoc,
154                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
155   bool ParseDirective(AsmToken DirectiveID);
156
157   bool MatchAndEmitInstruction(SMLoc IDLoc,
158                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
159                                MCStreamer &Out);
160 };
161 } // end anonymous namespace
162
163 namespace llvm {
164   // FIXME: TableGen this?
165   extern MCRegisterClass ARMMCRegisterClasses[]; // In ARMGenRegisterInfo.inc.
166 }
167
168 namespace {
169
170 /// ARMOperand - Instances of this class represent a parsed ARM machine
171 /// instruction.
172 class ARMOperand : public MCParsedAsmOperand {
173   enum KindTy {
174     CondCode,
175     CCOut,
176     CoprocNum,
177     CoprocReg,
178     Immediate,
179     MemBarrierOpt,
180     Memory,
181     MSRMask,
182     ProcIFlags,
183     Register,
184     RegisterList,
185     DPRRegisterList,
186     SPRRegisterList,
187     ShiftedRegister,
188     ShiftedImmediate,
189     ShifterImmediate,
190     Token
191   } Kind;
192
193   SMLoc StartLoc, EndLoc;
194   SmallVector<unsigned, 8> Registers;
195
196   union {
197     struct {
198       ARMCC::CondCodes Val;
199     } CC;
200
201     struct {
202       ARM_MB::MemBOpt Val;
203     } MBOpt;
204
205     struct {
206       unsigned Val;
207     } Cop;
208
209     struct {
210       ARM_PROC::IFlags Val;
211     } IFlags;
212
213     struct {
214       unsigned Val;
215     } MMask;
216
217     struct {
218       const char *Data;
219       unsigned Length;
220     } Tok;
221
222     struct {
223       unsigned RegNum;
224     } Reg;
225
226     struct {
227       const MCExpr *Val;
228     } Imm;
229
230     /// Combined record for all forms of ARM address expressions.
231     struct {
232       ARMII::AddrMode AddrMode;
233       unsigned BaseRegNum;
234       union {
235         unsigned RegNum;     ///< Offset register num, when OffsetIsReg.
236         const MCExpr *Value; ///< Offset value, when !OffsetIsReg.
237       } Offset;
238       const MCExpr *ShiftAmount;     // used when OffsetRegShifted is true
239       enum ARM_AM::ShiftOpc ShiftType; // used when OffsetRegShifted is true
240       unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
241       unsigned Preindexed       : 1;
242       unsigned Postindexed      : 1;
243       unsigned OffsetIsReg      : 1;
244       unsigned Negative         : 1; // only used when OffsetIsReg is true
245       unsigned Writeback        : 1;
246     } Mem;
247
248     struct {
249       bool isASR;
250       unsigned Imm;
251     } ShifterImm;
252     struct {
253       ARM_AM::ShiftOpc ShiftTy;
254       unsigned SrcReg;
255       unsigned ShiftReg;
256       unsigned ShiftImm;
257     } RegShiftedReg;
258     struct {
259       ARM_AM::ShiftOpc ShiftTy;
260       unsigned SrcReg;
261       unsigned ShiftImm;
262     } RegShiftedImm;
263   };
264
265   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
266 public:
267   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
268     Kind = o.Kind;
269     StartLoc = o.StartLoc;
270     EndLoc = o.EndLoc;
271     switch (Kind) {
272     case CondCode:
273       CC = o.CC;
274       break;
275     case Token:
276       Tok = o.Tok;
277       break;
278     case CCOut:
279     case Register:
280       Reg = o.Reg;
281       break;
282     case RegisterList:
283     case DPRRegisterList:
284     case SPRRegisterList:
285       Registers = o.Registers;
286       break;
287     case CoprocNum:
288     case CoprocReg:
289       Cop = o.Cop;
290       break;
291     case Immediate:
292       Imm = o.Imm;
293       break;
294     case MemBarrierOpt:
295       MBOpt = o.MBOpt;
296       break;
297     case Memory:
298       Mem = o.Mem;
299       break;
300     case MSRMask:
301       MMask = o.MMask;
302       break;
303     case ProcIFlags:
304       IFlags = o.IFlags;
305       break;
306     case ShifterImmediate:
307       ShifterImm = o.ShifterImm;
308       break;
309     case ShiftedRegister:
310       RegShiftedReg = o.RegShiftedReg;
311       break;
312     case ShiftedImmediate:
313       RegShiftedImm = o.RegShiftedImm;
314       break;
315     }
316   }
317
318   /// getStartLoc - Get the location of the first token of this operand.
319   SMLoc getStartLoc() const { return StartLoc; }
320   /// getEndLoc - Get the location of the last token of this operand.
321   SMLoc getEndLoc() const { return EndLoc; }
322
323   ARMCC::CondCodes getCondCode() const {
324     assert(Kind == CondCode && "Invalid access!");
325     return CC.Val;
326   }
327
328   unsigned getCoproc() const {
329     assert((Kind == CoprocNum || Kind == CoprocReg) && "Invalid access!");
330     return Cop.Val;
331   }
332
333   StringRef getToken() const {
334     assert(Kind == Token && "Invalid access!");
335     return StringRef(Tok.Data, Tok.Length);
336   }
337
338   unsigned getReg() const {
339     assert((Kind == Register || Kind == CCOut) && "Invalid access!");
340     return Reg.RegNum;
341   }
342
343   const SmallVectorImpl<unsigned> &getRegList() const {
344     assert((Kind == RegisterList || Kind == DPRRegisterList ||
345             Kind == SPRRegisterList) && "Invalid access!");
346     return Registers;
347   }
348
349   const MCExpr *getImm() const {
350     assert(Kind == Immediate && "Invalid access!");
351     return Imm.Val;
352   }
353
354   ARM_MB::MemBOpt getMemBarrierOpt() const {
355     assert(Kind == MemBarrierOpt && "Invalid access!");
356     return MBOpt.Val;
357   }
358
359   ARM_PROC::IFlags getProcIFlags() const {
360     assert(Kind == ProcIFlags && "Invalid access!");
361     return IFlags.Val;
362   }
363
364   unsigned getMSRMask() const {
365     assert(Kind == MSRMask && "Invalid access!");
366     return MMask.Val;
367   }
368
369   /// @name Memory Operand Accessors
370   /// @{
371   ARMII::AddrMode getMemAddrMode() const {
372     return Mem.AddrMode;
373   }
374   unsigned getMemBaseRegNum() const {
375     return Mem.BaseRegNum;
376   }
377   unsigned getMemOffsetRegNum() const {
378     assert(Mem.OffsetIsReg && "Invalid access!");
379     return Mem.Offset.RegNum;
380   }
381   const MCExpr *getMemOffset() const {
382     assert(!Mem.OffsetIsReg && "Invalid access!");
383     return Mem.Offset.Value;
384   }
385   unsigned getMemOffsetRegShifted() const {
386     assert(Mem.OffsetIsReg && "Invalid access!");
387     return Mem.OffsetRegShifted;
388   }
389   const MCExpr *getMemShiftAmount() const {
390     assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
391     return Mem.ShiftAmount;
392   }
393   enum ARM_AM::ShiftOpc getMemShiftType() const {
394     assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
395     return Mem.ShiftType;
396   }
397   bool getMemPreindexed() const { return Mem.Preindexed; }
398   bool getMemPostindexed() const { return Mem.Postindexed; }
399   bool getMemOffsetIsReg() const { return Mem.OffsetIsReg; }
400   bool getMemNegative() const { return Mem.Negative; }
401   bool getMemWriteback() const { return Mem.Writeback; }
402
403   /// @}
404
405   bool isCoprocNum() const { return Kind == CoprocNum; }
406   bool isCoprocReg() const { return Kind == CoprocReg; }
407   bool isCondCode() const { return Kind == CondCode; }
408   bool isCCOut() const { return Kind == CCOut; }
409   bool isImm() const { return Kind == Immediate; }
410   bool isImm0_255() const {
411     if (Kind != Immediate)
412       return false;
413     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
414     if (!CE) return false;
415     int64_t Value = CE->getValue();
416     return Value >= 0 && Value < 256;
417   }
418   bool isImm0_7() const {
419     if (Kind != Immediate)
420       return false;
421     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
422     if (!CE) return false;
423     int64_t Value = CE->getValue();
424     return Value >= 0 && Value < 8;
425   }
426   bool isImm0_15() const {
427     if (Kind != Immediate)
428       return false;
429     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
430     if (!CE) return false;
431     int64_t Value = CE->getValue();
432     return Value >= 0 && Value < 16;
433   }
434   bool isImm0_31() const {
435     if (Kind != Immediate)
436       return false;
437     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
438     if (!CE) return false;
439     int64_t Value = CE->getValue();
440     return Value >= 0 && Value < 32;
441   }
442   bool isImm1_16() const {
443     if (Kind != Immediate)
444       return false;
445     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
446     if (!CE) return false;
447     int64_t Value = CE->getValue();
448     return Value > 0 && Value < 17;
449   }
450   bool isImm1_32() const {
451     if (Kind != Immediate)
452       return false;
453     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
454     if (!CE) return false;
455     int64_t Value = CE->getValue();
456     return Value > 0 && Value < 33;
457   }
458   bool isImm0_65535() const {
459     if (Kind != Immediate)
460       return false;
461     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
462     if (!CE) return false;
463     int64_t Value = CE->getValue();
464     return Value >= 0 && Value < 65536;
465   }
466   bool isImm0_65535Expr() const {
467     if (Kind != Immediate)
468       return false;
469     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
470     // If it's not a constant expression, it'll generate a fixup and be
471     // handled later.
472     if (!CE) return true;
473     int64_t Value = CE->getValue();
474     return Value >= 0 && Value < 65536;
475   }
476   bool isImm24bit() const {
477     if (Kind != Immediate)
478       return false;
479     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
480     if (!CE) return false;
481     int64_t Value = CE->getValue();
482     return Value >= 0 && Value <= 0xffffff;
483   }
484   bool isPKHLSLImm() const {
485     if (Kind != Immediate)
486       return false;
487     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
488     if (!CE) return false;
489     int64_t Value = CE->getValue();
490     return Value >= 0 && Value < 32;
491   }
492   bool isPKHASRImm() const {
493     if (Kind != Immediate)
494       return false;
495     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
496     if (!CE) return false;
497     int64_t Value = CE->getValue();
498     return Value > 0 && Value <= 32;
499   }
500   bool isARMSOImm() const {
501     if (Kind != Immediate)
502       return false;
503     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
504     if (!CE) return false;
505     int64_t Value = CE->getValue();
506     return ARM_AM::getSOImmVal(Value) != -1;
507   }
508   bool isT2SOImm() const {
509     if (Kind != Immediate)
510       return false;
511     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
512     if (!CE) return false;
513     int64_t Value = CE->getValue();
514     return ARM_AM::getT2SOImmVal(Value) != -1;
515   }
516   bool isSetEndImm() const {
517     if (Kind != Immediate)
518       return false;
519     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
520     if (!CE) return false;
521     int64_t Value = CE->getValue();
522     return Value == 1 || Value == 0;
523   }
524   bool isReg() const { return Kind == Register; }
525   bool isRegList() const { return Kind == RegisterList; }
526   bool isDPRRegList() const { return Kind == DPRRegisterList; }
527   bool isSPRRegList() const { return Kind == SPRRegisterList; }
528   bool isToken() const { return Kind == Token; }
529   bool isMemBarrierOpt() const { return Kind == MemBarrierOpt; }
530   bool isMemory() const { return Kind == Memory; }
531   bool isShifterImm() const { return Kind == ShifterImmediate; }
532   bool isRegShiftedReg() const { return Kind == ShiftedRegister; }
533   bool isRegShiftedImm() const { return Kind == ShiftedImmediate; }
534   bool isMemMode2() const {
535     if (getMemAddrMode() != ARMII::AddrMode2)
536       return false;
537
538     if (getMemOffsetIsReg())
539       return true;
540
541     if (getMemNegative() &&
542         !(getMemPostindexed() || getMemPreindexed()))
543       return false;
544
545     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
546     if (!CE) return false;
547     int64_t Value = CE->getValue();
548
549     // The offset must be in the range 0-4095 (imm12).
550     if (Value > 4095 || Value < -4095)
551       return false;
552
553     return true;
554   }
555   bool isMemMode3() const {
556     if (getMemAddrMode() != ARMII::AddrMode3)
557       return false;
558
559     if (getMemOffsetIsReg()) {
560       if (getMemOffsetRegShifted())
561         return false; // No shift with offset reg allowed
562       return true;
563     }
564
565     if (getMemNegative() &&
566         !(getMemPostindexed() || getMemPreindexed()))
567       return false;
568
569     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
570     if (!CE) return false;
571     int64_t Value = CE->getValue();
572
573     // The offset must be in the range 0-255 (imm8).
574     if (Value > 255 || Value < -255)
575       return false;
576
577     return true;
578   }
579   bool isMemMode5() const {
580     if (!isMemory() || getMemOffsetIsReg() || getMemWriteback() ||
581         getMemNegative())
582       return false;
583
584     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
585     if (!CE) return false;
586
587     // The offset must be a multiple of 4 in the range 0-1020.
588     int64_t Value = CE->getValue();
589     return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
590   }
591   bool isMemMode7() const {
592     if (!isMemory() ||
593         getMemPreindexed() ||
594         getMemPostindexed() ||
595         getMemOffsetIsReg() ||
596         getMemNegative() ||
597         getMemWriteback())
598       return false;
599
600     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
601     if (!CE) return false;
602
603     if (CE->getValue())
604       return false;
605
606     return true;
607   }
608   bool isMemModeRegThumb() const {
609     if (!isMemory() || !getMemOffsetIsReg() || getMemWriteback())
610       return false;
611     return true;
612   }
613   bool isMemModeImmThumb() const {
614     if (!isMemory() || getMemOffsetIsReg() || getMemWriteback())
615       return false;
616
617     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
618     if (!CE) return false;
619
620     // The offset must be a multiple of 4 in the range 0-124.
621     uint64_t Value = CE->getValue();
622     return ((Value & 0x3) == 0 && Value <= 124);
623   }
624   bool isMSRMask() const { return Kind == MSRMask; }
625   bool isProcIFlags() const { return Kind == ProcIFlags; }
626
627   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
628     // Add as immediates when possible.  Null MCExpr = 0.
629     if (Expr == 0)
630       Inst.addOperand(MCOperand::CreateImm(0));
631     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
632       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
633     else
634       Inst.addOperand(MCOperand::CreateExpr(Expr));
635   }
636
637   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
638     assert(N == 2 && "Invalid number of operands!");
639     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
640     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
641     Inst.addOperand(MCOperand::CreateReg(RegNum));
642   }
643
644   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
645     assert(N == 1 && "Invalid number of operands!");
646     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
647   }
648
649   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
650     assert(N == 1 && "Invalid number of operands!");
651     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
652   }
653
654   void addCCOutOperands(MCInst &Inst, unsigned N) const {
655     assert(N == 1 && "Invalid number of operands!");
656     Inst.addOperand(MCOperand::CreateReg(getReg()));
657   }
658
659   void addRegOperands(MCInst &Inst, unsigned N) const {
660     assert(N == 1 && "Invalid number of operands!");
661     Inst.addOperand(MCOperand::CreateReg(getReg()));
662   }
663
664   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
665     assert(N == 3 && "Invalid number of operands!");
666     assert(isRegShiftedReg() && "addRegShiftedRegOperands() on non RegShiftedReg!");
667     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
668     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
669     Inst.addOperand(MCOperand::CreateImm(
670       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
671   }
672
673   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
674     assert(N == 2 && "Invalid number of operands!");
675     assert(isRegShiftedImm() && "addRegShiftedImmOperands() on non RegShiftedImm!");
676     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
677     Inst.addOperand(MCOperand::CreateImm(
678       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, RegShiftedImm.ShiftImm)));
679   }
680
681
682   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
683     assert(N == 1 && "Invalid number of operands!");
684     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
685                                          ShifterImm.Imm));
686   }
687
688   void addRegListOperands(MCInst &Inst, unsigned N) const {
689     assert(N == 1 && "Invalid number of operands!");
690     const SmallVectorImpl<unsigned> &RegList = getRegList();
691     for (SmallVectorImpl<unsigned>::const_iterator
692            I = RegList.begin(), E = RegList.end(); I != E; ++I)
693       Inst.addOperand(MCOperand::CreateReg(*I));
694   }
695
696   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
697     addRegListOperands(Inst, N);
698   }
699
700   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
701     addRegListOperands(Inst, N);
702   }
703
704   void addImmOperands(MCInst &Inst, unsigned N) const {
705     assert(N == 1 && "Invalid number of operands!");
706     addExpr(Inst, getImm());
707   }
708
709   void addImm0_255Operands(MCInst &Inst, unsigned N) const {
710     assert(N == 1 && "Invalid number of operands!");
711     addExpr(Inst, getImm());
712   }
713
714   void addImm0_7Operands(MCInst &Inst, unsigned N) const {
715     assert(N == 1 && "Invalid number of operands!");
716     addExpr(Inst, getImm());
717   }
718
719   void addImm0_15Operands(MCInst &Inst, unsigned N) const {
720     assert(N == 1 && "Invalid number of operands!");
721     addExpr(Inst, getImm());
722   }
723
724   void addImm0_31Operands(MCInst &Inst, unsigned N) const {
725     assert(N == 1 && "Invalid number of operands!");
726     addExpr(Inst, getImm());
727   }
728
729   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
730     assert(N == 1 && "Invalid number of operands!");
731     // The constant encodes as the immediate-1, and we store in the instruction
732     // the bits as encoded, so subtract off one here.
733     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
734     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
735   }
736
737   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
738     assert(N == 1 && "Invalid number of operands!");
739     // The constant encodes as the immediate-1, and we store in the instruction
740     // the bits as encoded, so subtract off one here.
741     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
742     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
743   }
744
745   void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
746     assert(N == 1 && "Invalid number of operands!");
747     addExpr(Inst, getImm());
748   }
749
750   void addImm0_65535ExprOperands(MCInst &Inst, unsigned N) const {
751     assert(N == 1 && "Invalid number of operands!");
752     addExpr(Inst, getImm());
753   }
754
755   void addImm24bitOperands(MCInst &Inst, unsigned N) const {
756     assert(N == 1 && "Invalid number of operands!");
757     addExpr(Inst, getImm());
758   }
759
760   void addPKHLSLImmOperands(MCInst &Inst, unsigned N) const {
761     assert(N == 1 && "Invalid number of operands!");
762     addExpr(Inst, getImm());
763   }
764
765   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
766     assert(N == 1 && "Invalid number of operands!");
767     // An ASR value of 32 encodes as 0, so that's how we want to add it to
768     // the instruction as well.
769     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
770     int Val = CE->getValue();
771     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
772   }
773
774   void addARMSOImmOperands(MCInst &Inst, unsigned N) const {
775     assert(N == 1 && "Invalid number of operands!");
776     addExpr(Inst, getImm());
777   }
778
779   void addT2SOImmOperands(MCInst &Inst, unsigned N) const {
780     assert(N == 1 && "Invalid number of operands!");
781     addExpr(Inst, getImm());
782   }
783
784   void addSetEndImmOperands(MCInst &Inst, unsigned N) const {
785     assert(N == 1 && "Invalid number of operands!");
786     addExpr(Inst, getImm());
787   }
788
789   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
790     assert(N == 1 && "Invalid number of operands!");
791     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
792   }
793
794   void addMemMode7Operands(MCInst &Inst, unsigned N) const {
795     assert(N == 1 && isMemMode7() && "Invalid number of operands!");
796     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
797
798     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
799     (void)CE;
800     assert((CE || CE->getValue() == 0) &&
801            "No offset operand support in mode 7");
802   }
803
804   void addMemMode2Operands(MCInst &Inst, unsigned N) const {
805     assert(isMemMode2() && "Invalid mode or number of operands!");
806     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
807     unsigned IdxMode = (getMemPreindexed() | getMemPostindexed() << 1);
808
809     if (getMemOffsetIsReg()) {
810       Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
811
812       ARM_AM::AddrOpc AMOpc = getMemNegative() ? ARM_AM::sub : ARM_AM::add;
813       ARM_AM::ShiftOpc ShOpc = ARM_AM::no_shift;
814       int64_t ShiftAmount = 0;
815
816       if (getMemOffsetRegShifted()) {
817         ShOpc = getMemShiftType();
818         const MCConstantExpr *CE =
819                    dyn_cast<MCConstantExpr>(getMemShiftAmount());
820         ShiftAmount = CE->getValue();
821       }
822
823       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(AMOpc, ShiftAmount,
824                                            ShOpc, IdxMode)));
825       return;
826     }
827
828     // Create a operand placeholder to always yield the same number of operands.
829     Inst.addOperand(MCOperand::CreateReg(0));
830
831     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
832     // the difference?
833     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
834     assert(CE && "Non-constant mode 2 offset operand!");
835     int64_t Offset = CE->getValue();
836
837     if (Offset >= 0)
838       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(ARM_AM::add,
839                                            Offset, ARM_AM::no_shift, IdxMode)));
840     else
841       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(ARM_AM::sub,
842                                           -Offset, ARM_AM::no_shift, IdxMode)));
843   }
844
845   void addMemMode3Operands(MCInst &Inst, unsigned N) const {
846     assert(isMemMode3() && "Invalid mode or number of operands!");
847     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
848     unsigned IdxMode = (getMemPreindexed() | getMemPostindexed() << 1);
849
850     if (getMemOffsetIsReg()) {
851       Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
852
853       ARM_AM::AddrOpc AMOpc = getMemNegative() ? ARM_AM::sub : ARM_AM::add;
854       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM3Opc(AMOpc, 0,
855                                                              IdxMode)));
856       return;
857     }
858
859     // Create a operand placeholder to always yield the same number of operands.
860     Inst.addOperand(MCOperand::CreateReg(0));
861
862     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
863     // the difference?
864     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
865     assert(CE && "Non-constant mode 3 offset operand!");
866     int64_t Offset = CE->getValue();
867
868     if (Offset >= 0)
869       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM3Opc(ARM_AM::add,
870                                            Offset, IdxMode)));
871     else
872       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM3Opc(ARM_AM::sub,
873                                            -Offset, IdxMode)));
874   }
875
876   void addMemMode5Operands(MCInst &Inst, unsigned N) const {
877     assert(N == 2 && isMemMode5() && "Invalid number of operands!");
878
879     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
880     assert(!getMemOffsetIsReg() && "Invalid mode 5 operand");
881
882     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
883     // the difference?
884     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
885     assert(CE && "Non-constant mode 5 offset operand!");
886
887     // The MCInst offset operand doesn't include the low two bits (like
888     // the instruction encoding).
889     int64_t Offset = CE->getValue() / 4;
890     if (Offset >= 0)
891       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
892                                                              Offset)));
893     else
894       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
895                                                              -Offset)));
896   }
897
898   void addMemModeRegThumbOperands(MCInst &Inst, unsigned N) const {
899     assert(N == 2 && isMemModeRegThumb() && "Invalid number of operands!");
900     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
901     Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
902   }
903
904   void addMemModeImmThumbOperands(MCInst &Inst, unsigned N) const {
905     assert(N == 2 && isMemModeImmThumb() && "Invalid number of operands!");
906     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
907     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
908     assert(CE && "Non-constant mode offset operand!");
909     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
910   }
911
912   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
913     assert(N == 1 && "Invalid number of operands!");
914     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
915   }
916
917   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
918     assert(N == 1 && "Invalid number of operands!");
919     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
920   }
921
922   virtual void print(raw_ostream &OS) const;
923
924   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
925     ARMOperand *Op = new ARMOperand(CondCode);
926     Op->CC.Val = CC;
927     Op->StartLoc = S;
928     Op->EndLoc = S;
929     return Op;
930   }
931
932   static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
933     ARMOperand *Op = new ARMOperand(CoprocNum);
934     Op->Cop.Val = CopVal;
935     Op->StartLoc = S;
936     Op->EndLoc = S;
937     return Op;
938   }
939
940   static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
941     ARMOperand *Op = new ARMOperand(CoprocReg);
942     Op->Cop.Val = CopVal;
943     Op->StartLoc = S;
944     Op->EndLoc = S;
945     return Op;
946   }
947
948   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
949     ARMOperand *Op = new ARMOperand(CCOut);
950     Op->Reg.RegNum = RegNum;
951     Op->StartLoc = S;
952     Op->EndLoc = S;
953     return Op;
954   }
955
956   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
957     ARMOperand *Op = new ARMOperand(Token);
958     Op->Tok.Data = Str.data();
959     Op->Tok.Length = Str.size();
960     Op->StartLoc = S;
961     Op->EndLoc = S;
962     return Op;
963   }
964
965   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
966     ARMOperand *Op = new ARMOperand(Register);
967     Op->Reg.RegNum = RegNum;
968     Op->StartLoc = S;
969     Op->EndLoc = E;
970     return Op;
971   }
972
973   static ARMOperand *CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,
974                                            unsigned SrcReg,
975                                            unsigned ShiftReg,
976                                            unsigned ShiftImm,
977                                            SMLoc S, SMLoc E) {
978     ARMOperand *Op = new ARMOperand(ShiftedRegister);
979     Op->RegShiftedReg.ShiftTy = ShTy;
980     Op->RegShiftedReg.SrcReg = SrcReg;
981     Op->RegShiftedReg.ShiftReg = ShiftReg;
982     Op->RegShiftedReg.ShiftImm = ShiftImm;
983     Op->StartLoc = S;
984     Op->EndLoc = E;
985     return Op;
986   }
987
988   static ARMOperand *CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,
989                                             unsigned SrcReg,
990                                             unsigned ShiftImm,
991                                             SMLoc S, SMLoc E) {
992     ARMOperand *Op = new ARMOperand(ShiftedImmediate);
993     Op->RegShiftedImm.ShiftTy = ShTy;
994     Op->RegShiftedImm.SrcReg = SrcReg;
995     Op->RegShiftedImm.ShiftImm = ShiftImm;
996     Op->StartLoc = S;
997     Op->EndLoc = E;
998     return Op;
999   }
1000
1001   static ARMOperand *CreateShifterImm(bool isASR, unsigned Imm,
1002                                    SMLoc S, SMLoc E) {
1003     ARMOperand *Op = new ARMOperand(ShifterImmediate);
1004     Op->ShifterImm.isASR = isASR;
1005     Op->ShifterImm.Imm = Imm;
1006     Op->StartLoc = S;
1007     Op->EndLoc = E;
1008     return Op;
1009   }
1010
1011   static ARMOperand *
1012   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
1013                 SMLoc StartLoc, SMLoc EndLoc) {
1014     KindTy Kind = RegisterList;
1015
1016     if (llvm::ARMMCRegisterClasses[ARM::DPRRegClassID].
1017         contains(Regs.front().first))
1018       Kind = DPRRegisterList;
1019     else if (llvm::ARMMCRegisterClasses[ARM::SPRRegClassID].
1020              contains(Regs.front().first))
1021       Kind = SPRRegisterList;
1022
1023     ARMOperand *Op = new ARMOperand(Kind);
1024     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1025            I = Regs.begin(), E = Regs.end(); I != E; ++I)
1026       Op->Registers.push_back(I->first);
1027     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
1028     Op->StartLoc = StartLoc;
1029     Op->EndLoc = EndLoc;
1030     return Op;
1031   }
1032
1033   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
1034     ARMOperand *Op = new ARMOperand(Immediate);
1035     Op->Imm.Val = Val;
1036     Op->StartLoc = S;
1037     Op->EndLoc = E;
1038     return Op;
1039   }
1040
1041   static ARMOperand *CreateMem(ARMII::AddrMode AddrMode, unsigned BaseRegNum,
1042                                bool OffsetIsReg, const MCExpr *Offset,
1043                                int OffsetRegNum, bool OffsetRegShifted,
1044                                enum ARM_AM::ShiftOpc ShiftType,
1045                                const MCExpr *ShiftAmount, bool Preindexed,
1046                                bool Postindexed, bool Negative, bool Writeback,
1047                                SMLoc S, SMLoc E) {
1048     assert((OffsetRegNum == -1 || OffsetIsReg) &&
1049            "OffsetRegNum must imply OffsetIsReg!");
1050     assert((!OffsetRegShifted || OffsetIsReg) &&
1051            "OffsetRegShifted must imply OffsetIsReg!");
1052     assert((Offset || OffsetIsReg) &&
1053            "Offset must exists unless register offset is used!");
1054     assert((!ShiftAmount || (OffsetIsReg && OffsetRegShifted)) &&
1055            "Cannot have shift amount without shifted register offset!");
1056     assert((!Offset || !OffsetIsReg) &&
1057            "Cannot have expression offset and register offset!");
1058
1059     ARMOperand *Op = new ARMOperand(Memory);
1060     Op->Mem.AddrMode = AddrMode;
1061     Op->Mem.BaseRegNum = BaseRegNum;
1062     Op->Mem.OffsetIsReg = OffsetIsReg;
1063     if (OffsetIsReg)
1064       Op->Mem.Offset.RegNum = OffsetRegNum;
1065     else
1066       Op->Mem.Offset.Value = Offset;
1067     Op->Mem.OffsetRegShifted = OffsetRegShifted;
1068     Op->Mem.ShiftType = ShiftType;
1069     Op->Mem.ShiftAmount = ShiftAmount;
1070     Op->Mem.Preindexed = Preindexed;
1071     Op->Mem.Postindexed = Postindexed;
1072     Op->Mem.Negative = Negative;
1073     Op->Mem.Writeback = Writeback;
1074
1075     Op->StartLoc = S;
1076     Op->EndLoc = E;
1077     return Op;
1078   }
1079
1080   static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
1081     ARMOperand *Op = new ARMOperand(MemBarrierOpt);
1082     Op->MBOpt.Val = Opt;
1083     Op->StartLoc = S;
1084     Op->EndLoc = S;
1085     return Op;
1086   }
1087
1088   static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
1089     ARMOperand *Op = new ARMOperand(ProcIFlags);
1090     Op->IFlags.Val = IFlags;
1091     Op->StartLoc = S;
1092     Op->EndLoc = S;
1093     return Op;
1094   }
1095
1096   static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
1097     ARMOperand *Op = new ARMOperand(MSRMask);
1098     Op->MMask.Val = MMask;
1099     Op->StartLoc = S;
1100     Op->EndLoc = S;
1101     return Op;
1102   }
1103 };
1104
1105 } // end anonymous namespace.
1106
1107 void ARMOperand::print(raw_ostream &OS) const {
1108   switch (Kind) {
1109   case CondCode:
1110     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
1111     break;
1112   case CCOut:
1113     OS << "<ccout " << getReg() << ">";
1114     break;
1115   case CoprocNum:
1116     OS << "<coprocessor number: " << getCoproc() << ">";
1117     break;
1118   case CoprocReg:
1119     OS << "<coprocessor register: " << getCoproc() << ">";
1120     break;
1121   case MSRMask:
1122     OS << "<mask: " << getMSRMask() << ">";
1123     break;
1124   case Immediate:
1125     getImm()->print(OS);
1126     break;
1127   case MemBarrierOpt:
1128     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
1129     break;
1130   case Memory:
1131     OS << "<memory "
1132        << "am:" << ARMII::AddrModeToString(getMemAddrMode())
1133        << " base:" << getMemBaseRegNum();
1134     if (getMemOffsetIsReg()) {
1135       OS << " offset:<register " << getMemOffsetRegNum();
1136       if (getMemOffsetRegShifted()) {
1137         OS << " offset-shift-type:" << getMemShiftType();
1138         OS << " offset-shift-amount:" << *getMemShiftAmount();
1139       }
1140     } else {
1141       OS << " offset:" << *getMemOffset();
1142     }
1143     if (getMemOffsetIsReg())
1144       OS << " (offset-is-reg)";
1145     if (getMemPreindexed())
1146       OS << " (pre-indexed)";
1147     if (getMemPostindexed())
1148       OS << " (post-indexed)";
1149     if (getMemNegative())
1150       OS << " (negative)";
1151     if (getMemWriteback())
1152       OS << " (writeback)";
1153     OS << ">";
1154     break;
1155   case ProcIFlags: {
1156     OS << "<ARM_PROC::";
1157     unsigned IFlags = getProcIFlags();
1158     for (int i=2; i >= 0; --i)
1159       if (IFlags & (1 << i))
1160         OS << ARM_PROC::IFlagsToString(1 << i);
1161     OS << ">";
1162     break;
1163   }
1164   case Register:
1165     OS << "<register " << getReg() << ">";
1166     break;
1167   case ShifterImmediate:
1168     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
1169        << " #" << ShifterImm.Imm << ">";
1170     break;
1171   case ShiftedRegister:
1172     OS << "<so_reg_reg "
1173        << RegShiftedReg.SrcReg
1174        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedReg.ShiftImm))
1175        << ", " << RegShiftedReg.ShiftReg << ", "
1176        << ARM_AM::getSORegOffset(RegShiftedReg.ShiftImm)
1177        << ">";
1178     break;
1179   case ShiftedImmediate:
1180     OS << "<so_reg_imm "
1181        << RegShiftedImm.SrcReg
1182        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedImm.ShiftImm))
1183        << ", " << ARM_AM::getSORegOffset(RegShiftedImm.ShiftImm)
1184        << ">";
1185     break;
1186   case RegisterList:
1187   case DPRRegisterList:
1188   case SPRRegisterList: {
1189     OS << "<register_list ";
1190
1191     const SmallVectorImpl<unsigned> &RegList = getRegList();
1192     for (SmallVectorImpl<unsigned>::const_iterator
1193            I = RegList.begin(), E = RegList.end(); I != E; ) {
1194       OS << *I;
1195       if (++I < E) OS << ", ";
1196     }
1197
1198     OS << ">";
1199     break;
1200   }
1201   case Token:
1202     OS << "'" << getToken() << "'";
1203     break;
1204   }
1205 }
1206
1207 /// @name Auto-generated Match Functions
1208 /// {
1209
1210 static unsigned MatchRegisterName(StringRef Name);
1211
1212 /// }
1213
1214 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
1215                                  SMLoc &StartLoc, SMLoc &EndLoc) {
1216   RegNo = tryParseRegister();
1217
1218   return (RegNo == (unsigned)-1);
1219 }
1220
1221 /// Try to parse a register name.  The token must be an Identifier when called,
1222 /// and if it is a register name the token is eaten and the register number is
1223 /// returned.  Otherwise return -1.
1224 ///
1225 int ARMAsmParser::tryParseRegister() {
1226   const AsmToken &Tok = Parser.getTok();
1227   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1228
1229   // FIXME: Validate register for the current architecture; we have to do
1230   // validation later, so maybe there is no need for this here.
1231   std::string upperCase = Tok.getString().str();
1232   std::string lowerCase = LowercaseString(upperCase);
1233   unsigned RegNum = MatchRegisterName(lowerCase);
1234   if (!RegNum) {
1235     RegNum = StringSwitch<unsigned>(lowerCase)
1236       .Case("r13", ARM::SP)
1237       .Case("r14", ARM::LR)
1238       .Case("r15", ARM::PC)
1239       .Case("ip", ARM::R12)
1240       .Default(0);
1241   }
1242   if (!RegNum) return -1;
1243
1244   Parser.Lex(); // Eat identifier token.
1245   return RegNum;
1246 }
1247
1248 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
1249 // If a recoverable error occurs, return 1. If an irrecoverable error
1250 // occurs, return -1. An irrecoverable error is one where tokens have been
1251 // consumed in the process of trying to parse the shifter (i.e., when it is
1252 // indeed a shifter operand, but malformed).
1253 int ARMAsmParser::tryparseShiftRegister(
1254                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1255   SMLoc S = Parser.getTok().getLoc();
1256   const AsmToken &Tok = Parser.getTok();
1257   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1258
1259   std::string upperCase = Tok.getString().str();
1260   std::string lowerCase = LowercaseString(upperCase);
1261   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
1262       .Case("lsl", ARM_AM::lsl)
1263       .Case("lsr", ARM_AM::lsr)
1264       .Case("asr", ARM_AM::asr)
1265       .Case("ror", ARM_AM::ror)
1266       .Case("rrx", ARM_AM::rrx)
1267       .Default(ARM_AM::no_shift);
1268
1269   if (ShiftTy == ARM_AM::no_shift)
1270     return 1;
1271
1272   Parser.Lex(); // Eat the operator.
1273
1274   // The source register for the shift has already been added to the
1275   // operand list, so we need to pop it off and combine it into the shifted
1276   // register operand instead.
1277   OwningPtr<ARMOperand> PrevOp((ARMOperand*)Operands.pop_back_val());
1278   if (!PrevOp->isReg())
1279     return Error(PrevOp->getStartLoc(), "shift must be of a register");
1280   int SrcReg = PrevOp->getReg();
1281   int64_t Imm = 0;
1282   int ShiftReg = 0;
1283   if (ShiftTy == ARM_AM::rrx) {
1284     // RRX Doesn't have an explicit shift amount. The encoder expects
1285     // the shift register to be the same as the source register. Seems odd,
1286     // but OK.
1287     ShiftReg = SrcReg;
1288   } else {
1289     // Figure out if this is shifted by a constant or a register (for non-RRX).
1290     if (Parser.getTok().is(AsmToken::Hash)) {
1291       Parser.Lex(); // Eat hash.
1292       SMLoc ImmLoc = Parser.getTok().getLoc();
1293       const MCExpr *ShiftExpr = 0;
1294       if (getParser().ParseExpression(ShiftExpr)) {
1295         Error(ImmLoc, "invalid immediate shift value");
1296         return -1;
1297       }
1298       // The expression must be evaluatable as an immediate.
1299       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
1300       if (!CE) {
1301         Error(ImmLoc, "invalid immediate shift value");
1302         return -1;
1303       }
1304       // Range check the immediate.
1305       // lsl, ror: 0 <= imm <= 31
1306       // lsr, asr: 0 <= imm <= 32
1307       Imm = CE->getValue();
1308       if (Imm < 0 ||
1309           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
1310           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
1311         Error(ImmLoc, "immediate shift value out of range");
1312         return -1;
1313       }
1314     } else if (Parser.getTok().is(AsmToken::Identifier)) {
1315       ShiftReg = tryParseRegister();
1316       SMLoc L = Parser.getTok().getLoc();
1317       if (ShiftReg == -1) {
1318         Error (L, "expected immediate or register in shift operand");
1319         return -1;
1320       }
1321     } else {
1322       Error (Parser.getTok().getLoc(),
1323                     "expected immediate or register in shift operand");
1324       return -1;
1325     }
1326   }
1327
1328   if (ShiftReg && ShiftTy != ARM_AM::rrx)
1329     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
1330                                                          ShiftReg, Imm,
1331                                                S, Parser.getTok().getLoc()));
1332   else
1333     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
1334                                                S, Parser.getTok().getLoc()));
1335
1336   return 0;
1337 }
1338
1339
1340 /// Try to parse a register name.  The token must be an Identifier when called.
1341 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
1342 /// if there is a "writeback". 'true' if it's not a register.
1343 ///
1344 /// TODO this is likely to change to allow different register types and or to
1345 /// parse for a specific register type.
1346 bool ARMAsmParser::
1347 tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1348   SMLoc S = Parser.getTok().getLoc();
1349   int RegNo = tryParseRegister();
1350   if (RegNo == -1)
1351     return true;
1352
1353   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
1354
1355   const AsmToken &ExclaimTok = Parser.getTok();
1356   if (ExclaimTok.is(AsmToken::Exclaim)) {
1357     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
1358                                                ExclaimTok.getLoc()));
1359     Parser.Lex(); // Eat exclaim token
1360   }
1361
1362   return false;
1363 }
1364
1365 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
1366 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
1367 /// "c5", ...
1368 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
1369   // Use the same layout as the tablegen'erated register name matcher. Ugly,
1370   // but efficient.
1371   switch (Name.size()) {
1372   default: break;
1373   case 2:
1374     if (Name[0] != CoprocOp)
1375       return -1;
1376     switch (Name[1]) {
1377     default:  return -1;
1378     case '0': return 0;
1379     case '1': return 1;
1380     case '2': return 2;
1381     case '3': return 3;
1382     case '4': return 4;
1383     case '5': return 5;
1384     case '6': return 6;
1385     case '7': return 7;
1386     case '8': return 8;
1387     case '9': return 9;
1388     }
1389     break;
1390   case 3:
1391     if (Name[0] != CoprocOp || Name[1] != '1')
1392       return -1;
1393     switch (Name[2]) {
1394     default:  return -1;
1395     case '0': return 10;
1396     case '1': return 11;
1397     case '2': return 12;
1398     case '3': return 13;
1399     case '4': return 14;
1400     case '5': return 15;
1401     }
1402     break;
1403   }
1404
1405   return -1;
1406 }
1407
1408 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
1409 /// token must be an Identifier when called, and if it is a coprocessor
1410 /// number, the token is eaten and the operand is added to the operand list.
1411 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1412 parseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1413   SMLoc S = Parser.getTok().getLoc();
1414   const AsmToken &Tok = Parser.getTok();
1415   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1416
1417   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
1418   if (Num == -1)
1419     return MatchOperand_NoMatch;
1420
1421   Parser.Lex(); // Eat identifier token.
1422   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
1423   return MatchOperand_Success;
1424 }
1425
1426 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
1427 /// token must be an Identifier when called, and if it is a coprocessor
1428 /// number, the token is eaten and the operand is added to the operand list.
1429 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1430 parseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1431   SMLoc S = Parser.getTok().getLoc();
1432   const AsmToken &Tok = Parser.getTok();
1433   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1434
1435   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
1436   if (Reg == -1)
1437     return MatchOperand_NoMatch;
1438
1439   Parser.Lex(); // Eat identifier token.
1440   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
1441   return MatchOperand_Success;
1442 }
1443
1444 /// Parse a register list, return it if successful else return null.  The first
1445 /// token must be a '{' when called.
1446 bool ARMAsmParser::
1447 parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1448   assert(Parser.getTok().is(AsmToken::LCurly) &&
1449          "Token is not a Left Curly Brace");
1450   SMLoc S = Parser.getTok().getLoc();
1451
1452   // Read the rest of the registers in the list.
1453   unsigned PrevRegNum = 0;
1454   SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
1455
1456   do {
1457     bool IsRange = Parser.getTok().is(AsmToken::Minus);
1458     Parser.Lex(); // Eat non-identifier token.
1459
1460     const AsmToken &RegTok = Parser.getTok();
1461     SMLoc RegLoc = RegTok.getLoc();
1462     if (RegTok.isNot(AsmToken::Identifier)) {
1463       Error(RegLoc, "register expected");
1464       return true;
1465     }
1466
1467     int RegNum = tryParseRegister();
1468     if (RegNum == -1) {
1469       Error(RegLoc, "register expected");
1470       return true;
1471     }
1472
1473     if (IsRange) {
1474       int Reg = PrevRegNum;
1475       do {
1476         ++Reg;
1477         Registers.push_back(std::make_pair(Reg, RegLoc));
1478       } while (Reg != RegNum);
1479     } else {
1480       Registers.push_back(std::make_pair(RegNum, RegLoc));
1481     }
1482
1483     PrevRegNum = RegNum;
1484   } while (Parser.getTok().is(AsmToken::Comma) ||
1485            Parser.getTok().is(AsmToken::Minus));
1486
1487   // Process the right curly brace of the list.
1488   const AsmToken &RCurlyTok = Parser.getTok();
1489   if (RCurlyTok.isNot(AsmToken::RCurly)) {
1490     Error(RCurlyTok.getLoc(), "'}' expected");
1491     return true;
1492   }
1493
1494   SMLoc E = RCurlyTok.getLoc();
1495   Parser.Lex(); // Eat right curly brace token.
1496
1497   // Verify the register list.
1498   SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1499     RI = Registers.begin(), RE = Registers.end();
1500
1501   unsigned HighRegNum = getARMRegisterNumbering(RI->first);
1502   bool EmittedWarning = false;
1503
1504   DenseMap<unsigned, bool> RegMap;
1505   RegMap[HighRegNum] = true;
1506
1507   for (++RI; RI != RE; ++RI) {
1508     const std::pair<unsigned, SMLoc> &RegInfo = *RI;
1509     unsigned Reg = getARMRegisterNumbering(RegInfo.first);
1510
1511     if (RegMap[Reg]) {
1512       Error(RegInfo.second, "register duplicated in register list");
1513       return true;
1514     }
1515
1516     if (!EmittedWarning && Reg < HighRegNum)
1517       Warning(RegInfo.second,
1518               "register not in ascending order in register list");
1519
1520     RegMap[Reg] = true;
1521     HighRegNum = std::max(Reg, HighRegNum);
1522   }
1523
1524   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
1525   return false;
1526 }
1527
1528 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
1529 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1530 parseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1531   SMLoc S = Parser.getTok().getLoc();
1532   const AsmToken &Tok = Parser.getTok();
1533   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1534   StringRef OptStr = Tok.getString();
1535
1536   unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
1537     .Case("sy",    ARM_MB::SY)
1538     .Case("st",    ARM_MB::ST)
1539     .Case("sh",    ARM_MB::ISH)
1540     .Case("ish",   ARM_MB::ISH)
1541     .Case("shst",  ARM_MB::ISHST)
1542     .Case("ishst", ARM_MB::ISHST)
1543     .Case("nsh",   ARM_MB::NSH)
1544     .Case("un",    ARM_MB::NSH)
1545     .Case("nshst", ARM_MB::NSHST)
1546     .Case("unst",  ARM_MB::NSHST)
1547     .Case("osh",   ARM_MB::OSH)
1548     .Case("oshst", ARM_MB::OSHST)
1549     .Default(~0U);
1550
1551   if (Opt == ~0U)
1552     return MatchOperand_NoMatch;
1553
1554   Parser.Lex(); // Eat identifier token.
1555   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
1556   return MatchOperand_Success;
1557 }
1558
1559 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
1560 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1561 parseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1562   SMLoc S = Parser.getTok().getLoc();
1563   const AsmToken &Tok = Parser.getTok();
1564   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1565   StringRef IFlagsStr = Tok.getString();
1566
1567   unsigned IFlags = 0;
1568   for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
1569     unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
1570     .Case("a", ARM_PROC::A)
1571     .Case("i", ARM_PROC::I)
1572     .Case("f", ARM_PROC::F)
1573     .Default(~0U);
1574
1575     // If some specific iflag is already set, it means that some letter is
1576     // present more than once, this is not acceptable.
1577     if (Flag == ~0U || (IFlags & Flag))
1578       return MatchOperand_NoMatch;
1579
1580     IFlags |= Flag;
1581   }
1582
1583   Parser.Lex(); // Eat identifier token.
1584   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
1585   return MatchOperand_Success;
1586 }
1587
1588 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
1589 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1590 parseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1591   SMLoc S = Parser.getTok().getLoc();
1592   const AsmToken &Tok = Parser.getTok();
1593   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1594   StringRef Mask = Tok.getString();
1595
1596   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
1597   size_t Start = 0, Next = Mask.find('_');
1598   StringRef Flags = "";
1599   std::string SpecReg = LowercaseString(Mask.slice(Start, Next));
1600   if (Next != StringRef::npos)
1601     Flags = Mask.slice(Next+1, Mask.size());
1602
1603   // FlagsVal contains the complete mask:
1604   // 3-0: Mask
1605   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1606   unsigned FlagsVal = 0;
1607
1608   if (SpecReg == "apsr") {
1609     FlagsVal = StringSwitch<unsigned>(Flags)
1610     .Case("nzcvq",  0x8) // same as CPSR_f
1611     .Case("g",      0x4) // same as CPSR_s
1612     .Case("nzcvqg", 0xc) // same as CPSR_fs
1613     .Default(~0U);
1614
1615     if (FlagsVal == ~0U) {
1616       if (!Flags.empty())
1617         return MatchOperand_NoMatch;
1618       else
1619         FlagsVal = 0; // No flag
1620     }
1621   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
1622     if (Flags == "all") // cpsr_all is an alias for cpsr_fc
1623       Flags = "fc";
1624     for (int i = 0, e = Flags.size(); i != e; ++i) {
1625       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
1626       .Case("c", 1)
1627       .Case("x", 2)
1628       .Case("s", 4)
1629       .Case("f", 8)
1630       .Default(~0U);
1631
1632       // If some specific flag is already set, it means that some letter is
1633       // present more than once, this is not acceptable.
1634       if (FlagsVal == ~0U || (FlagsVal & Flag))
1635         return MatchOperand_NoMatch;
1636       FlagsVal |= Flag;
1637     }
1638   } else // No match for special register.
1639     return MatchOperand_NoMatch;
1640
1641   // Special register without flags are equivalent to "fc" flags.
1642   if (!FlagsVal)
1643     FlagsVal = 0x9;
1644
1645   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1646   if (SpecReg == "spsr")
1647     FlagsVal |= 16;
1648
1649   Parser.Lex(); // Eat identifier token.
1650   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
1651   return MatchOperand_Success;
1652 }
1653
1654 /// parseMemMode2Operand - Try to parse memory addressing mode 2 operand.
1655 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1656 parseMemMode2Operand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1657   assert(Parser.getTok().is(AsmToken::LBrac) && "Token is not a \"[\"");
1658
1659   if (parseMemory(Operands, ARMII::AddrMode2))
1660     return MatchOperand_NoMatch;
1661
1662   return MatchOperand_Success;
1663 }
1664
1665 /// parseMemMode3Operand - Try to parse memory addressing mode 3 operand.
1666 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1667 parseMemMode3Operand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1668   assert(Parser.getTok().is(AsmToken::LBrac) && "Token is not a \"[\"");
1669
1670   if (parseMemory(Operands, ARMII::AddrMode3))
1671     return MatchOperand_NoMatch;
1672
1673   return MatchOperand_Success;
1674 }
1675
1676 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1677 parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands, StringRef Op,
1678             int Low, int High) {
1679   const AsmToken &Tok = Parser.getTok();
1680   if (Tok.isNot(AsmToken::Identifier)) {
1681     Error(Parser.getTok().getLoc(), Op + " operand expected.");
1682     return MatchOperand_ParseFail;
1683   }
1684   StringRef ShiftName = Tok.getString();
1685   std::string LowerOp = LowercaseString(Op);
1686   std::string UpperOp = UppercaseString(Op);
1687   if (ShiftName != LowerOp && ShiftName != UpperOp) {
1688     Error(Parser.getTok().getLoc(), Op + " operand expected.");
1689     return MatchOperand_ParseFail;
1690   }
1691   Parser.Lex(); // Eat shift type token.
1692
1693   // There must be a '#' and a shift amount.
1694   if (Parser.getTok().isNot(AsmToken::Hash)) {
1695     Error(Parser.getTok().getLoc(), "'#' expected");
1696     return MatchOperand_ParseFail;
1697   }
1698   Parser.Lex(); // Eat hash token.
1699
1700   const MCExpr *ShiftAmount;
1701   SMLoc Loc = Parser.getTok().getLoc();
1702   if (getParser().ParseExpression(ShiftAmount)) {
1703     Error(Loc, "illegal expression");
1704     return MatchOperand_ParseFail;
1705   }
1706   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
1707   if (!CE) {
1708     Error(Loc, "constant expression expected");
1709     return MatchOperand_ParseFail;
1710   }
1711   int Val = CE->getValue();
1712   if (Val < Low || Val > High) {
1713     Error(Loc, "immediate value out of range");
1714     return MatchOperand_ParseFail;
1715   }
1716
1717   Operands.push_back(ARMOperand::CreateImm(CE, Loc, Parser.getTok().getLoc()));
1718
1719   return MatchOperand_Success;
1720 }
1721
1722 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1723 parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1724   const AsmToken &Tok = Parser.getTok();
1725   SMLoc S = Tok.getLoc();
1726   if (Tok.isNot(AsmToken::Identifier)) {
1727     Error(Tok.getLoc(), "'be' or 'le' operand expected");
1728     return MatchOperand_ParseFail;
1729   }
1730   int Val = StringSwitch<int>(Tok.getString())
1731     .Case("be", 1)
1732     .Case("le", 0)
1733     .Default(-1);
1734   Parser.Lex(); // Eat the token.
1735
1736   if (Val == -1) {
1737     Error(Tok.getLoc(), "'be' or 'le' operand expected");
1738     return MatchOperand_ParseFail;
1739   }
1740   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
1741                                                                   getContext()),
1742                                            S, Parser.getTok().getLoc()));
1743   return MatchOperand_Success;
1744 }
1745
1746 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
1747 /// instructions. Legal values are:
1748 ///     lsl #n  'n' in [0,31]
1749 ///     asr #n  'n' in [1,32]
1750 ///             n == 32 encoded as n == 0.
1751 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1752 parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1753   const AsmToken &Tok = Parser.getTok();
1754   SMLoc S = Tok.getLoc();
1755   if (Tok.isNot(AsmToken::Identifier)) {
1756     Error(S, "shift operator 'asr' or 'lsl' expected");
1757     return MatchOperand_ParseFail;
1758   }
1759   StringRef ShiftName = Tok.getString();
1760   bool isASR;
1761   if (ShiftName == "lsl" || ShiftName == "LSL")
1762     isASR = false;
1763   else if (ShiftName == "asr" || ShiftName == "ASR")
1764     isASR = true;
1765   else {
1766     Error(S, "shift operator 'asr' or 'lsl' expected");
1767     return MatchOperand_ParseFail;
1768   }
1769   Parser.Lex(); // Eat the operator.
1770
1771   // A '#' and a shift amount.
1772   if (Parser.getTok().isNot(AsmToken::Hash)) {
1773     Error(Parser.getTok().getLoc(), "'#' expected");
1774     return MatchOperand_ParseFail;
1775   }
1776   Parser.Lex(); // Eat hash token.
1777
1778   const MCExpr *ShiftAmount;
1779   SMLoc E = Parser.getTok().getLoc();
1780   if (getParser().ParseExpression(ShiftAmount)) {
1781     Error(E, "malformed shift expression");
1782     return MatchOperand_ParseFail;
1783   }
1784   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
1785   if (!CE) {
1786     Error(E, "shift amount must be an immediate");
1787     return MatchOperand_ParseFail;
1788   }
1789
1790   int64_t Val = CE->getValue();
1791   if (isASR) {
1792     // Shift amount must be in [1,32]
1793     if (Val < 1 || Val > 32) {
1794       Error(E, "'asr' shift amount must be in range [1,32]");
1795       return MatchOperand_ParseFail;
1796     }
1797     // asr #32 encoded as asr #0.
1798     if (Val == 32) Val = 0;
1799   } else {
1800     // Shift amount must be in [1,32]
1801     if (Val < 0 || Val > 31) {
1802       Error(E, "'lsr' shift amount must be in range [0,31]");
1803       return MatchOperand_ParseFail;
1804     }
1805   }
1806
1807   E = Parser.getTok().getLoc();
1808   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, E));
1809
1810   return MatchOperand_Success;
1811 }
1812
1813 /// cvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
1814 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1815 /// when they refer multiple MIOperands inside a single one.
1816 bool ARMAsmParser::
1817 cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
1818                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1819   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1820
1821   // Create a writeback register dummy placeholder.
1822   Inst.addOperand(MCOperand::CreateImm(0));
1823
1824   ((ARMOperand*)Operands[3])->addMemMode2Operands(Inst, 3);
1825   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1826   return true;
1827 }
1828
1829 /// cvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
1830 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1831 /// when they refer multiple MIOperands inside a single one.
1832 bool ARMAsmParser::
1833 cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
1834                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1835   // Create a writeback register dummy placeholder.
1836   Inst.addOperand(MCOperand::CreateImm(0));
1837   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1838   ((ARMOperand*)Operands[3])->addMemMode2Operands(Inst, 3);
1839   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1840   return true;
1841 }
1842
1843 /// cvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
1844 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1845 /// when they refer multiple MIOperands inside a single one.
1846 bool ARMAsmParser::
1847 cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
1848                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1849   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1850
1851   // Create a writeback register dummy placeholder.
1852   Inst.addOperand(MCOperand::CreateImm(0));
1853
1854   ((ARMOperand*)Operands[3])->addMemMode3Operands(Inst, 3);
1855   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1856   return true;
1857 }
1858
1859 /// cvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
1860 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1861 /// when they refer multiple MIOperands inside a single one.
1862 bool ARMAsmParser::
1863 cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
1864                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1865   // Create a writeback register dummy placeholder.
1866   Inst.addOperand(MCOperand::CreateImm(0));
1867   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1868   ((ARMOperand*)Operands[3])->addMemMode3Operands(Inst, 3);
1869   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1870   return true;
1871 }
1872
1873 /// Parse an ARM memory expression, return false if successful else return true
1874 /// or an error.  The first token must be a '[' when called.
1875 ///
1876 /// TODO Only preindexing and postindexing addressing are started, unindexed
1877 /// with option, etc are still to do.
1878 bool ARMAsmParser::
1879 parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1880             ARMII::AddrMode AddrMode = ARMII::AddrModeNone) {
1881   SMLoc S, E;
1882   assert(Parser.getTok().is(AsmToken::LBrac) &&
1883          "Token is not a Left Bracket");
1884   S = Parser.getTok().getLoc();
1885   Parser.Lex(); // Eat left bracket token.
1886
1887   const AsmToken &BaseRegTok = Parser.getTok();
1888   if (BaseRegTok.isNot(AsmToken::Identifier)) {
1889     Error(BaseRegTok.getLoc(), "register expected");
1890     return true;
1891   }
1892   int BaseRegNum = tryParseRegister();
1893   if (BaseRegNum == -1) {
1894     Error(BaseRegTok.getLoc(), "register expected");
1895     return true;
1896   }
1897
1898   // The next token must either be a comma or a closing bracket.
1899   const AsmToken &Tok = Parser.getTok();
1900   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
1901     return true;
1902
1903   bool Preindexed = false;
1904   bool Postindexed = false;
1905   bool OffsetIsReg = false;
1906   bool Negative = false;
1907   bool Writeback = false;
1908   ARMOperand *WBOp = 0;
1909   int OffsetRegNum = -1;
1910   bool OffsetRegShifted = false;
1911   enum ARM_AM::ShiftOpc ShiftType = ARM_AM::lsl;
1912   const MCExpr *ShiftAmount = 0;
1913   const MCExpr *Offset = 0;
1914
1915   // First look for preindexed address forms, that is after the "[Rn" we now
1916   // have to see if the next token is a comma.
1917   if (Tok.is(AsmToken::Comma)) {
1918     Preindexed = true;
1919     Parser.Lex(); // Eat comma token.
1920
1921     if (parseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
1922                              Offset, OffsetIsReg, OffsetRegNum, E))
1923       return true;
1924     const AsmToken &RBracTok = Parser.getTok();
1925     if (RBracTok.isNot(AsmToken::RBrac)) {
1926       Error(RBracTok.getLoc(), "']' expected");
1927       return true;
1928     }
1929     E = RBracTok.getLoc();
1930     Parser.Lex(); // Eat right bracket token.
1931
1932     const AsmToken &ExclaimTok = Parser.getTok();
1933     if (ExclaimTok.is(AsmToken::Exclaim)) {
1934       // None of addrmode3 instruction uses "!"
1935       if (AddrMode == ARMII::AddrMode3)
1936         return true;
1937
1938       WBOp = ARMOperand::CreateToken(ExclaimTok.getString(),
1939                                      ExclaimTok.getLoc());
1940       Writeback = true;
1941       Parser.Lex(); // Eat exclaim token
1942     } else { // In addressing mode 2, pre-indexed mode always end with "!"
1943       if (AddrMode == ARMII::AddrMode2)
1944         Preindexed = false;
1945     }
1946   } else {
1947     // The "[Rn" we have so far was not followed by a comma.
1948
1949     // If there's anything other than the right brace, this is a post indexing
1950     // addressing form.
1951     E = Tok.getLoc();
1952     Parser.Lex(); // Eat right bracket token.
1953
1954     const AsmToken &NextTok = Parser.getTok();
1955
1956     if (NextTok.isNot(AsmToken::EndOfStatement)) {
1957       Postindexed = true;
1958       Writeback = true;
1959
1960       if (NextTok.isNot(AsmToken::Comma)) {
1961         Error(NextTok.getLoc(), "',' expected");
1962         return true;
1963       }
1964
1965       Parser.Lex(); // Eat comma token.
1966
1967       if (parseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
1968                                ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
1969                                E))
1970         return true;
1971     }
1972   }
1973
1974   // Force Offset to exist if used.
1975   if (!OffsetIsReg) {
1976     if (!Offset)
1977       Offset = MCConstantExpr::Create(0, getContext());
1978   } else {
1979     if (AddrMode == ARMII::AddrMode3 && OffsetRegShifted) {
1980       Error(E, "shift amount not supported");
1981       return true;
1982     }
1983   }
1984
1985   Operands.push_back(ARMOperand::CreateMem(AddrMode, BaseRegNum, OffsetIsReg,
1986                                      Offset, OffsetRegNum, OffsetRegShifted,
1987                                      ShiftType, ShiftAmount, Preindexed,
1988                                      Postindexed, Negative, Writeback, S, E));
1989   if (WBOp)
1990     Operands.push_back(WBOp);
1991
1992   return false;
1993 }
1994
1995 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
1996 /// we will parse the following (were +/- means that a plus or minus is
1997 /// optional):
1998 ///   +/-Rm
1999 ///   +/-Rm, shift
2000 ///   #offset
2001 /// we return false on success or an error otherwise.
2002 bool ARMAsmParser::parseMemoryOffsetReg(bool &Negative,
2003                                         bool &OffsetRegShifted,
2004                                         enum ARM_AM::ShiftOpc &ShiftType,
2005                                         const MCExpr *&ShiftAmount,
2006                                         const MCExpr *&Offset,
2007                                         bool &OffsetIsReg,
2008                                         int &OffsetRegNum,
2009                                         SMLoc &E) {
2010   Negative = false;
2011   OffsetRegShifted = false;
2012   OffsetIsReg = false;
2013   OffsetRegNum = -1;
2014   const AsmToken &NextTok = Parser.getTok();
2015   E = NextTok.getLoc();
2016   if (NextTok.is(AsmToken::Plus))
2017     Parser.Lex(); // Eat plus token.
2018   else if (NextTok.is(AsmToken::Minus)) {
2019     Negative = true;
2020     Parser.Lex(); // Eat minus token
2021   }
2022   // See if there is a register following the "[Rn," or "[Rn]," we have so far.
2023   const AsmToken &OffsetRegTok = Parser.getTok();
2024   if (OffsetRegTok.is(AsmToken::Identifier)) {
2025     SMLoc CurLoc = OffsetRegTok.getLoc();
2026     OffsetRegNum = tryParseRegister();
2027     if (OffsetRegNum != -1) {
2028       OffsetIsReg = true;
2029       E = CurLoc;
2030     }
2031   }
2032
2033   // If we parsed a register as the offset then there can be a shift after that.
2034   if (OffsetRegNum != -1) {
2035     // Look for a comma then a shift
2036     const AsmToken &Tok = Parser.getTok();
2037     if (Tok.is(AsmToken::Comma)) {
2038       Parser.Lex(); // Eat comma token.
2039
2040       const AsmToken &Tok = Parser.getTok();
2041       if (parseShift(ShiftType, ShiftAmount, E))
2042         return Error(Tok.getLoc(), "shift expected");
2043       OffsetRegShifted = true;
2044     }
2045   }
2046   else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
2047     // Look for #offset following the "[Rn," or "[Rn],"
2048     const AsmToken &HashTok = Parser.getTok();
2049     if (HashTok.isNot(AsmToken::Hash))
2050       return Error(HashTok.getLoc(), "'#' expected");
2051
2052     Parser.Lex(); // Eat hash token.
2053
2054     if (getParser().ParseExpression(Offset))
2055      return true;
2056     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2057   }
2058   return false;
2059 }
2060
2061 /// parseShift as one of these two:
2062 ///   ( lsl | lsr | asr | ror ) , # shift_amount
2063 ///   rrx
2064 /// and returns true if it parses a shift otherwise it returns false.
2065 bool ARMAsmParser::parseShift(ARM_AM::ShiftOpc &St,
2066                               const MCExpr *&ShiftAmount, SMLoc &E) {
2067   const AsmToken &Tok = Parser.getTok();
2068   if (Tok.isNot(AsmToken::Identifier))
2069     return true;
2070   StringRef ShiftName = Tok.getString();
2071   if (ShiftName == "lsl" || ShiftName == "LSL")
2072     St = ARM_AM::lsl;
2073   else if (ShiftName == "lsr" || ShiftName == "LSR")
2074     St = ARM_AM::lsr;
2075   else if (ShiftName == "asr" || ShiftName == "ASR")
2076     St = ARM_AM::asr;
2077   else if (ShiftName == "ror" || ShiftName == "ROR")
2078     St = ARM_AM::ror;
2079   else if (ShiftName == "rrx" || ShiftName == "RRX")
2080     St = ARM_AM::rrx;
2081   else
2082     return true;
2083   Parser.Lex(); // Eat shift type token.
2084
2085   // Rrx stands alone.
2086   if (St == ARM_AM::rrx)
2087     return false;
2088
2089   // Otherwise, there must be a '#' and a shift amount.
2090   const AsmToken &HashTok = Parser.getTok();
2091   if (HashTok.isNot(AsmToken::Hash))
2092     return Error(HashTok.getLoc(), "'#' expected");
2093   Parser.Lex(); // Eat hash token.
2094
2095   if (getParser().ParseExpression(ShiftAmount))
2096     return true;
2097
2098   return false;
2099 }
2100
2101 /// Parse a arm instruction operand.  For now this parses the operand regardless
2102 /// of the mnemonic.
2103 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2104                                 StringRef Mnemonic) {
2105   SMLoc S, E;
2106
2107   // Check if the current operand has a custom associated parser, if so, try to
2108   // custom parse the operand, or fallback to the general approach.
2109   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
2110   if (ResTy == MatchOperand_Success)
2111     return false;
2112   // If there wasn't a custom match, try the generic matcher below. Otherwise,
2113   // there was a match, but an error occurred, in which case, just return that
2114   // the operand parsing failed.
2115   if (ResTy == MatchOperand_ParseFail)
2116     return true;
2117
2118   switch (getLexer().getKind()) {
2119   default:
2120     Error(Parser.getTok().getLoc(), "unexpected token in operand");
2121     return true;
2122   case AsmToken::Identifier: {
2123     if (!tryParseRegisterWithWriteBack(Operands))
2124       return false;
2125     int Res = tryparseShiftRegister(Operands);
2126     if (Res == 0) // success
2127       return false;
2128     else if (Res == -1) // irrecoverable error
2129       return true;
2130
2131     // Fall though for the Identifier case that is not a register or a
2132     // special name.
2133   }
2134   case AsmToken::Integer: // things like 1f and 2b as a branch targets
2135   case AsmToken::Dot: {   // . as a branch target
2136     // This was not a register so parse other operands that start with an
2137     // identifier (like labels) as expressions and create them as immediates.
2138     const MCExpr *IdVal;
2139     S = Parser.getTok().getLoc();
2140     if (getParser().ParseExpression(IdVal))
2141       return true;
2142     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2143     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
2144     return false;
2145   }
2146   case AsmToken::LBrac:
2147     return parseMemory(Operands);
2148   case AsmToken::LCurly:
2149     return parseRegisterList(Operands);
2150   case AsmToken::Hash:
2151     // #42 -> immediate.
2152     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
2153     S = Parser.getTok().getLoc();
2154     Parser.Lex();
2155     const MCExpr *ImmVal;
2156     if (getParser().ParseExpression(ImmVal))
2157       return true;
2158     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2159     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
2160     return false;
2161   case AsmToken::Colon: {
2162     // ":lower16:" and ":upper16:" expression prefixes
2163     // FIXME: Check it's an expression prefix,
2164     // e.g. (FOO - :lower16:BAR) isn't legal.
2165     ARMMCExpr::VariantKind RefKind;
2166     if (parsePrefix(RefKind))
2167       return true;
2168
2169     const MCExpr *SubExprVal;
2170     if (getParser().ParseExpression(SubExprVal))
2171       return true;
2172
2173     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
2174                                                    getContext());
2175     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2176     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
2177     return false;
2178   }
2179   }
2180 }
2181
2182 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
2183 //  :lower16: and :upper16:.
2184 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
2185   RefKind = ARMMCExpr::VK_ARM_None;
2186
2187   // :lower16: and :upper16: modifiers
2188   assert(getLexer().is(AsmToken::Colon) && "expected a :");
2189   Parser.Lex(); // Eat ':'
2190
2191   if (getLexer().isNot(AsmToken::Identifier)) {
2192     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
2193     return true;
2194   }
2195
2196   StringRef IDVal = Parser.getTok().getIdentifier();
2197   if (IDVal == "lower16") {
2198     RefKind = ARMMCExpr::VK_ARM_LO16;
2199   } else if (IDVal == "upper16") {
2200     RefKind = ARMMCExpr::VK_ARM_HI16;
2201   } else {
2202     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
2203     return true;
2204   }
2205   Parser.Lex();
2206
2207   if (getLexer().isNot(AsmToken::Colon)) {
2208     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
2209     return true;
2210   }
2211   Parser.Lex(); // Eat the last ':'
2212   return false;
2213 }
2214
2215 const MCExpr *
2216 ARMAsmParser::applyPrefixToExpr(const MCExpr *E,
2217                                 MCSymbolRefExpr::VariantKind Variant) {
2218   // Recurse over the given expression, rebuilding it to apply the given variant
2219   // to the leftmost symbol.
2220   if (Variant == MCSymbolRefExpr::VK_None)
2221     return E;
2222
2223   switch (E->getKind()) {
2224   case MCExpr::Target:
2225     llvm_unreachable("Can't handle target expr yet");
2226   case MCExpr::Constant:
2227     llvm_unreachable("Can't handle lower16/upper16 of constant yet");
2228
2229   case MCExpr::SymbolRef: {
2230     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
2231
2232     if (SRE->getKind() != MCSymbolRefExpr::VK_None)
2233       return 0;
2234
2235     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
2236   }
2237
2238   case MCExpr::Unary:
2239     llvm_unreachable("Can't handle unary expressions yet");
2240
2241   case MCExpr::Binary: {
2242     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
2243     const MCExpr *LHS = applyPrefixToExpr(BE->getLHS(), Variant);
2244     const MCExpr *RHS = BE->getRHS();
2245     if (!LHS)
2246       return 0;
2247
2248     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
2249   }
2250   }
2251
2252   assert(0 && "Invalid expression kind!");
2253   return 0;
2254 }
2255
2256 /// \brief Given a mnemonic, split out possible predication code and carry
2257 /// setting letters to form a canonical mnemonic and flags.
2258 //
2259 // FIXME: Would be nice to autogen this.
2260 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
2261                                       unsigned &PredicationCode,
2262                                       bool &CarrySetting,
2263                                       unsigned &ProcessorIMod) {
2264   PredicationCode = ARMCC::AL;
2265   CarrySetting = false;
2266   ProcessorIMod = 0;
2267
2268   // Ignore some mnemonics we know aren't predicated forms.
2269   //
2270   // FIXME: Would be nice to autogen this.
2271   if ((Mnemonic == "movs" && isThumb()) ||
2272       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
2273       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
2274       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
2275       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
2276       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
2277       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
2278       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal")
2279     return Mnemonic;
2280
2281   // First, split out any predication code. Ignore mnemonics we know aren't
2282   // predicated but do have a carry-set and so weren't caught above.
2283   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
2284       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls") {
2285     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
2286       .Case("eq", ARMCC::EQ)
2287       .Case("ne", ARMCC::NE)
2288       .Case("hs", ARMCC::HS)
2289       .Case("cs", ARMCC::HS)
2290       .Case("lo", ARMCC::LO)
2291       .Case("cc", ARMCC::LO)
2292       .Case("mi", ARMCC::MI)
2293       .Case("pl", ARMCC::PL)
2294       .Case("vs", ARMCC::VS)
2295       .Case("vc", ARMCC::VC)
2296       .Case("hi", ARMCC::HI)
2297       .Case("ls", ARMCC::LS)
2298       .Case("ge", ARMCC::GE)
2299       .Case("lt", ARMCC::LT)
2300       .Case("gt", ARMCC::GT)
2301       .Case("le", ARMCC::LE)
2302       .Case("al", ARMCC::AL)
2303       .Default(~0U);
2304     if (CC != ~0U) {
2305       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
2306       PredicationCode = CC;
2307     }
2308   }
2309
2310   // Next, determine if we have a carry setting bit. We explicitly ignore all
2311   // the instructions we know end in 's'.
2312   if (Mnemonic.endswith("s") &&
2313       !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" ||
2314         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
2315         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
2316         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
2317         Mnemonic == "vrsqrts" || (Mnemonic == "movs" && isThumb()))) {
2318     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
2319     CarrySetting = true;
2320   }
2321
2322   // The "cps" instruction can have a interrupt mode operand which is glued into
2323   // the mnemonic. Check if this is the case, split it and parse the imod op
2324   if (Mnemonic.startswith("cps")) {
2325     // Split out any imod code.
2326     unsigned IMod =
2327       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
2328       .Case("ie", ARM_PROC::IE)
2329       .Case("id", ARM_PROC::ID)
2330       .Default(~0U);
2331     if (IMod != ~0U) {
2332       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
2333       ProcessorIMod = IMod;
2334     }
2335   }
2336
2337   return Mnemonic;
2338 }
2339
2340 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
2341 /// inclusion of carry set or predication code operands.
2342 //
2343 // FIXME: It would be nice to autogen this.
2344 void ARMAsmParser::
2345 getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
2346                       bool &CanAcceptPredicationCode) {
2347   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
2348       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
2349       Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" ||
2350       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
2351       Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mvn" ||
2352       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
2353       Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" ||
2354       Mnemonic == "eor" || Mnemonic == "smlal" ||
2355       (Mnemonic == "mov" && !isThumbOne())) {
2356     CanAcceptCarrySet = true;
2357   } else {
2358     CanAcceptCarrySet = false;
2359   }
2360
2361   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
2362       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
2363       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
2364       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
2365       Mnemonic == "dsb" || Mnemonic == "isb" || Mnemonic == "clrex" ||
2366       Mnemonic == "setend" ||
2367       Mnemonic.startswith("cps") || (Mnemonic == "movs" && isThumb())) {
2368     CanAcceptPredicationCode = false;
2369   } else {
2370     CanAcceptPredicationCode = true;
2371   }
2372
2373   if (isThumb())
2374     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
2375         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
2376       CanAcceptPredicationCode = false;
2377 }
2378
2379 /// Parse an arm instruction mnemonic followed by its operands.
2380 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
2381                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2382   // Create the leading tokens for the mnemonic, split by '.' characters.
2383   size_t Start = 0, Next = Name.find('.');
2384   StringRef Mnemonic = Name.slice(Start, Next);
2385
2386   // Split out the predication code and carry setting flag from the mnemonic.
2387   unsigned PredicationCode;
2388   unsigned ProcessorIMod;
2389   bool CarrySetting;
2390   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
2391                            ProcessorIMod);
2392
2393   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
2394
2395   // FIXME: This is all a pretty gross hack. We should automatically handle
2396   // optional operands like this via tblgen.
2397
2398   // Next, add the CCOut and ConditionCode operands, if needed.
2399   //
2400   // For mnemonics which can ever incorporate a carry setting bit or predication
2401   // code, our matching model involves us always generating CCOut and
2402   // ConditionCode operands to match the mnemonic "as written" and then we let
2403   // the matcher deal with finding the right instruction or generating an
2404   // appropriate error.
2405   bool CanAcceptCarrySet, CanAcceptPredicationCode;
2406   getMnemonicAcceptInfo(Mnemonic, CanAcceptCarrySet, CanAcceptPredicationCode);
2407
2408   // If we had a carry-set on an instruction that can't do that, issue an
2409   // error.
2410   if (!CanAcceptCarrySet && CarrySetting) {
2411     Parser.EatToEndOfStatement();
2412     return Error(NameLoc, "instruction '" + Mnemonic +
2413                  "' can not set flags, but 's' suffix specified");
2414   }
2415   // If we had a predication code on an instruction that can't do that, issue an
2416   // error.
2417   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
2418     Parser.EatToEndOfStatement();
2419     return Error(NameLoc, "instruction '" + Mnemonic +
2420                  "' is not predicable, but condition code specified");
2421   }
2422
2423   // Add the carry setting operand, if necessary.
2424   //
2425   // FIXME: It would be awesome if we could somehow invent a location such that
2426   // match errors on this operand would print a nice diagnostic about how the
2427   // 's' character in the mnemonic resulted in a CCOut operand.
2428   if (CanAcceptCarrySet)
2429     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
2430                                                NameLoc));
2431
2432   // Add the predication code operand, if necessary.
2433   if (CanAcceptPredicationCode) {
2434     Operands.push_back(ARMOperand::CreateCondCode(
2435                          ARMCC::CondCodes(PredicationCode), NameLoc));
2436   }
2437
2438   // Add the processor imod operand, if necessary.
2439   if (ProcessorIMod) {
2440     Operands.push_back(ARMOperand::CreateImm(
2441           MCConstantExpr::Create(ProcessorIMod, getContext()),
2442                                  NameLoc, NameLoc));
2443   } else {
2444     // This mnemonic can't ever accept a imod, but the user wrote
2445     // one (or misspelled another mnemonic).
2446
2447     // FIXME: Issue a nice error.
2448   }
2449
2450   // Add the remaining tokens in the mnemonic.
2451   while (Next != StringRef::npos) {
2452     Start = Next;
2453     Next = Name.find('.', Start + 1);
2454     StringRef ExtraToken = Name.slice(Start, Next);
2455
2456     Operands.push_back(ARMOperand::CreateToken(ExtraToken, NameLoc));
2457   }
2458
2459   // Read the remaining operands.
2460   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2461     // Read the first operand.
2462     if (parseOperand(Operands, Mnemonic)) {
2463       Parser.EatToEndOfStatement();
2464       return true;
2465     }
2466
2467     while (getLexer().is(AsmToken::Comma)) {
2468       Parser.Lex();  // Eat the comma.
2469
2470       // Parse and remember the operand.
2471       if (parseOperand(Operands, Mnemonic)) {
2472         Parser.EatToEndOfStatement();
2473         return true;
2474       }
2475     }
2476   }
2477
2478   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2479     Parser.EatToEndOfStatement();
2480     return TokError("unexpected token in argument list");
2481   }
2482
2483   Parser.Lex(); // Consume the EndOfStatement
2484
2485
2486   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
2487   // another does not. Specifically, the MOVW instruction does not. So we
2488   // special case it here and remove the defaulted (non-setting) cc_out
2489   // operand if that's the instruction we're trying to match.
2490   //
2491   // We do this post-processing of the explicit operands rather than just
2492   // conditionally adding the cc_out in the first place because we need
2493   // to check the type of the parsed immediate operand.
2494   if (Mnemonic == "mov" && Operands.size() > 4 &&
2495       !static_cast<ARMOperand*>(Operands[4])->isARMSOImm() &&
2496       static_cast<ARMOperand*>(Operands[4])->isImm0_65535Expr() &&
2497       static_cast<ARMOperand*>(Operands[1])->getReg() == 0) {
2498     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
2499     Operands.erase(Operands.begin() + 1);
2500     delete Op;
2501   }
2502
2503   return false;
2504 }
2505
2506 // Validate context-sensitive operand constraints.
2507 // FIXME: We would really like to be able to tablegen'erate this.
2508 bool ARMAsmParser::
2509 validateInstruction(MCInst &Inst,
2510                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2511   switch (Inst.getOpcode()) {
2512   case ARM::LDREXD: {
2513     // Rt2 must be Rt + 1.
2514     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
2515     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
2516     if (Rt2 != Rt + 1)
2517       return Error(Operands[3]->getStartLoc(),
2518                    "destination operands must be sequential");
2519     return false;
2520   }
2521   case ARM::STREXD: {
2522     // Rt2 must be Rt + 1.
2523     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(1).getReg());
2524     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(2).getReg());
2525     if (Rt2 != Rt + 1)
2526       return Error(Operands[4]->getStartLoc(),
2527                    "source operands must be sequential");
2528     return false;
2529   }
2530   }
2531
2532   return false;
2533 }
2534
2535 bool ARMAsmParser::
2536 MatchAndEmitInstruction(SMLoc IDLoc,
2537                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2538                         MCStreamer &Out) {
2539   MCInst Inst;
2540   unsigned ErrorInfo;
2541   MatchResultTy MatchResult;
2542   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
2543   switch (MatchResult) {
2544   case Match_Success:
2545     // Context sensitive operand constraints aren't handled by the matcher,
2546     // so check them here.
2547     if (validateInstruction(Inst, Operands))
2548       return true;
2549
2550     Out.EmitInstruction(Inst);
2551     return false;
2552   case Match_MissingFeature:
2553     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
2554     return true;
2555   case Match_InvalidOperand: {
2556     SMLoc ErrorLoc = IDLoc;
2557     if (ErrorInfo != ~0U) {
2558       if (ErrorInfo >= Operands.size())
2559         return Error(IDLoc, "too few operands for instruction");
2560
2561       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
2562       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
2563     }
2564
2565     return Error(ErrorLoc, "invalid operand for instruction");
2566   }
2567   case Match_MnemonicFail:
2568     return Error(IDLoc, "unrecognized instruction mnemonic");
2569   case Match_ConversionFail:
2570     return Error(IDLoc, "unable to convert operands to instruction");
2571   }
2572
2573   llvm_unreachable("Implement any new match types added!");
2574   return true;
2575 }
2576
2577 /// parseDirective parses the arm specific directives
2578 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
2579   StringRef IDVal = DirectiveID.getIdentifier();
2580   if (IDVal == ".word")
2581     return parseDirectiveWord(4, DirectiveID.getLoc());
2582   else if (IDVal == ".thumb")
2583     return parseDirectiveThumb(DirectiveID.getLoc());
2584   else if (IDVal == ".thumb_func")
2585     return parseDirectiveThumbFunc(DirectiveID.getLoc());
2586   else if (IDVal == ".code")
2587     return parseDirectiveCode(DirectiveID.getLoc());
2588   else if (IDVal == ".syntax")
2589     return parseDirectiveSyntax(DirectiveID.getLoc());
2590   return true;
2591 }
2592
2593 /// parseDirectiveWord
2594 ///  ::= .word [ expression (, expression)* ]
2595 bool ARMAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
2596   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2597     for (;;) {
2598       const MCExpr *Value;
2599       if (getParser().ParseExpression(Value))
2600         return true;
2601
2602       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
2603
2604       if (getLexer().is(AsmToken::EndOfStatement))
2605         break;
2606
2607       // FIXME: Improve diagnostic.
2608       if (getLexer().isNot(AsmToken::Comma))
2609         return Error(L, "unexpected token in directive");
2610       Parser.Lex();
2611     }
2612   }
2613
2614   Parser.Lex();
2615   return false;
2616 }
2617
2618 /// parseDirectiveThumb
2619 ///  ::= .thumb
2620 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
2621   if (getLexer().isNot(AsmToken::EndOfStatement))
2622     return Error(L, "unexpected token in directive");
2623   Parser.Lex();
2624
2625   // TODO: set thumb mode
2626   // TODO: tell the MC streamer the mode
2627   // getParser().getStreamer().Emit???();
2628   return false;
2629 }
2630
2631 /// parseDirectiveThumbFunc
2632 ///  ::= .thumbfunc symbol_name
2633 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
2634   const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
2635   bool isMachO = MAI.hasSubsectionsViaSymbols();
2636   StringRef Name;
2637
2638   // Darwin asm has function name after .thumb_func direction
2639   // ELF doesn't
2640   if (isMachO) {
2641     const AsmToken &Tok = Parser.getTok();
2642     if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
2643       return Error(L, "unexpected token in .thumb_func directive");
2644     Name = Tok.getString();
2645     Parser.Lex(); // Consume the identifier token.
2646   }
2647
2648   if (getLexer().isNot(AsmToken::EndOfStatement))
2649     return Error(L, "unexpected token in directive");
2650   Parser.Lex();
2651
2652   // FIXME: assuming function name will be the line following .thumb_func
2653   if (!isMachO) {
2654     Name = Parser.getTok().getString();
2655   }
2656
2657   // Mark symbol as a thumb symbol.
2658   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
2659   getParser().getStreamer().EmitThumbFunc(Func);
2660   return false;
2661 }
2662
2663 /// parseDirectiveSyntax
2664 ///  ::= .syntax unified | divided
2665 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
2666   const AsmToken &Tok = Parser.getTok();
2667   if (Tok.isNot(AsmToken::Identifier))
2668     return Error(L, "unexpected token in .syntax directive");
2669   StringRef Mode = Tok.getString();
2670   if (Mode == "unified" || Mode == "UNIFIED")
2671     Parser.Lex();
2672   else if (Mode == "divided" || Mode == "DIVIDED")
2673     return Error(L, "'.syntax divided' arm asssembly not supported");
2674   else
2675     return Error(L, "unrecognized syntax mode in .syntax directive");
2676
2677   if (getLexer().isNot(AsmToken::EndOfStatement))
2678     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
2679   Parser.Lex();
2680
2681   // TODO tell the MC streamer the mode
2682   // getParser().getStreamer().Emit???();
2683   return false;
2684 }
2685
2686 /// parseDirectiveCode
2687 ///  ::= .code 16 | 32
2688 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
2689   const AsmToken &Tok = Parser.getTok();
2690   if (Tok.isNot(AsmToken::Integer))
2691     return Error(L, "unexpected token in .code directive");
2692   int64_t Val = Parser.getTok().getIntVal();
2693   if (Val == 16)
2694     Parser.Lex();
2695   else if (Val == 32)
2696     Parser.Lex();
2697   else
2698     return Error(L, "invalid operand to .code directive");
2699
2700   if (getLexer().isNot(AsmToken::EndOfStatement))
2701     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
2702   Parser.Lex();
2703
2704   if (Val == 16) {
2705     if (!isThumb())
2706       SwitchMode();
2707     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
2708   } else {
2709     if (isThumb())
2710       SwitchMode();
2711     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2712   }
2713
2714   return false;
2715 }
2716
2717 extern "C" void LLVMInitializeARMAsmLexer();
2718
2719 /// Force static initialization.
2720 extern "C" void LLVMInitializeARMAsmParser() {
2721   RegisterMCAsmParser<ARMAsmParser> X(TheARMTarget);
2722   RegisterMCAsmParser<ARMAsmParser> Y(TheThumbTarget);
2723   LLVMInitializeARMAsmLexer();
2724 }
2725
2726 #define GET_REGISTER_MATCHER
2727 #define GET_MATCHER_IMPLEMENTATION
2728 #include "ARMGenAsmMatcher.inc"