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