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