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