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