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