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