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