Add the missing call to Error when a bad X86 scale expression is parsed.
[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             Error(Loc, "expected scale expression");
881             return 0;
882           }
883
884           // Validate the scale amount.
885           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
886             Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
887             return 0;
888           }
889           Scale = (unsigned)ScaleVal;
890         }
891       }
892     } else if (getLexer().isNot(AsmToken::RParen)) {
893       // A scale amount without an index is ignored.
894       // index.
895       SMLoc Loc = Parser.getTok().getLoc();
896
897       int64_t Value;
898       if (getParser().ParseAbsoluteExpression(Value))
899         return 0;
900
901       if (Value != 1)
902         Warning(Loc, "scale factor without index register is ignored");
903       Scale = 1;
904     }
905   }
906
907   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
908   if (getLexer().isNot(AsmToken::RParen)) {
909     Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
910     return 0;
911   }
912   SMLoc MemEnd = Parser.getTok().getLoc();
913   Parser.Lex(); // Eat the ')'.
914
915   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
916                                MemStart, MemEnd);
917 }
918
919 bool X86AsmParser::
920 ParseInstruction(StringRef Name, SMLoc NameLoc,
921                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
922   StringRef PatchedName = Name;
923
924   // FIXME: Hack to recognize setneb as setne.
925   if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
926       PatchedName != "setb" && PatchedName != "setnb")
927     PatchedName = PatchedName.substr(0, Name.size()-1);
928   
929   // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
930   const MCExpr *ExtraImmOp = 0;
931   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
932       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
933        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
934     bool IsVCMP = PatchedName.startswith("vcmp");
935     unsigned SSECCIdx = IsVCMP ? 4 : 3;
936     unsigned SSEComparisonCode = StringSwitch<unsigned>(
937       PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
938       .Case("eq",          0)
939       .Case("lt",          1)
940       .Case("le",          2)
941       .Case("unord",       3)
942       .Case("neq",         4)
943       .Case("nlt",         5)
944       .Case("nle",         6)
945       .Case("ord",         7)
946       .Case("eq_uq",       8)
947       .Case("nge",         9)
948       .Case("ngt",      0x0A)
949       .Case("false",    0x0B)
950       .Case("neq_oq",   0x0C)
951       .Case("ge",       0x0D)
952       .Case("gt",       0x0E)
953       .Case("true",     0x0F)
954       .Case("eq_os",    0x10)
955       .Case("lt_oq",    0x11)
956       .Case("le_oq",    0x12)
957       .Case("unord_s",  0x13)
958       .Case("neq_us",   0x14)
959       .Case("nlt_uq",   0x15)
960       .Case("nle_uq",   0x16)
961       .Case("ord_s",    0x17)
962       .Case("eq_us",    0x18)
963       .Case("nge_uq",   0x19)
964       .Case("ngt_uq",   0x1A)
965       .Case("false_os", 0x1B)
966       .Case("neq_os",   0x1C)
967       .Case("ge_oq",    0x1D)
968       .Case("gt_oq",    0x1E)
969       .Case("true_us",  0x1F)
970       .Default(~0U);
971     if (SSEComparisonCode != ~0U) {
972       ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
973                                           getParser().getContext());
974       if (PatchedName.endswith("ss")) {
975         PatchedName = IsVCMP ? "vcmpss" : "cmpss";
976       } else if (PatchedName.endswith("sd")) {
977         PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
978       } else if (PatchedName.endswith("ps")) {
979         PatchedName = IsVCMP ? "vcmpps" : "cmpps";
980       } else {
981         assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
982         PatchedName = IsVCMP ? "vcmppd" : "cmppd";
983       }
984     }
985   }
986
987   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
988
989   if (ExtraImmOp && !isParsingIntelSyntax())
990     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
991
992   // Determine whether this is an instruction prefix.
993   bool isPrefix =
994     Name == "lock" || Name == "rep" ||
995     Name == "repe" || Name == "repz" ||
996     Name == "repne" || Name == "repnz" ||
997     Name == "rex64" || Name == "data16";
998
999
1000   // This does the actual operand parsing.  Don't parse any more if we have a
1001   // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1002   // just want to parse the "lock" as the first instruction and the "incl" as
1003   // the next one.
1004   if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1005
1006     // Parse '*' modifier.
1007     if (getLexer().is(AsmToken::Star)) {
1008       SMLoc Loc = Parser.getTok().getLoc();
1009       Operands.push_back(X86Operand::CreateToken("*", Loc));
1010       Parser.Lex(); // Eat the star.
1011     }
1012
1013     // Read the first operand.
1014     if (X86Operand *Op = ParseOperand())
1015       Operands.push_back(Op);
1016     else {
1017       Parser.EatToEndOfStatement();
1018       return true;
1019     }
1020
1021     while (getLexer().is(AsmToken::Comma)) {
1022       Parser.Lex();  // Eat the comma.
1023
1024       // Parse and remember the operand.
1025       if (X86Operand *Op = ParseOperand())
1026         Operands.push_back(Op);
1027       else {
1028         Parser.EatToEndOfStatement();
1029         return true;
1030       }
1031     }
1032
1033     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1034       SMLoc Loc = getLexer().getLoc();
1035       Parser.EatToEndOfStatement();
1036       return Error(Loc, "unexpected token in argument list");
1037     }
1038   }
1039
1040   if (getLexer().is(AsmToken::EndOfStatement))
1041     Parser.Lex(); // Consume the EndOfStatement
1042   else if (isPrefix && getLexer().is(AsmToken::Slash))
1043     Parser.Lex(); // Consume the prefix separator Slash
1044
1045   if (ExtraImmOp && isParsingIntelSyntax())
1046     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1047
1048   // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1049   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
1050   // documented form in various unofficial manuals, so a lot of code uses it.
1051   if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1052       Operands.size() == 3) {
1053     X86Operand &Op = *(X86Operand*)Operands.back();
1054     if (Op.isMem() && Op.Mem.SegReg == 0 &&
1055         isa<MCConstantExpr>(Op.Mem.Disp) &&
1056         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1057         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1058       SMLoc Loc = Op.getEndLoc();
1059       Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1060       delete &Op;
1061     }
1062   }
1063   // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1064   if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1065       Operands.size() == 3) {
1066     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1067     if (Op.isMem() && Op.Mem.SegReg == 0 &&
1068         isa<MCConstantExpr>(Op.Mem.Disp) &&
1069         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1070         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1071       SMLoc Loc = Op.getEndLoc();
1072       Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1073       delete &Op;
1074     }
1075   }
1076   // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1077   if (Name.startswith("ins") && Operands.size() == 3 &&
1078       (Name == "insb" || Name == "insw" || Name == "insl")) {
1079     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1080     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1081     if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1082       Operands.pop_back();
1083       Operands.pop_back();
1084       delete &Op;
1085       delete &Op2;
1086     }
1087   }
1088
1089   // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1090   if (Name.startswith("outs") && Operands.size() == 3 &&
1091       (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1092     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1093     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1094     if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1095       Operands.pop_back();
1096       Operands.pop_back();
1097       delete &Op;
1098       delete &Op2;
1099     }
1100   }
1101
1102   // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1103   if (Name.startswith("movs") && Operands.size() == 3 &&
1104       (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1105        (is64BitMode() && Name == "movsq"))) {
1106     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1107     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1108     if (isSrcOp(Op) && isDstOp(Op2)) {
1109       Operands.pop_back();
1110       Operands.pop_back();
1111       delete &Op;
1112       delete &Op2;
1113     }
1114   }
1115   // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1116   if (Name.startswith("lods") && Operands.size() == 3 &&
1117       (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1118        Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1119     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1120     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1121     if (isSrcOp(*Op1) && Op2->isReg()) {
1122       const char *ins;
1123       unsigned reg = Op2->getReg();
1124       bool isLods = Name == "lods";
1125       if (reg == X86::AL && (isLods || Name == "lodsb"))
1126         ins = "lodsb";
1127       else if (reg == X86::AX && (isLods || Name == "lodsw"))
1128         ins = "lodsw";
1129       else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1130         ins = "lodsl";
1131       else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1132         ins = "lodsq";
1133       else
1134         ins = NULL;
1135       if (ins != NULL) {
1136         Operands.pop_back();
1137         Operands.pop_back();
1138         delete Op1;
1139         delete Op2;
1140         if (Name != ins)
1141           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1142       }
1143     }
1144   }
1145   // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1146   if (Name.startswith("stos") && Operands.size() == 3 &&
1147       (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1148        Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1149     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1150     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1151     if (isDstOp(*Op2) && Op1->isReg()) {
1152       const char *ins;
1153       unsigned reg = Op1->getReg();
1154       bool isStos = Name == "stos";
1155       if (reg == X86::AL && (isStos || Name == "stosb"))
1156         ins = "stosb";
1157       else if (reg == X86::AX && (isStos || Name == "stosw"))
1158         ins = "stosw";
1159       else if (reg == X86::EAX && (isStos || Name == "stosl"))
1160         ins = "stosl";
1161       else if (reg == X86::RAX && (isStos || Name == "stosq"))
1162         ins = "stosq";
1163       else
1164         ins = NULL;
1165       if (ins != NULL) {
1166         Operands.pop_back();
1167         Operands.pop_back();
1168         delete Op1;
1169         delete Op2;
1170         if (Name != ins)
1171           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1172       }
1173     }
1174   }
1175
1176   // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
1177   // "shift <op>".
1178   if ((Name.startswith("shr") || Name.startswith("sar") ||
1179        Name.startswith("shl") || Name.startswith("sal") ||
1180        Name.startswith("rcl") || Name.startswith("rcr") ||
1181        Name.startswith("rol") || Name.startswith("ror")) &&
1182       Operands.size() == 3) {
1183     if (isParsingIntelSyntax()) {
1184       // Intel syntax
1185       X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1186       if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1187           cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1188         delete Operands[2];
1189         Operands.pop_back();
1190       }
1191     } else {
1192       X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1193       if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1194           cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1195         delete Operands[1];
1196         Operands.erase(Operands.begin() + 1);
1197       }
1198     }
1199   }
1200   
1201   // Transforms "int $3" into "int3" as a size optimization.  We can't write an
1202   // instalias with an immediate operand yet.
1203   if (Name == "int" && Operands.size() == 2) {
1204     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1205     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1206         cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1207       delete Operands[1];
1208       Operands.erase(Operands.begin() + 1);
1209       static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1210     }
1211   }
1212
1213   return false;
1214 }
1215
1216 bool X86AsmParser::
1217 processInstruction(MCInst &Inst,
1218                    const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1219   switch (Inst.getOpcode()) {
1220   default: return false;
1221   case X86::AND16i16: {
1222     if (!Inst.getOperand(0).isImm() ||
1223         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1224       return false;
1225
1226     MCInst TmpInst;
1227     TmpInst.setOpcode(X86::AND16ri8);
1228     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1229     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1230     TmpInst.addOperand(Inst.getOperand(0));
1231     Inst = TmpInst;
1232     return true;
1233   }
1234   case X86::AND32i32: {
1235     if (!Inst.getOperand(0).isImm() ||
1236         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1237       return false;
1238
1239     MCInst TmpInst;
1240     TmpInst.setOpcode(X86::AND32ri8);
1241     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1242     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1243     TmpInst.addOperand(Inst.getOperand(0));
1244     Inst = TmpInst;
1245     return true;
1246   }
1247   case X86::AND64i32: {
1248     if (!Inst.getOperand(0).isImm() ||
1249         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1250       return false;
1251
1252     MCInst TmpInst;
1253     TmpInst.setOpcode(X86::AND64ri8);
1254     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1255     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1256     TmpInst.addOperand(Inst.getOperand(0));
1257     Inst = TmpInst;
1258     return true;
1259   }
1260   case X86::XOR16i16: {
1261     if (!Inst.getOperand(0).isImm() ||
1262         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1263       return false;
1264
1265     MCInst TmpInst;
1266     TmpInst.setOpcode(X86::XOR16ri8);
1267     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1268     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1269     TmpInst.addOperand(Inst.getOperand(0));
1270     Inst = TmpInst;
1271     return true;
1272   }
1273   case X86::XOR32i32: {
1274     if (!Inst.getOperand(0).isImm() ||
1275         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1276       return false;
1277
1278     MCInst TmpInst;
1279     TmpInst.setOpcode(X86::XOR32ri8);
1280     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1281     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1282     TmpInst.addOperand(Inst.getOperand(0));
1283     Inst = TmpInst;
1284     return true;
1285   }
1286   case X86::XOR64i32: {
1287     if (!Inst.getOperand(0).isImm() ||
1288         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1289       return false;
1290
1291     MCInst TmpInst;
1292     TmpInst.setOpcode(X86::XOR64ri8);
1293     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1294     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1295     TmpInst.addOperand(Inst.getOperand(0));
1296     Inst = TmpInst;
1297     return true;
1298   }
1299   case X86::OR16i16: {
1300     if (!Inst.getOperand(0).isImm() ||
1301         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1302       return false;
1303
1304     MCInst TmpInst;
1305     TmpInst.setOpcode(X86::OR16ri8);
1306     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1307     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1308     TmpInst.addOperand(Inst.getOperand(0));
1309     Inst = TmpInst;
1310     return true;
1311   }
1312   case X86::OR32i32: {
1313     if (!Inst.getOperand(0).isImm() ||
1314         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1315       return false;
1316
1317     MCInst TmpInst;
1318     TmpInst.setOpcode(X86::OR32ri8);
1319     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1320     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1321     TmpInst.addOperand(Inst.getOperand(0));
1322     Inst = TmpInst;
1323     return true;
1324   }
1325   case X86::OR64i32: {
1326     if (!Inst.getOperand(0).isImm() ||
1327         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1328       return false;
1329
1330     MCInst TmpInst;
1331     TmpInst.setOpcode(X86::OR64ri8);
1332     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1333     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1334     TmpInst.addOperand(Inst.getOperand(0));
1335     Inst = TmpInst;
1336     return true;
1337   }
1338   case X86::CMP16i16: {
1339     if (!Inst.getOperand(0).isImm() ||
1340         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1341       return false;
1342
1343     MCInst TmpInst;
1344     TmpInst.setOpcode(X86::CMP16ri8);
1345     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1346     TmpInst.addOperand(Inst.getOperand(0));
1347     Inst = TmpInst;
1348     return true;
1349   }
1350   case X86::CMP32i32: {
1351     if (!Inst.getOperand(0).isImm() ||
1352         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1353       return false;
1354
1355     MCInst TmpInst;
1356     TmpInst.setOpcode(X86::CMP32ri8);
1357     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1358     TmpInst.addOperand(Inst.getOperand(0));
1359     Inst = TmpInst;
1360     return true;
1361   }
1362   case X86::CMP64i32: {
1363     if (!Inst.getOperand(0).isImm() ||
1364         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1365       return false;
1366
1367     MCInst TmpInst;
1368     TmpInst.setOpcode(X86::CMP64ri8);
1369     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1370     TmpInst.addOperand(Inst.getOperand(0));
1371     Inst = TmpInst;
1372     return true;
1373   }
1374   case X86::ADD16i16: {
1375     if (!Inst.getOperand(0).isImm() ||
1376         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1377       return false;
1378
1379     MCInst TmpInst;
1380     TmpInst.setOpcode(X86::ADD16ri8);
1381     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1382     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1383     TmpInst.addOperand(Inst.getOperand(0));
1384     Inst = TmpInst;
1385     return true;
1386   }
1387   case X86::ADD32i32: {
1388     if (!Inst.getOperand(0).isImm() ||
1389         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1390       return false;
1391
1392     MCInst TmpInst;
1393     TmpInst.setOpcode(X86::ADD32ri8);
1394     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1395     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1396     TmpInst.addOperand(Inst.getOperand(0));
1397     Inst = TmpInst;
1398     return true;
1399   }
1400   case X86::ADD64i32: {
1401     if (!Inst.getOperand(0).isImm() ||
1402         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1403       return false;
1404
1405     MCInst TmpInst;
1406     TmpInst.setOpcode(X86::ADD64ri8);
1407     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1408     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1409     TmpInst.addOperand(Inst.getOperand(0));
1410     Inst = TmpInst;
1411     return true;
1412   }
1413   case X86::SUB16i16: {
1414     if (!Inst.getOperand(0).isImm() ||
1415         !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1416       return false;
1417
1418     MCInst TmpInst;
1419     TmpInst.setOpcode(X86::SUB16ri8);
1420     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1421     TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1422     TmpInst.addOperand(Inst.getOperand(0));
1423     Inst = TmpInst;
1424     return true;
1425   }
1426   case X86::SUB32i32: {
1427     if (!Inst.getOperand(0).isImm() ||
1428         !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1429       return false;
1430
1431     MCInst TmpInst;
1432     TmpInst.setOpcode(X86::SUB32ri8);
1433     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1434     TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1435     TmpInst.addOperand(Inst.getOperand(0));
1436     Inst = TmpInst;
1437     return true;
1438   }
1439   case X86::SUB64i32: {
1440     if (!Inst.getOperand(0).isImm() ||
1441         !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1442       return false;
1443
1444     MCInst TmpInst;
1445     TmpInst.setOpcode(X86::SUB64ri8);
1446     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1447     TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1448     TmpInst.addOperand(Inst.getOperand(0));
1449     Inst = TmpInst;
1450     return true;
1451   }
1452   }
1453 }
1454
1455 bool X86AsmParser::
1456 MatchAndEmitInstruction(SMLoc IDLoc,
1457                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1458                         MCStreamer &Out) {
1459   assert(!Operands.empty() && "Unexpect empty operand list!");
1460   X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1461   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1462
1463   // First, handle aliases that expand to multiple instructions.
1464   // FIXME: This should be replaced with a real .td file alias mechanism.
1465   // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1466   // call.
1467   if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1468       Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1469       Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1470       Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1471     MCInst Inst;
1472     Inst.setOpcode(X86::WAIT);
1473     Inst.setLoc(IDLoc);
1474     Out.EmitInstruction(Inst);
1475
1476     const char *Repl =
1477       StringSwitch<const char*>(Op->getToken())
1478         .Case("finit",  "fninit")
1479         .Case("fsave",  "fnsave")
1480         .Case("fstcw",  "fnstcw")
1481         .Case("fstcww",  "fnstcw")
1482         .Case("fstenv", "fnstenv")
1483         .Case("fstsw",  "fnstsw")
1484         .Case("fstsww", "fnstsw")
1485         .Case("fclex",  "fnclex")
1486         .Default(0);
1487     assert(Repl && "Unknown wait-prefixed instruction");
1488     delete Operands[0];
1489     Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1490   }
1491
1492   bool WasOriginallyInvalidOperand = false;
1493   unsigned OrigErrorInfo;
1494   MCInst Inst;
1495
1496   // First, try a direct match.
1497   switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo,
1498                                isParsingIntelSyntax())) {
1499   default: break;
1500   case Match_Success:
1501     // Some instructions need post-processing to, for example, tweak which
1502     // encoding is selected. Loop on it while changes happen so the
1503     // individual transformations can chain off each other. 
1504     while (processInstruction(Inst, Operands))
1505       ;
1506
1507     Inst.setLoc(IDLoc);
1508     Out.EmitInstruction(Inst);
1509     return false;
1510   case Match_MissingFeature:
1511     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1512     return true;
1513   case Match_ConversionFail:
1514     return Error(IDLoc, "unable to convert operands to instruction");
1515   case Match_InvalidOperand:
1516     WasOriginallyInvalidOperand = true;
1517     break;
1518   case Match_MnemonicFail:
1519     break;
1520   }
1521
1522   // FIXME: Ideally, we would only attempt suffix matches for things which are
1523   // valid prefixes, and we could just infer the right unambiguous
1524   // type. However, that requires substantially more matcher support than the
1525   // following hack.
1526
1527   // Change the operand to point to a temporary token.
1528   StringRef Base = Op->getToken();
1529   SmallString<16> Tmp;
1530   Tmp += Base;
1531   Tmp += ' ';
1532   Op->setTokenValue(Tmp.str());
1533
1534   // If this instruction starts with an 'f', then it is a floating point stack
1535   // instruction.  These come in up to three forms for 32-bit, 64-bit, and
1536   // 80-bit floating point, which use the suffixes s,l,t respectively.
1537   //
1538   // Otherwise, we assume that this may be an integer instruction, which comes
1539   // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1540   const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1541   
1542   // Check for the various suffix matches.
1543   Tmp[Base.size()] = Suffixes[0];
1544   unsigned ErrorInfoIgnore;
1545   unsigned Match1, Match2, Match3, Match4;
1546   
1547   Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1548   Tmp[Base.size()] = Suffixes[1];
1549   Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1550   Tmp[Base.size()] = Suffixes[2];
1551   Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1552   Tmp[Base.size()] = Suffixes[3];
1553   Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1554
1555   // Restore the old token.
1556   Op->setTokenValue(Base);
1557
1558   // If exactly one matched, then we treat that as a successful match (and the
1559   // instruction will already have been filled in correctly, since the failing
1560   // matches won't have modified it).
1561   unsigned NumSuccessfulMatches =
1562     (Match1 == Match_Success) + (Match2 == Match_Success) +
1563     (Match3 == Match_Success) + (Match4 == Match_Success);
1564   if (NumSuccessfulMatches == 1) {
1565     Inst.setLoc(IDLoc);
1566     Out.EmitInstruction(Inst);
1567     return false;
1568   }
1569
1570   // Otherwise, the match failed, try to produce a decent error message.
1571
1572   // If we had multiple suffix matches, then identify this as an ambiguous
1573   // match.
1574   if (NumSuccessfulMatches > 1) {
1575     char MatchChars[4];
1576     unsigned NumMatches = 0;
1577     if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1578     if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1579     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1580     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1581
1582     SmallString<126> Msg;
1583     raw_svector_ostream OS(Msg);
1584     OS << "ambiguous instructions require an explicit suffix (could be ";
1585     for (unsigned i = 0; i != NumMatches; ++i) {
1586       if (i != 0)
1587         OS << ", ";
1588       if (i + 1 == NumMatches)
1589         OS << "or ";
1590       OS << "'" << Base << MatchChars[i] << "'";
1591     }
1592     OS << ")";
1593     Error(IDLoc, OS.str());
1594     return true;
1595   }
1596
1597   // Okay, we know that none of the variants matched successfully.
1598
1599   // If all of the instructions reported an invalid mnemonic, then the original
1600   // mnemonic was invalid.
1601   if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1602       (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1603     if (!WasOriginallyInvalidOperand) {
1604       return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1605                    Op->getLocRange());
1606     }
1607
1608     // Recover location info for the operand if we know which was the problem.
1609     if (OrigErrorInfo != ~0U) {
1610       if (OrigErrorInfo >= Operands.size())
1611         return Error(IDLoc, "too few operands for instruction");
1612
1613       X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1614       if (Operand->getStartLoc().isValid()) {
1615         SMRange OperandRange = Operand->getLocRange();
1616         return Error(Operand->getStartLoc(), "invalid operand for instruction",
1617                      OperandRange);
1618       }
1619     }
1620
1621     return Error(IDLoc, "invalid operand for instruction");
1622   }
1623
1624   // If one instruction matched with a missing feature, report this as a
1625   // missing feature.
1626   if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1627       (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1628     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1629     return true;
1630   }
1631
1632   // If one instruction matched with an invalid operand, report this as an
1633   // operand failure.
1634   if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1635       (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1636     Error(IDLoc, "invalid operand for instruction");
1637     return true;
1638   }
1639
1640   // If all of these were an outright failure, report it in a useless way.
1641   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1642   return true;
1643 }
1644
1645
1646 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1647   StringRef IDVal = DirectiveID.getIdentifier();
1648   if (IDVal == ".word")
1649     return ParseDirectiveWord(2, DirectiveID.getLoc());
1650   else if (IDVal.startswith(".code"))
1651     return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1652   else if (IDVal.startswith(".intel_syntax")) {
1653     getParser().setAssemblerDialect(1);
1654     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1655       if(Parser.getTok().getString() == "noprefix") {
1656         // FIXME : Handle noprefix
1657         Parser.Lex();
1658       } else
1659         return true;
1660     }
1661     return false;
1662   }
1663   return true;
1664 }
1665
1666 /// ParseDirectiveWord
1667 ///  ::= .word [ expression (, expression)* ]
1668 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1669   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1670     for (;;) {
1671       const MCExpr *Value;
1672       if (getParser().ParseExpression(Value))
1673         return true;
1674       
1675       getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1676       
1677       if (getLexer().is(AsmToken::EndOfStatement))
1678         break;
1679       
1680       // FIXME: Improve diagnostic.
1681       if (getLexer().isNot(AsmToken::Comma))
1682         return Error(L, "unexpected token in directive");
1683       Parser.Lex();
1684     }
1685   }
1686   
1687   Parser.Lex();
1688   return false;
1689 }
1690
1691 /// ParseDirectiveCode
1692 ///  ::= .code32 | .code64
1693 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1694   if (IDVal == ".code32") {
1695     Parser.Lex();
1696     if (is64BitMode()) {
1697       SwitchMode();
1698       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1699     }
1700   } else if (IDVal == ".code64") {
1701     Parser.Lex();
1702     if (!is64BitMode()) {
1703       SwitchMode();
1704       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1705     }
1706   } else {
1707     return Error(L, "unexpected directive " + IDVal);
1708   }
1709
1710   return false;
1711 }
1712
1713
1714 extern "C" void LLVMInitializeX86AsmLexer();
1715
1716 // Force static initialization.
1717 extern "C" void LLVMInitializeX86AsmParser() {
1718   RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1719   RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1720   LLVMInitializeX86AsmLexer();
1721 }
1722
1723 #define GET_REGISTER_MATCHER
1724 #define GET_MATCHER_IMPLEMENTATION
1725 #include "X86GenAsmMatcher.inc"