ARMAsmParser.cpp revision e4e5e2aae7e1e0e84877061432e7b981a360a77d
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 "ARM.h"
11#include "ARMAddressingModes.h"
12#include "ARMMCExpr.h"
13#include "ARMBaseRegisterInfo.h"
14#include "ARMSubtarget.h"
15#include "llvm/MC/MCParser/MCAsmLexer.h"
16#include "llvm/MC/MCParser/MCAsmParser.h"
17#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
18#include "llvm/MC/MCContext.h"
19#include "llvm/MC/MCStreamer.h"
20#include "llvm/MC/MCExpr.h"
21#include "llvm/MC/MCInst.h"
22#include "llvm/Target/TargetRegistry.h"
23#include "llvm/Target/TargetAsmParser.h"
24#include "llvm/Support/SourceMgr.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringSwitch.h"
28#include "llvm/ADT/Twine.h"
29using namespace llvm;
30
31/// Shift types used for register controlled shifts in ARM memory addressing.
32enum ShiftType {
33  Lsl,
34  Lsr,
35  Asr,
36  Ror,
37  Rrx
38};
39
40namespace {
41
42class ARMOperand;
43
44class ARMAsmParser : public TargetAsmParser {
45  MCAsmParser &Parser;
46  TargetMachine &TM;
47
48  MCAsmParser &getParser() const { return Parser; }
49  MCAsmLexer &getLexer() const { return Parser.getLexer(); }
50
51  void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
52  bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
53
54  int TryParseRegister();
55  bool TryParseMCRName(SmallVectorImpl<MCParsedAsmOperand*>&);
56  bool TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
57  bool ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
58  bool ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
59  bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, bool isMCR);
60  bool ParsePrefix(ARMMCExpr::VariantKind &RefKind);
61  const MCExpr *ApplyPrefixToExpr(const MCExpr *E,
62                                  MCSymbolRefExpr::VariantKind Variant);
63
64
65  bool ParseMemoryOffsetReg(bool &Negative,
66                            bool &OffsetRegShifted,
67                            enum ShiftType &ShiftType,
68                            const MCExpr *&ShiftAmount,
69                            const MCExpr *&Offset,
70                            bool &OffsetIsReg,
71                            int &OffsetRegNum,
72                            SMLoc &E);
73  bool ParseShift(enum ShiftType &St, const MCExpr *&ShiftAmount, SMLoc &E);
74  bool ParseDirectiveWord(unsigned Size, SMLoc L);
75  bool ParseDirectiveThumb(SMLoc L);
76  bool ParseDirectiveThumbFunc(SMLoc L);
77  bool ParseDirectiveCode(SMLoc L);
78  bool ParseDirectiveSyntax(SMLoc L);
79
80  bool MatchAndEmitInstruction(SMLoc IDLoc,
81                               SmallVectorImpl<MCParsedAsmOperand*> &Operands,
82                               MCStreamer &Out);
83
84  /// @name Auto-generated Match Functions
85  /// {
86
87#define GET_ASSEMBLER_HEADER
88#include "ARMGenAsmMatcher.inc"
89
90  /// }
91
92public:
93  ARMAsmParser(const Target &T, MCAsmParser &_Parser, TargetMachine &_TM)
94    : TargetAsmParser(T), Parser(_Parser), TM(_TM) {
95      // Initialize the set of available features.
96      setAvailableFeatures(ComputeAvailableFeatures(
97          &TM.getSubtarget<ARMSubtarget>()));
98    }
99
100  virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
101                                SmallVectorImpl<MCParsedAsmOperand*> &Operands);
102  virtual bool ParseDirective(AsmToken DirectiveID);
103};
104} // end anonymous namespace
105
106namespace {
107
108/// ARMOperand - Instances of this class represent a parsed ARM machine
109/// instruction.
110class ARMOperand : public MCParsedAsmOperand {
111  enum KindTy {
112    CondCode,
113    CCOut,
114    Immediate,
115    Memory,
116    Register,
117    RegisterList,
118    DPRRegisterList,
119    SPRRegisterList,
120    Token
121  } Kind;
122
123  SMLoc StartLoc, EndLoc;
124  SmallVector<unsigned, 8> Registers;
125
126  union {
127    struct {
128      ARMCC::CondCodes Val;
129    } CC;
130
131    struct {
132      const char *Data;
133      unsigned Length;
134    } Tok;
135
136    struct {
137      unsigned RegNum;
138    } Reg;
139
140    struct {
141      const MCExpr *Val;
142    } Imm;
143
144    /// Combined record for all forms of ARM address expressions.
145    struct {
146      unsigned BaseRegNum;
147      unsigned OffsetRegNum;         // used when OffsetIsReg is true
148      const MCExpr *Offset;          // used when OffsetIsReg is false
149      const MCExpr *ShiftAmount;     // used when OffsetRegShifted is true
150      enum ShiftType ShiftType;      // used when OffsetRegShifted is true
151      unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
152      unsigned Preindexed       : 1;
153      unsigned Postindexed      : 1;
154      unsigned OffsetIsReg      : 1;
155      unsigned Negative         : 1; // only used when OffsetIsReg is true
156      unsigned Writeback        : 1;
157    } Mem;
158  };
159
160  ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
161public:
162  ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
163    Kind = o.Kind;
164    StartLoc = o.StartLoc;
165    EndLoc = o.EndLoc;
166    switch (Kind) {
167    case CondCode:
168      CC = o.CC;
169      break;
170    case Token:
171      Tok = o.Tok;
172      break;
173    case CCOut:
174    case Register:
175      Reg = o.Reg;
176      break;
177    case RegisterList:
178    case DPRRegisterList:
179    case SPRRegisterList:
180      Registers = o.Registers;
181      break;
182    case Immediate:
183      Imm = o.Imm;
184      break;
185    case Memory:
186      Mem = o.Mem;
187      break;
188    }
189  }
190
191  /// getStartLoc - Get the location of the first token of this operand.
192  SMLoc getStartLoc() const { return StartLoc; }
193  /// getEndLoc - Get the location of the last token of this operand.
194  SMLoc getEndLoc() const { return EndLoc; }
195
196  ARMCC::CondCodes getCondCode() const {
197    assert(Kind == CondCode && "Invalid access!");
198    return CC.Val;
199  }
200
201  StringRef getToken() const {
202    assert(Kind == Token && "Invalid access!");
203    return StringRef(Tok.Data, Tok.Length);
204  }
205
206  unsigned getReg() const {
207    assert((Kind == Register || Kind == CCOut) && "Invalid access!");
208    return Reg.RegNum;
209  }
210
211  const SmallVectorImpl<unsigned> &getRegList() const {
212    assert((Kind == RegisterList || Kind == DPRRegisterList ||
213            Kind == SPRRegisterList) && "Invalid access!");
214    return Registers;
215  }
216
217  const MCExpr *getImm() const {
218    assert(Kind == Immediate && "Invalid access!");
219    return Imm.Val;
220  }
221
222  bool isCondCode() const { return Kind == CondCode; }
223  bool isCCOut() const { return Kind == CCOut; }
224  bool isImm() const { return Kind == Immediate; }
225  bool isReg() const { return Kind == Register; }
226  bool isRegList() const { return Kind == RegisterList; }
227  bool isDPRRegList() const { return Kind == DPRRegisterList; }
228  bool isSPRRegList() const { return Kind == SPRRegisterList; }
229  bool isToken() const { return Kind == Token; }
230  bool isMemory() const { return Kind == Memory; }
231  bool isMemMode5() const {
232    if (!isMemory() || Mem.OffsetIsReg || Mem.OffsetRegShifted ||
233        Mem.Writeback || Mem.Negative)
234      return false;
235
236    // If there is an offset expression, make sure it's valid.
237    if (!Mem.Offset) return true;
238
239    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
240    if (!CE) return false;
241
242    // The offset must be a multiple of 4 in the range 0-1020.
243    int64_t Value = CE->getValue();
244    return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
245  }
246  bool isMemModeRegThumb() const {
247    if (!isMemory() || (!Mem.OffsetIsReg && !Mem.Offset) || Mem.Writeback)
248      return false;
249    return !Mem.Offset || !isa<MCConstantExpr>(Mem.Offset);
250  }
251  bool isMemModeImmThumb() const {
252    if (!isMemory() || (!Mem.OffsetIsReg && !Mem.Offset) || Mem.Writeback)
253      return false;
254
255    if (!Mem.Offset) return false;
256
257    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
258    if (!CE) return false;
259
260    // The offset must be a multiple of 4 in the range 0-124.
261    uint64_t Value = CE->getValue();
262    return ((Value & 0x3) == 0 && Value <= 124);
263  }
264
265  void addExpr(MCInst &Inst, const MCExpr *Expr) const {
266    // Add as immediates when possible.  Null MCExpr = 0.
267    if (Expr == 0)
268      Inst.addOperand(MCOperand::CreateImm(0));
269    else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
270      Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
271    else
272      Inst.addOperand(MCOperand::CreateExpr(Expr));
273  }
274
275  void addCondCodeOperands(MCInst &Inst, unsigned N) const {
276    assert(N == 2 && "Invalid number of operands!");
277    Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
278    unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
279    Inst.addOperand(MCOperand::CreateReg(RegNum));
280  }
281
282  void addCCOutOperands(MCInst &Inst, unsigned N) const {
283    assert(N == 1 && "Invalid number of operands!");
284    Inst.addOperand(MCOperand::CreateReg(getReg()));
285  }
286
287  void addRegOperands(MCInst &Inst, unsigned N) const {
288    assert(N == 1 && "Invalid number of operands!");
289    Inst.addOperand(MCOperand::CreateReg(getReg()));
290  }
291
292  void addRegListOperands(MCInst &Inst, unsigned N) const {
293    assert(N == 1 && "Invalid number of operands!");
294    const SmallVectorImpl<unsigned> &RegList = getRegList();
295    for (SmallVectorImpl<unsigned>::const_iterator
296           I = RegList.begin(), E = RegList.end(); I != E; ++I)
297      Inst.addOperand(MCOperand::CreateReg(*I));
298  }
299
300  void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
301    addRegListOperands(Inst, N);
302  }
303
304  void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
305    addRegListOperands(Inst, N);
306  }
307
308  void addImmOperands(MCInst &Inst, unsigned N) const {
309    assert(N == 1 && "Invalid number of operands!");
310    addExpr(Inst, getImm());
311  }
312
313  void addMemMode5Operands(MCInst &Inst, unsigned N) const {
314    assert(N == 2 && isMemMode5() && "Invalid number of operands!");
315
316    Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
317    assert(!Mem.OffsetIsReg && "Invalid mode 5 operand");
318
319    // FIXME: #-0 is encoded differently than #0. Does the parser preserve
320    // the difference?
321    if (Mem.Offset) {
322      const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
323      assert(CE && "Non-constant mode 5 offset operand!");
324
325      // The MCInst offset operand doesn't include the low two bits (like
326      // the instruction encoding).
327      int64_t Offset = CE->getValue() / 4;
328      if (Offset >= 0)
329        Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
330                                                               Offset)));
331      else
332        Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
333                                                               -Offset)));
334    } else {
335      Inst.addOperand(MCOperand::CreateImm(0));
336    }
337  }
338
339  void addMemModeRegThumbOperands(MCInst &Inst, unsigned N) const {
340    assert(N == 2 && isMemModeRegThumb() && "Invalid number of operands!");
341    Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
342    Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
343  }
344
345  void addMemModeImmThumbOperands(MCInst &Inst, unsigned N) const {
346    assert(N == 2 && isMemModeImmThumb() && "Invalid number of operands!");
347    Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
348    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
349    assert(CE && "Non-constant mode offset operand!");
350    Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
351  }
352
353  virtual void dump(raw_ostream &OS) const;
354
355  static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
356    ARMOperand *Op = new ARMOperand(CondCode);
357    Op->CC.Val = CC;
358    Op->StartLoc = S;
359    Op->EndLoc = S;
360    return Op;
361  }
362
363  static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
364    ARMOperand *Op = new ARMOperand(CCOut);
365    Op->Reg.RegNum = RegNum;
366    Op->StartLoc = S;
367    Op->EndLoc = S;
368    return Op;
369  }
370
371  static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
372    ARMOperand *Op = new ARMOperand(Token);
373    Op->Tok.Data = Str.data();
374    Op->Tok.Length = Str.size();
375    Op->StartLoc = S;
376    Op->EndLoc = S;
377    return Op;
378  }
379
380  static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
381    ARMOperand *Op = new ARMOperand(Register);
382    Op->Reg.RegNum = RegNum;
383    Op->StartLoc = S;
384    Op->EndLoc = E;
385    return Op;
386  }
387
388  static ARMOperand *
389  CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
390                SMLoc StartLoc, SMLoc EndLoc) {
391    KindTy Kind = RegisterList;
392
393    if (ARM::DPRRegClass.contains(Regs.front().first))
394      Kind = DPRRegisterList;
395    else if (ARM::SPRRegClass.contains(Regs.front().first))
396      Kind = SPRRegisterList;
397
398    ARMOperand *Op = new ARMOperand(Kind);
399    for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
400           I = Regs.begin(), E = Regs.end(); I != E; ++I)
401      Op->Registers.push_back(I->first);
402    array_pod_sort(Op->Registers.begin(), Op->Registers.end());
403    Op->StartLoc = StartLoc;
404    Op->EndLoc = EndLoc;
405    return Op;
406  }
407
408  static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
409    ARMOperand *Op = new ARMOperand(Immediate);
410    Op->Imm.Val = Val;
411    Op->StartLoc = S;
412    Op->EndLoc = E;
413    return Op;
414  }
415
416  static ARMOperand *CreateMem(unsigned BaseRegNum, bool OffsetIsReg,
417                               const MCExpr *Offset, unsigned OffsetRegNum,
418                               bool OffsetRegShifted, enum ShiftType ShiftType,
419                               const MCExpr *ShiftAmount, bool Preindexed,
420                               bool Postindexed, bool Negative, bool Writeback,
421                               SMLoc S, SMLoc E) {
422    ARMOperand *Op = new ARMOperand(Memory);
423    Op->Mem.BaseRegNum = BaseRegNum;
424    Op->Mem.OffsetIsReg = OffsetIsReg;
425    Op->Mem.Offset = Offset;
426    Op->Mem.OffsetRegNum = OffsetRegNum;
427    Op->Mem.OffsetRegShifted = OffsetRegShifted;
428    Op->Mem.ShiftType = ShiftType;
429    Op->Mem.ShiftAmount = ShiftAmount;
430    Op->Mem.Preindexed = Preindexed;
431    Op->Mem.Postindexed = Postindexed;
432    Op->Mem.Negative = Negative;
433    Op->Mem.Writeback = Writeback;
434
435    Op->StartLoc = S;
436    Op->EndLoc = E;
437    return Op;
438  }
439};
440
441} // end anonymous namespace.
442
443void ARMOperand::dump(raw_ostream &OS) const {
444  switch (Kind) {
445  case CondCode:
446    OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
447    break;
448  case CCOut:
449    OS << "<ccout " << getReg() << ">";
450    break;
451  case Immediate:
452    getImm()->print(OS);
453    break;
454  case Memory:
455    OS << "<memory>";
456    break;
457  case Register:
458    OS << "<register " << getReg() << ">";
459    break;
460  case RegisterList:
461  case DPRRegisterList:
462  case SPRRegisterList: {
463    OS << "<register_list ";
464
465    const SmallVectorImpl<unsigned> &RegList = getRegList();
466    for (SmallVectorImpl<unsigned>::const_iterator
467           I = RegList.begin(), E = RegList.end(); I != E; ) {
468      OS << *I;
469      if (++I < E) OS << ", ";
470    }
471
472    OS << ">";
473    break;
474  }
475  case Token:
476    OS << "'" << getToken() << "'";
477    break;
478  }
479}
480
481/// @name Auto-generated Match Functions
482/// {
483
484static unsigned MatchRegisterName(StringRef Name);
485
486/// }
487
488/// Try to parse a register name.  The token must be an Identifier when called,
489/// and if it is a register name the token is eaten and the register number is
490/// returned.  Otherwise return -1.
491///
492int ARMAsmParser::TryParseRegister() {
493  const AsmToken &Tok = Parser.getTok();
494  assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
495
496  // FIXME: Validate register for the current architecture; we have to do
497  // validation later, so maybe there is no need for this here.
498  unsigned RegNum = MatchRegisterName(Tok.getString());
499  if (RegNum == 0)
500    return -1;
501  Parser.Lex(); // Eat identifier token.
502  return RegNum;
503}
504
505
506/// Try to parse a register name.  The token must be an Identifier when called.
507/// If it's a register, an AsmOperand is created. Another AsmOperand is created
508/// if there is a "writeback". 'true' if it's not a register.
509///
510/// TODO this is likely to change to allow different register types and or to
511/// parse for a specific register type.
512bool ARMAsmParser::
513TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
514  SMLoc S = Parser.getTok().getLoc();
515  int RegNo = TryParseRegister();
516  if (RegNo == -1)
517    return true;
518
519  Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
520
521  const AsmToken &ExclaimTok = Parser.getTok();
522  if (ExclaimTok.is(AsmToken::Exclaim)) {
523    Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
524                                               ExclaimTok.getLoc()));
525    Parser.Lex(); // Eat exclaim token
526  }
527
528  return false;
529}
530
531static int MatchMCRName(StringRef Name) {
532  // Use the same layout as the tablegen'erated register name matcher. Ugly,
533  // but efficient.
534  switch (Name.size()) {
535  default: break;
536  case 2:
537    if (Name[0] != 'p' && Name[0] != 'c')
538      return -1;
539    switch (Name[1]) {
540    default:  return -1;
541    case '0': return 0;
542    case '1': return 1;
543    case '2': return 2;
544    case '3': return 3;
545    case '4': return 4;
546    case '5': return 5;
547    case '6': return 6;
548    case '7': return 7;
549    case '8': return 8;
550    case '9': return 9;
551    }
552    break;
553  case 3:
554    if ((Name[0] != 'p' && Name[0] != 'c') || Name[1] != '1')
555      return -1;
556    switch (Name[2]) {
557    default:  return -1;
558    case '0': return 10;
559    case '1': return 11;
560    case '2': return 12;
561    case '3': return 13;
562    case '4': return 14;
563    case '5': return 15;
564    }
565    break;
566  }
567
568  llvm_unreachable("Unhandled coprocessor operand string!");
569  return -1;
570}
571
572/// TryParseMCRName - Try to parse an MCR/MRC symbolic operand
573/// name.  The token must be an Identifier when called, and if it is a MCR
574/// operand name, the token is eaten and the operand is added to the
575/// operand list.
576bool ARMAsmParser::
577TryParseMCRName(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
578  SMLoc S = Parser.getTok().getLoc();
579  const AsmToken &Tok = Parser.getTok();
580  assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
581
582  int Num = MatchMCRName(Tok.getString());
583  if (Num == -1)
584    return true;
585
586  Parser.Lex(); // Eat identifier token.
587  Operands.push_back(ARMOperand::CreateImm(
588       MCConstantExpr::Create(Num, getContext()), S, Parser.getTok().getLoc()));
589  return false;
590}
591
592/// Parse a register list, return it if successful else return null.  The first
593/// token must be a '{' when called.
594bool ARMAsmParser::
595ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
596  assert(Parser.getTok().is(AsmToken::LCurly) &&
597         "Token is not a Left Curly Brace");
598  SMLoc S = Parser.getTok().getLoc();
599
600  // Read the rest of the registers in the list.
601  unsigned PrevRegNum = 0;
602  SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
603
604  do {
605    bool IsRange = Parser.getTok().is(AsmToken::Minus);
606    Parser.Lex(); // Eat non-identifier token.
607
608    const AsmToken &RegTok = Parser.getTok();
609    SMLoc RegLoc = RegTok.getLoc();
610    if (RegTok.isNot(AsmToken::Identifier)) {
611      Error(RegLoc, "register expected");
612      return true;
613    }
614
615    int RegNum = TryParseRegister();
616    if (RegNum == -1) {
617      Error(RegLoc, "register expected");
618      return true;
619    }
620
621    if (IsRange) {
622      int Reg = PrevRegNum;
623      do {
624        ++Reg;
625        Registers.push_back(std::make_pair(Reg, RegLoc));
626      } while (Reg != RegNum);
627    } else {
628      Registers.push_back(std::make_pair(RegNum, RegLoc));
629    }
630
631    PrevRegNum = RegNum;
632  } while (Parser.getTok().is(AsmToken::Comma) ||
633           Parser.getTok().is(AsmToken::Minus));
634
635  // Process the right curly brace of the list.
636  const AsmToken &RCurlyTok = Parser.getTok();
637  if (RCurlyTok.isNot(AsmToken::RCurly)) {
638    Error(RCurlyTok.getLoc(), "'}' expected");
639    return true;
640  }
641
642  SMLoc E = RCurlyTok.getLoc();
643  Parser.Lex(); // Eat right curly brace token.
644
645  // Verify the register list.
646  SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
647    RI = Registers.begin(), RE = Registers.end();
648
649  unsigned HighRegNum = getARMRegisterNumbering(RI->first);
650  bool EmittedWarning = false;
651
652  DenseMap<unsigned, bool> RegMap;
653  RegMap[HighRegNum] = true;
654
655  for (++RI; RI != RE; ++RI) {
656    const std::pair<unsigned, SMLoc> &RegInfo = *RI;
657    unsigned Reg = getARMRegisterNumbering(RegInfo.first);
658
659    if (RegMap[Reg]) {
660      Error(RegInfo.second, "register duplicated in register list");
661      return true;
662    }
663
664    if (!EmittedWarning && Reg < HighRegNum)
665      Warning(RegInfo.second,
666              "register not in ascending order in register list");
667
668    RegMap[Reg] = true;
669    HighRegNum = std::max(Reg, HighRegNum);
670  }
671
672  Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
673  return false;
674}
675
676/// Parse an ARM memory expression, return false if successful else return true
677/// or an error.  The first token must be a '[' when called.
678///
679/// TODO Only preindexing and postindexing addressing are started, unindexed
680/// with option, etc are still to do.
681bool ARMAsmParser::
682ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
683  SMLoc S, E;
684  assert(Parser.getTok().is(AsmToken::LBrac) &&
685         "Token is not a Left Bracket");
686  S = Parser.getTok().getLoc();
687  Parser.Lex(); // Eat left bracket token.
688
689  const AsmToken &BaseRegTok = Parser.getTok();
690  if (BaseRegTok.isNot(AsmToken::Identifier)) {
691    Error(BaseRegTok.getLoc(), "register expected");
692    return true;
693  }
694  int BaseRegNum = TryParseRegister();
695  if (BaseRegNum == -1) {
696    Error(BaseRegTok.getLoc(), "register expected");
697    return true;
698  }
699
700  bool Preindexed = false;
701  bool Postindexed = false;
702  bool OffsetIsReg = false;
703  bool Negative = false;
704  bool Writeback = false;
705
706  // First look for preindexed address forms, that is after the "[Rn" we now
707  // have to see if the next token is a comma.
708  const AsmToken &Tok = Parser.getTok();
709  if (Tok.is(AsmToken::Comma)) {
710    Preindexed = true;
711    Parser.Lex(); // Eat comma token.
712    int OffsetRegNum;
713    bool OffsetRegShifted;
714    enum ShiftType ShiftType;
715    const MCExpr *ShiftAmount = 0;
716    const MCExpr *Offset = 0;
717    if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
718                             Offset, OffsetIsReg, OffsetRegNum, E))
719      return true;
720    const AsmToken &RBracTok = Parser.getTok();
721    if (RBracTok.isNot(AsmToken::RBrac)) {
722      Error(RBracTok.getLoc(), "']' expected");
723      return true;
724    }
725    E = RBracTok.getLoc();
726    Parser.Lex(); // Eat right bracket token.
727
728
729    const AsmToken &ExclaimTok = Parser.getTok();
730    ARMOperand *WBOp = 0;
731    if (ExclaimTok.is(AsmToken::Exclaim)) {
732      WBOp = ARMOperand::CreateToken(ExclaimTok.getString(),
733                                     ExclaimTok.getLoc());
734      Writeback = true;
735      Parser.Lex(); // Eat exclaim token
736    }
737
738    Operands.push_back(ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset,
739                                             OffsetRegNum, OffsetRegShifted,
740                                             ShiftType, ShiftAmount, Preindexed,
741                                             Postindexed, Negative, Writeback,
742                                             S, E));
743    if (WBOp)
744      Operands.push_back(WBOp);
745
746    return false;
747  }
748  // The "[Rn" we have so far was not followed by a comma.
749  else if (Tok.is(AsmToken::RBrac)) {
750    // If there's anything other than the right brace, this is a post indexing
751    // addressing form.
752    E = Tok.getLoc();
753    Parser.Lex(); // Eat right bracket token.
754
755    int OffsetRegNum = 0;
756    bool OffsetRegShifted = false;
757    enum ShiftType ShiftType = Lsl;
758    const MCExpr *ShiftAmount = 0;
759    const MCExpr *Offset = 0;
760
761    const AsmToken &NextTok = Parser.getTok();
762
763    if (NextTok.isNot(AsmToken::EndOfStatement)) {
764      Postindexed = true;
765      Writeback = true;
766
767      if (NextTok.isNot(AsmToken::Comma)) {
768        Error(NextTok.getLoc(), "',' expected");
769        return true;
770      }
771
772      Parser.Lex(); // Eat comma token.
773
774      if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
775                               ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
776                               E))
777        return true;
778    }
779
780    Operands.push_back(ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset,
781                                             OffsetRegNum, OffsetRegShifted,
782                                             ShiftType, ShiftAmount, Preindexed,
783                                             Postindexed, Negative, Writeback,
784                                             S, E));
785    return false;
786  }
787
788  return true;
789}
790
791/// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
792/// we will parse the following (were +/- means that a plus or minus is
793/// optional):
794///   +/-Rm
795///   +/-Rm, shift
796///   #offset
797/// we return false on success or an error otherwise.
798bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
799                                        bool &OffsetRegShifted,
800                                        enum ShiftType &ShiftType,
801                                        const MCExpr *&ShiftAmount,
802                                        const MCExpr *&Offset,
803                                        bool &OffsetIsReg,
804                                        int &OffsetRegNum,
805                                        SMLoc &E) {
806  Negative = false;
807  OffsetRegShifted = false;
808  OffsetIsReg = false;
809  OffsetRegNum = -1;
810  const AsmToken &NextTok = Parser.getTok();
811  E = NextTok.getLoc();
812  if (NextTok.is(AsmToken::Plus))
813    Parser.Lex(); // Eat plus token.
814  else if (NextTok.is(AsmToken::Minus)) {
815    Negative = true;
816    Parser.Lex(); // Eat minus token
817  }
818  // See if there is a register following the "[Rn," or "[Rn]," we have so far.
819  const AsmToken &OffsetRegTok = Parser.getTok();
820  if (OffsetRegTok.is(AsmToken::Identifier)) {
821    SMLoc CurLoc = OffsetRegTok.getLoc();
822    OffsetRegNum = TryParseRegister();
823    if (OffsetRegNum != -1) {
824      OffsetIsReg = true;
825      E = CurLoc;
826    }
827  }
828
829  // If we parsed a register as the offset then there can be a shift after that.
830  if (OffsetRegNum != -1) {
831    // Look for a comma then a shift
832    const AsmToken &Tok = Parser.getTok();
833    if (Tok.is(AsmToken::Comma)) {
834      Parser.Lex(); // Eat comma token.
835
836      const AsmToken &Tok = Parser.getTok();
837      if (ParseShift(ShiftType, ShiftAmount, E))
838        return Error(Tok.getLoc(), "shift expected");
839      OffsetRegShifted = true;
840    }
841  }
842  else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
843    // Look for #offset following the "[Rn," or "[Rn],"
844    const AsmToken &HashTok = Parser.getTok();
845    if (HashTok.isNot(AsmToken::Hash))
846      return Error(HashTok.getLoc(), "'#' expected");
847
848    Parser.Lex(); // Eat hash token.
849
850    if (getParser().ParseExpression(Offset))
851     return true;
852    E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
853  }
854  return false;
855}
856
857/// ParseShift as one of these two:
858///   ( lsl | lsr | asr | ror ) , # shift_amount
859///   rrx
860/// and returns true if it parses a shift otherwise it returns false.
861bool ARMAsmParser::ParseShift(ShiftType &St, const MCExpr *&ShiftAmount,
862                              SMLoc &E) {
863  const AsmToken &Tok = Parser.getTok();
864  if (Tok.isNot(AsmToken::Identifier))
865    return true;
866  StringRef ShiftName = Tok.getString();
867  if (ShiftName == "lsl" || ShiftName == "LSL")
868    St = Lsl;
869  else if (ShiftName == "lsr" || ShiftName == "LSR")
870    St = Lsr;
871  else if (ShiftName == "asr" || ShiftName == "ASR")
872    St = Asr;
873  else if (ShiftName == "ror" || ShiftName == "ROR")
874    St = Ror;
875  else if (ShiftName == "rrx" || ShiftName == "RRX")
876    St = Rrx;
877  else
878    return true;
879  Parser.Lex(); // Eat shift type token.
880
881  // Rrx stands alone.
882  if (St == Rrx)
883    return false;
884
885  // Otherwise, there must be a '#' and a shift amount.
886  const AsmToken &HashTok = Parser.getTok();
887  if (HashTok.isNot(AsmToken::Hash))
888    return Error(HashTok.getLoc(), "'#' expected");
889  Parser.Lex(); // Eat hash token.
890
891  if (getParser().ParseExpression(ShiftAmount))
892    return true;
893
894  return false;
895}
896
897/// Parse a arm instruction operand.  For now this parses the operand regardless
898/// of the mnemonic.
899bool ARMAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
900                                bool isMCR){
901  SMLoc S, E;
902  switch (getLexer().getKind()) {
903  default:
904    Error(Parser.getTok().getLoc(), "unexpected token in operand");
905    return true;
906  case AsmToken::Identifier:
907    if (!TryParseRegisterWithWriteBack(Operands))
908      return false;
909    if (isMCR && !TryParseMCRName(Operands))
910      return false;
911
912    // Fall though for the Identifier case that is not a register or a
913    // special name.
914  case AsmToken::Integer: // things like 1f and 2b as a branch targets
915  case AsmToken::Dot: {   // . as a branch target
916    // This was not a register so parse other operands that start with an
917    // identifier (like labels) as expressions and create them as immediates.
918    const MCExpr *IdVal;
919    S = Parser.getTok().getLoc();
920    if (getParser().ParseExpression(IdVal))
921      return true;
922    E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
923    Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
924    return false;
925  }
926  case AsmToken::LBrac:
927    return ParseMemory(Operands);
928  case AsmToken::LCurly:
929    return ParseRegisterList(Operands);
930  case AsmToken::Hash:
931    // #42 -> immediate.
932    // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
933    S = Parser.getTok().getLoc();
934    Parser.Lex();
935    const MCExpr *ImmVal;
936    if (getParser().ParseExpression(ImmVal))
937      return true;
938    E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
939    Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
940    return false;
941  case AsmToken::Colon: {
942    // ":lower16:" and ":upper16:" expression prefixes
943    // FIXME: Check it's an expression prefix,
944    // e.g. (FOO - :lower16:BAR) isn't legal.
945    ARMMCExpr::VariantKind RefKind;
946    if (ParsePrefix(RefKind))
947      return true;
948
949    const MCExpr *SubExprVal;
950    if (getParser().ParseExpression(SubExprVal))
951      return true;
952
953    const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
954                                                   getContext());
955    E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
956    Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
957    return false;
958  }
959  }
960}
961
962// ParsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
963//  :lower16: and :upper16:.
964bool ARMAsmParser::ParsePrefix(ARMMCExpr::VariantKind &RefKind) {
965  RefKind = ARMMCExpr::VK_ARM_None;
966
967  // :lower16: and :upper16: modifiers
968  assert(getLexer().is(AsmToken::Colon) && "expected a :");
969  Parser.Lex(); // Eat ':'
970
971  if (getLexer().isNot(AsmToken::Identifier)) {
972    Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
973    return true;
974  }
975
976  StringRef IDVal = Parser.getTok().getIdentifier();
977  if (IDVal == "lower16") {
978    RefKind = ARMMCExpr::VK_ARM_LO16;
979  } else if (IDVal == "upper16") {
980    RefKind = ARMMCExpr::VK_ARM_HI16;
981  } else {
982    Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
983    return true;
984  }
985  Parser.Lex();
986
987  if (getLexer().isNot(AsmToken::Colon)) {
988    Error(Parser.getTok().getLoc(), "unexpected token after prefix");
989    return true;
990  }
991  Parser.Lex(); // Eat the last ':'
992  return false;
993}
994
995const MCExpr *
996ARMAsmParser::ApplyPrefixToExpr(const MCExpr *E,
997                                MCSymbolRefExpr::VariantKind Variant) {
998  // Recurse over the given expression, rebuilding it to apply the given variant
999  // to the leftmost symbol.
1000  if (Variant == MCSymbolRefExpr::VK_None)
1001    return E;
1002
1003  switch (E->getKind()) {
1004  case MCExpr::Target:
1005    llvm_unreachable("Can't handle target expr yet");
1006  case MCExpr::Constant:
1007    llvm_unreachable("Can't handle lower16/upper16 of constant yet");
1008
1009  case MCExpr::SymbolRef: {
1010    const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1011
1012    if (SRE->getKind() != MCSymbolRefExpr::VK_None)
1013      return 0;
1014
1015    return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
1016  }
1017
1018  case MCExpr::Unary:
1019    llvm_unreachable("Can't handle unary expressions yet");
1020
1021  case MCExpr::Binary: {
1022    const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1023    const MCExpr *LHS = ApplyPrefixToExpr(BE->getLHS(), Variant);
1024    const MCExpr *RHS = BE->getRHS();
1025    if (!LHS)
1026      return 0;
1027
1028    return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1029  }
1030  }
1031
1032  assert(0 && "Invalid expression kind!");
1033  return 0;
1034}
1035
1036/// \brief Given a mnemonic, split out possible predication code and carry
1037/// setting letters to form a canonical mnemonic and flags.
1038//
1039// FIXME: Would be nice to autogen this.
1040static StringRef SplitMnemonicAndCC(StringRef Mnemonic,
1041                                    unsigned &PredicationCode,
1042                                    bool &CarrySetting) {
1043  PredicationCode = ARMCC::AL;
1044  CarrySetting = false;
1045
1046  // Ignore some mnemonics we know aren't predicated forms.
1047  //
1048  // FIXME: Would be nice to autogen this.
1049  if (Mnemonic == "teq" || Mnemonic == "vceq" ||
1050      Mnemonic == "movs" ||
1051      Mnemonic == "svc" ||
1052      (Mnemonic == "mls" || Mnemonic == "smmls" || Mnemonic == "vcls" ||
1053       Mnemonic == "vmls" || Mnemonic == "vnmls") ||
1054      Mnemonic == "vacge" || Mnemonic == "vcge" ||
1055      Mnemonic == "vclt" ||
1056      Mnemonic == "vacgt" || Mnemonic == "vcgt" ||
1057      Mnemonic == "vcle" ||
1058      (Mnemonic == "smlal" || Mnemonic == "umaal" || Mnemonic == "umlal" ||
1059       Mnemonic == "vabal" || Mnemonic == "vmlal" || Mnemonic == "vpadal" ||
1060       Mnemonic == "vqdmlal"))
1061    return Mnemonic;
1062
1063  // First, split out any predication code.
1064  unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
1065    .Case("eq", ARMCC::EQ)
1066    .Case("ne", ARMCC::NE)
1067    .Case("hs", ARMCC::HS)
1068    .Case("lo", ARMCC::LO)
1069    .Case("mi", ARMCC::MI)
1070    .Case("pl", ARMCC::PL)
1071    .Case("vs", ARMCC::VS)
1072    .Case("vc", ARMCC::VC)
1073    .Case("hi", ARMCC::HI)
1074    .Case("ls", ARMCC::LS)
1075    .Case("ge", ARMCC::GE)
1076    .Case("lt", ARMCC::LT)
1077    .Case("gt", ARMCC::GT)
1078    .Case("le", ARMCC::LE)
1079    .Case("al", ARMCC::AL)
1080    .Default(~0U);
1081  if (CC != ~0U) {
1082    Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
1083    PredicationCode = CC;
1084  }
1085
1086  // Next, determine if we have a carry setting bit. We explicitly ignore all
1087  // the instructions we know end in 's'.
1088  if (Mnemonic.endswith("s") &&
1089      !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" ||
1090        Mnemonic == "movs" || Mnemonic == "mrs" || Mnemonic == "smmls" ||
1091        Mnemonic == "vabs" || Mnemonic == "vcls" || Mnemonic == "vmls" ||
1092        Mnemonic == "vmrs" || Mnemonic == "vnmls" || Mnemonic == "vqabs" ||
1093        Mnemonic == "vrecps" || Mnemonic == "vrsqrts")) {
1094    Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
1095    CarrySetting = true;
1096  }
1097
1098  return Mnemonic;
1099}
1100
1101/// \brief Given a canonical mnemonic, determine if the instruction ever allows
1102/// inclusion of carry set or predication code operands.
1103//
1104// FIXME: It would be nice to autogen this.
1105static void GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
1106                                  bool &CanAcceptPredicationCode) {
1107  if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
1108      Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
1109      Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" ||
1110      Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
1111      Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mov" ||
1112      Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
1113      Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" ||
1114      Mnemonic == "eor" || Mnemonic == "smlal" || Mnemonic == "mvn") {
1115    CanAcceptCarrySet = true;
1116  } else {
1117    CanAcceptCarrySet = false;
1118  }
1119
1120  if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
1121      Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
1122      Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
1123      Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
1124      Mnemonic == "dsb" || Mnemonic == "movs") {
1125    CanAcceptPredicationCode = false;
1126  } else {
1127    CanAcceptPredicationCode = true;
1128  }
1129}
1130
1131/// Parse an arm instruction mnemonic followed by its operands.
1132bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
1133                               SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1134  // Create the leading tokens for the mnemonic, split by '.' characters.
1135  size_t Start = 0, Next = Name.find('.');
1136  StringRef Head = Name.slice(Start, Next);
1137
1138  // Split out the predication code and carry setting flag from the mnemonic.
1139  unsigned PredicationCode;
1140  bool CarrySetting;
1141  Head = SplitMnemonicAndCC(Head, PredicationCode, CarrySetting);
1142
1143  Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1144
1145  // Next, add the CCOut and ConditionCode operands, if needed.
1146  //
1147  // For mnemonics which can ever incorporate a carry setting bit or predication
1148  // code, our matching model involves us always generating CCOut and
1149  // ConditionCode operands to match the mnemonic "as written" and then we let
1150  // the matcher deal with finding the right instruction or generating an
1151  // appropriate error.
1152  bool CanAcceptCarrySet, CanAcceptPredicationCode;
1153  GetMnemonicAcceptInfo(Head, CanAcceptCarrySet, CanAcceptPredicationCode);
1154
1155  // Add the carry setting operand, if necessary.
1156  //
1157  // FIXME: It would be awesome if we could somehow invent a location such that
1158  // match errors on this operand would print a nice diagnostic about how the
1159  // 's' character in the mnemonic resulted in a CCOut operand.
1160  if (CanAcceptCarrySet) {
1161    Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
1162                                               NameLoc));
1163  } else {
1164    // This mnemonic can't ever accept a carry set, but the user wrote one (or
1165    // misspelled another mnemonic).
1166
1167    // FIXME: Issue a nice error.
1168  }
1169
1170  // Add the predication code operand, if necessary.
1171  if (CanAcceptPredicationCode) {
1172    Operands.push_back(ARMOperand::CreateCondCode(
1173                         ARMCC::CondCodes(PredicationCode), NameLoc));
1174  } else {
1175    // This mnemonic can't ever accept a predication code, but the user wrote
1176    // one (or misspelled another mnemonic).
1177
1178    // FIXME: Issue a nice error.
1179  }
1180
1181  // Add the remaining tokens in the mnemonic.
1182  while (Next != StringRef::npos) {
1183    Start = Next;
1184    Next = Name.find('.', Start + 1);
1185    Head = Name.slice(Start, Next);
1186
1187    Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1188  }
1189
1190  bool isMCR = (Head == "mcr"  || Head == "mcr2" ||
1191                Head == "mcrr" || Head == "mcrr2" ||
1192                Head == "mrc"  || Head == "mrc2" ||
1193                Head == "mrrc" || Head == "mrrc2");
1194
1195  // Read the remaining operands.
1196  if (getLexer().isNot(AsmToken::EndOfStatement)) {
1197    // Read the first operand.
1198    if (ParseOperand(Operands, isMCR)) {
1199      Parser.EatToEndOfStatement();
1200      return true;
1201    }
1202
1203    while (getLexer().is(AsmToken::Comma)) {
1204      Parser.Lex();  // Eat the comma.
1205
1206      // Parse and remember the operand.
1207      if (ParseOperand(Operands, isMCR)) {
1208        Parser.EatToEndOfStatement();
1209        return true;
1210      }
1211    }
1212  }
1213
1214  if (getLexer().isNot(AsmToken::EndOfStatement)) {
1215    Parser.EatToEndOfStatement();
1216    return TokError("unexpected token in argument list");
1217  }
1218
1219  Parser.Lex(); // Consume the EndOfStatement
1220  return false;
1221}
1222
1223bool ARMAsmParser::
1224MatchAndEmitInstruction(SMLoc IDLoc,
1225                        SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1226                        MCStreamer &Out) {
1227  MCInst Inst;
1228  unsigned ErrorInfo;
1229  MatchResultTy MatchResult, MatchResult2;
1230  MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1231  if (MatchResult != Match_Success) {
1232    // If we get a Match_InvalidOperand it might be some arithmetic instruction
1233    // that does not update the condition codes.  So try adding a CCOut operand
1234    // with a value of reg0.
1235    if (MatchResult == Match_InvalidOperand) {
1236      Operands.insert(Operands.begin() + 1,
1237                      ARMOperand::CreateCCOut(0,
1238                                  ((ARMOperand*)Operands[0])->getStartLoc()));
1239      MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1240      if (MatchResult2 == Match_Success)
1241        MatchResult = Match_Success;
1242      else {
1243        ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1244        Operands.erase(Operands.begin() + 1);
1245        delete CCOut;
1246      }
1247    }
1248    // If we get a Match_MnemonicFail it might be some arithmetic instruction
1249    // that updates the condition codes if it ends in 's'.  So see if the
1250    // mnemonic ends in 's' and if so try removing the 's' and adding a CCOut
1251    // operand with a value of CPSR.
1252    else if(MatchResult == Match_MnemonicFail) {
1253      // Get the instruction mnemonic, which is the first token.
1254      StringRef Mnemonic = ((ARMOperand*)Operands[0])->getToken();
1255      if (Mnemonic.substr(Mnemonic.size()-1) == "s") {
1256        // removed the 's' from the mnemonic for matching.
1257        StringRef MnemonicNoS = Mnemonic.slice(0, Mnemonic.size() - 1);
1258        SMLoc NameLoc = ((ARMOperand*)Operands[0])->getStartLoc();
1259        ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1260        Operands.erase(Operands.begin());
1261        delete OldMnemonic;
1262        Operands.insert(Operands.begin(),
1263                        ARMOperand::CreateToken(MnemonicNoS, NameLoc));
1264        Operands.insert(Operands.begin() + 1,
1265                        ARMOperand::CreateCCOut(ARM::CPSR, NameLoc));
1266        MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1267        if (MatchResult2 == Match_Success)
1268          MatchResult = Match_Success;
1269        else {
1270          ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1271          Operands.erase(Operands.begin());
1272          delete OldMnemonic;
1273          Operands.insert(Operands.begin(),
1274                          ARMOperand::CreateToken(Mnemonic, NameLoc));
1275          ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1276          Operands.erase(Operands.begin() + 1);
1277          delete CCOut;
1278        }
1279      }
1280    }
1281  }
1282  switch (MatchResult) {
1283  case Match_Success:
1284    Out.EmitInstruction(Inst);
1285    return false;
1286  case Match_MissingFeature:
1287    Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1288    return true;
1289  case Match_InvalidOperand: {
1290    SMLoc ErrorLoc = IDLoc;
1291    if (ErrorInfo != ~0U) {
1292      if (ErrorInfo >= Operands.size())
1293        return Error(IDLoc, "too few operands for instruction");
1294
1295      ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
1296      if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1297    }
1298
1299    return Error(ErrorLoc, "invalid operand for instruction");
1300  }
1301  case Match_MnemonicFail:
1302    return Error(IDLoc, "unrecognized instruction mnemonic");
1303  }
1304
1305  llvm_unreachable("Implement any new match types added!");
1306  return true;
1307}
1308
1309/// ParseDirective parses the arm specific directives
1310bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
1311  StringRef IDVal = DirectiveID.getIdentifier();
1312  if (IDVal == ".word")
1313    return ParseDirectiveWord(4, DirectiveID.getLoc());
1314  else if (IDVal == ".thumb")
1315    return ParseDirectiveThumb(DirectiveID.getLoc());
1316  else if (IDVal == ".thumb_func")
1317    return ParseDirectiveThumbFunc(DirectiveID.getLoc());
1318  else if (IDVal == ".code")
1319    return ParseDirectiveCode(DirectiveID.getLoc());
1320  else if (IDVal == ".syntax")
1321    return ParseDirectiveSyntax(DirectiveID.getLoc());
1322  return true;
1323}
1324
1325/// ParseDirectiveWord
1326///  ::= .word [ expression (, expression)* ]
1327bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1328  if (getLexer().isNot(AsmToken::EndOfStatement)) {
1329    for (;;) {
1330      const MCExpr *Value;
1331      if (getParser().ParseExpression(Value))
1332        return true;
1333
1334      getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
1335
1336      if (getLexer().is(AsmToken::EndOfStatement))
1337        break;
1338
1339      // FIXME: Improve diagnostic.
1340      if (getLexer().isNot(AsmToken::Comma))
1341        return Error(L, "unexpected token in directive");
1342      Parser.Lex();
1343    }
1344  }
1345
1346  Parser.Lex();
1347  return false;
1348}
1349
1350/// ParseDirectiveThumb
1351///  ::= .thumb
1352bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
1353  if (getLexer().isNot(AsmToken::EndOfStatement))
1354    return Error(L, "unexpected token in directive");
1355  Parser.Lex();
1356
1357  // TODO: set thumb mode
1358  // TODO: tell the MC streamer the mode
1359  // getParser().getStreamer().Emit???();
1360  return false;
1361}
1362
1363/// ParseDirectiveThumbFunc
1364///  ::= .thumbfunc symbol_name
1365bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
1366  const AsmToken &Tok = Parser.getTok();
1367  if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
1368    return Error(L, "unexpected token in .thumb_func directive");
1369  StringRef Name = Tok.getString();
1370  Parser.Lex(); // Consume the identifier token.
1371  if (getLexer().isNot(AsmToken::EndOfStatement))
1372    return Error(L, "unexpected token in directive");
1373  Parser.Lex();
1374
1375  // Mark symbol as a thumb symbol.
1376  MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
1377  getParser().getStreamer().EmitThumbFunc(Func);
1378  return false;
1379}
1380
1381/// ParseDirectiveSyntax
1382///  ::= .syntax unified | divided
1383bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
1384  const AsmToken &Tok = Parser.getTok();
1385  if (Tok.isNot(AsmToken::Identifier))
1386    return Error(L, "unexpected token in .syntax directive");
1387  StringRef Mode = Tok.getString();
1388  if (Mode == "unified" || Mode == "UNIFIED")
1389    Parser.Lex();
1390  else if (Mode == "divided" || Mode == "DIVIDED")
1391    Parser.Lex();
1392  else
1393    return Error(L, "unrecognized syntax mode in .syntax directive");
1394
1395  if (getLexer().isNot(AsmToken::EndOfStatement))
1396    return Error(Parser.getTok().getLoc(), "unexpected token in directive");
1397  Parser.Lex();
1398
1399  // TODO tell the MC streamer the mode
1400  // getParser().getStreamer().Emit???();
1401  return false;
1402}
1403
1404/// ParseDirectiveCode
1405///  ::= .code 16 | 32
1406bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
1407  const AsmToken &Tok = Parser.getTok();
1408  if (Tok.isNot(AsmToken::Integer))
1409    return Error(L, "unexpected token in .code directive");
1410  int64_t Val = Parser.getTok().getIntVal();
1411  if (Val == 16)
1412    Parser.Lex();
1413  else if (Val == 32)
1414    Parser.Lex();
1415  else
1416    return Error(L, "invalid operand to .code directive");
1417
1418  if (getLexer().isNot(AsmToken::EndOfStatement))
1419    return Error(Parser.getTok().getLoc(), "unexpected token in directive");
1420  Parser.Lex();
1421
1422  // FIXME: We need to be able switch subtargets at this point so that
1423  // MatchInstructionImpl() will work when it gets the AvailableFeatures which
1424  // includes Feature_IsThumb or not to match the right instructions.  This is
1425  // blocked on the FIXME in llvm-mc.cpp when creating the TargetMachine.
1426  if (Val == 16){
1427    assert(TM.getSubtarget<ARMSubtarget>().isThumb() &&
1428	   "switching between arm/thumb not yet suppported via .code 16)");
1429    getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
1430  }
1431  else{
1432    assert(!TM.getSubtarget<ARMSubtarget>().isThumb() &&
1433           "switching between thumb/arm not yet suppported via .code 32)");
1434    getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1435   }
1436
1437  return false;
1438}
1439
1440extern "C" void LLVMInitializeARMAsmLexer();
1441
1442/// Force static initialization.
1443extern "C" void LLVMInitializeARMAsmParser() {
1444  RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
1445  RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);
1446  LLVMInitializeARMAsmLexer();
1447}
1448
1449#define GET_REGISTER_MATCHER
1450#define GET_MATCHER_IMPLEMENTATION
1451#include "ARMGenAsmMatcher.inc"
1452