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