dd9fa5820cfe45894b4923bfe8baaf4dfcb7b652
[oota-llvm.git] / lib / Target / ARM / AsmParser / ARMAsmParser.cpp
1 //===-- ARMAsmParser.cpp - Parse ARM 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 "ARM.h"
11 #include "ARMAddressingModes.h"
12 #include "ARMMCExpr.h"
13 #include "ARMBaseRegisterInfo.h"
14 #include "ARMSubtarget.h"
15 #include "llvm/MC/MCParser/MCAsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmParser.h"
17 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/Target/TargetRegistry.h"
23 #include "llvm/Target/TargetAsmParser.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/ADT/Twine.h"
30 using namespace llvm;
31
32 namespace {
33
34 class ARMOperand;
35
36 class ARMAsmParser : public TargetAsmParser {
37   MCAsmParser &Parser;
38   TargetMachine &TM;
39
40   MCAsmParser &getParser() const { return Parser; }
41   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
42
43   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
44   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
45
46   int TryParseRegister();
47   virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
48   bool TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
49   bool TryParseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
50   bool ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
51   bool ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &,
52                    ARMII::AddrMode AddrMode);
53   bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
54   bool ParsePrefix(ARMMCExpr::VariantKind &RefKind);
55   const MCExpr *ApplyPrefixToExpr(const MCExpr *E,
56                                   MCSymbolRefExpr::VariantKind Variant);
57
58
59   bool ParseMemoryOffsetReg(bool &Negative,
60                             bool &OffsetRegShifted,
61                             enum ARM_AM::ShiftOpc &ShiftType,
62                             const MCExpr *&ShiftAmount,
63                             const MCExpr *&Offset,
64                             bool &OffsetIsReg,
65                             int &OffsetRegNum,
66                             SMLoc &E);
67   bool ParseShift(enum ARM_AM::ShiftOpc &St,
68                   const MCExpr *&ShiftAmount, SMLoc &E);
69   bool ParseDirectiveWord(unsigned Size, SMLoc L);
70   bool ParseDirectiveThumb(SMLoc L);
71   bool ParseDirectiveThumbFunc(SMLoc L);
72   bool ParseDirectiveCode(SMLoc L);
73   bool ParseDirectiveSyntax(SMLoc L);
74
75   bool MatchAndEmitInstruction(SMLoc IDLoc,
76                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
77                                MCStreamer &Out);
78   void GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
79                              bool &CanAcceptPredicationCode);
80
81   /// @name Auto-generated Match Functions
82   /// {
83
84 #define GET_ASSEMBLER_HEADER
85 #include "ARMGenAsmMatcher.inc"
86
87   /// }
88
89   OperandMatchResultTy tryParseCoprocNumOperand(
90     SmallVectorImpl<MCParsedAsmOperand*>&);
91   OperandMatchResultTy tryParseCoprocRegOperand(
92     SmallVectorImpl<MCParsedAsmOperand*>&);
93   OperandMatchResultTy tryParseMemBarrierOptOperand(
94     SmallVectorImpl<MCParsedAsmOperand*>&);
95   OperandMatchResultTy tryParseProcIFlagsOperand(
96     SmallVectorImpl<MCParsedAsmOperand*>&);
97   OperandMatchResultTy tryParseMSRMaskOperand(
98     SmallVectorImpl<MCParsedAsmOperand*>&);
99   OperandMatchResultTy tryParseMemMode2Operand(
100     SmallVectorImpl<MCParsedAsmOperand*>&);
101
102   // Asm Match Converter Methods
103   bool CvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
104                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
105   bool CvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
106                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
107
108 public:
109   ARMAsmParser(const Target &T, MCAsmParser &_Parser, TargetMachine &_TM)
110     : TargetAsmParser(T), Parser(_Parser), TM(_TM) {
111       // Initialize the set of available features.
112       setAvailableFeatures(ComputeAvailableFeatures(
113           &TM.getSubtarget<ARMSubtarget>()));
114     }
115
116   virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
117                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
118   virtual bool ParseDirective(AsmToken DirectiveID);
119 };
120 } // end anonymous namespace
121
122 namespace {
123
124 /// ARMOperand - Instances of this class represent a parsed ARM machine
125 /// instruction.
126 class ARMOperand : public MCParsedAsmOperand {
127   enum KindTy {
128     CondCode,
129     CCOut,
130     CoprocNum,
131     CoprocReg,
132     Immediate,
133     MemBarrierOpt,
134     Memory,
135     MSRMask,
136     ProcIFlags,
137     Register,
138     RegisterList,
139     DPRRegisterList,
140     SPRRegisterList,
141     Shifter,
142     Token
143   } Kind;
144
145   SMLoc StartLoc, EndLoc;
146   SmallVector<unsigned, 8> Registers;
147
148   union {
149     struct {
150       ARMCC::CondCodes Val;
151     } CC;
152
153     struct {
154       ARM_MB::MemBOpt Val;
155     } MBOpt;
156
157     struct {
158       unsigned Val;
159     } Cop;
160
161     struct {
162       ARM_PROC::IFlags Val;
163     } IFlags;
164
165     struct {
166       unsigned Val;
167     } MMask;
168
169     struct {
170       const char *Data;
171       unsigned Length;
172     } Tok;
173
174     struct {
175       unsigned RegNum;
176     } Reg;
177
178     struct {
179       const MCExpr *Val;
180     } Imm;
181
182     /// Combined record for all forms of ARM address expressions.
183     struct {
184       ARMII::AddrMode AddrMode;
185       unsigned BaseRegNum;
186       union {
187         unsigned RegNum;     ///< Offset register num, when OffsetIsReg.
188         const MCExpr *Value; ///< Offset value, when !OffsetIsReg.
189       } Offset;
190       const MCExpr *ShiftAmount;     // used when OffsetRegShifted is true
191       enum ARM_AM::ShiftOpc ShiftType; // used when OffsetRegShifted is true
192       unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
193       unsigned Preindexed       : 1;
194       unsigned Postindexed      : 1;
195       unsigned OffsetIsReg      : 1;
196       unsigned Negative         : 1; // only used when OffsetIsReg is true
197       unsigned Writeback        : 1;
198     } Mem;
199
200     struct {
201       ARM_AM::ShiftOpc ShiftTy;
202       unsigned RegNum;
203     } Shift;
204   };
205
206   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
207 public:
208   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
209     Kind = o.Kind;
210     StartLoc = o.StartLoc;
211     EndLoc = o.EndLoc;
212     switch (Kind) {
213     case CondCode:
214       CC = o.CC;
215       break;
216     case Token:
217       Tok = o.Tok;
218       break;
219     case CCOut:
220     case Register:
221       Reg = o.Reg;
222       break;
223     case RegisterList:
224     case DPRRegisterList:
225     case SPRRegisterList:
226       Registers = o.Registers;
227       break;
228     case CoprocNum:
229     case CoprocReg:
230       Cop = o.Cop;
231       break;
232     case Immediate:
233       Imm = o.Imm;
234       break;
235     case MemBarrierOpt:
236       MBOpt = o.MBOpt;
237       break;
238     case Memory:
239       Mem = o.Mem;
240       break;
241     case MSRMask:
242       MMask = o.MMask;
243       break;
244     case ProcIFlags:
245       IFlags = o.IFlags;
246       break;
247     case Shifter:
248       Shift = o.Shift;
249       break;
250     }
251   }
252
253   /// getStartLoc - Get the location of the first token of this operand.
254   SMLoc getStartLoc() const { return StartLoc; }
255   /// getEndLoc - Get the location of the last token of this operand.
256   SMLoc getEndLoc() const { return EndLoc; }
257
258   ARMCC::CondCodes getCondCode() const {
259     assert(Kind == CondCode && "Invalid access!");
260     return CC.Val;
261   }
262
263   unsigned getCoproc() const {
264     assert((Kind == CoprocNum || Kind == CoprocReg) && "Invalid access!");
265     return Cop.Val;
266   }
267
268   StringRef getToken() const {
269     assert(Kind == Token && "Invalid access!");
270     return StringRef(Tok.Data, Tok.Length);
271   }
272
273   unsigned getReg() const {
274     assert((Kind == Register || Kind == CCOut) && "Invalid access!");
275     return Reg.RegNum;
276   }
277
278   const SmallVectorImpl<unsigned> &getRegList() const {
279     assert((Kind == RegisterList || Kind == DPRRegisterList ||
280             Kind == SPRRegisterList) && "Invalid access!");
281     return Registers;
282   }
283
284   const MCExpr *getImm() const {
285     assert(Kind == Immediate && "Invalid access!");
286     return Imm.Val;
287   }
288
289   ARM_MB::MemBOpt getMemBarrierOpt() const {
290     assert(Kind == MemBarrierOpt && "Invalid access!");
291     return MBOpt.Val;
292   }
293
294   ARM_PROC::IFlags getProcIFlags() const {
295     assert(Kind == ProcIFlags && "Invalid access!");
296     return IFlags.Val;
297   }
298
299   unsigned getMSRMask() const {
300     assert(Kind == MSRMask && "Invalid access!");
301     return MMask.Val;
302   }
303
304   /// @name Memory Operand Accessors
305   /// @{
306   ARMII::AddrMode getMemAddrMode() const {
307     return Mem.AddrMode;
308   }
309   unsigned getMemBaseRegNum() const {
310     return Mem.BaseRegNum;
311   }
312   unsigned getMemOffsetRegNum() const {
313     assert(Mem.OffsetIsReg && "Invalid access!");
314     return Mem.Offset.RegNum;
315   }
316   const MCExpr *getMemOffset() const {
317     assert(!Mem.OffsetIsReg && "Invalid access!");
318     return Mem.Offset.Value;
319   }
320   unsigned getMemOffsetRegShifted() const {
321     assert(Mem.OffsetIsReg && "Invalid access!");
322     return Mem.OffsetRegShifted;
323   }
324   const MCExpr *getMemShiftAmount() const {
325     assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
326     return Mem.ShiftAmount;
327   }
328   enum ARM_AM::ShiftOpc getMemShiftType() const {
329     assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
330     return Mem.ShiftType;
331   }
332   bool getMemPreindexed() const { return Mem.Preindexed; }
333   bool getMemPostindexed() const { return Mem.Postindexed; }
334   bool getMemOffsetIsReg() const { return Mem.OffsetIsReg; }
335   bool getMemNegative() const { return Mem.Negative; }
336   bool getMemWriteback() const { return Mem.Writeback; }
337
338   /// @}
339
340   bool isCoprocNum() const { return Kind == CoprocNum; }
341   bool isCoprocReg() const { return Kind == CoprocReg; }
342   bool isCondCode() const { return Kind == CondCode; }
343   bool isCCOut() const { return Kind == CCOut; }
344   bool isImm() const { return Kind == Immediate; }
345   bool isReg() const { return Kind == Register; }
346   bool isRegList() const { return Kind == RegisterList; }
347   bool isDPRRegList() const { return Kind == DPRRegisterList; }
348   bool isSPRRegList() const { return Kind == SPRRegisterList; }
349   bool isToken() const { return Kind == Token; }
350   bool isMemBarrierOpt() const { return Kind == MemBarrierOpt; }
351   bool isMemory() const { return Kind == Memory; }
352   bool isShifter() const { return Kind == Shifter; }
353   bool isMemMode2() const {
354     if (getMemAddrMode() != ARMII::AddrMode2)
355       return false;
356
357     if (getMemOffsetIsReg())
358       return true;
359
360     if (getMemNegative() &&
361         !(getMemPostindexed() || getMemPreindexed()))
362       return false;
363
364     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
365     if (!CE) return false;
366     int64_t Value = CE->getValue();
367
368     // The offset must be in the range 0-4095 (imm12).
369     if (Value > 4095 || Value < -4095)
370       return false;
371
372     return true;
373   }
374   bool isMemMode5() const {
375     if (!isMemory() || getMemOffsetIsReg() || getMemWriteback() ||
376         getMemNegative())
377       return false;
378
379     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
380     if (!CE) return false;
381
382     // The offset must be a multiple of 4 in the range 0-1020.
383     int64_t Value = CE->getValue();
384     return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
385   }
386   bool isMemMode7() const {
387     if (!isMemory() ||
388         getMemPreindexed() ||
389         getMemPostindexed() ||
390         getMemOffsetIsReg() ||
391         getMemNegative() ||
392         getMemWriteback())
393       return false;
394
395     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
396     if (!CE) return false;
397
398     if (CE->getValue())
399       return false;
400
401     return true;
402   }
403   bool isMemModeRegThumb() const {
404     if (!isMemory() || !getMemOffsetIsReg() || getMemWriteback())
405       return false;
406     return true;
407   }
408   bool isMemModeImmThumb() const {
409     if (!isMemory() || getMemOffsetIsReg() || getMemWriteback())
410       return false;
411
412     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
413     if (!CE) return false;
414
415     // The offset must be a multiple of 4 in the range 0-124.
416     uint64_t Value = CE->getValue();
417     return ((Value & 0x3) == 0 && Value <= 124);
418   }
419   bool isMSRMask() const { return Kind == MSRMask; }
420   bool isProcIFlags() const { return Kind == ProcIFlags; }
421
422   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
423     // Add as immediates when possible.  Null MCExpr = 0.
424     if (Expr == 0)
425       Inst.addOperand(MCOperand::CreateImm(0));
426     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
427       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
428     else
429       Inst.addOperand(MCOperand::CreateExpr(Expr));
430   }
431
432   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
433     assert(N == 2 && "Invalid number of operands!");
434     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
435     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
436     Inst.addOperand(MCOperand::CreateReg(RegNum));
437   }
438
439   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
440     assert(N == 1 && "Invalid number of operands!");
441     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
442   }
443
444   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
445     assert(N == 1 && "Invalid number of operands!");
446     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
447   }
448
449   void addCCOutOperands(MCInst &Inst, unsigned N) const {
450     assert(N == 1 && "Invalid number of operands!");
451     Inst.addOperand(MCOperand::CreateReg(getReg()));
452   }
453
454   void addRegOperands(MCInst &Inst, unsigned N) const {
455     assert(N == 1 && "Invalid number of operands!");
456     Inst.addOperand(MCOperand::CreateReg(getReg()));
457   }
458
459   void addShifterOperands(MCInst &Inst, unsigned N) const {
460     assert(N == 1 && "Invalid number of operands!");
461     Inst.addOperand(MCOperand::CreateImm(
462       ARM_AM::getSORegOpc(Shift.ShiftTy, 0)));
463   }
464
465   void addRegListOperands(MCInst &Inst, unsigned N) const {
466     assert(N == 1 && "Invalid number of operands!");
467     const SmallVectorImpl<unsigned> &RegList = getRegList();
468     for (SmallVectorImpl<unsigned>::const_iterator
469            I = RegList.begin(), E = RegList.end(); I != E; ++I)
470       Inst.addOperand(MCOperand::CreateReg(*I));
471   }
472
473   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
474     addRegListOperands(Inst, N);
475   }
476
477   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
478     addRegListOperands(Inst, N);
479   }
480
481   void addImmOperands(MCInst &Inst, unsigned N) const {
482     assert(N == 1 && "Invalid number of operands!");
483     addExpr(Inst, getImm());
484   }
485
486   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
487     assert(N == 1 && "Invalid number of operands!");
488     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
489   }
490
491   void addMemMode7Operands(MCInst &Inst, unsigned N) const {
492     assert(N == 1 && isMemMode7() && "Invalid number of operands!");
493     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
494
495     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
496     (void)CE;
497     assert((CE || CE->getValue() == 0) &&
498            "No offset operand support in mode 7");
499   }
500
501   void addMemMode2Operands(MCInst &Inst, unsigned N) const {
502     assert(isMemMode2() && "Invalid mode or number of operands!");
503     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
504     unsigned IdxMode = (getMemPreindexed() | getMemPostindexed() << 1);
505
506     if (getMemOffsetIsReg()) {
507       Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
508
509       ARM_AM::AddrOpc AMOpc = getMemNegative() ? ARM_AM::sub : ARM_AM::add;
510       ARM_AM::ShiftOpc ShOpc = ARM_AM::no_shift;
511       int64_t ShiftAmount = 0;
512
513       if (getMemOffsetRegShifted()) {
514         ShOpc = getMemShiftType();
515         const MCConstantExpr *CE =
516                    dyn_cast<MCConstantExpr>(getMemShiftAmount());
517         ShiftAmount = CE->getValue();
518       }
519
520       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(AMOpc, ShiftAmount,
521                                            ShOpc, IdxMode)));
522       return;
523     }
524
525     // Create a operand placeholder to always yield the same number of operands.
526     Inst.addOperand(MCOperand::CreateReg(0));
527
528     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
529     // the difference?
530     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
531     assert(CE && "Non-constant mode 2 offset operand!");
532     int64_t Offset = CE->getValue();
533
534     if (Offset >= 0)
535       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(ARM_AM::add,
536                                            Offset, ARM_AM::no_shift, IdxMode)));
537     else
538       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(ARM_AM::sub,
539                                           -Offset, ARM_AM::no_shift, IdxMode)));
540   }
541
542   void addMemMode5Operands(MCInst &Inst, unsigned N) const {
543     assert(N == 2 && isMemMode5() && "Invalid number of operands!");
544
545     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
546     assert(!getMemOffsetIsReg() && "Invalid mode 5 operand");
547
548     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
549     // the difference?
550     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
551     assert(CE && "Non-constant mode 5 offset operand!");
552
553     // The MCInst offset operand doesn't include the low two bits (like
554     // the instruction encoding).
555     int64_t Offset = CE->getValue() / 4;
556     if (Offset >= 0)
557       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
558                                                              Offset)));
559     else
560       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
561                                                              -Offset)));
562   }
563
564   void addMemModeRegThumbOperands(MCInst &Inst, unsigned N) const {
565     assert(N == 2 && isMemModeRegThumb() && "Invalid number of operands!");
566     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
567     Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
568   }
569
570   void addMemModeImmThumbOperands(MCInst &Inst, unsigned N) const {
571     assert(N == 2 && isMemModeImmThumb() && "Invalid number of operands!");
572     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
573     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
574     assert(CE && "Non-constant mode offset operand!");
575     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
576   }
577
578   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
579     assert(N == 1 && "Invalid number of operands!");
580     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
581   }
582
583   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
584     assert(N == 1 && "Invalid number of operands!");
585     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
586   }
587
588   virtual void dump(raw_ostream &OS) const;
589
590   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
591     ARMOperand *Op = new ARMOperand(CondCode);
592     Op->CC.Val = CC;
593     Op->StartLoc = S;
594     Op->EndLoc = S;
595     return Op;
596   }
597
598   static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
599     ARMOperand *Op = new ARMOperand(CoprocNum);
600     Op->Cop.Val = CopVal;
601     Op->StartLoc = S;
602     Op->EndLoc = S;
603     return Op;
604   }
605
606   static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
607     ARMOperand *Op = new ARMOperand(CoprocReg);
608     Op->Cop.Val = CopVal;
609     Op->StartLoc = S;
610     Op->EndLoc = S;
611     return Op;
612   }
613
614   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
615     ARMOperand *Op = new ARMOperand(CCOut);
616     Op->Reg.RegNum = RegNum;
617     Op->StartLoc = S;
618     Op->EndLoc = S;
619     return Op;
620   }
621
622   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
623     ARMOperand *Op = new ARMOperand(Token);
624     Op->Tok.Data = Str.data();
625     Op->Tok.Length = Str.size();
626     Op->StartLoc = S;
627     Op->EndLoc = S;
628     return Op;
629   }
630
631   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
632     ARMOperand *Op = new ARMOperand(Register);
633     Op->Reg.RegNum = RegNum;
634     Op->StartLoc = S;
635     Op->EndLoc = E;
636     return Op;
637   }
638
639   static ARMOperand *CreateShifter(ARM_AM::ShiftOpc ShTy,
640                                    SMLoc S, SMLoc E) {
641     ARMOperand *Op = new ARMOperand(Shifter);
642     Op->Shift.ShiftTy = ShTy;
643     Op->StartLoc = S;
644     Op->EndLoc = E;
645     return Op;
646   }
647
648   static ARMOperand *
649   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
650                 SMLoc StartLoc, SMLoc EndLoc) {
651     KindTy Kind = RegisterList;
652
653     if (ARM::DPRRegClass.contains(Regs.front().first))
654       Kind = DPRRegisterList;
655     else if (ARM::SPRRegClass.contains(Regs.front().first))
656       Kind = SPRRegisterList;
657
658     ARMOperand *Op = new ARMOperand(Kind);
659     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
660            I = Regs.begin(), E = Regs.end(); I != E; ++I)
661       Op->Registers.push_back(I->first);
662     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
663     Op->StartLoc = StartLoc;
664     Op->EndLoc = EndLoc;
665     return Op;
666   }
667
668   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
669     ARMOperand *Op = new ARMOperand(Immediate);
670     Op->Imm.Val = Val;
671     Op->StartLoc = S;
672     Op->EndLoc = E;
673     return Op;
674   }
675
676   static ARMOperand *CreateMem(ARMII::AddrMode AddrMode, unsigned BaseRegNum,
677                                bool OffsetIsReg, const MCExpr *Offset,
678                                int OffsetRegNum, bool OffsetRegShifted,
679                                enum ARM_AM::ShiftOpc ShiftType,
680                                const MCExpr *ShiftAmount, bool Preindexed,
681                                bool Postindexed, bool Negative, bool Writeback,
682                                SMLoc S, SMLoc E) {
683     assert((OffsetRegNum == -1 || OffsetIsReg) &&
684            "OffsetRegNum must imply OffsetIsReg!");
685     assert((!OffsetRegShifted || OffsetIsReg) &&
686            "OffsetRegShifted must imply OffsetIsReg!");
687     assert((Offset || OffsetIsReg) &&
688            "Offset must exists unless register offset is used!");
689     assert((!ShiftAmount || (OffsetIsReg && OffsetRegShifted)) &&
690            "Cannot have shift amount without shifted register offset!");
691     assert((!Offset || !OffsetIsReg) &&
692            "Cannot have expression offset and register offset!");
693
694     ARMOperand *Op = new ARMOperand(Memory);
695     Op->Mem.AddrMode = AddrMode;
696     Op->Mem.BaseRegNum = BaseRegNum;
697     Op->Mem.OffsetIsReg = OffsetIsReg;
698     if (OffsetIsReg)
699       Op->Mem.Offset.RegNum = OffsetRegNum;
700     else
701       Op->Mem.Offset.Value = Offset;
702     Op->Mem.OffsetRegShifted = OffsetRegShifted;
703     Op->Mem.ShiftType = ShiftType;
704     Op->Mem.ShiftAmount = ShiftAmount;
705     Op->Mem.Preindexed = Preindexed;
706     Op->Mem.Postindexed = Postindexed;
707     Op->Mem.Negative = Negative;
708     Op->Mem.Writeback = Writeback;
709
710     Op->StartLoc = S;
711     Op->EndLoc = E;
712     return Op;
713   }
714
715   static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
716     ARMOperand *Op = new ARMOperand(MemBarrierOpt);
717     Op->MBOpt.Val = Opt;
718     Op->StartLoc = S;
719     Op->EndLoc = S;
720     return Op;
721   }
722
723   static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
724     ARMOperand *Op = new ARMOperand(ProcIFlags);
725     Op->IFlags.Val = IFlags;
726     Op->StartLoc = S;
727     Op->EndLoc = S;
728     return Op;
729   }
730
731   static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
732     ARMOperand *Op = new ARMOperand(MSRMask);
733     Op->MMask.Val = MMask;
734     Op->StartLoc = S;
735     Op->EndLoc = S;
736     return Op;
737   }
738 };
739
740 } // end anonymous namespace.
741
742 void ARMOperand::dump(raw_ostream &OS) const {
743   switch (Kind) {
744   case CondCode:
745     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
746     break;
747   case CCOut:
748     OS << "<ccout " << getReg() << ">";
749     break;
750   case CoprocNum:
751     OS << "<coprocessor number: " << getCoproc() << ">";
752     break;
753   case CoprocReg:
754     OS << "<coprocessor register: " << getCoproc() << ">";
755     break;
756   case MSRMask:
757     OS << "<mask: " << getMSRMask() << ">";
758     break;
759   case Immediate:
760     getImm()->print(OS);
761     break;
762   case MemBarrierOpt:
763     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
764     break;
765   case Memory:
766     OS << "<memory "
767        << "am:" << ARMII::AddrModeToString(getMemAddrMode())
768        << " base:" << getMemBaseRegNum();
769     if (getMemOffsetIsReg()) {
770       OS << " offset:<register " << getMemOffsetRegNum();
771       if (getMemOffsetRegShifted()) {
772         OS << " offset-shift-type:" << getMemShiftType();
773         OS << " offset-shift-amount:" << *getMemShiftAmount();
774       }
775     } else {
776       OS << " offset:" << *getMemOffset();
777     }
778     if (getMemOffsetIsReg())
779       OS << " (offset-is-reg)";
780     if (getMemPreindexed())
781       OS << " (pre-indexed)";
782     if (getMemPostindexed())
783       OS << " (post-indexed)";
784     if (getMemNegative())
785       OS << " (negative)";
786     if (getMemWriteback())
787       OS << " (writeback)";
788     OS << ">";
789     break;
790   case ProcIFlags: {
791     OS << "<ARM_PROC::";
792     unsigned IFlags = getProcIFlags();
793     for (int i=2; i >= 0; --i)
794       if (IFlags & (1 << i))
795         OS << ARM_PROC::IFlagsToString(1 << i);
796     OS << ">";
797     break;
798   }
799   case Register:
800     OS << "<register " << getReg() << ">";
801     break;
802   case Shifter:
803     OS << "<shifter " << getShiftOpcStr(Shift.ShiftTy) << ">";
804     break;
805   case RegisterList:
806   case DPRRegisterList:
807   case SPRRegisterList: {
808     OS << "<register_list ";
809
810     const SmallVectorImpl<unsigned> &RegList = getRegList();
811     for (SmallVectorImpl<unsigned>::const_iterator
812            I = RegList.begin(), E = RegList.end(); I != E; ) {
813       OS << *I;
814       if (++I < E) OS << ", ";
815     }
816
817     OS << ">";
818     break;
819   }
820   case Token:
821     OS << "'" << getToken() << "'";
822     break;
823   }
824 }
825
826 /// @name Auto-generated Match Functions
827 /// {
828
829 static unsigned MatchRegisterName(StringRef Name);
830
831 /// }
832
833 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
834                                  SMLoc &StartLoc, SMLoc &EndLoc) {
835   RegNo = TryParseRegister();
836
837   return (RegNo == (unsigned)-1);
838 }
839
840 /// Try to parse a register name.  The token must be an Identifier when called,
841 /// and if it is a register name the token is eaten and the register number is
842 /// returned.  Otherwise return -1.
843 ///
844 int ARMAsmParser::TryParseRegister() {
845   const AsmToken &Tok = Parser.getTok();
846   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
847
848   // FIXME: Validate register for the current architecture; we have to do
849   // validation later, so maybe there is no need for this here.
850   std::string upperCase = Tok.getString().str();
851   std::string lowerCase = LowercaseString(upperCase);
852   unsigned RegNum = MatchRegisterName(lowerCase);
853   if (!RegNum) {
854     RegNum = StringSwitch<unsigned>(lowerCase)
855       .Case("r13", ARM::SP)
856       .Case("r14", ARM::LR)
857       .Case("r15", ARM::PC)
858       .Case("ip", ARM::R12)
859       .Default(0);
860   }
861   if (!RegNum) return -1;
862
863   Parser.Lex(); // Eat identifier token.
864   return RegNum;
865 }
866
867 /// Try to parse a register name.  The token must be an Identifier when called,
868 /// and if it is a register name the token is eaten and the register number is
869 /// returned.  Otherwise return -1.
870 ///
871 bool ARMAsmParser::TryParseShiftRegister(
872                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
873   SMLoc S = Parser.getTok().getLoc();
874   const AsmToken &Tok = Parser.getTok();
875   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
876
877   std::string upperCase = Tok.getString().str();
878   std::string lowerCase = LowercaseString(upperCase);
879   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
880       .Case("lsl", ARM_AM::lsl)
881       .Case("lsr", ARM_AM::lsr)
882       .Case("asr", ARM_AM::asr)
883       .Case("ror", ARM_AM::ror)
884       .Case("rrx", ARM_AM::rrx)
885       .Default(ARM_AM::no_shift);
886
887   if (ShiftTy == ARM_AM::no_shift)
888     return true;
889
890   Parser.Lex(); // Eat shift-type operand;
891   int RegNum = TryParseRegister();
892   if (RegNum == -1)
893     return Error(Parser.getTok().getLoc(), "register expected");
894
895   Operands.push_back(ARMOperand::CreateReg(RegNum,S, Parser.getTok().getLoc()));
896   Operands.push_back(ARMOperand::CreateShifter(ShiftTy,
897                                                S, Parser.getTok().getLoc()));
898
899   return false;
900 }
901
902
903 /// Try to parse a register name.  The token must be an Identifier when called.
904 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
905 /// if there is a "writeback". 'true' if it's not a register.
906 ///
907 /// TODO this is likely to change to allow different register types and or to
908 /// parse for a specific register type.
909 bool ARMAsmParser::
910 TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
911   SMLoc S = Parser.getTok().getLoc();
912   int RegNo = TryParseRegister();
913   if (RegNo == -1)
914     return true;
915
916   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
917
918   const AsmToken &ExclaimTok = Parser.getTok();
919   if (ExclaimTok.is(AsmToken::Exclaim)) {
920     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
921                                                ExclaimTok.getLoc()));
922     Parser.Lex(); // Eat exclaim token
923   }
924
925   return false;
926 }
927
928 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
929 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
930 /// "c5", ...
931 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
932   // Use the same layout as the tablegen'erated register name matcher. Ugly,
933   // but efficient.
934   switch (Name.size()) {
935   default: break;
936   case 2:
937     if (Name[0] != CoprocOp)
938       return -1;
939     switch (Name[1]) {
940     default:  return -1;
941     case '0': return 0;
942     case '1': return 1;
943     case '2': return 2;
944     case '3': return 3;
945     case '4': return 4;
946     case '5': return 5;
947     case '6': return 6;
948     case '7': return 7;
949     case '8': return 8;
950     case '9': return 9;
951     }
952     break;
953   case 3:
954     if (Name[0] != CoprocOp || Name[1] != '1')
955       return -1;
956     switch (Name[2]) {
957     default:  return -1;
958     case '0': return 10;
959     case '1': return 11;
960     case '2': return 12;
961     case '3': return 13;
962     case '4': return 14;
963     case '5': return 15;
964     }
965     break;
966   }
967
968   return -1;
969 }
970
971 /// tryParseCoprocNumOperand - Try to parse an coprocessor number operand. The
972 /// token must be an Identifier when called, and if it is a coprocessor
973 /// number, the token is eaten and the operand is added to the operand list.
974 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
975 tryParseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
976   SMLoc S = Parser.getTok().getLoc();
977   const AsmToken &Tok = Parser.getTok();
978   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
979
980   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
981   if (Num == -1)
982     return MatchOperand_NoMatch;
983
984   Parser.Lex(); // Eat identifier token.
985   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
986   return MatchOperand_Success;
987 }
988
989 /// tryParseCoprocRegOperand - Try to parse an coprocessor register operand. The
990 /// token must be an Identifier when called, and if it is a coprocessor
991 /// number, the token is eaten and the operand is added to the operand list.
992 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
993 tryParseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
994   SMLoc S = Parser.getTok().getLoc();
995   const AsmToken &Tok = Parser.getTok();
996   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
997
998   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
999   if (Reg == -1)
1000     return MatchOperand_NoMatch;
1001
1002   Parser.Lex(); // Eat identifier token.
1003   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
1004   return MatchOperand_Success;
1005 }
1006
1007 /// Parse a register list, return it if successful else return null.  The first
1008 /// token must be a '{' when called.
1009 bool ARMAsmParser::
1010 ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1011   assert(Parser.getTok().is(AsmToken::LCurly) &&
1012          "Token is not a Left Curly Brace");
1013   SMLoc S = Parser.getTok().getLoc();
1014
1015   // Read the rest of the registers in the list.
1016   unsigned PrevRegNum = 0;
1017   SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
1018
1019   do {
1020     bool IsRange = Parser.getTok().is(AsmToken::Minus);
1021     Parser.Lex(); // Eat non-identifier token.
1022
1023     const AsmToken &RegTok = Parser.getTok();
1024     SMLoc RegLoc = RegTok.getLoc();
1025     if (RegTok.isNot(AsmToken::Identifier)) {
1026       Error(RegLoc, "register expected");
1027       return true;
1028     }
1029
1030     int RegNum = TryParseRegister();
1031     if (RegNum == -1) {
1032       Error(RegLoc, "register expected");
1033       return true;
1034     }
1035
1036     if (IsRange) {
1037       int Reg = PrevRegNum;
1038       do {
1039         ++Reg;
1040         Registers.push_back(std::make_pair(Reg, RegLoc));
1041       } while (Reg != RegNum);
1042     } else {
1043       Registers.push_back(std::make_pair(RegNum, RegLoc));
1044     }
1045
1046     PrevRegNum = RegNum;
1047   } while (Parser.getTok().is(AsmToken::Comma) ||
1048            Parser.getTok().is(AsmToken::Minus));
1049
1050   // Process the right curly brace of the list.
1051   const AsmToken &RCurlyTok = Parser.getTok();
1052   if (RCurlyTok.isNot(AsmToken::RCurly)) {
1053     Error(RCurlyTok.getLoc(), "'}' expected");
1054     return true;
1055   }
1056
1057   SMLoc E = RCurlyTok.getLoc();
1058   Parser.Lex(); // Eat right curly brace token.
1059
1060   // Verify the register list.
1061   SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1062     RI = Registers.begin(), RE = Registers.end();
1063
1064   unsigned HighRegNum = getARMRegisterNumbering(RI->first);
1065   bool EmittedWarning = false;
1066
1067   DenseMap<unsigned, bool> RegMap;
1068   RegMap[HighRegNum] = true;
1069
1070   for (++RI; RI != RE; ++RI) {
1071     const std::pair<unsigned, SMLoc> &RegInfo = *RI;
1072     unsigned Reg = getARMRegisterNumbering(RegInfo.first);
1073
1074     if (RegMap[Reg]) {
1075       Error(RegInfo.second, "register duplicated in register list");
1076       return true;
1077     }
1078
1079     if (!EmittedWarning && Reg < HighRegNum)
1080       Warning(RegInfo.second,
1081               "register not in ascending order in register list");
1082
1083     RegMap[Reg] = true;
1084     HighRegNum = std::max(Reg, HighRegNum);
1085   }
1086
1087   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
1088   return false;
1089 }
1090
1091 /// tryParseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
1092 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1093 tryParseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1094   SMLoc S = Parser.getTok().getLoc();
1095   const AsmToken &Tok = Parser.getTok();
1096   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1097   StringRef OptStr = Tok.getString();
1098
1099   unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
1100     .Case("sy",    ARM_MB::SY)
1101     .Case("st",    ARM_MB::ST)
1102     .Case("ish",   ARM_MB::ISH)
1103     .Case("ishst", ARM_MB::ISHST)
1104     .Case("nsh",   ARM_MB::NSH)
1105     .Case("nshst", ARM_MB::NSHST)
1106     .Case("osh",   ARM_MB::OSH)
1107     .Case("oshst", ARM_MB::OSHST)
1108     .Default(~0U);
1109
1110   if (Opt == ~0U)
1111     return MatchOperand_NoMatch;
1112
1113   Parser.Lex(); // Eat identifier token.
1114   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
1115   return MatchOperand_Success;
1116 }
1117
1118 /// tryParseProcIFlagsOperand - Try to parse iflags from CPS instruction.
1119 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1120 tryParseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1121   SMLoc S = Parser.getTok().getLoc();
1122   const AsmToken &Tok = Parser.getTok();
1123   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1124   StringRef IFlagsStr = Tok.getString();
1125
1126   unsigned IFlags = 0;
1127   for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
1128     unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
1129     .Case("a", ARM_PROC::A)
1130     .Case("i", ARM_PROC::I)
1131     .Case("f", ARM_PROC::F)
1132     .Default(~0U);
1133
1134     // If some specific iflag is already set, it means that some letter is
1135     // present more than once, this is not acceptable.
1136     if (Flag == ~0U || (IFlags & Flag))
1137       return MatchOperand_NoMatch;
1138
1139     IFlags |= Flag;
1140   }
1141
1142   Parser.Lex(); // Eat identifier token.
1143   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
1144   return MatchOperand_Success;
1145 }
1146
1147 /// tryParseMSRMaskOperand - Try to parse mask flags from MSR instruction.
1148 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1149 tryParseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1150   SMLoc S = Parser.getTok().getLoc();
1151   const AsmToken &Tok = Parser.getTok();
1152   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1153   StringRef Mask = Tok.getString();
1154
1155   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
1156   size_t Start = 0, Next = Mask.find('_');
1157   StringRef Flags = "";
1158   StringRef SpecReg = Mask.slice(Start, Next);
1159   if (Next != StringRef::npos)
1160     Flags = Mask.slice(Next+1, Mask.size());
1161
1162   // FlagsVal contains the complete mask:
1163   // 3-0: Mask
1164   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1165   unsigned FlagsVal = 0;
1166
1167   if (SpecReg == "apsr") {
1168     FlagsVal = StringSwitch<unsigned>(Flags)
1169     .Case("nzcvq",  0x8) // same as CPSR_c
1170     .Case("g",      0x4) // same as CPSR_s
1171     .Case("nzcvqg", 0xc) // same as CPSR_fs
1172     .Default(~0U);
1173
1174     if (FlagsVal == ~0U) {
1175       if (!Flags.empty())
1176         return MatchOperand_NoMatch;
1177       else
1178         FlagsVal = 0; // No flag
1179     }
1180   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
1181     for (int i = 0, e = Flags.size(); i != e; ++i) {
1182       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
1183       .Case("c", 1)
1184       .Case("x", 2)
1185       .Case("s", 4)
1186       .Case("f", 8)
1187       .Default(~0U);
1188
1189       // If some specific flag is already set, it means that some letter is
1190       // present more than once, this is not acceptable.
1191       if (FlagsVal == ~0U || (FlagsVal & Flag))
1192         return MatchOperand_NoMatch;
1193       FlagsVal |= Flag;
1194     }
1195   } else // No match for special register.
1196     return MatchOperand_NoMatch;
1197
1198   // Special register without flags are equivalent to "fc" flags.
1199   if (!FlagsVal)
1200     FlagsVal = 0x9;
1201
1202   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1203   if (SpecReg == "spsr")
1204     FlagsVal |= 16;
1205
1206   Parser.Lex(); // Eat identifier token.
1207   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
1208   return MatchOperand_Success;
1209 }
1210
1211 /// tryParseMemMode2Operand - Try to parse memory addressing mode 2 operand.
1212 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1213 tryParseMemMode2Operand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1214   SMLoc S = Parser.getTok().getLoc();
1215   const AsmToken &Tok = Parser.getTok();
1216   assert(Tok.is(AsmToken::LBrac) && "Token is not a \"[\"");
1217
1218   if (ParseMemory(Operands, ARMII::AddrMode2))
1219     return MatchOperand_NoMatch;
1220
1221   return MatchOperand_Success;
1222 }
1223
1224 /// CvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
1225 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1226 /// when they refer multiple MIOperands inside a single one.
1227 bool ARMAsmParser::
1228 CvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
1229                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1230   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1231
1232   // Create a writeback register dummy placeholder.
1233   Inst.addOperand(MCOperand::CreateImm(0));
1234
1235   ((ARMOperand*)Operands[3])->addMemMode2Operands(Inst, 3);
1236   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1237   return true;
1238 }
1239
1240 /// CvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
1241 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1242 /// when they refer multiple MIOperands inside a single one.
1243 bool ARMAsmParser::
1244 CvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
1245                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1246   // Create a writeback register dummy placeholder.
1247   Inst.addOperand(MCOperand::CreateImm(0));
1248   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1249   ((ARMOperand*)Operands[3])->addMemMode2Operands(Inst, 3);
1250   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1251   return true;
1252 }
1253
1254 /// Parse an ARM memory expression, return false if successful else return true
1255 /// or an error.  The first token must be a '[' when called.
1256 ///
1257 /// TODO Only preindexing and postindexing addressing are started, unindexed
1258 /// with option, etc are still to do.
1259 bool ARMAsmParser::
1260 ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1261             ARMII::AddrMode AddrMode = ARMII::AddrModeNone) {
1262   SMLoc S, E;
1263   assert(Parser.getTok().is(AsmToken::LBrac) &&
1264          "Token is not a Left Bracket");
1265   S = Parser.getTok().getLoc();
1266   Parser.Lex(); // Eat left bracket token.
1267
1268   const AsmToken &BaseRegTok = Parser.getTok();
1269   if (BaseRegTok.isNot(AsmToken::Identifier)) {
1270     Error(BaseRegTok.getLoc(), "register expected");
1271     return true;
1272   }
1273   int BaseRegNum = TryParseRegister();
1274   if (BaseRegNum == -1) {
1275     Error(BaseRegTok.getLoc(), "register expected");
1276     return true;
1277   }
1278
1279   // The next token must either be a comma or a closing bracket.
1280   const AsmToken &Tok = Parser.getTok();
1281   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
1282     return true;
1283
1284   bool Preindexed = false;
1285   bool Postindexed = false;
1286   bool OffsetIsReg = false;
1287   bool Negative = false;
1288   bool Writeback = false;
1289   ARMOperand *WBOp = 0;
1290   int OffsetRegNum = -1;
1291   bool OffsetRegShifted = false;
1292   enum ARM_AM::ShiftOpc ShiftType = ARM_AM::lsl;
1293   const MCExpr *ShiftAmount = 0;
1294   const MCExpr *Offset = 0;
1295
1296   // First look for preindexed address forms, that is after the "[Rn" we now
1297   // have to see if the next token is a comma.
1298   if (Tok.is(AsmToken::Comma)) {
1299     Preindexed = true;
1300     Parser.Lex(); // Eat comma token.
1301
1302     if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
1303                              Offset, OffsetIsReg, OffsetRegNum, E))
1304       return true;
1305     const AsmToken &RBracTok = Parser.getTok();
1306     if (RBracTok.isNot(AsmToken::RBrac)) {
1307       Error(RBracTok.getLoc(), "']' expected");
1308       return true;
1309     }
1310     E = RBracTok.getLoc();
1311     Parser.Lex(); // Eat right bracket token.
1312
1313     const AsmToken &ExclaimTok = Parser.getTok();
1314     if (ExclaimTok.is(AsmToken::Exclaim)) {
1315       WBOp = ARMOperand::CreateToken(ExclaimTok.getString(),
1316                                      ExclaimTok.getLoc());
1317       Writeback = true;
1318       Parser.Lex(); // Eat exclaim token
1319     } else { // In addressing mode 2, pre-indexed mode always end with "!"
1320       if (AddrMode == ARMII::AddrMode2)
1321         Preindexed = false;
1322     }
1323   } else {
1324     // The "[Rn" we have so far was not followed by a comma.
1325
1326     // If there's anything other than the right brace, this is a post indexing
1327     // addressing form.
1328     E = Tok.getLoc();
1329     Parser.Lex(); // Eat right bracket token.
1330
1331     const AsmToken &NextTok = Parser.getTok();
1332
1333     if (NextTok.isNot(AsmToken::EndOfStatement)) {
1334       Postindexed = true;
1335       Writeback = true;
1336
1337       if (NextTok.isNot(AsmToken::Comma)) {
1338         Error(NextTok.getLoc(), "',' expected");
1339         return true;
1340       }
1341
1342       Parser.Lex(); // Eat comma token.
1343
1344       if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
1345                                ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
1346                                E))
1347         return true;
1348     }
1349   }
1350
1351   // Force Offset to exist if used.
1352   if (!OffsetIsReg) {
1353     if (!Offset)
1354       Offset = MCConstantExpr::Create(0, getContext());
1355   }
1356
1357   Operands.push_back(ARMOperand::CreateMem(AddrMode, BaseRegNum, OffsetIsReg,
1358                                      Offset, OffsetRegNum, OffsetRegShifted,
1359                                      ShiftType, ShiftAmount, Preindexed,
1360                                      Postindexed, Negative, Writeback, S, E));
1361   if (WBOp)
1362     Operands.push_back(WBOp);
1363
1364   return false;
1365 }
1366
1367 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
1368 /// we will parse the following (were +/- means that a plus or minus is
1369 /// optional):
1370 ///   +/-Rm
1371 ///   +/-Rm, shift
1372 ///   #offset
1373 /// we return false on success or an error otherwise.
1374 bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
1375                                         bool &OffsetRegShifted,
1376                                         enum ARM_AM::ShiftOpc &ShiftType,
1377                                         const MCExpr *&ShiftAmount,
1378                                         const MCExpr *&Offset,
1379                                         bool &OffsetIsReg,
1380                                         int &OffsetRegNum,
1381                                         SMLoc &E) {
1382   Negative = false;
1383   OffsetRegShifted = false;
1384   OffsetIsReg = false;
1385   OffsetRegNum = -1;
1386   const AsmToken &NextTok = Parser.getTok();
1387   E = NextTok.getLoc();
1388   if (NextTok.is(AsmToken::Plus))
1389     Parser.Lex(); // Eat plus token.
1390   else if (NextTok.is(AsmToken::Minus)) {
1391     Negative = true;
1392     Parser.Lex(); // Eat minus token
1393   }
1394   // See if there is a register following the "[Rn," or "[Rn]," we have so far.
1395   const AsmToken &OffsetRegTok = Parser.getTok();
1396   if (OffsetRegTok.is(AsmToken::Identifier)) {
1397     SMLoc CurLoc = OffsetRegTok.getLoc();
1398     OffsetRegNum = TryParseRegister();
1399     if (OffsetRegNum != -1) {
1400       OffsetIsReg = true;
1401       E = CurLoc;
1402     }
1403   }
1404
1405   // If we parsed a register as the offset then there can be a shift after that.
1406   if (OffsetRegNum != -1) {
1407     // Look for a comma then a shift
1408     const AsmToken &Tok = Parser.getTok();
1409     if (Tok.is(AsmToken::Comma)) {
1410       Parser.Lex(); // Eat comma token.
1411
1412       const AsmToken &Tok = Parser.getTok();
1413       if (ParseShift(ShiftType, ShiftAmount, E))
1414         return Error(Tok.getLoc(), "shift expected");
1415       OffsetRegShifted = true;
1416     }
1417   }
1418   else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
1419     // Look for #offset following the "[Rn," or "[Rn],"
1420     const AsmToken &HashTok = Parser.getTok();
1421     if (HashTok.isNot(AsmToken::Hash))
1422       return Error(HashTok.getLoc(), "'#' expected");
1423
1424     Parser.Lex(); // Eat hash token.
1425
1426     if (getParser().ParseExpression(Offset))
1427      return true;
1428     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1429   }
1430   return false;
1431 }
1432
1433 /// ParseShift as one of these two:
1434 ///   ( lsl | lsr | asr | ror ) , # shift_amount
1435 ///   rrx
1436 /// and returns true if it parses a shift otherwise it returns false.
1437 bool ARMAsmParser::ParseShift(ARM_AM::ShiftOpc &St,
1438                               const MCExpr *&ShiftAmount, SMLoc &E) {
1439   const AsmToken &Tok = Parser.getTok();
1440   if (Tok.isNot(AsmToken::Identifier))
1441     return true;
1442   StringRef ShiftName = Tok.getString();
1443   if (ShiftName == "lsl" || ShiftName == "LSL")
1444     St = ARM_AM::lsl;
1445   else if (ShiftName == "lsr" || ShiftName == "LSR")
1446     St = ARM_AM::lsr;
1447   else if (ShiftName == "asr" || ShiftName == "ASR")
1448     St = ARM_AM::asr;
1449   else if (ShiftName == "ror" || ShiftName == "ROR")
1450     St = ARM_AM::ror;
1451   else if (ShiftName == "rrx" || ShiftName == "RRX")
1452     St = ARM_AM::rrx;
1453   else
1454     return true;
1455   Parser.Lex(); // Eat shift type token.
1456
1457   // Rrx stands alone.
1458   if (St == ARM_AM::rrx)
1459     return false;
1460
1461   // Otherwise, there must be a '#' and a shift amount.
1462   const AsmToken &HashTok = Parser.getTok();
1463   if (HashTok.isNot(AsmToken::Hash))
1464     return Error(HashTok.getLoc(), "'#' expected");
1465   Parser.Lex(); // Eat hash token.
1466
1467   if (getParser().ParseExpression(ShiftAmount))
1468     return true;
1469
1470   return false;
1471 }
1472
1473 /// Parse a arm instruction operand.  For now this parses the operand regardless
1474 /// of the mnemonic.
1475 bool ARMAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1476                                 StringRef Mnemonic) {
1477   SMLoc S, E;
1478
1479   // Check if the current operand has a custom associated parser, if so, try to
1480   // custom parse the operand, or fallback to the general approach.
1481   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1482   if (ResTy == MatchOperand_Success)
1483     return false;
1484   // If there wasn't a custom match, try the generic matcher below. Otherwise,
1485   // there was a match, but an error occurred, in which case, just return that
1486   // the operand parsing failed.
1487   if (ResTy == MatchOperand_ParseFail)
1488     return true;
1489
1490   switch (getLexer().getKind()) {
1491   default:
1492     Error(Parser.getTok().getLoc(), "unexpected token in operand");
1493     return true;
1494   case AsmToken::Identifier:
1495     if (!TryParseRegisterWithWriteBack(Operands))
1496       return false;
1497     if (!TryParseShiftRegister(Operands))
1498       return false;
1499
1500
1501     // Fall though for the Identifier case that is not a register or a
1502     // special name.
1503   case AsmToken::Integer: // things like 1f and 2b as a branch targets
1504   case AsmToken::Dot: {   // . as a branch target
1505     // This was not a register so parse other operands that start with an
1506     // identifier (like labels) as expressions and create them as immediates.
1507     const MCExpr *IdVal;
1508     S = Parser.getTok().getLoc();
1509     if (getParser().ParseExpression(IdVal))
1510       return true;
1511     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1512     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
1513     return false;
1514   }
1515   case AsmToken::LBrac:
1516     return ParseMemory(Operands);
1517   case AsmToken::LCurly:
1518     return ParseRegisterList(Operands);
1519   case AsmToken::Hash:
1520     // #42 -> immediate.
1521     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
1522     S = Parser.getTok().getLoc();
1523     Parser.Lex();
1524     const MCExpr *ImmVal;
1525     if (getParser().ParseExpression(ImmVal))
1526       return true;
1527     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1528     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
1529     return false;
1530   case AsmToken::Colon: {
1531     // ":lower16:" and ":upper16:" expression prefixes
1532     // FIXME: Check it's an expression prefix,
1533     // e.g. (FOO - :lower16:BAR) isn't legal.
1534     ARMMCExpr::VariantKind RefKind;
1535     if (ParsePrefix(RefKind))
1536       return true;
1537
1538     const MCExpr *SubExprVal;
1539     if (getParser().ParseExpression(SubExprVal))
1540       return true;
1541
1542     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
1543                                                    getContext());
1544     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1545     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
1546     return false;
1547   }
1548   }
1549 }
1550
1551 // ParsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
1552 //  :lower16: and :upper16:.
1553 bool ARMAsmParser::ParsePrefix(ARMMCExpr::VariantKind &RefKind) {
1554   RefKind = ARMMCExpr::VK_ARM_None;
1555
1556   // :lower16: and :upper16: modifiers
1557   assert(getLexer().is(AsmToken::Colon) && "expected a :");
1558   Parser.Lex(); // Eat ':'
1559
1560   if (getLexer().isNot(AsmToken::Identifier)) {
1561     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
1562     return true;
1563   }
1564
1565   StringRef IDVal = Parser.getTok().getIdentifier();
1566   if (IDVal == "lower16") {
1567     RefKind = ARMMCExpr::VK_ARM_LO16;
1568   } else if (IDVal == "upper16") {
1569     RefKind = ARMMCExpr::VK_ARM_HI16;
1570   } else {
1571     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
1572     return true;
1573   }
1574   Parser.Lex();
1575
1576   if (getLexer().isNot(AsmToken::Colon)) {
1577     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
1578     return true;
1579   }
1580   Parser.Lex(); // Eat the last ':'
1581   return false;
1582 }
1583
1584 const MCExpr *
1585 ARMAsmParser::ApplyPrefixToExpr(const MCExpr *E,
1586                                 MCSymbolRefExpr::VariantKind Variant) {
1587   // Recurse over the given expression, rebuilding it to apply the given variant
1588   // to the leftmost symbol.
1589   if (Variant == MCSymbolRefExpr::VK_None)
1590     return E;
1591
1592   switch (E->getKind()) {
1593   case MCExpr::Target:
1594     llvm_unreachable("Can't handle target expr yet");
1595   case MCExpr::Constant:
1596     llvm_unreachable("Can't handle lower16/upper16 of constant yet");
1597
1598   case MCExpr::SymbolRef: {
1599     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1600
1601     if (SRE->getKind() != MCSymbolRefExpr::VK_None)
1602       return 0;
1603
1604     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
1605   }
1606
1607   case MCExpr::Unary:
1608     llvm_unreachable("Can't handle unary expressions yet");
1609
1610   case MCExpr::Binary: {
1611     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1612     const MCExpr *LHS = ApplyPrefixToExpr(BE->getLHS(), Variant);
1613     const MCExpr *RHS = BE->getRHS();
1614     if (!LHS)
1615       return 0;
1616
1617     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1618   }
1619   }
1620
1621   assert(0 && "Invalid expression kind!");
1622   return 0;
1623 }
1624
1625 /// \brief Given a mnemonic, split out possible predication code and carry
1626 /// setting letters to form a canonical mnemonic and flags.
1627 //
1628 // FIXME: Would be nice to autogen this.
1629 static StringRef SplitMnemonic(StringRef Mnemonic,
1630                                unsigned &PredicationCode,
1631                                bool &CarrySetting,
1632                                unsigned &ProcessorIMod) {
1633   PredicationCode = ARMCC::AL;
1634   CarrySetting = false;
1635   ProcessorIMod = 0;
1636
1637   // Ignore some mnemonics we know aren't predicated forms.
1638   //
1639   // FIXME: Would be nice to autogen this.
1640   if (Mnemonic == "teq" || Mnemonic == "vceq" ||
1641       Mnemonic == "movs" ||
1642       Mnemonic == "svc" ||
1643       (Mnemonic == "mls" || Mnemonic == "smmls" || Mnemonic == "vcls" ||
1644        Mnemonic == "vmls" || Mnemonic == "vnmls") ||
1645       Mnemonic == "vacge" || Mnemonic == "vcge" ||
1646       Mnemonic == "vclt" ||
1647       Mnemonic == "vacgt" || Mnemonic == "vcgt" ||
1648       Mnemonic == "vcle" ||
1649       (Mnemonic == "smlal" || Mnemonic == "umaal" || Mnemonic == "umlal" ||
1650        Mnemonic == "vabal" || Mnemonic == "vmlal" || Mnemonic == "vpadal" ||
1651        Mnemonic == "vqdmlal"))
1652     return Mnemonic;
1653
1654   // First, split out any predication code.
1655   unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
1656     .Case("eq", ARMCC::EQ)
1657     .Case("ne", ARMCC::NE)
1658     .Case("hs", ARMCC::HS)
1659     .Case("lo", ARMCC::LO)
1660     .Case("mi", ARMCC::MI)
1661     .Case("pl", ARMCC::PL)
1662     .Case("vs", ARMCC::VS)
1663     .Case("vc", ARMCC::VC)
1664     .Case("hi", ARMCC::HI)
1665     .Case("ls", ARMCC::LS)
1666     .Case("ge", ARMCC::GE)
1667     .Case("lt", ARMCC::LT)
1668     .Case("gt", ARMCC::GT)
1669     .Case("le", ARMCC::LE)
1670     .Case("al", ARMCC::AL)
1671     .Default(~0U);
1672   if (CC != ~0U) {
1673     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
1674     PredicationCode = CC;
1675   }
1676
1677   // Next, determine if we have a carry setting bit. We explicitly ignore all
1678   // the instructions we know end in 's'.
1679   if (Mnemonic.endswith("s") &&
1680       !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" ||
1681         Mnemonic == "movs" || Mnemonic == "mrs" || Mnemonic == "smmls" ||
1682         Mnemonic == "vabs" || Mnemonic == "vcls" || Mnemonic == "vmls" ||
1683         Mnemonic == "vmrs" || Mnemonic == "vnmls" || Mnemonic == "vqabs" ||
1684         Mnemonic == "vrecps" || Mnemonic == "vrsqrts")) {
1685     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
1686     CarrySetting = true;
1687   }
1688
1689   // The "cps" instruction can have a interrupt mode operand which is glued into
1690   // the mnemonic. Check if this is the case, split it and parse the imod op
1691   if (Mnemonic.startswith("cps")) {
1692     // Split out any imod code.
1693     unsigned IMod =
1694       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
1695       .Case("ie", ARM_PROC::IE)
1696       .Case("id", ARM_PROC::ID)
1697       .Default(~0U);
1698     if (IMod != ~0U) {
1699       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
1700       ProcessorIMod = IMod;
1701     }
1702   }
1703
1704   return Mnemonic;
1705 }
1706
1707 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
1708 /// inclusion of carry set or predication code operands.
1709 //
1710 // FIXME: It would be nice to autogen this.
1711 void ARMAsmParser::
1712 GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
1713                       bool &CanAcceptPredicationCode) {
1714   bool isThumb = TM.getSubtarget<ARMSubtarget>().isThumb();
1715
1716   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
1717       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
1718       Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" ||
1719       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
1720       Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mov" ||
1721       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
1722       Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" ||
1723       Mnemonic == "eor" || Mnemonic == "smlal" || Mnemonic == "mvn") {
1724     CanAcceptCarrySet = true;
1725   } else {
1726     CanAcceptCarrySet = false;
1727   }
1728
1729   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
1730       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
1731       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
1732       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
1733       Mnemonic == "dsb" || Mnemonic == "movs" || Mnemonic == "isb" ||
1734       Mnemonic == "clrex" || Mnemonic.startswith("cps")) {
1735     CanAcceptPredicationCode = false;
1736   } else {
1737     CanAcceptPredicationCode = true;
1738   }
1739
1740   if (isThumb)
1741     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
1742         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
1743       CanAcceptPredicationCode = false;
1744 }
1745
1746 /// Parse an arm instruction mnemonic followed by its operands.
1747 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
1748                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1749   // Create the leading tokens for the mnemonic, split by '.' characters.
1750   size_t Start = 0, Next = Name.find('.');
1751   StringRef Head = Name.slice(Start, Next);
1752
1753   // Split out the predication code and carry setting flag from the mnemonic.
1754   unsigned PredicationCode;
1755   unsigned ProcessorIMod;
1756   bool CarrySetting;
1757   Head = SplitMnemonic(Head, PredicationCode, CarrySetting,
1758                        ProcessorIMod);
1759
1760   Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1761
1762   // Next, add the CCOut and ConditionCode operands, if needed.
1763   //
1764   // For mnemonics which can ever incorporate a carry setting bit or predication
1765   // code, our matching model involves us always generating CCOut and
1766   // ConditionCode operands to match the mnemonic "as written" and then we let
1767   // the matcher deal with finding the right instruction or generating an
1768   // appropriate error.
1769   bool CanAcceptCarrySet, CanAcceptPredicationCode;
1770   GetMnemonicAcceptInfo(Head, CanAcceptCarrySet, CanAcceptPredicationCode);
1771
1772   // Add the carry setting operand, if necessary.
1773   //
1774   // FIXME: It would be awesome if we could somehow invent a location such that
1775   // match errors on this operand would print a nice diagnostic about how the
1776   // 's' character in the mnemonic resulted in a CCOut operand.
1777   if (CanAcceptCarrySet) {
1778     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
1779                                                NameLoc));
1780   } else {
1781     // This mnemonic can't ever accept a carry set, but the user wrote one (or
1782     // misspelled another mnemonic).
1783
1784     // FIXME: Issue a nice error.
1785   }
1786
1787   // Add the predication code operand, if necessary.
1788   if (CanAcceptPredicationCode) {
1789     Operands.push_back(ARMOperand::CreateCondCode(
1790                          ARMCC::CondCodes(PredicationCode), NameLoc));
1791   } else {
1792     // This mnemonic can't ever accept a predication code, but the user wrote
1793     // one (or misspelled another mnemonic).
1794
1795     // FIXME: Issue a nice error.
1796   }
1797
1798   // Add the processor imod operand, if necessary.
1799   if (ProcessorIMod) {
1800     Operands.push_back(ARMOperand::CreateImm(
1801           MCConstantExpr::Create(ProcessorIMod, getContext()),
1802                                  NameLoc, NameLoc));
1803   } else {
1804     // This mnemonic can't ever accept a imod, but the user wrote
1805     // one (or misspelled another mnemonic).
1806
1807     // FIXME: Issue a nice error.
1808   }
1809
1810   // Add the remaining tokens in the mnemonic.
1811   while (Next != StringRef::npos) {
1812     Start = Next;
1813     Next = Name.find('.', Start + 1);
1814     StringRef ExtraToken = Name.slice(Start, Next);
1815
1816     Operands.push_back(ARMOperand::CreateToken(ExtraToken, NameLoc));
1817   }
1818
1819   // Read the remaining operands.
1820   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1821     // Read the first operand.
1822     if (ParseOperand(Operands, Head)) {
1823       Parser.EatToEndOfStatement();
1824       return true;
1825     }
1826
1827     while (getLexer().is(AsmToken::Comma)) {
1828       Parser.Lex();  // Eat the comma.
1829
1830       // Parse and remember the operand.
1831       if (ParseOperand(Operands, Head)) {
1832         Parser.EatToEndOfStatement();
1833         return true;
1834       }
1835     }
1836   }
1837
1838   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1839     Parser.EatToEndOfStatement();
1840     return TokError("unexpected token in argument list");
1841   }
1842
1843   Parser.Lex(); // Consume the EndOfStatement
1844   return false;
1845 }
1846
1847 bool ARMAsmParser::
1848 MatchAndEmitInstruction(SMLoc IDLoc,
1849                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1850                         MCStreamer &Out) {
1851   MCInst Inst;
1852   unsigned ErrorInfo;
1853   MatchResultTy MatchResult, MatchResult2;
1854   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1855   if (MatchResult != Match_Success) {
1856     // If we get a Match_InvalidOperand it might be some arithmetic instruction
1857     // that does not update the condition codes.  So try adding a CCOut operand
1858     // with a value of reg0.
1859     if (MatchResult == Match_InvalidOperand) {
1860       Operands.insert(Operands.begin() + 1,
1861                       ARMOperand::CreateCCOut(0,
1862                                   ((ARMOperand*)Operands[0])->getStartLoc()));
1863       MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1864       if (MatchResult2 == Match_Success)
1865         MatchResult = Match_Success;
1866       else {
1867         ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1868         Operands.erase(Operands.begin() + 1);
1869         delete CCOut;
1870       }
1871     }
1872     // If we get a Match_MnemonicFail it might be some arithmetic instruction
1873     // that updates the condition codes if it ends in 's'.  So see if the
1874     // mnemonic ends in 's' and if so try removing the 's' and adding a CCOut
1875     // operand with a value of CPSR.
1876     else if(MatchResult == Match_MnemonicFail) {
1877       // Get the instruction mnemonic, which is the first token.
1878       StringRef Mnemonic = ((ARMOperand*)Operands[0])->getToken();
1879       if (Mnemonic.substr(Mnemonic.size()-1) == "s") {
1880         // removed the 's' from the mnemonic for matching.
1881         StringRef MnemonicNoS = Mnemonic.slice(0, Mnemonic.size() - 1);
1882         SMLoc NameLoc = ((ARMOperand*)Operands[0])->getStartLoc();
1883         ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1884         Operands.erase(Operands.begin());
1885         delete OldMnemonic;
1886         Operands.insert(Operands.begin(),
1887                         ARMOperand::CreateToken(MnemonicNoS, NameLoc));
1888         Operands.insert(Operands.begin() + 1,
1889                         ARMOperand::CreateCCOut(ARM::CPSR, NameLoc));
1890         MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1891         if (MatchResult2 == Match_Success)
1892           MatchResult = Match_Success;
1893         else {
1894           ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1895           Operands.erase(Operands.begin());
1896           delete OldMnemonic;
1897           Operands.insert(Operands.begin(),
1898                           ARMOperand::CreateToken(Mnemonic, NameLoc));
1899           ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1900           Operands.erase(Operands.begin() + 1);
1901           delete CCOut;
1902         }
1903       }
1904     }
1905   }
1906   switch (MatchResult) {
1907   case Match_Success:
1908     Out.EmitInstruction(Inst);
1909     return false;
1910   case Match_MissingFeature:
1911     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1912     return true;
1913   case Match_InvalidOperand: {
1914     SMLoc ErrorLoc = IDLoc;
1915     if (ErrorInfo != ~0U) {
1916       if (ErrorInfo >= Operands.size())
1917         return Error(IDLoc, "too few operands for instruction");
1918
1919       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
1920       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1921     }
1922
1923     return Error(ErrorLoc, "invalid operand for instruction");
1924   }
1925   case Match_MnemonicFail:
1926     return Error(IDLoc, "unrecognized instruction mnemonic");
1927   case Match_ConversionFail:
1928     return Error(IDLoc, "unable to convert operands to instruction");
1929   }
1930
1931   llvm_unreachable("Implement any new match types added!");
1932   return true;
1933 }
1934
1935 /// ParseDirective parses the arm specific directives
1936 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
1937   StringRef IDVal = DirectiveID.getIdentifier();
1938   if (IDVal == ".word")
1939     return ParseDirectiveWord(4, DirectiveID.getLoc());
1940   else if (IDVal == ".thumb")
1941     return ParseDirectiveThumb(DirectiveID.getLoc());
1942   else if (IDVal == ".thumb_func")
1943     return ParseDirectiveThumbFunc(DirectiveID.getLoc());
1944   else if (IDVal == ".code")
1945     return ParseDirectiveCode(DirectiveID.getLoc());
1946   else if (IDVal == ".syntax")
1947     return ParseDirectiveSyntax(DirectiveID.getLoc());
1948   return true;
1949 }
1950
1951 /// ParseDirectiveWord
1952 ///  ::= .word [ expression (, expression)* ]
1953 bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1954   if (getLexer().isNot(AsmToken::EndOfStatement)) {
1955     for (;;) {
1956       const MCExpr *Value;
1957       if (getParser().ParseExpression(Value))
1958         return true;
1959
1960       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
1961
1962       if (getLexer().is(AsmToken::EndOfStatement))
1963         break;
1964
1965       // FIXME: Improve diagnostic.
1966       if (getLexer().isNot(AsmToken::Comma))
1967         return Error(L, "unexpected token in directive");
1968       Parser.Lex();
1969     }
1970   }
1971
1972   Parser.Lex();
1973   return false;
1974 }
1975
1976 /// ParseDirectiveThumb
1977 ///  ::= .thumb
1978 bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
1979   if (getLexer().isNot(AsmToken::EndOfStatement))
1980     return Error(L, "unexpected token in directive");
1981   Parser.Lex();
1982
1983   // TODO: set thumb mode
1984   // TODO: tell the MC streamer the mode
1985   // getParser().getStreamer().Emit???();
1986   return false;
1987 }
1988
1989 /// ParseDirectiveThumbFunc
1990 ///  ::= .thumbfunc symbol_name
1991 bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
1992   const AsmToken &Tok = Parser.getTok();
1993   if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
1994     return Error(L, "unexpected token in .thumb_func directive");
1995   StringRef Name = Tok.getString();
1996   Parser.Lex(); // Consume the identifier token.
1997   if (getLexer().isNot(AsmToken::EndOfStatement))
1998     return Error(L, "unexpected token in directive");
1999   Parser.Lex();
2000
2001   // Mark symbol as a thumb symbol.
2002   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
2003   getParser().getStreamer().EmitThumbFunc(Func);
2004   return false;
2005 }
2006
2007 /// ParseDirectiveSyntax
2008 ///  ::= .syntax unified | divided
2009 bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
2010   const AsmToken &Tok = Parser.getTok();
2011   if (Tok.isNot(AsmToken::Identifier))
2012     return Error(L, "unexpected token in .syntax directive");
2013   StringRef Mode = Tok.getString();
2014   if (Mode == "unified" || Mode == "UNIFIED")
2015     Parser.Lex();
2016   else if (Mode == "divided" || Mode == "DIVIDED")
2017     return Error(L, "'.syntax divided' arm asssembly not supported");
2018   else
2019     return Error(L, "unrecognized syntax mode in .syntax directive");
2020
2021   if (getLexer().isNot(AsmToken::EndOfStatement))
2022     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
2023   Parser.Lex();
2024
2025   // TODO tell the MC streamer the mode
2026   // getParser().getStreamer().Emit???();
2027   return false;
2028 }
2029
2030 /// ParseDirectiveCode
2031 ///  ::= .code 16 | 32
2032 bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
2033   const AsmToken &Tok = Parser.getTok();
2034   if (Tok.isNot(AsmToken::Integer))
2035     return Error(L, "unexpected token in .code directive");
2036   int64_t Val = Parser.getTok().getIntVal();
2037   if (Val == 16)
2038     Parser.Lex();
2039   else if (Val == 32)
2040     Parser.Lex();
2041   else
2042     return Error(L, "invalid operand to .code directive");
2043
2044   if (getLexer().isNot(AsmToken::EndOfStatement))
2045     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
2046   Parser.Lex();
2047
2048   // FIXME: We need to be able switch subtargets at this point so that
2049   // MatchInstructionImpl() will work when it gets the AvailableFeatures which
2050   // includes Feature_IsThumb or not to match the right instructions.  This is
2051   // blocked on the FIXME in llvm-mc.cpp when creating the TargetMachine.
2052   if (Val == 16){
2053     assert(TM.getSubtarget<ARMSubtarget>().isThumb() &&
2054            "switching between arm/thumb not yet suppported via .code 16)");
2055     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
2056   }
2057   else{
2058     assert(!TM.getSubtarget<ARMSubtarget>().isThumb() &&
2059            "switching between thumb/arm not yet suppported via .code 32)");
2060     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2061    }
2062
2063   return false;
2064 }
2065
2066 extern "C" void LLVMInitializeARMAsmLexer();
2067
2068 /// Force static initialization.
2069 extern "C" void LLVMInitializeARMAsmParser() {
2070   RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
2071   RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);
2072   LLVMInitializeARMAsmLexer();
2073 }
2074
2075 #define GET_REGISTER_MATCHER
2076 #define GET_MATCHER_IMPLEMENTATION
2077 #include "ARMGenAsmMatcher.inc"