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