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