Move TargetAsmParser.h TargetAsmBackend.h and TargetAsmLexer.h to MC where they belong.
[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/MC/TargetAsmParser.h"
11 #include "X86.h"
12 #include "X86Subtarget.h"
13 #include "llvm/Target/TargetRegistry.h"
14 #include "llvm/MC/MCStreamer.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCSubtargetInfo.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/raw_ostream.h"
29
30 using namespace llvm;
31
32 namespace {
33 struct X86Operand;
34
35 class X86ATTAsmParser : public TargetAsmParser {
36   MCSubtargetInfo &STI;
37   MCAsmParser &Parser;
38
39 private:
40   MCAsmParser &getParser() const { return Parser; }
41
42   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
43
44   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
45
46   X86Operand *ParseOperand();
47   X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
48
49   bool ParseDirectiveWord(unsigned Size, SMLoc L);
50
51   bool MatchAndEmitInstruction(SMLoc IDLoc,
52                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
53                                MCStreamer &Out);
54
55   /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
56   /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
57   bool isSrcOp(X86Operand &Op);
58
59   /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
60   /// or %es:(%edi) in 32bit mode.
61   bool isDstOp(X86Operand &Op);
62
63   bool is64BitMode() const {
64     // FIXME: Can tablegen auto-generate this?
65     return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
66   }
67
68   /// @name Auto-generated Matcher Functions
69   /// {
70
71 #define GET_ASSEMBLER_HEADER
72 #include "X86GenAsmMatcher.inc"
73
74   /// }
75
76 public:
77   X86ATTAsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
78     : TargetAsmParser(), STI(sti), Parser(parser) {
79
80     // Initialize the set of available features.
81     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
82   }
83   virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
84
85   virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
86                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
87
88   virtual bool ParseDirective(AsmToken DirectiveID);
89 };
90 } // end anonymous namespace
91
92 /// @name Auto-generated Match Functions
93 /// {
94
95 static unsigned MatchRegisterName(StringRef Name);
96
97 /// }
98
99 namespace {
100
101 /// X86Operand - Instances of this class represent a parsed X86 machine
102 /// instruction.
103 struct X86Operand : public MCParsedAsmOperand {
104   enum KindTy {
105     Token,
106     Register,
107     Immediate,
108     Memory
109   } Kind;
110
111   SMLoc StartLoc, EndLoc;
112
113   union {
114     struct {
115       const char *Data;
116       unsigned Length;
117     } Tok;
118
119     struct {
120       unsigned RegNo;
121     } Reg;
122
123     struct {
124       const MCExpr *Val;
125     } Imm;
126
127     struct {
128       unsigned SegReg;
129       const MCExpr *Disp;
130       unsigned BaseReg;
131       unsigned IndexReg;
132       unsigned Scale;
133     } Mem;
134   };
135
136   X86Operand(KindTy K, SMLoc Start, SMLoc End)
137     : Kind(K), StartLoc(Start), EndLoc(End) {}
138
139   /// getStartLoc - Get the location of the first token of this operand.
140   SMLoc getStartLoc() const { return StartLoc; }
141   /// getEndLoc - Get the location of the last token of this operand.
142   SMLoc getEndLoc() const { return EndLoc; }
143
144   virtual void print(raw_ostream &OS) const {}
145
146   StringRef getToken() const {
147     assert(Kind == Token && "Invalid access!");
148     return StringRef(Tok.Data, Tok.Length);
149   }
150   void setTokenValue(StringRef Value) {
151     assert(Kind == Token && "Invalid access!");
152     Tok.Data = Value.data();
153     Tok.Length = Value.size();
154   }
155
156   unsigned getReg() const {
157     assert(Kind == Register && "Invalid access!");
158     return Reg.RegNo;
159   }
160
161   const MCExpr *getImm() const {
162     assert(Kind == Immediate && "Invalid access!");
163     return Imm.Val;
164   }
165
166   const MCExpr *getMemDisp() const {
167     assert(Kind == Memory && "Invalid access!");
168     return Mem.Disp;
169   }
170   unsigned getMemSegReg() const {
171     assert(Kind == Memory && "Invalid access!");
172     return Mem.SegReg;
173   }
174   unsigned getMemBaseReg() const {
175     assert(Kind == Memory && "Invalid access!");
176     return Mem.BaseReg;
177   }
178   unsigned getMemIndexReg() const {
179     assert(Kind == Memory && "Invalid access!");
180     return Mem.IndexReg;
181   }
182   unsigned getMemScale() const {
183     assert(Kind == Memory && "Invalid access!");
184     return Mem.Scale;
185   }
186
187   bool isToken() const {return Kind == Token; }
188
189   bool isImm() const { return Kind == Immediate; }
190
191   bool isImmSExti16i8() const {
192     if (!isImm())
193       return false;
194
195     // If this isn't a constant expr, just assume it fits and let relaxation
196     // handle it.
197     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
198     if (!CE)
199       return true;
200
201     // Otherwise, check the value is in a range that makes sense for this
202     // extension.
203     uint64_t Value = CE->getValue();
204     return ((                                  Value <= 0x000000000000007FULL)||
205             (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
206             (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
207   }
208   bool isImmSExti32i8() const {
209     if (!isImm())
210       return false;
211
212     // If this isn't a constant expr, just assume it fits and let relaxation
213     // handle it.
214     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
215     if (!CE)
216       return true;
217
218     // Otherwise, check the value is in a range that makes sense for this
219     // extension.
220     uint64_t Value = CE->getValue();
221     return ((                                  Value <= 0x000000000000007FULL)||
222             (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
223             (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
224   }
225   bool isImmSExti64i8() const {
226     if (!isImm())
227       return false;
228
229     // If this isn't a constant expr, just assume it fits and let relaxation
230     // handle it.
231     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
232     if (!CE)
233       return true;
234
235     // Otherwise, check the value is in a range that makes sense for this
236     // extension.
237     uint64_t Value = CE->getValue();
238     return ((                                  Value <= 0x000000000000007FULL)||
239             (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
240   }
241   bool isImmSExti64i32() const {
242     if (!isImm())
243       return false;
244
245     // If this isn't a constant expr, just assume it fits and let relaxation
246     // handle it.
247     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
248     if (!CE)
249       return true;
250
251     // Otherwise, check the value is in a range that makes sense for this
252     // extension.
253     uint64_t Value = CE->getValue();
254     return ((                                  Value <= 0x000000007FFFFFFFULL)||
255             (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
256   }
257
258   bool isMem() const { return Kind == Memory; }
259
260   bool isAbsMem() const {
261     return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
262       !getMemIndexReg() && getMemScale() == 1;
263   }
264
265   bool isReg() const { return Kind == Register; }
266
267   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
268     // Add as immediates when possible.
269     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
270       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
271     else
272       Inst.addOperand(MCOperand::CreateExpr(Expr));
273   }
274
275   void addRegOperands(MCInst &Inst, unsigned N) const {
276     assert(N == 1 && "Invalid number of operands!");
277     Inst.addOperand(MCOperand::CreateReg(getReg()));
278   }
279
280   void addImmOperands(MCInst &Inst, unsigned N) const {
281     assert(N == 1 && "Invalid number of operands!");
282     addExpr(Inst, getImm());
283   }
284
285   void addMemOperands(MCInst &Inst, unsigned N) const {
286     assert((N == 5) && "Invalid number of operands!");
287     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
288     Inst.addOperand(MCOperand::CreateImm(getMemScale()));
289     Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
290     addExpr(Inst, getMemDisp());
291     Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
292   }
293
294   void addAbsMemOperands(MCInst &Inst, unsigned N) const {
295     assert((N == 1) && "Invalid number of operands!");
296     Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
297   }
298
299   static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
300     X86Operand *Res = new X86Operand(Token, Loc, Loc);
301     Res->Tok.Data = Str.data();
302     Res->Tok.Length = Str.size();
303     return Res;
304   }
305
306   static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
307     X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
308     Res->Reg.RegNo = RegNo;
309     return Res;
310   }
311
312   static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
313     X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
314     Res->Imm.Val = Val;
315     return Res;
316   }
317
318   /// Create an absolute memory operand.
319   static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
320                                SMLoc EndLoc) {
321     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
322     Res->Mem.SegReg   = 0;
323     Res->Mem.Disp     = Disp;
324     Res->Mem.BaseReg  = 0;
325     Res->Mem.IndexReg = 0;
326     Res->Mem.Scale    = 1;
327     return Res;
328   }
329
330   /// Create a generalized memory operand.
331   static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
332                                unsigned BaseReg, unsigned IndexReg,
333                                unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
334     // We should never just have a displacement, that should be parsed as an
335     // absolute memory operand.
336     assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
337
338     // The scale should always be one of {1,2,4,8}.
339     assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
340            "Invalid scale!");
341     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
342     Res->Mem.SegReg   = SegReg;
343     Res->Mem.Disp     = Disp;
344     Res->Mem.BaseReg  = BaseReg;
345     Res->Mem.IndexReg = IndexReg;
346     Res->Mem.Scale    = Scale;
347     return Res;
348   }
349 };
350
351 } // end anonymous namespace.
352
353 bool X86ATTAsmParser::isSrcOp(X86Operand &Op) {
354   unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
355
356   return (Op.isMem() &&
357     (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
358     isa<MCConstantExpr>(Op.Mem.Disp) &&
359     cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
360     Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
361 }
362
363 bool X86ATTAsmParser::isDstOp(X86Operand &Op) {
364   unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
365
366   return Op.isMem() && Op.Mem.SegReg == X86::ES &&
367     isa<MCConstantExpr>(Op.Mem.Disp) &&
368     cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
369     Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
370 }
371
372 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
373                                     SMLoc &StartLoc, SMLoc &EndLoc) {
374   RegNo = 0;
375   const AsmToken &TokPercent = Parser.getTok();
376   assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
377   StartLoc = TokPercent.getLoc();
378   Parser.Lex(); // Eat percent token.
379
380   const AsmToken &Tok = Parser.getTok();
381   if (Tok.isNot(AsmToken::Identifier))
382     return Error(Tok.getLoc(), "invalid register name");
383
384   // FIXME: Validate register for the current architecture; we have to do
385   // validation later, so maybe there is no need for this here.
386   RegNo = MatchRegisterName(Tok.getString());
387
388   // If the match failed, try the register name as lowercase.
389   if (RegNo == 0)
390     RegNo = MatchRegisterName(LowercaseString(Tok.getString()));
391
392   // FIXME: This should be done using Requires<In32BitMode> and
393   // Requires<In64BitMode> so "eiz" usage in 64-bit instructions
394   // can be also checked.
395   if (RegNo == X86::RIZ && !is64BitMode())
396     return Error(Tok.getLoc(), "riz register in 64-bit mode only");
397
398   // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
399   if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
400     RegNo = X86::ST0;
401     EndLoc = Tok.getLoc();
402     Parser.Lex(); // Eat 'st'
403
404     // Check to see if we have '(4)' after %st.
405     if (getLexer().isNot(AsmToken::LParen))
406       return false;
407     // Lex the paren.
408     getParser().Lex();
409
410     const AsmToken &IntTok = Parser.getTok();
411     if (IntTok.isNot(AsmToken::Integer))
412       return Error(IntTok.getLoc(), "expected stack index");
413     switch (IntTok.getIntVal()) {
414     case 0: RegNo = X86::ST0; break;
415     case 1: RegNo = X86::ST1; break;
416     case 2: RegNo = X86::ST2; break;
417     case 3: RegNo = X86::ST3; break;
418     case 4: RegNo = X86::ST4; break;
419     case 5: RegNo = X86::ST5; break;
420     case 6: RegNo = X86::ST6; break;
421     case 7: RegNo = X86::ST7; break;
422     default: return Error(IntTok.getLoc(), "invalid stack index");
423     }
424
425     if (getParser().Lex().isNot(AsmToken::RParen))
426       return Error(Parser.getTok().getLoc(), "expected ')'");
427
428     EndLoc = Tok.getLoc();
429     Parser.Lex(); // Eat ')'
430     return false;
431   }
432
433   // If this is "db[0-7]", match it as an alias
434   // for dr[0-7].
435   if (RegNo == 0 && Tok.getString().size() == 3 &&
436       Tok.getString().startswith("db")) {
437     switch (Tok.getString()[2]) {
438     case '0': RegNo = X86::DR0; break;
439     case '1': RegNo = X86::DR1; break;
440     case '2': RegNo = X86::DR2; break;
441     case '3': RegNo = X86::DR3; break;
442     case '4': RegNo = X86::DR4; break;
443     case '5': RegNo = X86::DR5; break;
444     case '6': RegNo = X86::DR6; break;
445     case '7': RegNo = X86::DR7; break;
446     }
447
448     if (RegNo != 0) {
449       EndLoc = Tok.getLoc();
450       Parser.Lex(); // Eat it.
451       return false;
452     }
453   }
454
455   if (RegNo == 0)
456     return Error(Tok.getLoc(), "invalid register name");
457
458   EndLoc = Tok.getLoc();
459   Parser.Lex(); // Eat identifier token.
460   return false;
461 }
462
463 X86Operand *X86ATTAsmParser::ParseOperand() {
464   switch (getLexer().getKind()) {
465   default:
466     // Parse a memory operand with no segment register.
467     return ParseMemOperand(0, Parser.getTok().getLoc());
468   case AsmToken::Percent: {
469     // Read the register.
470     unsigned RegNo;
471     SMLoc Start, End;
472     if (ParseRegister(RegNo, Start, End)) return 0;
473     if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
474       Error(Start, "eiz and riz can only be used as index registers");
475       return 0;
476     }
477
478     // If this is a segment register followed by a ':', then this is the start
479     // of a memory reference, otherwise this is a normal register reference.
480     if (getLexer().isNot(AsmToken::Colon))
481       return X86Operand::CreateReg(RegNo, Start, End);
482
483
484     getParser().Lex(); // Eat the colon.
485     return ParseMemOperand(RegNo, Start);
486   }
487   case AsmToken::Dollar: {
488     // $42 -> immediate.
489     SMLoc Start = Parser.getTok().getLoc(), End;
490     Parser.Lex();
491     const MCExpr *Val;
492     if (getParser().ParseExpression(Val, End))
493       return 0;
494     return X86Operand::CreateImm(Val, Start, End);
495   }
496   }
497 }
498
499 /// ParseMemOperand: segment: disp(basereg, indexreg, scale).  The '%ds:' prefix
500 /// has already been parsed if present.
501 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
502
503   // We have to disambiguate a parenthesized expression "(4+5)" from the start
504   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
505   // only way to do this without lookahead is to eat the '(' and see what is
506   // after it.
507   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
508   if (getLexer().isNot(AsmToken::LParen)) {
509     SMLoc ExprEnd;
510     if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
511
512     // After parsing the base expression we could either have a parenthesized
513     // memory address or not.  If not, return now.  If so, eat the (.
514     if (getLexer().isNot(AsmToken::LParen)) {
515       // Unless we have a segment register, treat this as an immediate.
516       if (SegReg == 0)
517         return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
518       return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
519     }
520
521     // Eat the '('.
522     Parser.Lex();
523   } else {
524     // Okay, we have a '('.  We don't know if this is an expression or not, but
525     // so we have to eat the ( to see beyond it.
526     SMLoc LParenLoc = Parser.getTok().getLoc();
527     Parser.Lex(); // Eat the '('.
528
529     if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
530       // Nothing to do here, fall into the code below with the '(' part of the
531       // memory operand consumed.
532     } else {
533       SMLoc ExprEnd;
534
535       // It must be an parenthesized expression, parse it now.
536       if (getParser().ParseParenExpression(Disp, ExprEnd))
537         return 0;
538
539       // After parsing the base expression we could either have a parenthesized
540       // memory address or not.  If not, return now.  If so, eat the (.
541       if (getLexer().isNot(AsmToken::LParen)) {
542         // Unless we have a segment register, treat this as an immediate.
543         if (SegReg == 0)
544           return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
545         return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
546       }
547
548       // Eat the '('.
549       Parser.Lex();
550     }
551   }
552
553   // If we reached here, then we just ate the ( of the memory operand.  Process
554   // the rest of the memory operand.
555   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
556
557   if (getLexer().is(AsmToken::Percent)) {
558     SMLoc L;
559     if (ParseRegister(BaseReg, L, L)) return 0;
560     if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
561       Error(L, "eiz and riz can only be used as index registers");
562       return 0;
563     }
564   }
565
566   if (getLexer().is(AsmToken::Comma)) {
567     Parser.Lex(); // Eat the comma.
568
569     // Following the comma we should have either an index register, or a scale
570     // value. We don't support the later form, but we want to parse it
571     // correctly.
572     //
573     // Not that even though it would be completely consistent to support syntax
574     // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
575     if (getLexer().is(AsmToken::Percent)) {
576       SMLoc L;
577       if (ParseRegister(IndexReg, L, L)) return 0;
578
579       if (getLexer().isNot(AsmToken::RParen)) {
580         // Parse the scale amount:
581         //  ::= ',' [scale-expression]
582         if (getLexer().isNot(AsmToken::Comma)) {
583           Error(Parser.getTok().getLoc(),
584                 "expected comma in scale expression");
585           return 0;
586         }
587         Parser.Lex(); // Eat the comma.
588
589         if (getLexer().isNot(AsmToken::RParen)) {
590           SMLoc Loc = Parser.getTok().getLoc();
591
592           int64_t ScaleVal;
593           if (getParser().ParseAbsoluteExpression(ScaleVal))
594             return 0;
595
596           // Validate the scale amount.
597           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
598             Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
599             return 0;
600           }
601           Scale = (unsigned)ScaleVal;
602         }
603       }
604     } else if (getLexer().isNot(AsmToken::RParen)) {
605       // A scale amount without an index is ignored.
606       // index.
607       SMLoc Loc = Parser.getTok().getLoc();
608
609       int64_t Value;
610       if (getParser().ParseAbsoluteExpression(Value))
611         return 0;
612
613       if (Value != 1)
614         Warning(Loc, "scale factor without index register is ignored");
615       Scale = 1;
616     }
617   }
618
619   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
620   if (getLexer().isNot(AsmToken::RParen)) {
621     Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
622     return 0;
623   }
624   SMLoc MemEnd = Parser.getTok().getLoc();
625   Parser.Lex(); // Eat the ')'.
626
627   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
628                                MemStart, MemEnd);
629 }
630
631 bool X86ATTAsmParser::
632 ParseInstruction(StringRef Name, SMLoc NameLoc,
633                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
634   StringRef PatchedName = Name;
635
636   // FIXME: Hack to recognize setneb as setne.
637   if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
638       PatchedName != "setb" && PatchedName != "setnb")
639     PatchedName = PatchedName.substr(0, Name.size()-1);
640   
641   // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
642   const MCExpr *ExtraImmOp = 0;
643   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
644       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
645        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
646     bool IsVCMP = PatchedName.startswith("vcmp");
647     unsigned SSECCIdx = IsVCMP ? 4 : 3;
648     unsigned SSEComparisonCode = StringSwitch<unsigned>(
649       PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
650       .Case("eq",          0)
651       .Case("lt",          1)
652       .Case("le",          2)
653       .Case("unord",       3)
654       .Case("neq",         4)
655       .Case("nlt",         5)
656       .Case("nle",         6)
657       .Case("ord",         7)
658       .Case("eq_uq",       8)
659       .Case("nge",         9)
660       .Case("ngt",      0x0A)
661       .Case("false",    0x0B)
662       .Case("neq_oq",   0x0C)
663       .Case("ge",       0x0D)
664       .Case("gt",       0x0E)
665       .Case("true",     0x0F)
666       .Case("eq_os",    0x10)
667       .Case("lt_oq",    0x11)
668       .Case("le_oq",    0x12)
669       .Case("unord_s",  0x13)
670       .Case("neq_us",   0x14)
671       .Case("nlt_uq",   0x15)
672       .Case("nle_uq",   0x16)
673       .Case("ord_s",    0x17)
674       .Case("eq_us",    0x18)
675       .Case("nge_uq",   0x19)
676       .Case("ngt_uq",   0x1A)
677       .Case("false_os", 0x1B)
678       .Case("neq_os",   0x1C)
679       .Case("ge_oq",    0x1D)
680       .Case("gt_oq",    0x1E)
681       .Case("true_us",  0x1F)
682       .Default(~0U);
683     if (SSEComparisonCode != ~0U) {
684       ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
685                                           getParser().getContext());
686       if (PatchedName.endswith("ss")) {
687         PatchedName = IsVCMP ? "vcmpss" : "cmpss";
688       } else if (PatchedName.endswith("sd")) {
689         PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
690       } else if (PatchedName.endswith("ps")) {
691         PatchedName = IsVCMP ? "vcmpps" : "cmpps";
692       } else {
693         assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
694         PatchedName = IsVCMP ? "vcmppd" : "cmppd";
695       }
696     }
697   }
698
699   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
700
701   if (ExtraImmOp)
702     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
703
704
705   // Determine whether this is an instruction prefix.
706   bool isPrefix =
707     Name == "lock" || Name == "rep" ||
708     Name == "repe" || Name == "repz" ||
709     Name == "repne" || Name == "repnz" ||
710     Name == "rex64" || Name == "data16";
711
712
713   // This does the actual operand parsing.  Don't parse any more if we have a
714   // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
715   // just want to parse the "lock" as the first instruction and the "incl" as
716   // the next one.
717   if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
718
719     // Parse '*' modifier.
720     if (getLexer().is(AsmToken::Star)) {
721       SMLoc Loc = Parser.getTok().getLoc();
722       Operands.push_back(X86Operand::CreateToken("*", Loc));
723       Parser.Lex(); // Eat the star.
724     }
725
726     // Read the first operand.
727     if (X86Operand *Op = ParseOperand())
728       Operands.push_back(Op);
729     else {
730       Parser.EatToEndOfStatement();
731       return true;
732     }
733
734     while (getLexer().is(AsmToken::Comma)) {
735       Parser.Lex();  // Eat the comma.
736
737       // Parse and remember the operand.
738       if (X86Operand *Op = ParseOperand())
739         Operands.push_back(Op);
740       else {
741         Parser.EatToEndOfStatement();
742         return true;
743       }
744     }
745
746     if (getLexer().isNot(AsmToken::EndOfStatement)) {
747       SMLoc Loc = getLexer().getLoc();
748       Parser.EatToEndOfStatement();
749       return Error(Loc, "unexpected token in argument list");
750     }
751   }
752
753   if (getLexer().is(AsmToken::EndOfStatement))
754     Parser.Lex(); // Consume the EndOfStatement
755   else if (isPrefix && getLexer().is(AsmToken::Slash))
756     Parser.Lex(); // Consume the prefix separator Slash
757
758   // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
759   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
760   // documented form in various unofficial manuals, so a lot of code uses it.
761   if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
762       Operands.size() == 3) {
763     X86Operand &Op = *(X86Operand*)Operands.back();
764     if (Op.isMem() && Op.Mem.SegReg == 0 &&
765         isa<MCConstantExpr>(Op.Mem.Disp) &&
766         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
767         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
768       SMLoc Loc = Op.getEndLoc();
769       Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
770       delete &Op;
771     }
772   }
773   // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
774   if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
775       Operands.size() == 3) {
776     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
777     if (Op.isMem() && Op.Mem.SegReg == 0 &&
778         isa<MCConstantExpr>(Op.Mem.Disp) &&
779         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
780         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
781       SMLoc Loc = Op.getEndLoc();
782       Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
783       delete &Op;
784     }
785   }
786   // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
787   if (Name.startswith("ins") && Operands.size() == 3 &&
788       (Name == "insb" || Name == "insw" || Name == "insl")) {
789     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
790     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
791     if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
792       Operands.pop_back();
793       Operands.pop_back();
794       delete &Op;
795       delete &Op2;
796     }
797   }
798
799   // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
800   if (Name.startswith("outs") && Operands.size() == 3 &&
801       (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
802     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
803     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
804     if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
805       Operands.pop_back();
806       Operands.pop_back();
807       delete &Op;
808       delete &Op2;
809     }
810   }
811
812   // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
813   if (Name.startswith("movs") && Operands.size() == 3 &&
814       (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
815        (is64BitMode() && Name == "movsq"))) {
816     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
817     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
818     if (isSrcOp(Op) && isDstOp(Op2)) {
819       Operands.pop_back();
820       Operands.pop_back();
821       delete &Op;
822       delete &Op2;
823     }
824   }
825   // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
826   if (Name.startswith("lods") && Operands.size() == 3 &&
827       (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
828        Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
829     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
830     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
831     if (isSrcOp(*Op1) && Op2->isReg()) {
832       const char *ins;
833       unsigned reg = Op2->getReg();
834       bool isLods = Name == "lods";
835       if (reg == X86::AL && (isLods || Name == "lodsb"))
836         ins = "lodsb";
837       else if (reg == X86::AX && (isLods || Name == "lodsw"))
838         ins = "lodsw";
839       else if (reg == X86::EAX && (isLods || Name == "lodsl"))
840         ins = "lodsl";
841       else if (reg == X86::RAX && (isLods || Name == "lodsq"))
842         ins = "lodsq";
843       else
844         ins = NULL;
845       if (ins != NULL) {
846         Operands.pop_back();
847         Operands.pop_back();
848         delete Op1;
849         delete Op2;
850         if (Name != ins)
851           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
852       }
853     }
854   }
855   // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
856   if (Name.startswith("stos") && Operands.size() == 3 &&
857       (Name == "stos" || Name == "stosb" || Name == "stosw" ||
858        Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
859     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
860     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
861     if (isDstOp(*Op2) && Op1->isReg()) {
862       const char *ins;
863       unsigned reg = Op1->getReg();
864       bool isStos = Name == "stos";
865       if (reg == X86::AL && (isStos || Name == "stosb"))
866         ins = "stosb";
867       else if (reg == X86::AX && (isStos || Name == "stosw"))
868         ins = "stosw";
869       else if (reg == X86::EAX && (isStos || Name == "stosl"))
870         ins = "stosl";
871       else if (reg == X86::RAX && (isStos || Name == "stosq"))
872         ins = "stosq";
873       else
874         ins = NULL;
875       if (ins != NULL) {
876         Operands.pop_back();
877         Operands.pop_back();
878         delete Op1;
879         delete Op2;
880         if (Name != ins)
881           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
882       }
883     }
884   }
885
886   // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
887   // "shift <op>".
888   if ((Name.startswith("shr") || Name.startswith("sar") ||
889        Name.startswith("shl") || Name.startswith("sal") ||
890        Name.startswith("rcl") || Name.startswith("rcr") ||
891        Name.startswith("rol") || Name.startswith("ror")) &&
892       Operands.size() == 3) {
893     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
894     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
895         cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
896       delete Operands[1];
897       Operands.erase(Operands.begin() + 1);
898     }
899   }
900   
901   // Transforms "int $3" into "int3" as a size optimization.  We can't write an
902   // instalias with an immediate operand yet.
903   if (Name == "int" && Operands.size() == 2) {
904     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
905     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
906         cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
907       delete Operands[1];
908       Operands.erase(Operands.begin() + 1);
909       static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
910     }
911   }
912
913   return false;
914 }
915
916 bool X86ATTAsmParser::
917 MatchAndEmitInstruction(SMLoc IDLoc,
918                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
919                         MCStreamer &Out) {
920   assert(!Operands.empty() && "Unexpect empty operand list!");
921   X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
922   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
923
924   // First, handle aliases that expand to multiple instructions.
925   // FIXME: This should be replaced with a real .td file alias mechanism.
926   // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
927   // call.
928   if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
929       Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
930       Op->getToken() == "finit" || Op->getToken() == "fsave" ||
931       Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
932     MCInst Inst;
933     Inst.setOpcode(X86::WAIT);
934     Out.EmitInstruction(Inst);
935
936     const char *Repl =
937       StringSwitch<const char*>(Op->getToken())
938         .Case("finit",  "fninit")
939         .Case("fsave",  "fnsave")
940         .Case("fstcw",  "fnstcw")
941         .Case("fstcww",  "fnstcw")
942         .Case("fstenv", "fnstenv")
943         .Case("fstsw",  "fnstsw")
944         .Case("fstsww", "fnstsw")
945         .Case("fclex",  "fnclex")
946         .Default(0);
947     assert(Repl && "Unknown wait-prefixed instruction");
948     delete Operands[0];
949     Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
950   }
951
952   bool WasOriginallyInvalidOperand = false;
953   unsigned OrigErrorInfo;
954   MCInst Inst;
955
956   // First, try a direct match.
957   switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
958   case Match_Success:
959     Out.EmitInstruction(Inst);
960     return false;
961   case Match_MissingFeature:
962     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
963     return true;
964   case Match_ConversionFail:
965     return Error(IDLoc, "unable to convert operands to instruction");
966   case Match_InvalidOperand:
967     WasOriginallyInvalidOperand = true;
968     break;
969   case Match_MnemonicFail:
970     break;
971   }
972
973   // FIXME: Ideally, we would only attempt suffix matches for things which are
974   // valid prefixes, and we could just infer the right unambiguous
975   // type. However, that requires substantially more matcher support than the
976   // following hack.
977
978   // Change the operand to point to a temporary token.
979   StringRef Base = Op->getToken();
980   SmallString<16> Tmp;
981   Tmp += Base;
982   Tmp += ' ';
983   Op->setTokenValue(Tmp.str());
984
985   // If this instruction starts with an 'f', then it is a floating point stack
986   // instruction.  These come in up to three forms for 32-bit, 64-bit, and
987   // 80-bit floating point, which use the suffixes s,l,t respectively.
988   //
989   // Otherwise, we assume that this may be an integer instruction, which comes
990   // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
991   const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
992   
993   // Check for the various suffix matches.
994   Tmp[Base.size()] = Suffixes[0];
995   unsigned ErrorInfoIgnore;
996   MatchResultTy Match1, Match2, Match3, Match4;
997   
998   Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
999   Tmp[Base.size()] = Suffixes[1];
1000   Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1001   Tmp[Base.size()] = Suffixes[2];
1002   Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1003   Tmp[Base.size()] = Suffixes[3];
1004   Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1005
1006   // Restore the old token.
1007   Op->setTokenValue(Base);
1008
1009   // If exactly one matched, then we treat that as a successful match (and the
1010   // instruction will already have been filled in correctly, since the failing
1011   // matches won't have modified it).
1012   unsigned NumSuccessfulMatches =
1013     (Match1 == Match_Success) + (Match2 == Match_Success) +
1014     (Match3 == Match_Success) + (Match4 == Match_Success);
1015   if (NumSuccessfulMatches == 1) {
1016     Out.EmitInstruction(Inst);
1017     return false;
1018   }
1019
1020   // Otherwise, the match failed, try to produce a decent error message.
1021
1022   // If we had multiple suffix matches, then identify this as an ambiguous
1023   // match.
1024   if (NumSuccessfulMatches > 1) {
1025     char MatchChars[4];
1026     unsigned NumMatches = 0;
1027     if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1028     if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1029     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1030     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1031
1032     SmallString<126> Msg;
1033     raw_svector_ostream OS(Msg);
1034     OS << "ambiguous instructions require an explicit suffix (could be ";
1035     for (unsigned i = 0; i != NumMatches; ++i) {
1036       if (i != 0)
1037         OS << ", ";
1038       if (i + 1 == NumMatches)
1039         OS << "or ";
1040       OS << "'" << Base << MatchChars[i] << "'";
1041     }
1042     OS << ")";
1043     Error(IDLoc, OS.str());
1044     return true;
1045   }
1046
1047   // Okay, we know that none of the variants matched successfully.
1048
1049   // If all of the instructions reported an invalid mnemonic, then the original
1050   // mnemonic was invalid.
1051   if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1052       (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1053     if (!WasOriginallyInvalidOperand) {
1054       Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
1055       return true;
1056     }
1057
1058     // Recover location info for the operand if we know which was the problem.
1059     SMLoc ErrorLoc = IDLoc;
1060     if (OrigErrorInfo != ~0U) {
1061       if (OrigErrorInfo >= Operands.size())
1062         return Error(IDLoc, "too few operands for instruction");
1063
1064       ErrorLoc = ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
1065       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1066     }
1067
1068     return Error(ErrorLoc, "invalid operand for instruction");
1069   }
1070
1071   // If one instruction matched with a missing feature, report this as a
1072   // missing feature.
1073   if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1074       (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1075     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1076     return true;
1077   }
1078
1079   // If one instruction matched with an invalid operand, report this as an
1080   // operand failure.
1081   if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1082       (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1083     Error(IDLoc, "invalid operand for instruction");
1084     return true;
1085   }
1086
1087   // If all of these were an outright failure, report it in a useless way.
1088   // FIXME: We should give nicer diagnostics about the exact failure.
1089   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1090   return true;
1091 }
1092
1093
1094 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
1095   StringRef IDVal = DirectiveID.getIdentifier();
1096   if (IDVal == ".word")
1097     return ParseDirectiveWord(2, DirectiveID.getLoc());
1098   return true;
1099 }
1100
1101 /// ParseDirectiveWord
1102 ///  ::= .word [ expression (, expression)* ]
1103 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1104   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1105     for (;;) {
1106       const MCExpr *Value;
1107       if (getParser().ParseExpression(Value))
1108         return true;
1109       
1110       getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1111       
1112       if (getLexer().is(AsmToken::EndOfStatement))
1113         break;
1114       
1115       // FIXME: Improve diagnostic.
1116       if (getLexer().isNot(AsmToken::Comma))
1117         return Error(L, "unexpected token in directive");
1118       Parser.Lex();
1119     }
1120   }
1121   
1122   Parser.Lex();
1123   return false;
1124 }
1125
1126
1127
1128
1129 extern "C" void LLVMInitializeX86AsmLexer();
1130
1131 // Force static initialization.
1132 extern "C" void LLVMInitializeX86AsmParser() {
1133   RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
1134   RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
1135   LLVMInitializeX86AsmLexer();
1136 }
1137
1138 #define GET_REGISTER_MATCHER
1139 #define GET_MATCHER_IMPLEMENTATION
1140 #include "X86GenAsmMatcher.inc"