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