General cleanup:
[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 "ARMSubtarget.h"
13 #include "llvm/MC/MCParser/MCAsmLexer.h"
14 #include "llvm/MC/MCParser/MCAsmParser.h"
15 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCStreamer.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/Target/TargetRegistry.h"
21 #include "llvm/Target/TargetAsmParser.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Twine.h"
27 using namespace llvm;
28
29 // The shift types for register controlled shifts in arm memory addressing
30 enum ShiftType {
31   Lsl,
32   Lsr,
33   Asr,
34   Ror,
35   Rrx
36 };
37
38 namespace {
39
40 class ARMOperand;
41
42 class ARMAsmParser : public TargetAsmParser {
43   MCAsmParser &Parser;
44   TargetMachine &TM;
45
46   MCAsmParser &getParser() const { return Parser; }
47   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
48
49   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
50   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
51
52   int TryParseRegister();
53   ARMOperand *TryParseRegisterWithWriteBack();
54   ARMOperand *ParseRegisterList();
55   ARMOperand *ParseMemory();
56   ARMOperand *ParseOperand();
57
58   bool ParseMemoryOffsetReg(bool &Negative,
59                             bool &OffsetRegShifted,
60                             enum ShiftType &ShiftType,
61                             const MCExpr *&ShiftAmount,
62                             const MCExpr *&Offset,
63                             bool &OffsetIsReg,
64                             int &OffsetRegNum,
65                             SMLoc &E);
66   bool ParseShift(enum ShiftType &St, const MCExpr *&ShiftAmount, SMLoc &E);
67   bool ParseDirectiveWord(unsigned Size, SMLoc L);
68   bool ParseDirectiveThumb(SMLoc L);
69   bool ParseDirectiveThumbFunc(SMLoc L);
70   bool ParseDirectiveCode(SMLoc L);
71   bool ParseDirectiveSyntax(SMLoc L);
72
73   bool MatchAndEmitInstruction(SMLoc IDLoc,
74                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
75                                MCStreamer &Out);
76
77   /// @name Auto-generated Match Functions
78   /// {
79
80 #define GET_ASSEMBLER_HEADER
81 #include "ARMGenAsmMatcher.inc"
82
83   /// }
84
85
86 public:
87   ARMAsmParser(const Target &T, MCAsmParser &_Parser, TargetMachine &_TM)
88     : TargetAsmParser(T), Parser(_Parser), TM(_TM) {
89       // Initialize the set of available features.
90       setAvailableFeatures(ComputeAvailableFeatures(
91           &TM.getSubtarget<ARMSubtarget>()));
92     }
93
94   virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
95                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
96
97   virtual bool ParseDirective(AsmToken DirectiveID);
98 };
99 } // end anonymous namespace
100
101 namespace {
102
103 /// ARMOperand - Instances of this class represent a parsed ARM machine
104 /// instruction.
105 class ARMOperand : public MCParsedAsmOperand {
106   enum KindTy {
107     CondCode,
108     Immediate,
109     Memory,
110     Register,
111     RegisterList,
112     Token
113   } Kind;
114
115   SMLoc StartLoc, EndLoc;
116
117   union {
118     struct {
119       ARMCC::CondCodes Val;
120     } CC;
121
122     struct {
123       const char *Data;
124       unsigned Length;
125     } Tok;
126
127     struct {
128       unsigned RegNum;
129       bool Writeback;
130     } Reg;
131
132      struct {
133       unsigned RegStart;
134       unsigned Number;
135     } RegList;
136
137     struct {
138       const MCExpr *Val;
139     } Imm;
140
141     // This is for all forms of ARM address expressions
142     struct {
143       unsigned BaseRegNum;
144       unsigned OffsetRegNum;         // used when OffsetIsReg is true
145       const MCExpr *Offset;          // used when OffsetIsReg is false
146       const MCExpr *ShiftAmount;     // used when OffsetRegShifted is true
147       enum ShiftType ShiftType;      // used when OffsetRegShifted is true
148       unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
149       unsigned Preindexed : 1;
150       unsigned Postindexed : 1;
151       unsigned OffsetIsReg : 1;
152       unsigned Negative : 1;         // only used when OffsetIsReg is true
153       unsigned Writeback : 1;
154     } Mem;
155   };
156
157   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
158 public:
159   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
160     Kind = o.Kind;
161     StartLoc = o.StartLoc;
162     EndLoc = o.EndLoc;
163     switch (Kind) {
164     case CondCode:
165       CC = o.CC;
166       break;
167     case Token:
168       Tok = o.Tok;
169       break;
170     case Register:
171       Reg = o.Reg;
172       break;
173     case RegisterList:
174       RegList = o.RegList;
175       break;
176     case Immediate:
177       Imm = o.Imm;
178       break;
179     case Memory:
180       Mem = o.Mem;
181       break;
182     }
183   }
184
185   /// getStartLoc - Get the location of the first token of this operand.
186   SMLoc getStartLoc() const { return StartLoc; }
187   /// getEndLoc - Get the location of the last token of this operand.
188   SMLoc getEndLoc() const { return EndLoc; }
189
190   ARMCC::CondCodes getCondCode() const {
191     assert(Kind == CondCode && "Invalid access!");
192     return CC.Val;
193   }
194
195   StringRef getToken() const {
196     assert(Kind == Token && "Invalid access!");
197     return StringRef(Tok.Data, Tok.Length);
198   }
199
200   unsigned getReg() const {
201     assert(Kind == Register && "Invalid access!");
202     return Reg.RegNum;
203   }
204
205   std::pair<unsigned, unsigned> getRegList() const {
206     assert(Kind == RegisterList && "Invalid access!");
207     return std::make_pair(RegList.RegStart, RegList.Number);
208   }
209
210   const MCExpr *getImm() const {
211     assert(Kind == Immediate && "Invalid access!");
212     return Imm.Val;
213   }
214
215   bool isCondCode() const { return Kind == CondCode; }
216   bool isImm() const { return Kind == Immediate; }
217   bool isReg() const { return Kind == Register; }
218   bool isRegList() const { return Kind == RegisterList; }
219   bool isToken() const { return Kind == Token; }
220   bool isMemory() const { return Kind == Memory; }
221
222   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
223     // Add as immediates when possible.  Null MCExpr = 0.
224     if (Expr == 0)
225       Inst.addOperand(MCOperand::CreateImm(0));
226     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
227       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
228     else
229       Inst.addOperand(MCOperand::CreateExpr(Expr));
230   }
231
232   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
233     assert(N == 2 && "Invalid number of operands!");
234     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
235     // FIXME: What belongs here?
236     Inst.addOperand(MCOperand::CreateReg(0));
237   }
238
239   void addRegOperands(MCInst &Inst, unsigned N) const {
240     assert(N == 1 && "Invalid number of operands!");
241     Inst.addOperand(MCOperand::CreateReg(getReg()));
242   }
243
244   void addImmOperands(MCInst &Inst, unsigned N) const {
245     assert(N == 1 && "Invalid number of operands!");
246     addExpr(Inst, getImm());
247   }
248
249   bool isMemMode5() const {
250     if (!isMemory() || Mem.OffsetIsReg || Mem.OffsetRegShifted ||
251         Mem.Writeback || Mem.Negative)
252       return false;
253     // If there is an offset expression, make sure it's valid.
254     if (!Mem.Offset)
255       return true;
256     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
257     if (!CE)
258       return false;
259     // The offset must be a multiple of 4 in the range 0-1020.
260     int64_t Value = CE->getValue();
261     return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
262   }
263
264   void addMemMode5Operands(MCInst &Inst, unsigned N) const {
265     assert(N == 2 && isMemMode5() && "Invalid number of operands!");
266
267     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
268     assert(!Mem.OffsetIsReg && "Invalid mode 5 operand");
269
270     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
271     // the difference?
272     if (Mem.Offset) {
273       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.Offset);
274       assert(CE && "Non-constant mode 5 offset operand!");
275
276       // The MCInst offset operand doesn't include the low two bits (like
277       // the instruction encoding).
278       int64_t Offset = CE->getValue() / 4;
279       if (Offset >= 0)
280         Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
281                                                                Offset)));
282       else
283         Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
284                                                                -Offset)));
285     } else {
286       Inst.addOperand(MCOperand::CreateImm(0));
287     }
288   }
289
290   virtual void dump(raw_ostream &OS) const;
291
292   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
293     ARMOperand *Op = new ARMOperand(CondCode);
294     Op->CC.Val = CC;
295     Op->StartLoc = S;
296     Op->EndLoc = S;
297     return Op;
298   }
299
300   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
301     ARMOperand *Op = new ARMOperand(Token);
302     Op->Tok.Data = Str.data();
303     Op->Tok.Length = Str.size();
304     Op->StartLoc = S;
305     Op->EndLoc = S;
306     return Op;
307   }
308
309   static ARMOperand *CreateReg(unsigned RegNum, bool Writeback, SMLoc S,
310                                SMLoc E) {
311     ARMOperand *Op = new ARMOperand(Register);
312     Op->Reg.RegNum = RegNum;
313     Op->Reg.Writeback = Writeback;
314     Op->StartLoc = S;
315     Op->EndLoc = E;
316     return Op;
317   }
318
319   static ARMOperand *CreateRegList(unsigned RegStart, unsigned Number,
320                                    SMLoc S, SMLoc E) {
321     ARMOperand *Op = new ARMOperand(RegisterList);
322     Op->RegList.RegStart = RegStart;
323     Op->RegList.Number = Number;
324     Op->StartLoc = S;
325     Op->EndLoc = E;
326     return Op;
327   }
328
329   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
330     ARMOperand *Op = new ARMOperand(Immediate);
331     Op->Imm.Val = Val;
332     Op->StartLoc = S;
333     Op->EndLoc = E;
334     return Op;
335   }
336
337   static ARMOperand *CreateMem(unsigned BaseRegNum, bool OffsetIsReg,
338                                const MCExpr *Offset, unsigned OffsetRegNum,
339                                bool OffsetRegShifted, enum ShiftType ShiftType,
340                                const MCExpr *ShiftAmount, bool Preindexed,
341                                bool Postindexed, bool Negative, bool Writeback,
342                                SMLoc S, SMLoc E) {
343     ARMOperand *Op = new ARMOperand(Memory);
344     Op->Mem.BaseRegNum = BaseRegNum;
345     Op->Mem.OffsetIsReg = OffsetIsReg;
346     Op->Mem.Offset = Offset;
347     Op->Mem.OffsetRegNum = OffsetRegNum;
348     Op->Mem.OffsetRegShifted = OffsetRegShifted;
349     Op->Mem.ShiftType = ShiftType;
350     Op->Mem.ShiftAmount = ShiftAmount;
351     Op->Mem.Preindexed = Preindexed;
352     Op->Mem.Postindexed = Postindexed;
353     Op->Mem.Negative = Negative;
354     Op->Mem.Writeback = Writeback;
355
356     Op->StartLoc = S;
357     Op->EndLoc = E;
358     return Op;
359   }
360 };
361
362 } // end anonymous namespace.
363
364 void ARMOperand::dump(raw_ostream &OS) const {
365   switch (Kind) {
366   case CondCode:
367     OS << ARMCondCodeToString(getCondCode());
368     break;
369   case Immediate:
370     getImm()->print(OS);
371     break;
372   case Memory:
373     OS << "<memory>";
374     break;
375   case Register:
376     OS << "<register " << getReg() << ">";
377     break;
378   case RegisterList: {
379     OS << "<register_list ";
380     std::pair<unsigned, unsigned> List = getRegList();
381     unsigned RegEnd = List.first + List.second;
382
383     for (unsigned Idx = List.first; Idx < RegEnd; ) {
384       OS << Idx;
385       if (++Idx < RegEnd) OS << ", ";
386     }
387
388     OS << ">";
389     break;
390   }
391   case Token:
392     OS << "'" << getToken() << "'";
393     break;
394   }
395 }
396
397 /// @name Auto-generated Match Functions
398 /// {
399
400 static unsigned MatchRegisterName(StringRef Name);
401
402 /// }
403
404 /// Try to parse a register name.  The token must be an Identifier when called,
405 /// and if it is a register name the token is eaten and the register number is
406 /// returned.  Otherwise return -1.
407 ///
408 int ARMAsmParser::TryParseRegister() {
409   const AsmToken &Tok = Parser.getTok();
410   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
411
412   // FIXME: Validate register for the current architecture; we have to do
413   // validation later, so maybe there is no need for this here.
414   unsigned RegNum = MatchRegisterName(Tok.getString());
415   if (RegNum == 0)
416     return -1;
417   Parser.Lex(); // Eat identifier token.
418   return RegNum;
419 }
420
421
422 /// Try to parse a register name.  The token must be an Identifier when called,
423 /// and if it is a register name the token is eaten and the register number is
424 /// returned.  Otherwise return -1.
425 ///
426 /// TODO this is likely to change to allow different register types and or to
427 /// parse for a specific register type.
428 ARMOperand *ARMAsmParser::TryParseRegisterWithWriteBack() {
429   SMLoc S = Parser.getTok().getLoc();
430   int RegNo = TryParseRegister();
431   if (RegNo == -1) return 0;
432
433   SMLoc E = Parser.getTok().getLoc();
434
435   bool Writeback = false;
436   const AsmToken &ExclaimTok = Parser.getTok();
437   if (ExclaimTok.is(AsmToken::Exclaim)) {
438     E = ExclaimTok.getLoc();
439     Writeback = true;
440     Parser.Lex(); // Eat exclaim token
441   }
442
443   return ARMOperand::CreateReg(RegNo, Writeback, S, E);
444 }
445
446 /// Parse a register list, return it if successful else return null.  The first
447 /// token must be a '{' when called.
448 ARMOperand *ARMAsmParser::ParseRegisterList() {
449   SMLoc S, E;
450   assert(Parser.getTok().is(AsmToken::LCurly) &&
451          "Token is not a Left Curly Brace");
452   S = Parser.getTok().getLoc();
453   Parser.Lex(); // Eat left curly brace token.
454
455   const AsmToken &RegTok = Parser.getTok();
456   SMLoc RegLoc = RegTok.getLoc();
457   if (RegTok.isNot(AsmToken::Identifier)) {
458     Error(RegLoc, "register expected");
459     return 0;
460   }
461   int RegNum = TryParseRegister();
462   if (RegNum == -1) {
463     Error(RegLoc, "register expected");
464     return 0;
465   }
466
467   unsigned RegList = 1 << RegNum;
468
469   int HighRegNum = RegNum;
470   // TODO ranges like "{Rn-Rm}"
471   while (Parser.getTok().is(AsmToken::Comma)) {
472     Parser.Lex(); // Eat comma token.
473
474     const AsmToken &RegTok = Parser.getTok();
475     SMLoc RegLoc = RegTok.getLoc();
476     if (RegTok.isNot(AsmToken::Identifier)) {
477       Error(RegLoc, "register expected");
478       return 0;
479     }
480     int RegNum = TryParseRegister();
481     if (RegNum == -1) {
482       Error(RegLoc, "register expected");
483       return 0;
484     }
485
486     if (RegList & (1 << RegNum))
487       Warning(RegLoc, "register duplicated in register list");
488     else if (RegNum <= HighRegNum)
489       Warning(RegLoc, "register not in ascending order in register list");
490     RegList |= 1 << RegNum;
491     HighRegNum = RegNum;
492   }
493   const AsmToken &RCurlyTok = Parser.getTok();
494   if (RCurlyTok.isNot(AsmToken::RCurly)) {
495     Error(RCurlyTok.getLoc(), "'}' expected");
496     return 0;
497   }
498   E = RCurlyTok.getLoc();
499   Parser.Lex(); // Eat left curly brace token.
500
501   // FIXME: Need to return an operand!
502   Error(E, "FIXME: register list parsing not implemented");
503   return 0;
504 }
505
506 /// Parse an arm memory expression, return false if successful else return true
507 /// or an error.  The first token must be a '[' when called.
508 /// TODO Only preindexing and postindexing addressing are started, unindexed
509 /// with option, etc are still to do.
510 ARMOperand *ARMAsmParser::ParseMemory() {
511   SMLoc S, E;
512   assert(Parser.getTok().is(AsmToken::LBrac) &&
513          "Token is not a Left Bracket");
514   S = Parser.getTok().getLoc();
515   Parser.Lex(); // Eat left bracket token.
516
517   const AsmToken &BaseRegTok = Parser.getTok();
518   if (BaseRegTok.isNot(AsmToken::Identifier)) {
519     Error(BaseRegTok.getLoc(), "register expected");
520     return 0;
521   }
522   int BaseRegNum = TryParseRegister();
523   if (BaseRegNum == -1) {
524     Error(BaseRegTok.getLoc(), "register expected");
525     return 0;
526   }
527
528   bool Preindexed = false;
529   bool Postindexed = false;
530   bool OffsetIsReg = false;
531   bool Negative = false;
532   bool Writeback = false;
533
534   // First look for preindexed address forms, that is after the "[Rn" we now
535   // have to see if the next token is a comma.
536   const AsmToken &Tok = Parser.getTok();
537   if (Tok.is(AsmToken::Comma)) {
538     Preindexed = true;
539     Parser.Lex(); // Eat comma token.
540     int OffsetRegNum;
541     bool OffsetRegShifted;
542     enum ShiftType ShiftType;
543     const MCExpr *ShiftAmount;
544     const MCExpr *Offset;
545     if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
546                              Offset, OffsetIsReg, OffsetRegNum, E))
547       return 0;
548     const AsmToken &RBracTok = Parser.getTok();
549     if (RBracTok.isNot(AsmToken::RBrac)) {
550       Error(RBracTok.getLoc(), "']' expected");
551       return 0;
552     }
553     E = RBracTok.getLoc();
554     Parser.Lex(); // Eat right bracket token.
555
556     const AsmToken &ExclaimTok = Parser.getTok();
557     if (ExclaimTok.is(AsmToken::Exclaim)) {
558       E = ExclaimTok.getLoc();
559       Writeback = true;
560       Parser.Lex(); // Eat exclaim token
561     }
562     return ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset, OffsetRegNum,
563                                  OffsetRegShifted, ShiftType, ShiftAmount,
564                                  Preindexed, Postindexed, Negative, Writeback,
565                                  S, E);
566   }
567   // The "[Rn" we have so far was not followed by a comma.
568   else if (Tok.is(AsmToken::RBrac)) {
569     // If there's anything other than the right brace, this is a post indexing
570     // addressing form.
571     E = Tok.getLoc();
572     Parser.Lex(); // Eat right bracket token.
573
574     int OffsetRegNum = 0;
575     bool OffsetRegShifted = false;
576     enum ShiftType ShiftType;
577     const MCExpr *ShiftAmount;
578     const MCExpr *Offset = 0;
579
580     const AsmToken &NextTok = Parser.getTok();
581     if (NextTok.isNot(AsmToken::EndOfStatement)) {
582       Postindexed = true;
583       Writeback = true;
584       if (NextTok.isNot(AsmToken::Comma)) {
585         Error(NextTok.getLoc(), "',' expected");
586         return 0;
587       }
588       Parser.Lex(); // Eat comma token.
589       if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
590                                ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
591                                E))
592         return 0;
593     }
594
595     return ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset, OffsetRegNum,
596                                  OffsetRegShifted, ShiftType, ShiftAmount,
597                                  Preindexed, Postindexed, Negative, Writeback,
598                                  S, E);
599   }
600
601   return 0;
602 }
603
604 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
605 /// we will parse the following (were +/- means that a plus or minus is
606 /// optional):
607 ///   +/-Rm
608 ///   +/-Rm, shift
609 ///   #offset
610 /// we return false on success or an error otherwise.
611 bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
612                                         bool &OffsetRegShifted,
613                                         enum ShiftType &ShiftType,
614                                         const MCExpr *&ShiftAmount,
615                                         const MCExpr *&Offset,
616                                         bool &OffsetIsReg,
617                                         int &OffsetRegNum,
618                                         SMLoc &E) {
619   Negative = false;
620   OffsetRegShifted = false;
621   OffsetIsReg = false;
622   OffsetRegNum = -1;
623   const AsmToken &NextTok = Parser.getTok();
624   E = NextTok.getLoc();
625   if (NextTok.is(AsmToken::Plus))
626     Parser.Lex(); // Eat plus token.
627   else if (NextTok.is(AsmToken::Minus)) {
628     Negative = true;
629     Parser.Lex(); // Eat minus token
630   }
631   // See if there is a register following the "[Rn," or "[Rn]," we have so far.
632   const AsmToken &OffsetRegTok = Parser.getTok();
633   if (OffsetRegTok.is(AsmToken::Identifier)) {
634     SMLoc CurLoc = OffsetRegTok.getLoc();
635     OffsetRegNum = TryParseRegister();
636     if (OffsetRegNum != -1) {
637       OffsetIsReg = true;
638       E = CurLoc;
639     }
640   }
641
642   // If we parsed a register as the offset then there can be a shift after that.
643   if (OffsetRegNum != -1) {
644     // Look for a comma then a shift
645     const AsmToken &Tok = Parser.getTok();
646     if (Tok.is(AsmToken::Comma)) {
647       Parser.Lex(); // Eat comma token.
648
649       const AsmToken &Tok = Parser.getTok();
650       if (ParseShift(ShiftType, ShiftAmount, E))
651         return Error(Tok.getLoc(), "shift expected");
652       OffsetRegShifted = true;
653     }
654   }
655   else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
656     // Look for #offset following the "[Rn," or "[Rn],"
657     const AsmToken &HashTok = Parser.getTok();
658     if (HashTok.isNot(AsmToken::Hash))
659       return Error(HashTok.getLoc(), "'#' expected");
660
661     Parser.Lex(); // Eat hash token.
662
663     if (getParser().ParseExpression(Offset))
664      return true;
665     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
666   }
667   return false;
668 }
669
670 /// ParseShift as one of these two:
671 ///   ( lsl | lsr | asr | ror ) , # shift_amount
672 ///   rrx
673 /// and returns true if it parses a shift otherwise it returns false.
674 bool ARMAsmParser::ParseShift(ShiftType &St, const MCExpr *&ShiftAmount,
675                               SMLoc &E) {
676   const AsmToken &Tok = Parser.getTok();
677   if (Tok.isNot(AsmToken::Identifier))
678     return true;
679   StringRef ShiftName = Tok.getString();
680   if (ShiftName == "lsl" || ShiftName == "LSL")
681     St = Lsl;
682   else if (ShiftName == "lsr" || ShiftName == "LSR")
683     St = Lsr;
684   else if (ShiftName == "asr" || ShiftName == "ASR")
685     St = Asr;
686   else if (ShiftName == "ror" || ShiftName == "ROR")
687     St = Ror;
688   else if (ShiftName == "rrx" || ShiftName == "RRX")
689     St = Rrx;
690   else
691     return true;
692   Parser.Lex(); // Eat shift type token.
693
694   // Rrx stands alone.
695   if (St == Rrx)
696     return false;
697
698   // Otherwise, there must be a '#' and a shift amount.
699   const AsmToken &HashTok = Parser.getTok();
700   if (HashTok.isNot(AsmToken::Hash))
701     return Error(HashTok.getLoc(), "'#' expected");
702   Parser.Lex(); // Eat hash token.
703
704   if (getParser().ParseExpression(ShiftAmount))
705     return true;
706
707   return false;
708 }
709
710 /// Parse a arm instruction operand.  For now this parses the operand regardless
711 /// of the mnemonic.
712 ARMOperand *ARMAsmParser::ParseOperand() {
713   SMLoc S, E;
714   switch (getLexer().getKind()) {
715   default:
716     Error(Parser.getTok().getLoc(), "unexpected token in operand");
717     return 0;
718   case AsmToken::Identifier:
719     if (ARMOperand *Op = TryParseRegisterWithWriteBack())
720       return Op;
721
722     // This was not a register so parse other operands that start with an
723     // identifier (like labels) as expressions and create them as immediates.
724     const MCExpr *IdVal;
725     S = Parser.getTok().getLoc();
726     if (getParser().ParseExpression(IdVal))
727       return 0;
728     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
729     return ARMOperand::CreateImm(IdVal, S, E);
730   case AsmToken::LBrac:
731     return ParseMemory();
732   case AsmToken::LCurly:
733     return ParseRegisterList();
734   case AsmToken::Hash:
735     // #42 -> immediate.
736     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
737     S = Parser.getTok().getLoc();
738     Parser.Lex();
739     const MCExpr *ImmVal;
740     if (getParser().ParseExpression(ImmVal))
741       return 0;
742     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
743     return ARMOperand::CreateImm(ImmVal, S, E);
744   }
745 }
746
747 /// Parse an arm instruction mnemonic followed by its operands.
748 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
749                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
750   // Create the leading tokens for the mnemonic, split by '.' characters.
751   size_t Start = 0, Next = Name.find('.');
752   StringRef Head = Name.slice(Start, Next);
753
754   // Determine the predicate, if any.
755   //
756   // FIXME: We need a way to check whether a prefix supports predication,
757   // otherwise we will end up with an ambiguity for instructions that happen to
758   // end with a predicate name.
759   // FIXME: Likewise, some arithmetic instructions have an 's' prefix which
760   // indicates to update the condition codes. Those instructions have an
761   // additional immediate operand which encodes the prefix as reg0 or CPSR.
762   // Just checking for a suffix of 's' definitely creates ambiguities; e.g,
763   // the SMMLS instruction.
764   unsigned CC = StringSwitch<unsigned>(Head.substr(Head.size()-2))
765     .Case("eq", ARMCC::EQ)
766     .Case("ne", ARMCC::NE)
767     .Case("hs", ARMCC::HS)
768     .Case("lo", ARMCC::LO)
769     .Case("mi", ARMCC::MI)
770     .Case("pl", ARMCC::PL)
771     .Case("vs", ARMCC::VS)
772     .Case("vc", ARMCC::VC)
773     .Case("hi", ARMCC::HI)
774     .Case("ls", ARMCC::LS)
775     .Case("ge", ARMCC::GE)
776     .Case("lt", ARMCC::LT)
777     .Case("gt", ARMCC::GT)
778     .Case("le", ARMCC::LE)
779     .Case("al", ARMCC::AL)
780     .Default(~0U);
781
782   if (CC == ~0U ||
783       (CC == ARMCC::LS && (Head == "vmls" || Head == "vnmls"))) {
784     CC = ARMCC::AL;
785   } else {
786     Head = Head.slice(0, Head.size() - 2);
787   }
788
789   Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
790   // FIXME: Should only add this operand for predicated instructions
791   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), NameLoc));
792
793   // Add the remaining tokens in the mnemonic.
794   while (Next != StringRef::npos) {
795     Start = Next;
796     Next = Name.find('.', Start + 1);
797     Head = Name.slice(Start, Next);
798
799     Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
800   }
801
802   // Read the remaining operands.
803   if (getLexer().isNot(AsmToken::EndOfStatement)) {
804     // Read the first operand.
805     if (ARMOperand *Op = ParseOperand())
806       Operands.push_back(Op);
807     else {
808       Parser.EatToEndOfStatement();
809       return true;
810     }
811
812     while (getLexer().is(AsmToken::Comma)) {
813       Parser.Lex();  // Eat the comma.
814
815       // Parse and remember the operand.
816       if (ARMOperand *Op = ParseOperand())
817         Operands.push_back(Op);
818       else {
819         Parser.EatToEndOfStatement();
820         return true;
821       }
822     }
823   }
824
825   if (getLexer().isNot(AsmToken::EndOfStatement)) {
826     Parser.EatToEndOfStatement();
827     return TokError("unexpected token in argument list");
828   }
829
830   Parser.Lex(); // Consume the EndOfStatement
831   return false;
832 }
833
834 bool ARMAsmParser::
835 MatchAndEmitInstruction(SMLoc IDLoc,
836                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
837                         MCStreamer &Out) {
838   MCInst Inst;
839   unsigned ErrorInfo;
840   switch (MatchInstructionImpl(Operands, Inst, ErrorInfo)) {
841   case Match_Success:
842     Out.EmitInstruction(Inst);
843     return false;
844   case Match_MissingFeature:
845     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
846     return true;
847   case Match_InvalidOperand: {
848     SMLoc ErrorLoc = IDLoc;
849     if (ErrorInfo != ~0U) {
850       if (ErrorInfo >= Operands.size())
851         return Error(IDLoc, "too few operands for instruction");
852
853       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
854       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
855     }
856
857     return Error(ErrorLoc, "invalid operand for instruction");
858   }
859   case Match_MnemonicFail:
860     return Error(IDLoc, "unrecognized instruction mnemonic");
861   }
862
863   llvm_unreachable("Implement any new match types added!");
864   return true;
865 }
866
867 /// ParseDirective parses the arm specific directives
868 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
869   StringRef IDVal = DirectiveID.getIdentifier();
870   if (IDVal == ".word")
871     return ParseDirectiveWord(4, DirectiveID.getLoc());
872   else if (IDVal == ".thumb")
873     return ParseDirectiveThumb(DirectiveID.getLoc());
874   else if (IDVal == ".thumb_func")
875     return ParseDirectiveThumbFunc(DirectiveID.getLoc());
876   else if (IDVal == ".code")
877     return ParseDirectiveCode(DirectiveID.getLoc());
878   else if (IDVal == ".syntax")
879     return ParseDirectiveSyntax(DirectiveID.getLoc());
880   return true;
881 }
882
883 /// ParseDirectiveWord
884 ///  ::= .word [ expression (, expression)* ]
885 bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
886   if (getLexer().isNot(AsmToken::EndOfStatement)) {
887     for (;;) {
888       const MCExpr *Value;
889       if (getParser().ParseExpression(Value))
890         return true;
891
892       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
893
894       if (getLexer().is(AsmToken::EndOfStatement))
895         break;
896
897       // FIXME: Improve diagnostic.
898       if (getLexer().isNot(AsmToken::Comma))
899         return Error(L, "unexpected token in directive");
900       Parser.Lex();
901     }
902   }
903
904   Parser.Lex();
905   return false;
906 }
907
908 /// ParseDirectiveThumb
909 ///  ::= .thumb
910 bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
911   if (getLexer().isNot(AsmToken::EndOfStatement))
912     return Error(L, "unexpected token in directive");
913   Parser.Lex();
914
915   // TODO: set thumb mode
916   // TODO: tell the MC streamer the mode
917   // getParser().getStreamer().Emit???();
918   return false;
919 }
920
921 /// ParseDirectiveThumbFunc
922 ///  ::= .thumbfunc symbol_name
923 bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
924   const AsmToken &Tok = Parser.getTok();
925   if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
926     return Error(L, "unexpected token in .thumb_func directive");
927   StringRef Name = Tok.getString();
928   Parser.Lex(); // Consume the identifier token.
929   if (getLexer().isNot(AsmToken::EndOfStatement))
930     return Error(L, "unexpected token in directive");
931   Parser.Lex();
932
933   // Mark symbol as a thumb symbol.
934   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
935   getParser().getStreamer().EmitThumbFunc(Func);
936   return false;
937 }
938
939 /// ParseDirectiveSyntax
940 ///  ::= .syntax unified | divided
941 bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
942   const AsmToken &Tok = Parser.getTok();
943   if (Tok.isNot(AsmToken::Identifier))
944     return Error(L, "unexpected token in .syntax directive");
945   StringRef Mode = Tok.getString();
946   if (Mode == "unified" || Mode == "UNIFIED")
947     Parser.Lex();
948   else if (Mode == "divided" || Mode == "DIVIDED")
949     Parser.Lex();
950   else
951     return Error(L, "unrecognized syntax mode in .syntax directive");
952
953   if (getLexer().isNot(AsmToken::EndOfStatement))
954     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
955   Parser.Lex();
956
957   // TODO tell the MC streamer the mode
958   // getParser().getStreamer().Emit???();
959   return false;
960 }
961
962 /// ParseDirectiveCode
963 ///  ::= .code 16 | 32
964 bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
965   const AsmToken &Tok = Parser.getTok();
966   if (Tok.isNot(AsmToken::Integer))
967     return Error(L, "unexpected token in .code directive");
968   int64_t Val = Parser.getTok().getIntVal();
969   if (Val == 16)
970     Parser.Lex();
971   else if (Val == 32)
972     Parser.Lex();
973   else
974     return Error(L, "invalid operand to .code directive");
975
976   if (getLexer().isNot(AsmToken::EndOfStatement))
977     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
978   Parser.Lex();
979
980   if (Val == 16)
981     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
982   else
983     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
984
985   return false;
986 }
987
988 extern "C" void LLVMInitializeARMAsmLexer();
989
990 /// Force static initialization.
991 extern "C" void LLVMInitializeARMAsmParser() {
992   RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
993   RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);
994   LLVMInitializeARMAsmLexer();
995 }
996
997 #define GET_REGISTER_MATCHER
998 #define GET_MATCHER_IMPLEMENTATION
999 #include "ARMGenAsmMatcher.inc"