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