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