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