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