[ms-inline asm] Remove some dead code.
[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/ADT/APFloat.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCParser/MCAsmLexer.h"
20 #include "llvm/MC/MCParser/MCAsmParser.h"
21 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCTargetAsmParser.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
30
31 using namespace llvm;
32
33 namespace {
34 struct X86Operand;
35
36 class X86AsmParser : public MCTargetAsmParser {
37   MCSubtargetInfo &STI;
38   MCAsmParser &Parser;
39   ParseInstructionInfo *InstInfo;
40 private:
41   MCAsmParser &getParser() const { return Parser; }
42
43   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
44
45   bool Error(SMLoc L, const Twine &Msg,
46              ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
47              bool MatchingInlineAsm = false) {
48     if (MatchingInlineAsm) return true;
49     return Parser.Error(L, Msg, Ranges);
50   }
51
52   X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
53     Error(Loc, Msg);
54     return 0;
55   }
56
57   X86Operand *ParseOperand();
58   X86Operand *ParseATTOperand();
59   X86Operand *ParseIntelOperand();
60   X86Operand *ParseIntelOffsetOfOperator();
61   X86Operand *ParseIntelOperator(unsigned OpKind);
62   X86Operand *ParseIntelMemOperand(unsigned SegReg, uint64_t ImmDisp,
63                                    SMLoc StartLoc);
64   X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
65                                        uint64_t ImmDisp, unsigned Size);
66   X86Operand *ParseIntelVarWithQualifier(const MCExpr *&Disp,
67                                          StringRef &Identifier);
68   X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
69
70   X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
71                                     unsigned BaseReg, unsigned IndexReg,
72                                     unsigned Scale, SMLoc Start, SMLoc End,
73                                     unsigned Size, StringRef SymName);
74
75   bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr **NewDisp,
76                              SmallString<64> &Err);
77
78   bool ParseDirectiveWord(unsigned Size, SMLoc L);
79   bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
80
81   bool processInstruction(MCInst &Inst,
82                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
83
84   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
85                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
86                                MCStreamer &Out, unsigned &ErrorInfo,
87                                bool MatchingInlineAsm);
88
89   /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
90   /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
91   bool isSrcOp(X86Operand &Op);
92
93   /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
94   /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
95   bool isDstOp(X86Operand &Op);
96
97   bool is64BitMode() const {
98     // FIXME: Can tablegen auto-generate this?
99     return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
100   }
101   void SwitchMode() {
102     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
103     setAvailableFeatures(FB);
104   }
105
106   /// @name Auto-generated Matcher Functions
107   /// {
108
109 #define GET_ASSEMBLER_HEADER
110 #include "X86GenAsmMatcher.inc"
111
112   /// }
113
114 public:
115   X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
116     : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
117
118     // Initialize the set of available features.
119     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
120   }
121   virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
122
123   virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
124                                 SMLoc NameLoc,
125                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
126
127   virtual bool ParseDirective(AsmToken DirectiveID);
128
129   bool isParsingIntelSyntax() {
130     return getParser().getAssemblerDialect();
131   }
132 };
133 } // end anonymous namespace
134
135 /// @name Auto-generated Match Functions
136 /// {
137
138 static unsigned MatchRegisterName(StringRef Name);
139
140 /// }
141
142 static bool isImmSExti16i8Value(uint64_t Value) {
143   return ((                                  Value <= 0x000000000000007FULL)||
144           (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
145           (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
146 }
147
148 static bool isImmSExti32i8Value(uint64_t Value) {
149   return ((                                  Value <= 0x000000000000007FULL)||
150           (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
151           (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
152 }
153
154 static bool isImmZExtu32u8Value(uint64_t Value) {
155     return (Value <= 0x00000000000000FFULL);
156 }
157
158 static bool isImmSExti64i8Value(uint64_t Value) {
159   return ((                                  Value <= 0x000000000000007FULL)||
160           (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
161 }
162
163 static bool isImmSExti64i32Value(uint64_t Value) {
164   return ((                                  Value <= 0x000000007FFFFFFFULL)||
165           (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
166 }
167 namespace {
168
169 /// X86Operand - Instances of this class represent a parsed X86 machine
170 /// instruction.
171 struct X86Operand : public MCParsedAsmOperand {
172   enum KindTy {
173     Token,
174     Register,
175     Immediate,
176     Memory
177   } Kind;
178
179   SMLoc StartLoc, EndLoc;
180   SMLoc OffsetOfLoc;
181   StringRef SymName;
182   bool AddressOf;
183
184   struct TokOp {
185     const char *Data;
186     unsigned Length;
187   };
188
189   struct RegOp {
190     unsigned RegNo;
191   };
192
193   struct ImmOp {
194     const MCExpr *Val;
195   };
196
197   struct MemOp {
198     unsigned SegReg;
199     const MCExpr *Disp;
200     unsigned BaseReg;
201     unsigned IndexReg;
202     unsigned Scale;
203     unsigned Size;
204   };
205
206   union {
207     struct TokOp Tok;
208     struct RegOp Reg;
209     struct ImmOp Imm;
210     struct MemOp Mem;
211   };
212
213   X86Operand(KindTy K, SMLoc Start, SMLoc End)
214     : Kind(K), StartLoc(Start), EndLoc(End) {}
215
216   StringRef getSymName() { return SymName; }
217
218   /// getStartLoc - Get the location of the first token of this operand.
219   SMLoc getStartLoc() const { return StartLoc; }
220   /// getEndLoc - Get the location of the last token of this operand.
221   SMLoc getEndLoc() const { return EndLoc; }
222   /// getLocRange - Get the range between the first and last token of this
223   /// operand.
224   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
225   /// getOffsetOfLoc - Get the location of the offset operator.
226   SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
227
228   virtual void print(raw_ostream &OS) const {}
229
230   StringRef getToken() const {
231     assert(Kind == Token && "Invalid access!");
232     return StringRef(Tok.Data, Tok.Length);
233   }
234   void setTokenValue(StringRef Value) {
235     assert(Kind == Token && "Invalid access!");
236     Tok.Data = Value.data();
237     Tok.Length = Value.size();
238   }
239
240   unsigned getReg() const {
241     assert(Kind == Register && "Invalid access!");
242     return Reg.RegNo;
243   }
244
245   const MCExpr *getImm() const {
246     assert(Kind == Immediate && "Invalid access!");
247     return Imm.Val;
248   }
249
250   const MCExpr *getMemDisp() const {
251     assert(Kind == Memory && "Invalid access!");
252     return Mem.Disp;
253   }
254   unsigned getMemSegReg() const {
255     assert(Kind == Memory && "Invalid access!");
256     return Mem.SegReg;
257   }
258   unsigned getMemBaseReg() const {
259     assert(Kind == Memory && "Invalid access!");
260     return Mem.BaseReg;
261   }
262   unsigned getMemIndexReg() const {
263     assert(Kind == Memory && "Invalid access!");
264     return Mem.IndexReg;
265   }
266   unsigned getMemScale() const {
267     assert(Kind == Memory && "Invalid access!");
268     return Mem.Scale;
269   }
270
271   bool isToken() const {return Kind == Token; }
272
273   bool isImm() const { return Kind == Immediate; }
274
275   bool isImmSExti16i8() 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 isImmSExti16i8Value(CE->getValue());
288   }
289   bool isImmSExti32i8() 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 isImmSExti32i8Value(CE->getValue());
302   }
303   bool isImmZExtu32u8() 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 isImmZExtu32u8Value(CE->getValue());
316   }
317   bool isImmSExti64i8() const {
318     if (!isImm())
319       return false;
320
321     // If this isn't a constant expr, just assume it fits and let relaxation
322     // handle it.
323     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
324     if (!CE)
325       return true;
326
327     // Otherwise, check the value is in a range that makes sense for this
328     // extension.
329     return isImmSExti64i8Value(CE->getValue());
330   }
331   bool isImmSExti64i32() const {
332     if (!isImm())
333       return false;
334
335     // If this isn't a constant expr, just assume it fits and let relaxation
336     // handle it.
337     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
338     if (!CE)
339       return true;
340
341     // Otherwise, check the value is in a range that makes sense for this
342     // extension.
343     return isImmSExti64i32Value(CE->getValue());
344   }
345
346   bool isOffsetOf() const {
347     return OffsetOfLoc.getPointer();
348   }
349
350   bool needAddressOf() const {
351     return AddressOf;
352   }
353
354   bool isMem() const { return Kind == Memory; }
355   bool isMem8() const {
356     return Kind == Memory && (!Mem.Size || Mem.Size == 8);
357   }
358   bool isMem16() const {
359     return Kind == Memory && (!Mem.Size || Mem.Size == 16);
360   }
361   bool isMem32() const {
362     return Kind == Memory && (!Mem.Size || Mem.Size == 32);
363   }
364   bool isMem64() const {
365     return Kind == Memory && (!Mem.Size || Mem.Size == 64);
366   }
367   bool isMem80() const {
368     return Kind == Memory && (!Mem.Size || Mem.Size == 80);
369   }
370   bool isMem128() const {
371     return Kind == Memory && (!Mem.Size || Mem.Size == 128);
372   }
373   bool isMem256() const {
374     return Kind == Memory && (!Mem.Size || Mem.Size == 256);
375   }
376
377   bool isMemVX32() const {
378     return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
379       getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
380   }
381   bool isMemVY32() const {
382     return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
383       getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
384   }
385   bool isMemVX64() const {
386     return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
387       getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
388   }
389   bool isMemVY64() const {
390     return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
391       getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
392   }
393
394   bool isAbsMem() const {
395     return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
396       !getMemIndexReg() && getMemScale() == 1;
397   }
398
399   bool isReg() const { return Kind == Register; }
400
401   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
402     // Add as immediates when possible.
403     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
404       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
405     else
406       Inst.addOperand(MCOperand::CreateExpr(Expr));
407   }
408
409   void addRegOperands(MCInst &Inst, unsigned N) const {
410     assert(N == 1 && "Invalid number of operands!");
411     Inst.addOperand(MCOperand::CreateReg(getReg()));
412   }
413
414   void addImmOperands(MCInst &Inst, unsigned N) const {
415     assert(N == 1 && "Invalid number of operands!");
416     addExpr(Inst, getImm());
417   }
418
419   void addMem8Operands(MCInst &Inst, unsigned N) const {
420     addMemOperands(Inst, N);
421   }
422   void addMem16Operands(MCInst &Inst, unsigned N) const {
423     addMemOperands(Inst, N);
424   }
425   void addMem32Operands(MCInst &Inst, unsigned N) const {
426     addMemOperands(Inst, N);
427   }
428   void addMem64Operands(MCInst &Inst, unsigned N) const {
429     addMemOperands(Inst, N);
430   }
431   void addMem80Operands(MCInst &Inst, unsigned N) const {
432     addMemOperands(Inst, N);
433   }
434   void addMem128Operands(MCInst &Inst, unsigned N) const {
435     addMemOperands(Inst, N);
436   }
437   void addMem256Operands(MCInst &Inst, unsigned N) const {
438     addMemOperands(Inst, N);
439   }
440   void addMemVX32Operands(MCInst &Inst, unsigned N) const {
441     addMemOperands(Inst, N);
442   }
443   void addMemVY32Operands(MCInst &Inst, unsigned N) const {
444     addMemOperands(Inst, N);
445   }
446   void addMemVX64Operands(MCInst &Inst, unsigned N) const {
447     addMemOperands(Inst, N);
448   }
449   void addMemVY64Operands(MCInst &Inst, unsigned N) const {
450     addMemOperands(Inst, N);
451   }
452
453   void addMemOperands(MCInst &Inst, unsigned N) const {
454     assert((N == 5) && "Invalid number of operands!");
455     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
456     Inst.addOperand(MCOperand::CreateImm(getMemScale()));
457     Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
458     addExpr(Inst, getMemDisp());
459     Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
460   }
461
462   void addAbsMemOperands(MCInst &Inst, unsigned N) const {
463     assert((N == 1) && "Invalid number of operands!");
464     // Add as immediates when possible.
465     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
466       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
467     else
468       Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
469   }
470
471   static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
472     SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
473     X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
474     Res->Tok.Data = Str.data();
475     Res->Tok.Length = Str.size();
476     return Res;
477   }
478
479   static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
480                                bool AddressOf = false,
481                                SMLoc OffsetOfLoc = SMLoc(),
482                                StringRef SymName = StringRef()) {
483     X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
484     Res->Reg.RegNo = RegNo;
485     Res->AddressOf = AddressOf;
486     Res->OffsetOfLoc = OffsetOfLoc;
487     Res->SymName = SymName;
488     return Res;
489   }
490
491   static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
492     X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
493     Res->Imm.Val = Val;
494     return Res;
495   }
496
497   /// Create an absolute memory operand.
498   static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
499                                unsigned Size = 0,
500                                StringRef SymName = StringRef()) {
501     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
502     Res->Mem.SegReg   = 0;
503     Res->Mem.Disp     = Disp;
504     Res->Mem.BaseReg  = 0;
505     Res->Mem.IndexReg = 0;
506     Res->Mem.Scale    = 1;
507     Res->Mem.Size     = Size;
508     Res->SymName = SymName;
509     Res->AddressOf = false;
510     return Res;
511   }
512
513   /// Create a generalized memory operand.
514   static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
515                                unsigned BaseReg, unsigned IndexReg,
516                                unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
517                                unsigned Size = 0,
518                                StringRef SymName = StringRef()) {
519     // We should never just have a displacement, that should be parsed as an
520     // absolute memory operand.
521     assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
522
523     // The scale should always be one of {1,2,4,8}.
524     assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
525            "Invalid scale!");
526     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
527     Res->Mem.SegReg   = SegReg;
528     Res->Mem.Disp     = Disp;
529     Res->Mem.BaseReg  = BaseReg;
530     Res->Mem.IndexReg = IndexReg;
531     Res->Mem.Scale    = Scale;
532     Res->Mem.Size     = Size;
533     Res->SymName = SymName;
534     Res->AddressOf = false;
535     return Res;
536   }
537 };
538
539 } // end anonymous namespace.
540
541 bool X86AsmParser::isSrcOp(X86Operand &Op) {
542   unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
543
544   return (Op.isMem() &&
545     (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
546     isa<MCConstantExpr>(Op.Mem.Disp) &&
547     cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
548     Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
549 }
550
551 bool X86AsmParser::isDstOp(X86Operand &Op) {
552   unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
553
554   return Op.isMem() &&
555     (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
556     isa<MCConstantExpr>(Op.Mem.Disp) &&
557     cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
558     Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
559 }
560
561 bool X86AsmParser::ParseRegister(unsigned &RegNo,
562                                  SMLoc &StartLoc, SMLoc &EndLoc) {
563   RegNo = 0;
564   const AsmToken &PercentTok = Parser.getTok();
565   StartLoc = PercentTok.getLoc();
566
567   // If we encounter a %, ignore it. This code handles registers with and
568   // without the prefix, unprefixed registers can occur in cfi directives.
569   if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
570     Parser.Lex(); // Eat percent token.
571
572   const AsmToken &Tok = Parser.getTok();
573   EndLoc = Tok.getEndLoc();
574
575   if (Tok.isNot(AsmToken::Identifier)) {
576     if (isParsingIntelSyntax()) return true;
577     return Error(StartLoc, "invalid register name",
578                  SMRange(StartLoc, EndLoc));
579   }
580
581   RegNo = MatchRegisterName(Tok.getString());
582
583   // If the match failed, try the register name as lowercase.
584   if (RegNo == 0)
585     RegNo = MatchRegisterName(Tok.getString().lower());
586
587   if (!is64BitMode()) {
588     // FIXME: This should be done using Requires<In32BitMode> and
589     // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
590     // checked.
591     // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
592     // REX prefix.
593     if (RegNo == X86::RIZ ||
594         X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
595         X86II::isX86_64NonExtLowByteReg(RegNo) ||
596         X86II::isX86_64ExtendedReg(RegNo))
597       return Error(StartLoc, "register %"
598                    + Tok.getString() + " is only available in 64-bit mode",
599                    SMRange(StartLoc, EndLoc));
600   }
601
602   // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
603   if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
604     RegNo = X86::ST0;
605     Parser.Lex(); // Eat 'st'
606
607     // Check to see if we have '(4)' after %st.
608     if (getLexer().isNot(AsmToken::LParen))
609       return false;
610     // Lex the paren.
611     getParser().Lex();
612
613     const AsmToken &IntTok = Parser.getTok();
614     if (IntTok.isNot(AsmToken::Integer))
615       return Error(IntTok.getLoc(), "expected stack index");
616     switch (IntTok.getIntVal()) {
617     case 0: RegNo = X86::ST0; break;
618     case 1: RegNo = X86::ST1; break;
619     case 2: RegNo = X86::ST2; break;
620     case 3: RegNo = X86::ST3; break;
621     case 4: RegNo = X86::ST4; break;
622     case 5: RegNo = X86::ST5; break;
623     case 6: RegNo = X86::ST6; break;
624     case 7: RegNo = X86::ST7; break;
625     default: return Error(IntTok.getLoc(), "invalid stack index");
626     }
627
628     if (getParser().Lex().isNot(AsmToken::RParen))
629       return Error(Parser.getTok().getLoc(), "expected ')'");
630
631     EndLoc = Parser.getTok().getEndLoc();
632     Parser.Lex(); // Eat ')'
633     return false;
634   }
635
636   EndLoc = Parser.getTok().getEndLoc();
637
638   // If this is "db[0-7]", match it as an alias
639   // for dr[0-7].
640   if (RegNo == 0 && Tok.getString().size() == 3 &&
641       Tok.getString().startswith("db")) {
642     switch (Tok.getString()[2]) {
643     case '0': RegNo = X86::DR0; break;
644     case '1': RegNo = X86::DR1; break;
645     case '2': RegNo = X86::DR2; break;
646     case '3': RegNo = X86::DR3; break;
647     case '4': RegNo = X86::DR4; break;
648     case '5': RegNo = X86::DR5; break;
649     case '6': RegNo = X86::DR6; break;
650     case '7': RegNo = X86::DR7; break;
651     }
652
653     if (RegNo != 0) {
654       EndLoc = Parser.getTok().getEndLoc();
655       Parser.Lex(); // Eat it.
656       return false;
657     }
658   }
659
660   if (RegNo == 0) {
661     if (isParsingIntelSyntax()) return true;
662     return Error(StartLoc, "invalid register name",
663                  SMRange(StartLoc, EndLoc));
664   }
665
666   Parser.Lex(); // Eat identifier token.
667   return false;
668 }
669
670 X86Operand *X86AsmParser::ParseOperand() {
671   if (isParsingIntelSyntax())
672     return ParseIntelOperand();
673   return ParseATTOperand();
674 }
675
676 /// getIntelMemOperandSize - Return intel memory operand size.
677 static unsigned getIntelMemOperandSize(StringRef OpStr) {
678   unsigned Size = StringSwitch<unsigned>(OpStr)
679     .Cases("BYTE", "byte", 8)
680     .Cases("WORD", "word", 16)
681     .Cases("DWORD", "dword", 32)
682     .Cases("QWORD", "qword", 64)
683     .Cases("XWORD", "xword", 80)
684     .Cases("XMMWORD", "xmmword", 128)
685     .Cases("YMMWORD", "ymmword", 256)
686     .Default(0);
687   return Size;
688 }
689
690 enum InfixCalculatorTok {
691   IC_PLUS = 0,
692   IC_MINUS,
693   IC_MULTIPLY,
694   IC_DIVIDE,
695   IC_RPAREN,
696   IC_LPAREN,
697   IC_IMM,
698   IC_REGISTER
699 };
700 static const char OpPrecedence[] = {
701   0, // IC_PLUS
702   0, // IC_MINUS
703   1, // IC_MULTIPLY
704   1, // IC_DIVIDE
705   2, // IC_RPAREN
706   3, // IC_LPAREN
707   0, // IC_IMM
708   0  // IC_REGISTER
709 };
710
711 class InfixCalculator {
712   typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
713   SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
714   SmallVector<ICToken, 4> PostfixStack;
715
716 public:
717   int64_t popOperand() {
718     assert (!PostfixStack.empty() && "Poped an empty stack!");
719     ICToken Op = PostfixStack.pop_back_val();
720     assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
721             && "Expected and immediate or register!");
722     return Op.second;
723   }
724   void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
725     assert ((Op == IC_IMM || Op == IC_REGISTER) &&
726             "Unexpected operand!");
727     PostfixStack.push_back(std::make_pair(Op, Val));
728   }
729
730   void popOperator() { InfixOperatorStack.pop_back_val(); }
731   void pushOperator(InfixCalculatorTok Op) {
732     // Push the new operator if the stack is empty.
733     if (InfixOperatorStack.empty()) {
734       InfixOperatorStack.push_back(Op);
735       return;
736     }
737
738     // Push the new operator if it has a higher precedence than the operator on
739     // the top of the stack or the operator on the top of the stack is a left
740     // parentheses.
741     unsigned Idx = InfixOperatorStack.size() - 1;
742     InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
743     if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
744       InfixOperatorStack.push_back(Op);
745       return;
746     }
747
748     // The operator on the top of the stack has higher precedence than the
749     // new operator.
750     unsigned ParenCount = 0;
751     while (1) {
752       // Nothing to process.
753       if (InfixOperatorStack.empty())
754         break;
755
756       Idx = InfixOperatorStack.size() - 1;
757       StackOp = InfixOperatorStack[Idx];
758       if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
759         break;
760
761       // If we have an even parentheses count and we see a left parentheses,
762       // then stop processing.
763       if (!ParenCount && StackOp == IC_LPAREN)
764         break;
765
766       if (StackOp == IC_RPAREN) {
767         ++ParenCount;
768         InfixOperatorStack.pop_back_val();
769       } else if (StackOp == IC_LPAREN) {
770         --ParenCount;
771         InfixOperatorStack.pop_back_val();
772       } else {
773         InfixOperatorStack.pop_back_val();
774         PostfixStack.push_back(std::make_pair(StackOp, 0));
775       }
776     }
777     // Push the new operator.
778     InfixOperatorStack.push_back(Op);
779   }
780   int64_t execute() {
781     // Push any remaining operators onto the postfix stack.
782     while (!InfixOperatorStack.empty()) {
783       InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
784       if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
785         PostfixStack.push_back(std::make_pair(StackOp, 0));
786     }
787
788     if (PostfixStack.empty())
789       return 0;
790
791     SmallVector<ICToken, 16> OperandStack;
792     for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
793       ICToken Op = PostfixStack[i];
794       if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
795         OperandStack.push_back(Op);
796       } else {
797         assert (OperandStack.size() > 1 && "Too few operands.");
798         int64_t Val;
799         ICToken Op2 = OperandStack.pop_back_val();
800         ICToken Op1 = OperandStack.pop_back_val();
801         switch (Op.first) {
802         default:
803           report_fatal_error("Unexpected operator!");
804           break;
805         case IC_PLUS:
806           Val = Op1.second + Op2.second;
807           OperandStack.push_back(std::make_pair(IC_IMM, Val));
808           break;
809         case IC_MINUS:
810           Val = Op1.second - Op2.second;
811           OperandStack.push_back(std::make_pair(IC_IMM, Val));
812           break;
813         case IC_MULTIPLY:
814           assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
815                   "Multiply operation with an immediate and a register!");
816           Val = Op1.second * Op2.second;
817           OperandStack.push_back(std::make_pair(IC_IMM, Val));
818           break;
819         case IC_DIVIDE:
820           assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
821                   "Divide operation with an immediate and a register!");
822           assert (Op2.second != 0 && "Division by zero!");
823           Val = Op1.second / Op2.second;
824           OperandStack.push_back(std::make_pair(IC_IMM, Val));
825           break;
826         }
827       }
828     }
829     assert (OperandStack.size() == 1 && "Expected a single result.");
830     return OperandStack.pop_back_val().second;
831   }
832 };
833
834 enum IntelBracExprState {
835   IBES_PLUS,
836   IBES_MINUS,
837   IBES_MULTIPLY,
838   IBES_DIVIDE,
839   IBES_LBRAC,
840   IBES_RBRAC,
841   IBES_LPAREN,
842   IBES_RPAREN,
843   IBES_REGISTER,
844   IBES_REGISTER_STAR,
845   IBES_INTEGER,
846   IBES_INTEGER_STAR,
847   IBES_IDENTIFIER,
848   IBES_ERROR
849 };
850
851 class IntelBracExprStateMachine {
852   IntelBracExprState State;
853   unsigned BaseReg, IndexReg, TmpReg, Scale;
854   int64_t Disp;
855   const MCExpr *Sym;
856   StringRef SymName;
857   InfixCalculator IC;
858 public:
859   IntelBracExprStateMachine(MCAsmParser &parser, int64_t disp) :
860     State(IBES_PLUS), BaseReg(0), IndexReg(0), TmpReg(0), Scale(1), Disp(disp),
861     Sym(0) {}
862
863   unsigned getBaseReg() { return BaseReg; }
864   unsigned getIndexReg() { return IndexReg; }
865   unsigned getScale() { return Scale; }
866   const MCExpr *getSym() { return Sym; }
867   StringRef getSymName() { return SymName; }
868   int64_t getImmDisp() { return Disp + IC.execute(); }
869   bool isValidEndState() { return State == IBES_RBRAC; }
870
871   void onPlus() {
872     switch (State) {
873     default:
874       State = IBES_ERROR;
875       break;
876     case IBES_INTEGER:
877     case IBES_RPAREN:
878       State = IBES_PLUS;
879       IC.pushOperator(IC_PLUS);
880       break;
881     case IBES_REGISTER:
882       State = IBES_PLUS;
883       // If we already have a BaseReg, then assume this is the IndexReg with a
884       // scale of 1.
885       if (!BaseReg) {
886         BaseReg = TmpReg;
887       } else {
888         assert (!IndexReg && "BaseReg/IndexReg already set!");
889         IndexReg = TmpReg;
890         Scale = 1;
891       }
892       IC.pushOperator(IC_PLUS);
893       break;
894     }
895   }
896   void onMinus() {
897     switch (State) {
898     default:
899       State = IBES_ERROR;
900       break;
901     case IBES_PLUS:
902     case IBES_LPAREN:
903       IC.pushOperand(IC_IMM);
904     case IBES_INTEGER:
905     case IBES_RPAREN:
906       State = IBES_MINUS;
907       IC.pushOperator(IC_MINUS);
908       break;
909     case IBES_REGISTER:
910       State = IBES_MINUS;
911       // If we already have a BaseReg, then assume this is the IndexReg with a
912       // scale of 1.
913       if (!BaseReg) {
914         BaseReg = TmpReg;
915       } else {
916         assert (!IndexReg && "BaseReg/IndexReg already set!");
917         IndexReg = TmpReg;
918         Scale = 1;
919       }
920       IC.pushOperator(IC_MINUS);
921       break;
922     }
923   }
924   void onRegister(unsigned Reg) {
925     switch (State) {
926     default:
927       State = IBES_ERROR;
928       break;
929     case IBES_PLUS:
930     case IBES_LPAREN:
931       State = IBES_REGISTER;
932       TmpReg = Reg;
933       IC.pushOperand(IC_REGISTER);
934       break;
935     case IBES_INTEGER_STAR:
936       assert (!IndexReg && "IndexReg already set!");
937       State = IBES_INTEGER;
938       IndexReg = Reg;
939       Scale = IC.popOperand();
940       IC.pushOperand(IC_IMM);
941       IC.popOperator();
942       break;
943     }
944   }
945   void onDispExpr(const MCExpr *SymRef, StringRef SymRefName) {
946     switch (State) {
947     default:
948       State = IBES_ERROR;
949       break;
950     case IBES_PLUS:
951     case IBES_MINUS:
952       State = IBES_INTEGER;
953       Sym = SymRef;
954       SymName = SymRefName;
955       IC.pushOperand(IC_IMM);
956       break;
957     }
958   }
959   void onInteger(int64_t TmpInt) {
960     switch (State) {
961     default:
962       State = IBES_ERROR;
963       break;
964     case IBES_PLUS:
965     case IBES_MINUS:
966     case IBES_MULTIPLY:
967     case IBES_DIVIDE:
968     case IBES_LPAREN:
969     case IBES_INTEGER_STAR:
970       State = IBES_INTEGER;
971       IC.pushOperand(IC_IMM, TmpInt);
972       break;
973     case IBES_REGISTER_STAR:
974       assert (!IndexReg && "IndexReg already set!");
975       State = IBES_INTEGER;
976       IndexReg = TmpReg;
977       Scale = TmpInt;
978       IC.popOperator();
979       break;
980     }
981   }
982   void onStar() {
983     switch (State) {
984     default:
985       State = IBES_ERROR;
986       break;
987     case IBES_INTEGER:
988       State = IBES_INTEGER_STAR;
989       IC.pushOperator(IC_MULTIPLY);
990       break;
991     case IBES_REGISTER:
992       State = IBES_REGISTER_STAR;
993       IC.pushOperator(IC_MULTIPLY);
994       break;
995     case IBES_RPAREN:
996       State = IBES_MULTIPLY;
997       IC.pushOperator(IC_MULTIPLY);
998       break;
999     }
1000   }
1001   void onDivide() {
1002     switch (State) {
1003     default:
1004       State = IBES_ERROR;
1005       break;
1006     case IBES_INTEGER:
1007       State = IBES_DIVIDE;
1008       IC.pushOperator(IC_DIVIDE);
1009       break;
1010     }
1011   }
1012   void onLBrac() {
1013     switch (State) {
1014     default:
1015       State = IBES_ERROR;
1016       break;
1017     case IBES_RBRAC:
1018       State = IBES_PLUS;
1019       IC.pushOperator(IC_PLUS);
1020       break;
1021     }
1022   }
1023   void onRBrac() {
1024     switch (State) {
1025     default:
1026       State = IBES_ERROR;
1027       break;
1028     case IBES_RPAREN:
1029     case IBES_INTEGER:
1030       State = IBES_RBRAC;
1031       break;
1032     case IBES_REGISTER:
1033       State = IBES_RBRAC;
1034       // If we already have a BaseReg, then assume this is the IndexReg with a
1035       // scale of 1.
1036       if (!BaseReg) {
1037         BaseReg = TmpReg;
1038       } else {
1039         assert (!IndexReg && "BaseReg/IndexReg already set!");
1040         IndexReg = TmpReg;
1041         Scale = 1;
1042       }
1043       break;
1044     }
1045   }
1046   void onLParen() {
1047     switch (State) {
1048     default:
1049       State = IBES_ERROR;
1050       break;
1051     case IBES_PLUS:
1052     case IBES_MINUS:
1053     case IBES_MULTIPLY:
1054     case IBES_DIVIDE:
1055     case IBES_INTEGER_STAR:
1056     case IBES_LPAREN:
1057       State = IBES_LPAREN;
1058       IC.pushOperator(IC_LPAREN);
1059       break;
1060     }
1061   }
1062   void onRParen() {
1063     switch (State) {
1064     default:
1065       State = IBES_ERROR;
1066       break;
1067     case IBES_REGISTER:
1068     case IBES_INTEGER:
1069     case IBES_PLUS:
1070     case IBES_MINUS:
1071     case IBES_MULTIPLY:
1072     case IBES_DIVIDE:
1073     case IBES_RPAREN:
1074       State = IBES_RPAREN;
1075       IC.pushOperator(IC_RPAREN);
1076       break;
1077     }
1078   }
1079 };
1080
1081 X86Operand *
1082 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1083                                     unsigned BaseReg, unsigned IndexReg,
1084                                     unsigned Scale, SMLoc Start, SMLoc End,
1085                                     unsigned Size, StringRef SymName) {
1086   bool NeedSizeDir = false;
1087   if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
1088     const MCSymbol &Sym = SymRef->getSymbol();
1089     // FIXME: The SemaLookup will fail if the name is anything other then an
1090     // identifier.
1091     // FIXME: Pass a valid SMLoc.
1092     bool IsVarDecl = false;
1093     unsigned tLength, tSize, tType;
1094     SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, tLength, tSize,
1095                                             tType, IsVarDecl);
1096     if (!Size) {
1097       Size = tType * 8; // Size is in terms of bits in this context.
1098       NeedSizeDir = Size > 0;
1099     }
1100     // If this is not a VarDecl then assume it is a FuncDecl or some other label
1101     // reference.  We need an 'r' constraint here, so we need to create register
1102     // operand to ensure proper matching.  Just pick a GPR based on the size of
1103     // a pointer.
1104     if (!IsVarDecl) {
1105       unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1106       return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1107                                    SMLoc(), SymName);
1108     }
1109   }
1110
1111   if (NeedSizeDir)
1112     InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1113                                                 /*Len=*/0, Size));  
1114
1115   // When parsing inline assembly we set the base register to a non-zero value
1116   // if we don't know the actual value at this time.  This is necessary to
1117   // get the matching correct in some cases.
1118   BaseReg = BaseReg ? BaseReg : 1;
1119   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1120                                End, Size, SymName);
1121 }
1122
1123 static void
1124 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1125                            StringRef SymName, int64_t ImmDisp,
1126                            int64_t FinalImmDisp, SMLoc &BracLoc,
1127                            SMLoc &StartInBrac, SMLoc &End) {
1128   // Remove the '[' and ']' from the IR string.
1129   AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1130   AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1131
1132   // If ImmDisp is non-zero, then we parsed a displacement before the
1133   // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1134   // If ImmDisp doesn't match the displacement computed by the state machine
1135   // then we have an additional displacement in the bracketed expression.
1136   if (ImmDisp != FinalImmDisp) {
1137     if (ImmDisp) {
1138       // We have an immediate displacement before the bracketed expression.
1139       // Adjust this to match the final immediate displacement.
1140       bool Found = false;
1141       for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1142              E = AsmRewrites->end(); I != E; ++I) {
1143         if ((*I).Loc.getPointer() > BracLoc.getPointer())
1144           continue;
1145         if ((*I).Kind == AOK_ImmPrefix) {
1146           (*I).Kind = AOK_Imm;
1147           (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1148           (*I).Val = FinalImmDisp;
1149           Found = true;
1150           break;
1151         }
1152       }
1153       assert (Found && "Unable to rewrite ImmDisp.");
1154     } else {
1155       // We have a symbolic and an immediate displacement, but no displacement
1156       // before the bracketed expression.
1157       
1158       // Put the immediate displacement before the bracketed expression.
1159       AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0,
1160                                         FinalImmDisp));
1161     }
1162   }
1163   // Remove all the ImmPrefix rewrites within the brackets.
1164   for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1165          E = AsmRewrites->end(); I != E; ++I) {
1166     if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1167       continue;
1168     if ((*I).Kind == AOK_ImmPrefix)
1169       (*I).Kind = AOK_Delete;
1170   }
1171   const char *SymLocPtr = SymName.data();
1172   // Skip everything before the symbol.        
1173   if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1174     assert(Len > 0 && "Expected a non-negative length.");
1175     AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1176   }
1177   // Skip everything after the symbol.
1178   if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1179     SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1180     assert(Len > 0 && "Expected a non-negative length.");
1181     AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1182   }
1183 }
1184
1185 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1186                                                    uint64_t ImmDisp,
1187                                                    unsigned Size) {
1188   const AsmToken &Tok = Parser.getTok();
1189   SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1190   if (getLexer().isNot(AsmToken::LBrac))
1191     return ErrorOperand(BracLoc, "Expected '[' token!");
1192   Parser.Lex(); // Eat '['
1193
1194   SMLoc StartInBrac = Tok.getLoc();
1195   // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ].  We
1196   // may have already parsed an immediate displacement before the bracketed
1197   // expression.
1198   bool Done = false;
1199   IntelBracExprStateMachine SM(Parser, ImmDisp);
1200   while (!Done) {
1201     bool UpdateLocLex = true;
1202
1203     // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1204     // identifier.  Don't try an parse it as a register.
1205     if (Tok.getString().startswith("."))
1206       break;
1207
1208     switch (getLexer().getKind()) {
1209     default: {
1210       if (SM.isValidEndState()) {
1211         Done = true;
1212         break;
1213       }
1214       return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1215     }
1216     case AsmToken::Identifier: {
1217       // This could be a register or a symbolic displacement.
1218       unsigned TmpReg;
1219       const MCExpr *Disp = 0;
1220       SMLoc IdentLoc = Tok.getLoc();
1221       StringRef Identifier = Tok.getString();
1222       if(!ParseRegister(TmpReg, IdentLoc, End)) {
1223         SM.onRegister(TmpReg);
1224         UpdateLocLex = false;
1225         break;
1226       } else if (!getParser().parsePrimaryExpr(Disp, End)) {
1227         if (X86Operand *Err = ParseIntelVarWithQualifier(Disp, Identifier))
1228           return Err;
1229
1230         SM.onDispExpr(Disp, Identifier);
1231         UpdateLocLex = false;
1232         break;
1233       }
1234       return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1235     }
1236     case AsmToken::Integer:
1237       if (isParsingInlineAsm())
1238         InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1239                                                     Tok.getLoc()));
1240       SM.onInteger(Tok.getIntVal());
1241       break;
1242     case AsmToken::Plus:    SM.onPlus(); break;
1243     case AsmToken::Minus:   SM.onMinus(); break;
1244     case AsmToken::Star:    SM.onStar(); break;
1245     case AsmToken::Slash:   SM.onDivide(); break;
1246     case AsmToken::LBrac:   SM.onLBrac(); break;
1247     case AsmToken::RBrac:   SM.onRBrac(); break;
1248     case AsmToken::LParen:  SM.onLParen(); break;
1249     case AsmToken::RParen:  SM.onRParen(); break;
1250     }
1251     if (!Done && UpdateLocLex) {
1252       End = Tok.getLoc();
1253       Parser.Lex(); // Consume the token.
1254     }
1255   }
1256
1257   const MCExpr *Disp;
1258   if (const MCExpr *Sym = SM.getSym()) {
1259     // A symbolic displacement.
1260     Disp = Sym;
1261     if (isParsingInlineAsm())
1262       RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1263                                  ImmDisp, SM.getImmDisp(), BracLoc, StartInBrac,
1264                                  End);
1265   } else {
1266     // An immediate displacement only.
1267     Disp = MCConstantExpr::Create(SM.getImmDisp(), getContext());
1268   }
1269
1270   // Parse the dot operator (e.g., [ebx].foo.bar).
1271   if (Tok.getString().startswith(".")) {
1272     SmallString<64> Err;
1273     const MCExpr *NewDisp;
1274     if (ParseIntelDotOperator(Disp, &NewDisp, Err))
1275       return ErrorOperand(Tok.getLoc(), Err);
1276     
1277     End = Tok.getEndLoc();
1278     Parser.Lex();  // Eat the field.
1279     Disp = NewDisp;
1280   }
1281
1282   int BaseReg = SM.getBaseReg();
1283   int IndexReg = SM.getIndexReg();
1284   int Scale = SM.getScale();
1285
1286   if (isParsingInlineAsm())
1287     return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1288                                  End, Size, SM.getSymName());
1289
1290   // handle [-42]
1291   if (!BaseReg && !IndexReg) {
1292     if (!SegReg)
1293       return X86Operand::CreateMem(Disp, Start, End, Size);
1294     else
1295       return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1296   }
1297   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1298                                End, Size);
1299 }
1300
1301 // Inline assembly may use variable names with namespace alias qualifiers.
1302 X86Operand *X86AsmParser::ParseIntelVarWithQualifier(const MCExpr *&Disp,
1303                                                      StringRef &Identifier) {
1304   // We should only see Foo::Bar if we're parsing inline assembly.
1305   if (!isParsingInlineAsm())
1306     return 0;
1307
1308   // If we don't see a ':' then there can't be a qualifier.
1309   if (getLexer().isNot(AsmToken::Colon))
1310     return 0;
1311
1312   bool Done = false;
1313   const AsmToken &Tok = Parser.getTok();
1314   AsmToken IdentEnd = Tok;
1315   while (!Done) {
1316     switch (getLexer().getKind()) {
1317     default:
1318       Done = true; 
1319       break;
1320     case AsmToken::Colon:
1321       getLexer().Lex(); // Consume ':'.
1322       if (getLexer().isNot(AsmToken::Colon))
1323         return ErrorOperand(Tok.getLoc(), "Expected ':' token!");
1324       getLexer().Lex(); // Consume second ':'.
1325       if (getLexer().isNot(AsmToken::Identifier))
1326         return ErrorOperand(Tok.getLoc(), "Expected an identifier token!");
1327       break;
1328     case AsmToken::Identifier:
1329       IdentEnd = Tok;
1330       getLexer().Lex(); // Consume the identifier.
1331       break;
1332     }
1333   }
1334
1335   unsigned Len = IdentEnd.getLoc().getPointer() - Identifier.data();
1336   Identifier = StringRef(Identifier.data(), Len + IdentEnd.getString().size());
1337   MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1338   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1339   Disp = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1340   return 0;
1341 }
1342
1343 /// ParseIntelMemOperand - Parse intel style memory operand.
1344 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg,
1345                                                uint64_t ImmDisp,
1346                                                SMLoc Start) {
1347   const AsmToken &Tok = Parser.getTok();
1348   SMLoc End;
1349
1350   unsigned Size = getIntelMemOperandSize(Tok.getString());
1351   if (Size) {
1352     Parser.Lex();
1353     assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
1354             "Unexpected token!");
1355     Parser.Lex();
1356   }
1357
1358   // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1359   if (getLexer().is(AsmToken::Integer)) {
1360     if (isParsingInlineAsm())
1361       InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1362                                                   Tok.getLoc()));
1363     uint64_t ImmDisp = Tok.getIntVal();
1364     Parser.Lex(); // Eat the integer.
1365     if (getLexer().isNot(AsmToken::LBrac))
1366       return ErrorOperand(Start, "Expected '[' token!");
1367     return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1368   }
1369
1370   if (getLexer().is(AsmToken::LBrac))
1371     return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1372
1373   if (!ParseRegister(SegReg, Start, End)) {
1374     // Handel SegReg : [ ... ]
1375     if (getLexer().isNot(AsmToken::Colon))
1376       return ErrorOperand(Start, "Expected ':' token!");
1377     Parser.Lex(); // Eat :
1378     if (getLexer().isNot(AsmToken::LBrac))
1379       return ErrorOperand(Start, "Expected '[' token!");
1380     return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1381   }
1382
1383   const MCExpr *Disp = 0;
1384   StringRef Identifier = Tok.getString();
1385   if (getParser().parsePrimaryExpr(Disp, End))
1386     return 0;
1387
1388   if (!isParsingInlineAsm())
1389     return X86Operand::CreateMem(Disp, Start, End, Size);
1390
1391   if (X86Operand *Err = ParseIntelVarWithQualifier(Disp, Identifier))
1392     return Err;
1393
1394   return CreateMemForInlineAsm(/*SegReg=*/0, Disp, /*BaseReg=*/0,/*IndexReg=*/0,
1395                                /*Scale=*/1, Start, End, Size, Identifier);
1396 }
1397
1398 /// Parse the '.' operator.
1399 bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1400                                          const MCExpr **NewDisp,
1401                                          SmallString<64> &Err) {
1402   const AsmToken &Tok = Parser.getTok();
1403   uint64_t OrigDispVal, DotDispVal;
1404
1405   // FIXME: Handle non-constant expressions.
1406   if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp)) {
1407     OrigDispVal = OrigDisp->getValue();
1408   } else {
1409     Err = "Non-constant offsets are not supported!";
1410     return true;
1411   }
1412
1413   // Drop the '.'.
1414   StringRef DotDispStr = Tok.getString().drop_front(1);
1415
1416   // .Imm gets lexed as a real.
1417   if (Tok.is(AsmToken::Real)) {
1418     APInt DotDisp;
1419     DotDispStr.getAsInteger(10, DotDisp);
1420     DotDispVal = DotDisp.getZExtValue();
1421   } else if (Tok.is(AsmToken::Identifier)) {
1422     // We should only see an identifier when parsing the original inline asm.
1423     // The front-end should rewrite this in terms of immediates.
1424     assert (isParsingInlineAsm() && "Unexpected field name!");
1425
1426     unsigned DotDisp;
1427     std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1428     if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1429                                            DotDisp)) {
1430       Err = "Unable to lookup field reference!";
1431       return true;
1432     }
1433     DotDispVal = DotDisp;
1434   } else {
1435     Err = "Unexpected token type!";
1436     return true;
1437   }
1438
1439   if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1440     SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1441     unsigned Len = DotDispStr.size();
1442     unsigned Val = OrigDispVal + DotDispVal;
1443     InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1444                                                 Val));
1445   }
1446
1447   *NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1448   return false;
1449 }
1450
1451 /// Parse the 'offset' operator.  This operator is used to specify the
1452 /// location rather then the content of a variable.
1453 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1454   const AsmToken &Tok = Parser.getTok();
1455   SMLoc OffsetOfLoc = Tok.getLoc();
1456   Parser.Lex(); // Eat offset.
1457   assert (Tok.is(AsmToken::Identifier) && "Expected an identifier");
1458
1459   const MCExpr *Val;
1460   SMLoc Start = Tok.getLoc(), End;
1461   StringRef Identifier = Tok.getString();
1462   if (getParser().parsePrimaryExpr(Val, End))
1463     return ErrorOperand(Start, "Unable to parse expression!");
1464
1465   const MCExpr *Disp = 0;
1466   if (X86Operand *Err = ParseIntelVarWithQualifier(Disp, Identifier))
1467     return Err;
1468
1469   // Don't emit the offset operator.
1470   InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1471
1472   // The offset operator will have an 'r' constraint, thus we need to create
1473   // register operand to ensure proper matching.  Just pick a GPR based on
1474   // the size of a pointer.
1475   unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1476   return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1477                                OffsetOfLoc, Identifier);
1478 }
1479
1480 enum IntelOperatorKind {
1481   IOK_LENGTH,
1482   IOK_SIZE,
1483   IOK_TYPE
1484 };
1485
1486 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators.  The LENGTH operator
1487 /// returns the number of elements in an array.  It returns the value 1 for
1488 /// non-array variables.  The SIZE operator returns the size of a C or C++
1489 /// variable.  A variable's size is the product of its LENGTH and TYPE.  The
1490 /// TYPE operator returns the size of a C or C++ type or variable. If the
1491 /// variable is an array, TYPE returns the size of a single element.
1492 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1493   const AsmToken &Tok = Parser.getTok();
1494   SMLoc TypeLoc = Tok.getLoc();
1495   Parser.Lex(); // Eat operator.
1496   assert (Tok.is(AsmToken::Identifier) && "Expected an identifier");
1497
1498   const MCExpr *Val;
1499   AsmToken StartTok = Tok;
1500   SMLoc Start = Tok.getLoc(), End;
1501   StringRef Identifier = Tok.getString();
1502   if (getParser().parsePrimaryExpr(Val, End))
1503     return ErrorOperand(Start, "Unable to parse expression!");
1504
1505   const MCExpr *Disp = 0;
1506   if (X86Operand *Err = ParseIntelVarWithQualifier(Disp, Identifier))
1507     return Err;
1508
1509   unsigned Length = 0, Size = 0, Type = 0;
1510   if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Val)) {
1511     const MCSymbol &Sym = SymRef->getSymbol();
1512     // FIXME: The SemaLookup will fail if the name is anything other then an
1513     // identifier.
1514     // FIXME: Pass a valid SMLoc.
1515     bool IsVarDecl;
1516     if (!SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Length,
1517                                                  Size, Type, IsVarDecl))
1518       // FIXME: We don't warn on variables with namespace alias qualifiers
1519       // because support still needs to be added in the frontend.
1520       if (Identifier.equals(StartTok.getString()))
1521         return ErrorOperand(Start, "Unable to lookup expr!");
1522   }
1523   unsigned CVal;
1524   switch(OpKind) {
1525   default: llvm_unreachable("Unexpected operand kind!");
1526   case IOK_LENGTH: CVal = Length; break;
1527   case IOK_SIZE: CVal = Size; break;
1528   case IOK_TYPE: CVal = Type; break;
1529   }
1530
1531   // Rewrite the type operator and the C or C++ type or variable in terms of an
1532   // immediate.  E.g. TYPE foo -> $$4
1533   unsigned Len = End.getPointer() - TypeLoc.getPointer();
1534   InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1535
1536   const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1537   return X86Operand::CreateImm(Imm, Start, End);
1538 }
1539
1540 X86Operand *X86AsmParser::ParseIntelOperand() {
1541   const AsmToken &Tok = Parser.getTok();
1542   SMLoc Start = Tok.getLoc(), End;
1543   StringRef AsmTokStr = Tok.getString();
1544
1545   // Offset, length, type and size operators.
1546   if (isParsingInlineAsm()) {
1547     if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1548       return ParseIntelOffsetOfOperator();
1549     if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1550       return ParseIntelOperator(IOK_LENGTH);
1551     if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1552       return ParseIntelOperator(IOK_SIZE);
1553     if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1554       return ParseIntelOperator(IOK_TYPE);
1555   }
1556
1557   // Immediate.
1558   if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
1559       getLexer().is(AsmToken::Minus)) {
1560     const MCExpr *Val;
1561     bool isInteger = getLexer().is(AsmToken::Integer);
1562     if (!getParser().parseExpression(Val, End)) {
1563       if (isParsingInlineAsm())
1564         InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1565       // Immediate.
1566       if (getLexer().isNot(AsmToken::LBrac))
1567         return X86Operand::CreateImm(Val, Start, End);
1568
1569       // Only positive immediates are valid.
1570       if (!isInteger) {
1571         Error(Tok.getLoc(), "expected a positive immediate "
1572               "displacement before bracketed expr.");
1573         return 0;
1574       }
1575
1576       // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1577       if (uint64_t ImmDisp = dyn_cast<MCConstantExpr>(Val)->getValue())
1578         return ParseIntelMemOperand(/*SegReg=*/0, ImmDisp, Start);
1579     }
1580   }
1581
1582   // Register.
1583   unsigned RegNo = 0;
1584   if (!ParseRegister(RegNo, Start, End)) {
1585     // If this is a segment register followed by a ':', then this is the start
1586     // of a memory reference, otherwise this is a normal register reference.
1587     if (getLexer().isNot(AsmToken::Colon))
1588       return X86Operand::CreateReg(RegNo, Start, End);
1589
1590     getParser().Lex(); // Eat the colon.
1591     return ParseIntelMemOperand(/*SegReg=*/RegNo, /*Disp=*/0, Start);
1592   }
1593
1594   // Memory operand.
1595   return ParseIntelMemOperand(/*SegReg=*/0, /*Disp=*/0, Start);
1596 }
1597
1598 X86Operand *X86AsmParser::ParseATTOperand() {
1599   switch (getLexer().getKind()) {
1600   default:
1601     // Parse a memory operand with no segment register.
1602     return ParseMemOperand(0, Parser.getTok().getLoc());
1603   case AsmToken::Percent: {
1604     // Read the register.
1605     unsigned RegNo;
1606     SMLoc Start, End;
1607     if (ParseRegister(RegNo, Start, End)) return 0;
1608     if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1609       Error(Start, "%eiz and %riz can only be used as index registers",
1610             SMRange(Start, End));
1611       return 0;
1612     }
1613
1614     // If this is a segment register followed by a ':', then this is the start
1615     // of a memory reference, otherwise this is a normal register reference.
1616     if (getLexer().isNot(AsmToken::Colon))
1617       return X86Operand::CreateReg(RegNo, Start, End);
1618
1619     getParser().Lex(); // Eat the colon.
1620     return ParseMemOperand(RegNo, Start);
1621   }
1622   case AsmToken::Dollar: {
1623     // $42 -> immediate.
1624     SMLoc Start = Parser.getTok().getLoc(), End;
1625     Parser.Lex();
1626     const MCExpr *Val;
1627     if (getParser().parseExpression(Val, End))
1628       return 0;
1629     return X86Operand::CreateImm(Val, Start, End);
1630   }
1631   }
1632 }
1633
1634 /// ParseMemOperand: segment: disp(basereg, indexreg, scale).  The '%ds:' prefix
1635 /// has already been parsed if present.
1636 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1637
1638   // We have to disambiguate a parenthesized expression "(4+5)" from the start
1639   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
1640   // only way to do this without lookahead is to eat the '(' and see what is
1641   // after it.
1642   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1643   if (getLexer().isNot(AsmToken::LParen)) {
1644     SMLoc ExprEnd;
1645     if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1646
1647     // After parsing the base expression we could either have a parenthesized
1648     // memory address or not.  If not, return now.  If so, eat the (.
1649     if (getLexer().isNot(AsmToken::LParen)) {
1650       // Unless we have a segment register, treat this as an immediate.
1651       if (SegReg == 0)
1652         return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1653       return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1654     }
1655
1656     // Eat the '('.
1657     Parser.Lex();
1658   } else {
1659     // Okay, we have a '('.  We don't know if this is an expression or not, but
1660     // so we have to eat the ( to see beyond it.
1661     SMLoc LParenLoc = Parser.getTok().getLoc();
1662     Parser.Lex(); // Eat the '('.
1663
1664     if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1665       // Nothing to do here, fall into the code below with the '(' part of the
1666       // memory operand consumed.
1667     } else {
1668       SMLoc ExprEnd;
1669
1670       // It must be an parenthesized expression, parse it now.
1671       if (getParser().parseParenExpression(Disp, ExprEnd))
1672         return 0;
1673
1674       // After parsing the base expression we could either have a parenthesized
1675       // memory address or not.  If not, return now.  If so, eat the (.
1676       if (getLexer().isNot(AsmToken::LParen)) {
1677         // Unless we have a segment register, treat this as an immediate.
1678         if (SegReg == 0)
1679           return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1680         return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1681       }
1682
1683       // Eat the '('.
1684       Parser.Lex();
1685     }
1686   }
1687
1688   // If we reached here, then we just ate the ( of the memory operand.  Process
1689   // the rest of the memory operand.
1690   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1691   SMLoc IndexLoc;
1692
1693   if (getLexer().is(AsmToken::Percent)) {
1694     SMLoc StartLoc, EndLoc;
1695     if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1696     if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1697       Error(StartLoc, "eiz and riz can only be used as index registers",
1698             SMRange(StartLoc, EndLoc));
1699       return 0;
1700     }
1701   }
1702
1703   if (getLexer().is(AsmToken::Comma)) {
1704     Parser.Lex(); // Eat the comma.
1705     IndexLoc = Parser.getTok().getLoc();
1706
1707     // Following the comma we should have either an index register, or a scale
1708     // value. We don't support the later form, but we want to parse it
1709     // correctly.
1710     //
1711     // Not that even though it would be completely consistent to support syntax
1712     // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1713     if (getLexer().is(AsmToken::Percent)) {
1714       SMLoc L;
1715       if (ParseRegister(IndexReg, L, L)) return 0;
1716
1717       if (getLexer().isNot(AsmToken::RParen)) {
1718         // Parse the scale amount:
1719         //  ::= ',' [scale-expression]
1720         if (getLexer().isNot(AsmToken::Comma)) {
1721           Error(Parser.getTok().getLoc(),
1722                 "expected comma in scale expression");
1723           return 0;
1724         }
1725         Parser.Lex(); // Eat the comma.
1726
1727         if (getLexer().isNot(AsmToken::RParen)) {
1728           SMLoc Loc = Parser.getTok().getLoc();
1729
1730           int64_t ScaleVal;
1731           if (getParser().parseAbsoluteExpression(ScaleVal)){
1732             Error(Loc, "expected scale expression");
1733             return 0;
1734           }
1735
1736           // Validate the scale amount.
1737           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1738             Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1739             return 0;
1740           }
1741           Scale = (unsigned)ScaleVal;
1742         }
1743       }
1744     } else if (getLexer().isNot(AsmToken::RParen)) {
1745       // A scale amount without an index is ignored.
1746       // index.
1747       SMLoc Loc = Parser.getTok().getLoc();
1748
1749       int64_t Value;
1750       if (getParser().parseAbsoluteExpression(Value))
1751         return 0;
1752
1753       if (Value != 1)
1754         Warning(Loc, "scale factor without index register is ignored");
1755       Scale = 1;
1756     }
1757   }
1758
1759   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1760   if (getLexer().isNot(AsmToken::RParen)) {
1761     Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1762     return 0;
1763   }
1764   SMLoc MemEnd = Parser.getTok().getEndLoc();
1765   Parser.Lex(); // Eat the ')'.
1766
1767   // If we have both a base register and an index register make sure they are
1768   // both 64-bit or 32-bit registers.
1769   // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1770   if (BaseReg != 0 && IndexReg != 0) {
1771     if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1772         (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1773          X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1774         IndexReg != X86::RIZ) {
1775       Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1776       return 0;
1777     }
1778     if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1779         (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1780          X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1781         IndexReg != X86::EIZ){
1782       Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1783       return 0;
1784     }
1785   }
1786
1787   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1788                                MemStart, MemEnd);
1789 }
1790
1791 bool X86AsmParser::
1792 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1793                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1794   InstInfo = &Info;
1795   StringRef PatchedName = Name;
1796
1797   // FIXME: Hack to recognize setneb as setne.
1798   if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1799       PatchedName != "setb" && PatchedName != "setnb")
1800     PatchedName = PatchedName.substr(0, Name.size()-1);
1801
1802   // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1803   const MCExpr *ExtraImmOp = 0;
1804   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1805       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1806        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1807     bool IsVCMP = PatchedName[0] == 'v';
1808     unsigned SSECCIdx = IsVCMP ? 4 : 3;
1809     unsigned SSEComparisonCode = StringSwitch<unsigned>(
1810       PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1811       .Case("eq",       0x00)
1812       .Case("lt",       0x01)
1813       .Case("le",       0x02)
1814       .Case("unord",    0x03)
1815       .Case("neq",      0x04)
1816       .Case("nlt",      0x05)
1817       .Case("nle",      0x06)
1818       .Case("ord",      0x07)
1819       /* AVX only from here */
1820       .Case("eq_uq",    0x08)
1821       .Case("nge",      0x09)
1822       .Case("ngt",      0x0A)
1823       .Case("false",    0x0B)
1824       .Case("neq_oq",   0x0C)
1825       .Case("ge",       0x0D)
1826       .Case("gt",       0x0E)
1827       .Case("true",     0x0F)
1828       .Case("eq_os",    0x10)
1829       .Case("lt_oq",    0x11)
1830       .Case("le_oq",    0x12)
1831       .Case("unord_s",  0x13)
1832       .Case("neq_us",   0x14)
1833       .Case("nlt_uq",   0x15)
1834       .Case("nle_uq",   0x16)
1835       .Case("ord_s",    0x17)
1836       .Case("eq_us",    0x18)
1837       .Case("nge_uq",   0x19)
1838       .Case("ngt_uq",   0x1A)
1839       .Case("false_os", 0x1B)
1840       .Case("neq_os",   0x1C)
1841       .Case("ge_oq",    0x1D)
1842       .Case("gt_oq",    0x1E)
1843       .Case("true_us",  0x1F)
1844       .Default(~0U);
1845     if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1846       ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1847                                           getParser().getContext());
1848       if (PatchedName.endswith("ss")) {
1849         PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1850       } else if (PatchedName.endswith("sd")) {
1851         PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1852       } else if (PatchedName.endswith("ps")) {
1853         PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1854       } else {
1855         assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1856         PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1857       }
1858     }
1859   }
1860
1861   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1862
1863   if (ExtraImmOp && !isParsingIntelSyntax())
1864     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1865
1866   // Determine whether this is an instruction prefix.
1867   bool isPrefix =
1868     Name == "lock" || Name == "rep" ||
1869     Name == "repe" || Name == "repz" ||
1870     Name == "repne" || Name == "repnz" ||
1871     Name == "rex64" || Name == "data16";
1872
1873
1874   // This does the actual operand parsing.  Don't parse any more if we have a
1875   // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1876   // just want to parse the "lock" as the first instruction and the "incl" as
1877   // the next one.
1878   if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1879
1880     // Parse '*' modifier.
1881     if (getLexer().is(AsmToken::Star)) {
1882       SMLoc Loc = Parser.getTok().getLoc();
1883       Operands.push_back(X86Operand::CreateToken("*", Loc));
1884       Parser.Lex(); // Eat the star.
1885     }
1886
1887     // Read the first operand.
1888     if (X86Operand *Op = ParseOperand())
1889       Operands.push_back(Op);
1890     else {
1891       Parser.eatToEndOfStatement();
1892       return true;
1893     }
1894
1895     while (getLexer().is(AsmToken::Comma)) {
1896       Parser.Lex();  // Eat the comma.
1897
1898       // Parse and remember the operand.
1899       if (X86Operand *Op = ParseOperand())
1900         Operands.push_back(Op);
1901       else {
1902         Parser.eatToEndOfStatement();
1903         return true;
1904       }
1905     }
1906
1907     if (getLexer().isNot(AsmToken::EndOfStatement)) {
1908       SMLoc Loc = getLexer().getLoc();
1909       Parser.eatToEndOfStatement();
1910       return Error(Loc, "unexpected token in argument list");
1911     }
1912   }
1913
1914   if (getLexer().is(AsmToken::EndOfStatement))
1915     Parser.Lex(); // Consume the EndOfStatement
1916   else if (isPrefix && getLexer().is(AsmToken::Slash))
1917     Parser.Lex(); // Consume the prefix separator Slash
1918
1919   if (ExtraImmOp && isParsingIntelSyntax())
1920     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1921
1922   // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1923   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
1924   // documented form in various unofficial manuals, so a lot of code uses it.
1925   if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1926       Operands.size() == 3) {
1927     X86Operand &Op = *(X86Operand*)Operands.back();
1928     if (Op.isMem() && Op.Mem.SegReg == 0 &&
1929         isa<MCConstantExpr>(Op.Mem.Disp) &&
1930         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1931         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1932       SMLoc Loc = Op.getEndLoc();
1933       Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1934       delete &Op;
1935     }
1936   }
1937   // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1938   if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1939       Operands.size() == 3) {
1940     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1941     if (Op.isMem() && Op.Mem.SegReg == 0 &&
1942         isa<MCConstantExpr>(Op.Mem.Disp) &&
1943         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1944         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1945       SMLoc Loc = Op.getEndLoc();
1946       Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1947       delete &Op;
1948     }
1949   }
1950   // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1951   if (Name.startswith("ins") && Operands.size() == 3 &&
1952       (Name == "insb" || Name == "insw" || Name == "insl")) {
1953     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1954     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1955     if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1956       Operands.pop_back();
1957       Operands.pop_back();
1958       delete &Op;
1959       delete &Op2;
1960     }
1961   }
1962
1963   // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1964   if (Name.startswith("outs") && Operands.size() == 3 &&
1965       (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1966     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1967     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1968     if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1969       Operands.pop_back();
1970       Operands.pop_back();
1971       delete &Op;
1972       delete &Op2;
1973     }
1974   }
1975
1976   // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1977   if (Name.startswith("movs") && Operands.size() == 3 &&
1978       (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1979        (is64BitMode() && Name == "movsq"))) {
1980     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1981     X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1982     if (isSrcOp(Op) && isDstOp(Op2)) {
1983       Operands.pop_back();
1984       Operands.pop_back();
1985       delete &Op;
1986       delete &Op2;
1987     }
1988   }
1989   // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1990   if (Name.startswith("lods") && Operands.size() == 3 &&
1991       (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1992        Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1993     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1994     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1995     if (isSrcOp(*Op1) && Op2->isReg()) {
1996       const char *ins;
1997       unsigned reg = Op2->getReg();
1998       bool isLods = Name == "lods";
1999       if (reg == X86::AL && (isLods || Name == "lodsb"))
2000         ins = "lodsb";
2001       else if (reg == X86::AX && (isLods || Name == "lodsw"))
2002         ins = "lodsw";
2003       else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2004         ins = "lodsl";
2005       else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2006         ins = "lodsq";
2007       else
2008         ins = NULL;
2009       if (ins != NULL) {
2010         Operands.pop_back();
2011         Operands.pop_back();
2012         delete Op1;
2013         delete Op2;
2014         if (Name != ins)
2015           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2016       }
2017     }
2018   }
2019   // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2020   if (Name.startswith("stos") && Operands.size() == 3 &&
2021       (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2022        Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2023     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2024     X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2025     if (isDstOp(*Op2) && Op1->isReg()) {
2026       const char *ins;
2027       unsigned reg = Op1->getReg();
2028       bool isStos = Name == "stos";
2029       if (reg == X86::AL && (isStos || Name == "stosb"))
2030         ins = "stosb";
2031       else if (reg == X86::AX && (isStos || Name == "stosw"))
2032         ins = "stosw";
2033       else if (reg == X86::EAX && (isStos || Name == "stosl"))
2034         ins = "stosl";
2035       else if (reg == X86::RAX && (isStos || Name == "stosq"))
2036         ins = "stosq";
2037       else
2038         ins = NULL;
2039       if (ins != NULL) {
2040         Operands.pop_back();
2041         Operands.pop_back();
2042         delete Op1;
2043         delete Op2;
2044         if (Name != ins)
2045           static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2046       }
2047     }
2048   }
2049
2050   // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
2051   // "shift <op>".
2052   if ((Name.startswith("shr") || Name.startswith("sar") ||
2053        Name.startswith("shl") || Name.startswith("sal") ||
2054        Name.startswith("rcl") || Name.startswith("rcr") ||
2055        Name.startswith("rol") || Name.startswith("ror")) &&
2056       Operands.size() == 3) {
2057     if (isParsingIntelSyntax()) {
2058       // Intel syntax
2059       X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2060       if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2061           cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2062         delete Operands[2];
2063         Operands.pop_back();
2064       }
2065     } else {
2066       X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2067       if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2068           cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2069         delete Operands[1];
2070         Operands.erase(Operands.begin() + 1);
2071       }
2072     }
2073   }
2074
2075   // Transforms "int $3" into "int3" as a size optimization.  We can't write an
2076   // instalias with an immediate operand yet.
2077   if (Name == "int" && Operands.size() == 2) {
2078     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2079     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2080         cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2081       delete Operands[1];
2082       Operands.erase(Operands.begin() + 1);
2083       static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2084     }
2085   }
2086
2087   return false;
2088 }
2089
2090 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2091                             bool isCmp) {
2092   MCInst TmpInst;
2093   TmpInst.setOpcode(Opcode);
2094   if (!isCmp)
2095     TmpInst.addOperand(MCOperand::CreateReg(Reg));
2096   TmpInst.addOperand(MCOperand::CreateReg(Reg));
2097   TmpInst.addOperand(Inst.getOperand(0));
2098   Inst = TmpInst;
2099   return true;
2100 }
2101
2102 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2103                                 bool isCmp = false) {
2104   if (!Inst.getOperand(0).isImm() ||
2105       !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2106     return false;
2107
2108   return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2109 }
2110
2111 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2112                                 bool isCmp = false) {
2113   if (!Inst.getOperand(0).isImm() ||
2114       !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2115     return false;
2116
2117   return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2118 }
2119
2120 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2121                                 bool isCmp = false) {
2122   if (!Inst.getOperand(0).isImm() ||
2123       !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2124     return false;
2125
2126   return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2127 }
2128
2129 bool X86AsmParser::
2130 processInstruction(MCInst &Inst,
2131                    const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2132   switch (Inst.getOpcode()) {
2133   default: return false;
2134   case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2135   case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2136   case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2137   case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2138   case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2139   case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2140   case X86::OR16i16:  return convert16i16to16ri8(Inst, X86::OR16ri8);
2141   case X86::OR32i32:  return convert32i32to32ri8(Inst, X86::OR32ri8);
2142   case X86::OR64i32:  return convert64i32to64ri8(Inst, X86::OR64ri8);
2143   case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2144   case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2145   case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2146   case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2147   case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2148   case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2149   case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2150   case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2151   case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2152   case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2153   case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2154   case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2155   case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2156   case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2157   case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2158   }
2159 }
2160
2161 static const char *getSubtargetFeatureName(unsigned Val);
2162 bool X86AsmParser::
2163 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2164                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2165                         MCStreamer &Out, unsigned &ErrorInfo,
2166                         bool MatchingInlineAsm) {
2167   assert(!Operands.empty() && "Unexpect empty operand list!");
2168   X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2169   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2170   ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
2171
2172   // First, handle aliases that expand to multiple instructions.
2173   // FIXME: This should be replaced with a real .td file alias mechanism.
2174   // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2175   // call.
2176   if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2177       Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2178       Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2179       Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2180     MCInst Inst;
2181     Inst.setOpcode(X86::WAIT);
2182     Inst.setLoc(IDLoc);
2183     if (!MatchingInlineAsm)
2184       Out.EmitInstruction(Inst);
2185
2186     const char *Repl =
2187       StringSwitch<const char*>(Op->getToken())
2188         .Case("finit",  "fninit")
2189         .Case("fsave",  "fnsave")
2190         .Case("fstcw",  "fnstcw")
2191         .Case("fstcww",  "fnstcw")
2192         .Case("fstenv", "fnstenv")
2193         .Case("fstsw",  "fnstsw")
2194         .Case("fstsww", "fnstsw")
2195         .Case("fclex",  "fnclex")
2196         .Default(0);
2197     assert(Repl && "Unknown wait-prefixed instruction");
2198     delete Operands[0];
2199     Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2200   }
2201
2202   bool WasOriginallyInvalidOperand = false;
2203   MCInst Inst;
2204
2205   // First, try a direct match.
2206   switch (MatchInstructionImpl(Operands, Inst,
2207                                ErrorInfo, MatchingInlineAsm,
2208                                isParsingIntelSyntax())) {
2209   default: break;
2210   case Match_Success:
2211     // Some instructions need post-processing to, for example, tweak which
2212     // encoding is selected. Loop on it while changes happen so the
2213     // individual transformations can chain off each other.
2214     if (!MatchingInlineAsm)
2215       while (processInstruction(Inst, Operands))
2216         ;
2217
2218     Inst.setLoc(IDLoc);
2219     if (!MatchingInlineAsm)
2220       Out.EmitInstruction(Inst);
2221     Opcode = Inst.getOpcode();
2222     return false;
2223   case Match_MissingFeature: {
2224     assert(ErrorInfo && "Unknown missing feature!");
2225     // Special case the error message for the very common case where only
2226     // a single subtarget feature is missing.
2227     std::string Msg = "instruction requires:";
2228     unsigned Mask = 1;
2229     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2230       if (ErrorInfo & Mask) {
2231         Msg += " ";
2232         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2233       }
2234       Mask <<= 1;
2235     }
2236     return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2237   }
2238   case Match_InvalidOperand:
2239     WasOriginallyInvalidOperand = true;
2240     break;
2241   case Match_MnemonicFail:
2242     break;
2243   }
2244
2245   // FIXME: Ideally, we would only attempt suffix matches for things which are
2246   // valid prefixes, and we could just infer the right unambiguous
2247   // type. However, that requires substantially more matcher support than the
2248   // following hack.
2249
2250   // Change the operand to point to a temporary token.
2251   StringRef Base = Op->getToken();
2252   SmallString<16> Tmp;
2253   Tmp += Base;
2254   Tmp += ' ';
2255   Op->setTokenValue(Tmp.str());
2256
2257   // If this instruction starts with an 'f', then it is a floating point stack
2258   // instruction.  These come in up to three forms for 32-bit, 64-bit, and
2259   // 80-bit floating point, which use the suffixes s,l,t respectively.
2260   //
2261   // Otherwise, we assume that this may be an integer instruction, which comes
2262   // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2263   const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2264
2265   // Check for the various suffix matches.
2266   Tmp[Base.size()] = Suffixes[0];
2267   unsigned ErrorInfoIgnore;
2268   unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2269   unsigned Match1, Match2, Match3, Match4;
2270
2271   Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2272                                 isParsingIntelSyntax());
2273   // If this returned as a missing feature failure, remember that.
2274   if (Match1 == Match_MissingFeature)
2275     ErrorInfoMissingFeature = ErrorInfoIgnore;
2276   Tmp[Base.size()] = Suffixes[1];
2277   Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2278                                 isParsingIntelSyntax());
2279   // If this returned as a missing feature failure, remember that.
2280   if (Match2 == Match_MissingFeature)
2281     ErrorInfoMissingFeature = ErrorInfoIgnore;
2282   Tmp[Base.size()] = Suffixes[2];
2283   Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2284                                 isParsingIntelSyntax());
2285   // If this returned as a missing feature failure, remember that.
2286   if (Match3 == Match_MissingFeature)
2287     ErrorInfoMissingFeature = ErrorInfoIgnore;
2288   Tmp[Base.size()] = Suffixes[3];
2289   Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2290                                 isParsingIntelSyntax());
2291   // If this returned as a missing feature failure, remember that.
2292   if (Match4 == Match_MissingFeature)
2293     ErrorInfoMissingFeature = ErrorInfoIgnore;
2294
2295   // Restore the old token.
2296   Op->setTokenValue(Base);
2297
2298   // If exactly one matched, then we treat that as a successful match (and the
2299   // instruction will already have been filled in correctly, since the failing
2300   // matches won't have modified it).
2301   unsigned NumSuccessfulMatches =
2302     (Match1 == Match_Success) + (Match2 == Match_Success) +
2303     (Match3 == Match_Success) + (Match4 == Match_Success);
2304   if (NumSuccessfulMatches == 1) {
2305     Inst.setLoc(IDLoc);
2306     if (!MatchingInlineAsm)
2307       Out.EmitInstruction(Inst);
2308     Opcode = Inst.getOpcode();
2309     return false;
2310   }
2311
2312   // Otherwise, the match failed, try to produce a decent error message.
2313
2314   // If we had multiple suffix matches, then identify this as an ambiguous
2315   // match.
2316   if (NumSuccessfulMatches > 1) {
2317     char MatchChars[4];
2318     unsigned NumMatches = 0;
2319     if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2320     if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2321     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2322     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2323
2324     SmallString<126> Msg;
2325     raw_svector_ostream OS(Msg);
2326     OS << "ambiguous instructions require an explicit suffix (could be ";
2327     for (unsigned i = 0; i != NumMatches; ++i) {
2328       if (i != 0)
2329         OS << ", ";
2330       if (i + 1 == NumMatches)
2331         OS << "or ";
2332       OS << "'" << Base << MatchChars[i] << "'";
2333     }
2334     OS << ")";
2335     Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2336     return true;
2337   }
2338
2339   // Okay, we know that none of the variants matched successfully.
2340
2341   // If all of the instructions reported an invalid mnemonic, then the original
2342   // mnemonic was invalid.
2343   if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2344       (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2345     if (!WasOriginallyInvalidOperand) {
2346       ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2347         Op->getLocRange();
2348       return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2349                    Ranges, MatchingInlineAsm);
2350     }
2351
2352     // Recover location info for the operand if we know which was the problem.
2353     if (ErrorInfo != ~0U) {
2354       if (ErrorInfo >= Operands.size())
2355         return Error(IDLoc, "too few operands for instruction",
2356                      EmptyRanges, MatchingInlineAsm);
2357
2358       X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2359       if (Operand->getStartLoc().isValid()) {
2360         SMRange OperandRange = Operand->getLocRange();
2361         return Error(Operand->getStartLoc(), "invalid operand for instruction",
2362                      OperandRange, MatchingInlineAsm);
2363       }
2364     }
2365
2366     return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2367                  MatchingInlineAsm);
2368   }
2369
2370   // If one instruction matched with a missing feature, report this as a
2371   // missing feature.
2372   if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2373       (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2374     std::string Msg = "instruction requires:";
2375     unsigned Mask = 1;
2376     for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2377       if (ErrorInfoMissingFeature & Mask) {
2378         Msg += " ";
2379         Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2380       }
2381       Mask <<= 1;
2382     }
2383     return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2384   }
2385
2386   // If one instruction matched with an invalid operand, report this as an
2387   // operand failure.
2388   if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2389       (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2390     Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2391           MatchingInlineAsm);
2392     return true;
2393   }
2394
2395   // If all of these were an outright failure, report it in a useless way.
2396   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2397         EmptyRanges, MatchingInlineAsm);
2398   return true;
2399 }
2400
2401
2402 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2403   StringRef IDVal = DirectiveID.getIdentifier();
2404   if (IDVal == ".word")
2405     return ParseDirectiveWord(2, DirectiveID.getLoc());
2406   else if (IDVal.startswith(".code"))
2407     return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2408   else if (IDVal.startswith(".att_syntax")) {
2409     getParser().setAssemblerDialect(0);
2410     return false;
2411   } else if (IDVal.startswith(".intel_syntax")) {
2412     getParser().setAssemblerDialect(1);
2413     if (getLexer().isNot(AsmToken::EndOfStatement)) {
2414       if(Parser.getTok().getString() == "noprefix") {
2415         // FIXME : Handle noprefix
2416         Parser.Lex();
2417       } else
2418         return true;
2419     }
2420     return false;
2421   }
2422   return true;
2423 }
2424
2425 /// ParseDirectiveWord
2426 ///  ::= .word [ expression (, expression)* ]
2427 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2428   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2429     for (;;) {
2430       const MCExpr *Value;
2431       if (getParser().parseExpression(Value))
2432         return true;
2433
2434       getParser().getStreamer().EmitValue(Value, Size);
2435
2436       if (getLexer().is(AsmToken::EndOfStatement))
2437         break;
2438
2439       // FIXME: Improve diagnostic.
2440       if (getLexer().isNot(AsmToken::Comma))
2441         return Error(L, "unexpected token in directive");
2442       Parser.Lex();
2443     }
2444   }
2445
2446   Parser.Lex();
2447   return false;
2448 }
2449
2450 /// ParseDirectiveCode
2451 ///  ::= .code32 | .code64
2452 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2453   if (IDVal == ".code32") {
2454     Parser.Lex();
2455     if (is64BitMode()) {
2456       SwitchMode();
2457       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2458     }
2459   } else if (IDVal == ".code64") {
2460     Parser.Lex();
2461     if (!is64BitMode()) {
2462       SwitchMode();
2463       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2464     }
2465   } else {
2466     return Error(L, "unexpected directive " + IDVal);
2467   }
2468
2469   return false;
2470 }
2471
2472 // Force static initialization.
2473 extern "C" void LLVMInitializeX86AsmParser() {
2474   RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2475   RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2476 }
2477
2478 #define GET_REGISTER_MATCHER
2479 #define GET_MATCHER_IMPLEMENTATION
2480 #define GET_SUBTARGET_FEATURE_NAME
2481 #include "X86GenAsmMatcher.inc"