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