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