Modified the register matcher function in AsmMatcher to
[oota-llvm.git] / lib / Target / X86 / AsmParser / X86AsmParser.cpp
1 //===-- X86AsmParser.cpp - Parse X86 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 "llvm/Target/TargetAsmParser.h"
11 #include "X86.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCStreamer.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/Support/SourceMgr.h"
21 #include "llvm/Target/TargetRegistry.h"
22 #include "llvm/Target/TargetAsmParser.h"
23 using namespace llvm;
24
25 namespace {
26 struct X86Operand;
27
28 class X86ATTAsmParser : public TargetAsmParser {
29   MCAsmParser &Parser;
30
31 private:
32   MCAsmParser &getParser() const { return Parser; }
33
34   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
35
36   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
37
38   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
39
40   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
41
42   X86Operand *ParseOperand();
43   X86Operand *ParseMemOperand();
44
45   bool ParseDirectiveWord(unsigned Size, SMLoc L);
46
47   /// @name Auto-generated Match Functions
48   /// {  
49
50   bool MatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
51                         MCInst &Inst);
52
53   /// }
54
55 public:
56   X86ATTAsmParser(const Target &T, MCAsmParser &_Parser)
57     : TargetAsmParser(T), Parser(_Parser) {}
58
59   virtual bool ParseInstruction(const StringRef &Name, SMLoc NameLoc,
60                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
61
62   virtual bool ParseDirective(AsmToken DirectiveID);
63 };
64   
65 } // end anonymous namespace
66
67 /// @name Auto-generated Match Functions
68 /// {  
69
70 static unsigned MatchRegisterName(const StringRef &Name);
71
72 /// }
73
74 namespace {
75
76 /// X86Operand - Instances of this class represent a parsed X86 machine
77 /// instruction.
78 struct X86Operand : public MCParsedAsmOperand {
79   enum KindTy {
80     Token,
81     Register,
82     Immediate,
83     Memory
84   } Kind;
85
86   SMLoc StartLoc, EndLoc;
87   
88   union {
89     struct {
90       const char *Data;
91       unsigned Length;
92     } Tok;
93
94     struct {
95       unsigned RegNo;
96     } Reg;
97
98     struct {
99       const MCExpr *Val;
100     } Imm;
101
102     struct {
103       unsigned SegReg;
104       const MCExpr *Disp;
105       unsigned BaseReg;
106       unsigned IndexReg;
107       unsigned Scale;
108     } Mem;
109   };
110
111   X86Operand(KindTy K, SMLoc Start, SMLoc End)
112     : Kind(K), StartLoc(Start), EndLoc(End) {}
113   
114   /// getStartLoc - Get the location of the first token of this operand.
115   SMLoc getStartLoc() const { return StartLoc; }
116   /// getEndLoc - Get the location of the last token of this operand.
117   SMLoc getEndLoc() const { return EndLoc; }
118
119   StringRef getToken() const {
120     assert(Kind == Token && "Invalid access!");
121     return StringRef(Tok.Data, Tok.Length);
122   }
123
124   unsigned getReg() const {
125     assert(Kind == Register && "Invalid access!");
126     return Reg.RegNo;
127   }
128
129   const MCExpr *getImm() const {
130     assert(Kind == Immediate && "Invalid access!");
131     return Imm.Val;
132   }
133
134   const MCExpr *getMemDisp() const {
135     assert(Kind == Memory && "Invalid access!");
136     return Mem.Disp;
137   }
138   unsigned getMemSegReg() const {
139     assert(Kind == Memory && "Invalid access!");
140     return Mem.SegReg;
141   }
142   unsigned getMemBaseReg() const {
143     assert(Kind == Memory && "Invalid access!");
144     return Mem.BaseReg;
145   }
146   unsigned getMemIndexReg() const {
147     assert(Kind == Memory && "Invalid access!");
148     return Mem.IndexReg;
149   }
150   unsigned getMemScale() const {
151     assert(Kind == Memory && "Invalid access!");
152     return Mem.Scale;
153   }
154
155   bool isToken() const {return Kind == Token; }
156
157   bool isImm() const { return Kind == Immediate; }
158   
159   bool isImmSExt8() const { 
160     // Accept immediates which fit in 8 bits when sign extended, and
161     // non-absolute immediates.
162     if (!isImm())
163       return false;
164
165     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
166       int64_t Value = CE->getValue();
167       return Value == (int64_t) (int8_t) Value;
168     }
169
170     return true;
171   }
172   
173   bool isMem() const { return Kind == Memory; }
174
175   bool isReg() const { return Kind == Register; }
176
177   void addRegOperands(MCInst &Inst, unsigned N) const {
178     assert(N == 1 && "Invalid number of operands!");
179     Inst.addOperand(MCOperand::CreateReg(getReg()));
180   }
181
182   void addImmOperands(MCInst &Inst, unsigned N) const {
183     assert(N == 1 && "Invalid number of operands!");
184     Inst.addOperand(MCOperand::CreateExpr(getImm()));
185   }
186
187   void addImmSExt8Operands(MCInst &Inst, unsigned N) const {
188     // FIXME: Support user customization of the render method.
189     assert(N == 1 && "Invalid number of operands!");
190     Inst.addOperand(MCOperand::CreateExpr(getImm()));
191   }
192
193   void addMemOperands(MCInst &Inst, unsigned N) const {
194     assert((N == 4 || N == 5) && "Invalid number of operands!");
195
196     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
197     Inst.addOperand(MCOperand::CreateImm(getMemScale()));
198     Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
199     Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
200
201     // FIXME: What a hack.
202     if (N == 5)
203       Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
204   }
205
206   static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
207     X86Operand *Res = new X86Operand(Token, Loc, Loc);
208     Res->Tok.Data = Str.data();
209     Res->Tok.Length = Str.size();
210     return Res;
211   }
212
213   static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
214     X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
215     Res->Reg.RegNo = RegNo;
216     return Res;
217   }
218
219   static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
220     X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
221     Res->Imm.Val = Val;
222     return Res;
223   }
224
225   static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
226                                unsigned BaseReg, unsigned IndexReg,
227                                unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
228     // We should never just have a displacement, that would be an immediate.
229     assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
230
231     // The scale should always be one of {1,2,4,8}.
232     assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
233            "Invalid scale!");
234     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
235     Res->Mem.SegReg   = SegReg;
236     Res->Mem.Disp     = Disp;
237     Res->Mem.BaseReg  = BaseReg;
238     Res->Mem.IndexReg = IndexReg;
239     Res->Mem.Scale    = Scale;
240     return Res;
241   }
242 };
243
244 } // end anonymous namespace.
245
246
247 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
248                                     SMLoc &StartLoc, SMLoc &EndLoc) {
249   RegNo = 0;
250   const AsmToken &TokPercent = Parser.getTok();
251   assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
252   StartLoc = TokPercent.getLoc();
253   Parser.Lex(); // Eat percent token.
254
255   const AsmToken &Tok = Parser.getTok();
256   if (Tok.isNot(AsmToken::Identifier))
257     return Error(Tok.getLoc(), "invalid register name");
258
259   // FIXME: Validate register for the current architecture; we have to do
260   // validation later, so maybe there is no need for this here.
261   RegNo = MatchRegisterName(Tok.getString());
262   if (RegNo == 0)
263     return Error(Tok.getLoc(), "invalid register name");
264
265   EndLoc = Tok.getLoc();
266   Parser.Lex(); // Eat identifier token.
267   return false;
268 }
269
270 X86Operand *X86ATTAsmParser::ParseOperand() {
271   switch (getLexer().getKind()) {
272   default:
273     return ParseMemOperand();
274   case AsmToken::Percent: {
275     // FIXME: if a segment register, this could either be just the seg reg, or
276     // the start of a memory operand.
277     unsigned RegNo;
278     SMLoc Start, End;
279     if (ParseRegister(RegNo, Start, End)) return 0;
280     return X86Operand::CreateReg(RegNo, Start, End);
281   }
282   case AsmToken::Dollar: {
283     // $42 -> immediate.
284     SMLoc Start = Parser.getTok().getLoc(), End;
285     Parser.Lex();
286     const MCExpr *Val;
287     if (getParser().ParseExpression(Val, End))
288       return 0;
289     return X86Operand::CreateImm(Val, Start, End);
290   }
291   }
292 }
293
294 /// ParseMemOperand: segment: disp(basereg, indexreg, scale)
295 X86Operand *X86ATTAsmParser::ParseMemOperand() {
296   SMLoc MemStart = Parser.getTok().getLoc();
297   
298   // FIXME: If SegReg ':'  (e.g. %gs:), eat and remember.
299   unsigned SegReg = 0;
300   
301   // We have to disambiguate a parenthesized expression "(4+5)" from the start
302   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
303   // only way to do this without lookahead is to eat the ( and see what is after
304   // it.
305   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
306   if (getLexer().isNot(AsmToken::LParen)) {
307     SMLoc ExprEnd;
308     if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
309     
310     // After parsing the base expression we could either have a parenthesized
311     // memory address or not.  If not, return now.  If so, eat the (.
312     if (getLexer().isNot(AsmToken::LParen)) {
313       // Unless we have a segment register, treat this as an immediate.
314       if (SegReg == 0)
315         return X86Operand::CreateImm(Disp, MemStart, ExprEnd);
316       return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
317     }
318     
319     // Eat the '('.
320     Parser.Lex();
321   } else {
322     // Okay, we have a '('.  We don't know if this is an expression or not, but
323     // so we have to eat the ( to see beyond it.
324     SMLoc LParenLoc = Parser.getTok().getLoc();
325     Parser.Lex(); // Eat the '('.
326     
327     if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
328       // Nothing to do here, fall into the code below with the '(' part of the
329       // memory operand consumed.
330     } else {
331       SMLoc ExprEnd;
332       
333       // It must be an parenthesized expression, parse it now.
334       if (getParser().ParseParenExpression(Disp, ExprEnd))
335         return 0;
336       
337       // After parsing the base expression we could either have a parenthesized
338       // memory address or not.  If not, return now.  If so, eat the (.
339       if (getLexer().isNot(AsmToken::LParen)) {
340         // Unless we have a segment register, treat this as an immediate.
341         if (SegReg == 0)
342           return X86Operand::CreateImm(Disp, LParenLoc, ExprEnd);
343         return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
344       }
345       
346       // Eat the '('.
347       Parser.Lex();
348     }
349   }
350   
351   // If we reached here, then we just ate the ( of the memory operand.  Process
352   // the rest of the memory operand.
353   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
354   
355   if (getLexer().is(AsmToken::Percent)) {
356     SMLoc L;
357     if (ParseRegister(BaseReg, L, L)) return 0;
358   }
359   
360   if (getLexer().is(AsmToken::Comma)) {
361     Parser.Lex(); // Eat the comma.
362
363     // Following the comma we should have either an index register, or a scale
364     // value. We don't support the later form, but we want to parse it
365     // correctly.
366     //
367     // Not that even though it would be completely consistent to support syntax
368     // like "1(%eax,,1)", the assembler doesn't.
369     if (getLexer().is(AsmToken::Percent)) {
370       SMLoc L;
371       if (ParseRegister(IndexReg, L, L)) return 0;
372     
373       if (getLexer().isNot(AsmToken::RParen)) {
374         // Parse the scale amount:
375         //  ::= ',' [scale-expression]
376         if (getLexer().isNot(AsmToken::Comma)) {
377           Error(Parser.getTok().getLoc(),
378                 "expected comma in scale expression");
379           return 0;
380         }
381         Parser.Lex(); // Eat the comma.
382
383         if (getLexer().isNot(AsmToken::RParen)) {
384           SMLoc Loc = Parser.getTok().getLoc();
385
386           int64_t ScaleVal;
387           if (getParser().ParseAbsoluteExpression(ScaleVal))
388             return 0;
389           
390           // Validate the scale amount.
391           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
392             Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
393             return 0;
394           }
395           Scale = (unsigned)ScaleVal;
396         }
397       }
398     } else if (getLexer().isNot(AsmToken::RParen)) {
399       // Otherwise we have the unsupported form of a scale amount without an
400       // index.
401       SMLoc Loc = Parser.getTok().getLoc();
402
403       int64_t Value;
404       if (getParser().ParseAbsoluteExpression(Value))
405         return 0;
406       
407       Error(Loc, "cannot have scale factor without index register");
408       return 0;
409     }
410   }
411   
412   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
413   if (getLexer().isNot(AsmToken::RParen)) {
414     Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
415     return 0;
416   }
417   SMLoc MemEnd = Parser.getTok().getLoc();
418   Parser.Lex(); // Eat the ')'.
419   
420   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
421                                MemStart, MemEnd);
422 }
423
424 bool X86ATTAsmParser::
425 ParseInstruction(const StringRef &Name, SMLoc NameLoc,
426                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
427
428   Operands.push_back(X86Operand::CreateToken(Name, NameLoc));
429
430   if (getLexer().isNot(AsmToken::EndOfStatement)) {
431
432     // Parse '*' modifier.
433     if (getLexer().is(AsmToken::Star)) {
434       SMLoc Loc = Parser.getTok().getLoc();
435       Operands.push_back(X86Operand::CreateToken("*", Loc));
436       Parser.Lex(); // Eat the star.
437     }
438
439     // Read the first operand.
440     if (X86Operand *Op = ParseOperand())
441       Operands.push_back(Op);
442     else
443       return true;
444     
445     while (getLexer().is(AsmToken::Comma)) {
446       Parser.Lex();  // Eat the comma.
447
448       // Parse and remember the operand.
449       if (X86Operand *Op = ParseOperand())
450         Operands.push_back(Op);
451       else
452         return true;
453     }
454   }
455
456   return false;
457 }
458
459 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
460   StringRef IDVal = DirectiveID.getIdentifier();
461   if (IDVal == ".word")
462     return ParseDirectiveWord(2, DirectiveID.getLoc());
463   return true;
464 }
465
466 /// ParseDirectiveWord
467 ///  ::= .word [ expression (, expression)* ]
468 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
469   if (getLexer().isNot(AsmToken::EndOfStatement)) {
470     for (;;) {
471       const MCExpr *Value;
472       if (getParser().ParseExpression(Value))
473         return true;
474
475       getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
476
477       if (getLexer().is(AsmToken::EndOfStatement))
478         break;
479       
480       // FIXME: Improve diagnostic.
481       if (getLexer().isNot(AsmToken::Comma))
482         return Error(L, "unexpected token in directive");
483       Parser.Lex();
484     }
485   }
486
487   Parser.Lex();
488   return false;
489 }
490
491 // Force static initialization.
492 extern "C" void LLVMInitializeX86AsmParser() {
493   RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
494   RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
495 }
496
497 #include "X86GenAsmMatcher.inc"