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