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