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