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