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