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