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