149c46f28c5c57a8ae4d5168af595454d31928da
[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 "MCTargetDesc/ARMBaseInfo.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMMCExpr.h"
13 #include "llvm/MC/MCParser/MCAsmLexer.h"
14 #include "llvm/MC/MCParser/MCAsmParser.h"
15 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCStreamer.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCInstrDesc.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCTargetAsmParser.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringSwitch.h"
35 #include "llvm/ADT/Twine.h"
36
37 using namespace llvm;
38
39 namespace {
40
41 class ARMOperand;
42
43 class ARMAsmParser : public MCTargetAsmParser {
44   MCSubtargetInfo &STI;
45   MCAsmParser &Parser;
46
47   struct {
48     ARMCC::CondCodes Cond;    // Condition for IT block.
49     unsigned Mask:4;          // Condition mask for instructions.
50                               // Starting at first 1 (from lsb).
51                               //   '1'  condition as indicated in IT.
52                               //   '0'  inverse of condition (else).
53                               // Count of instructions in IT block is
54                               // 4 - trailingzeroes(mask)
55
56     bool FirstCond;           // Explicit flag for when we're parsing the
57                               // First instruction in the IT block. It's
58                               // implied in the mask, so needs special
59                               // handling.
60
61     unsigned CurPosition;     // Current position in parsing of IT
62                               // block. In range [0,3]. Initialized
63                               // according to count of instructions in block.
64                               // ~0U if no active IT block.
65   } ITState;
66   bool inITBlock() { return ITState.CurPosition != ~0U;}
67   void forwardITPosition() {
68     if (!inITBlock()) return;
69     // Move to the next instruction in the IT block, if there is one. If not,
70     // mark the block as done.
71     unsigned TZ = CountTrailingZeros_32(ITState.Mask);
72     if (++ITState.CurPosition == 5 - TZ)
73       ITState.CurPosition = ~0U; // Done with the IT block after this.
74   }
75
76
77   MCAsmParser &getParser() const { return Parser; }
78   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
79
80   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
81   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
82
83   int tryParseRegister();
84   bool tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
85   int tryParseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
86   bool parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
87   bool parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
88   bool parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
89   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
90   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
91                               unsigned &ShiftAmount);
92   bool parseDirectiveWord(unsigned Size, SMLoc L);
93   bool parseDirectiveThumb(SMLoc L);
94   bool parseDirectiveThumbFunc(SMLoc L);
95   bool parseDirectiveCode(SMLoc L);
96   bool parseDirectiveSyntax(SMLoc L);
97
98   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
99                           bool &CarrySetting, unsigned &ProcessorIMod,
100                           StringRef &ITMask);
101   void getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
102                              bool &CanAcceptPredicationCode);
103
104   bool isThumb() const {
105     // FIXME: Can tablegen auto-generate this?
106     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
107   }
108   bool isThumbOne() const {
109     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
110   }
111   bool isThumbTwo() const {
112     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2);
113   }
114   bool hasV6Ops() const {
115     return STI.getFeatureBits() & ARM::HasV6Ops;
116   }
117   void SwitchMode() {
118     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
119     setAvailableFeatures(FB);
120   }
121
122   /// @name Auto-generated Match Functions
123   /// {
124
125 #define GET_ASSEMBLER_HEADER
126 #include "ARMGenAsmMatcher.inc"
127
128   /// }
129
130   OperandMatchResultTy parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*>&);
131   OperandMatchResultTy parseCoprocNumOperand(
132     SmallVectorImpl<MCParsedAsmOperand*>&);
133   OperandMatchResultTy parseCoprocRegOperand(
134     SmallVectorImpl<MCParsedAsmOperand*>&);
135   OperandMatchResultTy parseMemBarrierOptOperand(
136     SmallVectorImpl<MCParsedAsmOperand*>&);
137   OperandMatchResultTy parseProcIFlagsOperand(
138     SmallVectorImpl<MCParsedAsmOperand*>&);
139   OperandMatchResultTy parseMSRMaskOperand(
140     SmallVectorImpl<MCParsedAsmOperand*>&);
141   OperandMatchResultTy parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &O,
142                                    StringRef Op, int Low, int High);
143   OperandMatchResultTy parsePKHLSLImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
144     return parsePKHImm(O, "lsl", 0, 31);
145   }
146   OperandMatchResultTy parsePKHASRImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
147     return parsePKHImm(O, "asr", 1, 32);
148   }
149   OperandMatchResultTy parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*>&);
150   OperandMatchResultTy parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*>&);
151   OperandMatchResultTy parseRotImm(SmallVectorImpl<MCParsedAsmOperand*>&);
152   OperandMatchResultTy parseBitfield(SmallVectorImpl<MCParsedAsmOperand*>&);
153   OperandMatchResultTy parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*>&);
154   OperandMatchResultTy parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*>&);
155
156   // Asm Match Converter Methods
157   bool cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
158                     const SmallVectorImpl<MCParsedAsmOperand*> &);
159   bool cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
160                     const SmallVectorImpl<MCParsedAsmOperand*> &);
161   bool cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
162                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
163   bool cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
164                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
165   bool cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
166                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
167   bool cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
168                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
169   bool cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
170                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
171   bool cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
172                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
173   bool cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
174                              const SmallVectorImpl<MCParsedAsmOperand*> &);
175   bool cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
176                              const SmallVectorImpl<MCParsedAsmOperand*> &);
177   bool cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
178                              const SmallVectorImpl<MCParsedAsmOperand*> &);
179   bool cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
180                              const SmallVectorImpl<MCParsedAsmOperand*> &);
181   bool cvtLdrdPre(MCInst &Inst, unsigned Opcode,
182                   const SmallVectorImpl<MCParsedAsmOperand*> &);
183   bool cvtStrdPre(MCInst &Inst, unsigned Opcode,
184                   const SmallVectorImpl<MCParsedAsmOperand*> &);
185   bool cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
186                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
187   bool cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
188                         const SmallVectorImpl<MCParsedAsmOperand*> &);
189
190   bool validateInstruction(MCInst &Inst,
191                            const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
192   void processInstruction(MCInst &Inst,
193                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
194   bool shouldOmitCCOutOperand(StringRef Mnemonic,
195                               SmallVectorImpl<MCParsedAsmOperand*> &Operands);
196
197 public:
198   enum ARMMatchResultTy {
199     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
200     Match_RequiresNotITBlock,
201     Match_RequiresV6,
202     Match_RequiresThumb2
203   };
204
205   ARMAsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser)
206     : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
207     MCAsmParserExtension::Initialize(_Parser);
208
209     // Initialize the set of available features.
210     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
211
212     // Not in an ITBlock to start with.
213     ITState.CurPosition = ~0U;
214   }
215
216   // Implementation of the MCTargetAsmParser interface:
217   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
218   bool ParseInstruction(StringRef Name, SMLoc NameLoc,
219                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
220   bool ParseDirective(AsmToken DirectiveID);
221
222   unsigned checkTargetMatchPredicate(MCInst &Inst);
223
224   bool MatchAndEmitInstruction(SMLoc IDLoc,
225                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
226                                MCStreamer &Out);
227 };
228 } // end anonymous namespace
229
230 namespace {
231
232 /// ARMOperand - Instances of this class represent a parsed ARM machine
233 /// instruction.
234 class ARMOperand : public MCParsedAsmOperand {
235   enum KindTy {
236     CondCode,
237     CCOut,
238     ITCondMask,
239     CoprocNum,
240     CoprocReg,
241     Immediate,
242     MemBarrierOpt,
243     Memory,
244     PostIndexRegister,
245     MSRMask,
246     ProcIFlags,
247     Register,
248     RegisterList,
249     DPRRegisterList,
250     SPRRegisterList,
251     ShiftedRegister,
252     ShiftedImmediate,
253     ShifterImmediate,
254     RotateImmediate,
255     BitfieldDescriptor,
256     Token
257   } Kind;
258
259   SMLoc StartLoc, EndLoc;
260   SmallVector<unsigned, 8> Registers;
261
262   union {
263     struct {
264       ARMCC::CondCodes Val;
265     } CC;
266
267     struct {
268       unsigned Val;
269     } Cop;
270
271     struct {
272       unsigned Mask:4;
273     } ITMask;
274
275     struct {
276       ARM_MB::MemBOpt Val;
277     } MBOpt;
278
279     struct {
280       ARM_PROC::IFlags Val;
281     } IFlags;
282
283     struct {
284       unsigned Val;
285     } MMask;
286
287     struct {
288       const char *Data;
289       unsigned Length;
290     } Tok;
291
292     struct {
293       unsigned RegNum;
294     } Reg;
295
296     struct {
297       const MCExpr *Val;
298     } Imm;
299
300     /// Combined record for all forms of ARM address expressions.
301     struct {
302       unsigned BaseRegNum;
303       // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
304       // was specified.
305       const MCConstantExpr *OffsetImm;  // Offset immediate value
306       unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
307       ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
308       unsigned ShiftImm;      // shift for OffsetReg.
309       unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
310     } Mem;
311
312     struct {
313       unsigned RegNum;
314       bool isAdd;
315       ARM_AM::ShiftOpc ShiftTy;
316       unsigned ShiftImm;
317     } PostIdxReg;
318
319     struct {
320       bool isASR;
321       unsigned Imm;
322     } ShifterImm;
323     struct {
324       ARM_AM::ShiftOpc ShiftTy;
325       unsigned SrcReg;
326       unsigned ShiftReg;
327       unsigned ShiftImm;
328     } RegShiftedReg;
329     struct {
330       ARM_AM::ShiftOpc ShiftTy;
331       unsigned SrcReg;
332       unsigned ShiftImm;
333     } RegShiftedImm;
334     struct {
335       unsigned Imm;
336     } RotImm;
337     struct {
338       unsigned LSB;
339       unsigned Width;
340     } Bitfield;
341   };
342
343   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
344 public:
345   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
346     Kind = o.Kind;
347     StartLoc = o.StartLoc;
348     EndLoc = o.EndLoc;
349     switch (Kind) {
350     case CondCode:
351       CC = o.CC;
352       break;
353     case ITCondMask:
354       ITMask = o.ITMask;
355       break;
356     case Token:
357       Tok = o.Tok;
358       break;
359     case CCOut:
360     case Register:
361       Reg = o.Reg;
362       break;
363     case RegisterList:
364     case DPRRegisterList:
365     case SPRRegisterList:
366       Registers = o.Registers;
367       break;
368     case CoprocNum:
369     case CoprocReg:
370       Cop = o.Cop;
371       break;
372     case Immediate:
373       Imm = o.Imm;
374       break;
375     case MemBarrierOpt:
376       MBOpt = o.MBOpt;
377       break;
378     case Memory:
379       Mem = o.Mem;
380       break;
381     case PostIndexRegister:
382       PostIdxReg = o.PostIdxReg;
383       break;
384     case MSRMask:
385       MMask = o.MMask;
386       break;
387     case ProcIFlags:
388       IFlags = o.IFlags;
389       break;
390     case ShifterImmediate:
391       ShifterImm = o.ShifterImm;
392       break;
393     case ShiftedRegister:
394       RegShiftedReg = o.RegShiftedReg;
395       break;
396     case ShiftedImmediate:
397       RegShiftedImm = o.RegShiftedImm;
398       break;
399     case RotateImmediate:
400       RotImm = o.RotImm;
401       break;
402     case BitfieldDescriptor:
403       Bitfield = o.Bitfield;
404       break;
405     }
406   }
407
408   /// getStartLoc - Get the location of the first token of this operand.
409   SMLoc getStartLoc() const { return StartLoc; }
410   /// getEndLoc - Get the location of the last token of this operand.
411   SMLoc getEndLoc() const { return EndLoc; }
412
413   ARMCC::CondCodes getCondCode() const {
414     assert(Kind == CondCode && "Invalid access!");
415     return CC.Val;
416   }
417
418   unsigned getCoproc() const {
419     assert((Kind == CoprocNum || Kind == CoprocReg) && "Invalid access!");
420     return Cop.Val;
421   }
422
423   StringRef getToken() const {
424     assert(Kind == Token && "Invalid access!");
425     return StringRef(Tok.Data, Tok.Length);
426   }
427
428   unsigned getReg() const {
429     assert((Kind == Register || Kind == CCOut) && "Invalid access!");
430     return Reg.RegNum;
431   }
432
433   const SmallVectorImpl<unsigned> &getRegList() const {
434     assert((Kind == RegisterList || Kind == DPRRegisterList ||
435             Kind == SPRRegisterList) && "Invalid access!");
436     return Registers;
437   }
438
439   const MCExpr *getImm() const {
440     assert(Kind == Immediate && "Invalid access!");
441     return Imm.Val;
442   }
443
444   ARM_MB::MemBOpt getMemBarrierOpt() const {
445     assert(Kind == MemBarrierOpt && "Invalid access!");
446     return MBOpt.Val;
447   }
448
449   ARM_PROC::IFlags getProcIFlags() const {
450     assert(Kind == ProcIFlags && "Invalid access!");
451     return IFlags.Val;
452   }
453
454   unsigned getMSRMask() const {
455     assert(Kind == MSRMask && "Invalid access!");
456     return MMask.Val;
457   }
458
459   bool isCoprocNum() const { return Kind == CoprocNum; }
460   bool isCoprocReg() const { return Kind == CoprocReg; }
461   bool isCondCode() const { return Kind == CondCode; }
462   bool isCCOut() const { return Kind == CCOut; }
463   bool isITMask() const { return Kind == ITCondMask; }
464   bool isITCondCode() const { return Kind == CondCode; }
465   bool isImm() const { return Kind == Immediate; }
466   bool isImm8s4() const {
467     if (Kind != Immediate)
468       return false;
469     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
470     if (!CE) return false;
471     int64_t Value = CE->getValue();
472     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
473   }
474   bool isImm0_1020s4() const {
475     if (Kind != Immediate)
476       return false;
477     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
478     if (!CE) return false;
479     int64_t Value = CE->getValue();
480     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
481   }
482   bool isImm0_508s4() const {
483     if (Kind != Immediate)
484       return false;
485     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
486     if (!CE) return false;
487     int64_t Value = CE->getValue();
488     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
489   }
490   bool isImm0_255() const {
491     if (Kind != Immediate)
492       return false;
493     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
494     if (!CE) return false;
495     int64_t Value = CE->getValue();
496     return Value >= 0 && Value < 256;
497   }
498   bool isImm0_7() const {
499     if (Kind != Immediate)
500       return false;
501     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
502     if (!CE) return false;
503     int64_t Value = CE->getValue();
504     return Value >= 0 && Value < 8;
505   }
506   bool isImm0_15() const {
507     if (Kind != Immediate)
508       return false;
509     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
510     if (!CE) return false;
511     int64_t Value = CE->getValue();
512     return Value >= 0 && Value < 16;
513   }
514   bool isImm0_31() const {
515     if (Kind != Immediate)
516       return false;
517     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
518     if (!CE) return false;
519     int64_t Value = CE->getValue();
520     return Value >= 0 && Value < 32;
521   }
522   bool isImm1_16() const {
523     if (Kind != Immediate)
524       return false;
525     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
526     if (!CE) return false;
527     int64_t Value = CE->getValue();
528     return Value > 0 && Value < 17;
529   }
530   bool isImm1_32() const {
531     if (Kind != Immediate)
532       return false;
533     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
534     if (!CE) return false;
535     int64_t Value = CE->getValue();
536     return Value > 0 && Value < 33;
537   }
538   bool isImm0_65535() const {
539     if (Kind != Immediate)
540       return false;
541     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
542     if (!CE) return false;
543     int64_t Value = CE->getValue();
544     return Value >= 0 && Value < 65536;
545   }
546   bool isImm0_65535Expr() const {
547     if (Kind != Immediate)
548       return false;
549     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
550     // If it's not a constant expression, it'll generate a fixup and be
551     // handled later.
552     if (!CE) return true;
553     int64_t Value = CE->getValue();
554     return Value >= 0 && Value < 65536;
555   }
556   bool isImm24bit() const {
557     if (Kind != Immediate)
558       return false;
559     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
560     if (!CE) return false;
561     int64_t Value = CE->getValue();
562     return Value >= 0 && Value <= 0xffffff;
563   }
564   bool isImmThumbSR() const {
565     if (Kind != Immediate)
566       return false;
567     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
568     if (!CE) return false;
569     int64_t Value = CE->getValue();
570     return Value > 0 && Value < 33;
571   }
572   bool isPKHLSLImm() const {
573     if (Kind != Immediate)
574       return false;
575     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
576     if (!CE) return false;
577     int64_t Value = CE->getValue();
578     return Value >= 0 && Value < 32;
579   }
580   bool isPKHASRImm() const {
581     if (Kind != Immediate)
582       return false;
583     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
584     if (!CE) return false;
585     int64_t Value = CE->getValue();
586     return Value > 0 && Value <= 32;
587   }
588   bool isARMSOImm() const {
589     if (Kind != Immediate)
590       return false;
591     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
592     if (!CE) return false;
593     int64_t Value = CE->getValue();
594     return ARM_AM::getSOImmVal(Value) != -1;
595   }
596   bool isT2SOImm() const {
597     if (Kind != Immediate)
598       return false;
599     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
600     if (!CE) return false;
601     int64_t Value = CE->getValue();
602     return ARM_AM::getT2SOImmVal(Value) != -1;
603   }
604   bool isSetEndImm() const {
605     if (Kind != Immediate)
606       return false;
607     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
608     if (!CE) return false;
609     int64_t Value = CE->getValue();
610     return Value == 1 || Value == 0;
611   }
612   bool isReg() const { return Kind == Register; }
613   bool isRegList() const { return Kind == RegisterList; }
614   bool isDPRRegList() const { return Kind == DPRRegisterList; }
615   bool isSPRRegList() const { return Kind == SPRRegisterList; }
616   bool isToken() const { return Kind == Token; }
617   bool isMemBarrierOpt() const { return Kind == MemBarrierOpt; }
618   bool isMemory() const { return Kind == Memory; }
619   bool isShifterImm() const { return Kind == ShifterImmediate; }
620   bool isRegShiftedReg() const { return Kind == ShiftedRegister; }
621   bool isRegShiftedImm() const { return Kind == ShiftedImmediate; }
622   bool isRotImm() const { return Kind == RotateImmediate; }
623   bool isBitfield() const { return Kind == BitfieldDescriptor; }
624   bool isPostIdxRegShifted() const { return Kind == PostIndexRegister; }
625   bool isPostIdxReg() const {
626     return Kind == PostIndexRegister && PostIdxReg.ShiftTy == ARM_AM::no_shift;
627   }
628   bool isMemNoOffset() const {
629     if (Kind != Memory)
630       return false;
631     // No offset of any kind.
632     return Mem.OffsetRegNum == 0 && Mem.OffsetImm == 0;
633   }
634   bool isAddrMode2() const {
635     if (Kind != Memory)
636       return false;
637     // Check for register offset.
638     if (Mem.OffsetRegNum) return true;
639     // Immediate offset in range [-4095, 4095].
640     if (!Mem.OffsetImm) return true;
641     int64_t Val = Mem.OffsetImm->getValue();
642     return Val > -4096 && Val < 4096;
643   }
644   bool isAM2OffsetImm() const {
645     if (Kind != Immediate)
646       return false;
647     // Immediate offset in range [-4095, 4095].
648     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
649     if (!CE) return false;
650     int64_t Val = CE->getValue();
651     return Val > -4096 && Val < 4096;
652   }
653   bool isAddrMode3() const {
654     if (Kind != Memory)
655       return false;
656     // No shifts are legal for AM3.
657     if (Mem.ShiftType != ARM_AM::no_shift) return false;
658     // Check for register offset.
659     if (Mem.OffsetRegNum) return true;
660     // Immediate offset in range [-255, 255].
661     if (!Mem.OffsetImm) return true;
662     int64_t Val = Mem.OffsetImm->getValue();
663     return Val > -256 && Val < 256;
664   }
665   bool isAM3Offset() const {
666     if (Kind != Immediate && Kind != PostIndexRegister)
667       return false;
668     if (Kind == PostIndexRegister)
669       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
670     // Immediate offset in range [-255, 255].
671     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
672     if (!CE) return false;
673     int64_t Val = CE->getValue();
674     // Special case, #-0 is INT32_MIN.
675     return (Val > -256 && Val < 256) || Val == INT32_MIN;
676   }
677   bool isAddrMode5() const {
678     if (Kind != Memory)
679       return false;
680     // Check for register offset.
681     if (Mem.OffsetRegNum) return false;
682     // Immediate offset in range [-1020, 1020] and a multiple of 4.
683     if (!Mem.OffsetImm) return true;
684     int64_t Val = Mem.OffsetImm->getValue();
685     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
686            Val == INT32_MIN;
687   }
688   bool isMemRegOffset() const {
689     if (Kind != Memory || !Mem.OffsetRegNum)
690       return false;
691     return true;
692   }
693   bool isT2MemRegOffset() const {
694     if (Kind != Memory || !Mem.OffsetRegNum || Mem.isNegative)
695       return false;
696     // Only lsl #{0, 1, 2, 3} allowed.
697     if (Mem.ShiftType == ARM_AM::no_shift)
698       return true;
699     if (Mem.ShiftType != ARM_AM::lsl || Mem.ShiftImm > 3)
700       return false;
701     return true;
702   }
703   bool isMemThumbRR() const {
704     // Thumb reg+reg addressing is simple. Just two registers, a base and
705     // an offset. No shifts, negations or any other complicating factors.
706     if (Kind != Memory || !Mem.OffsetRegNum || Mem.isNegative ||
707         Mem.ShiftType != ARM_AM::no_shift)
708       return false;
709     return isARMLowRegister(Mem.BaseRegNum) &&
710       (!Mem.OffsetRegNum || isARMLowRegister(Mem.OffsetRegNum));
711   }
712   bool isMemThumbRIs4() const {
713     if (Kind != Memory || Mem.OffsetRegNum != 0 ||
714         !isARMLowRegister(Mem.BaseRegNum))
715       return false;
716     // Immediate offset, multiple of 4 in range [0, 124].
717     if (!Mem.OffsetImm) return true;
718     int64_t Val = Mem.OffsetImm->getValue();
719     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
720   }
721   bool isMemThumbRIs2() const {
722     if (Kind != Memory || Mem.OffsetRegNum != 0 ||
723         !isARMLowRegister(Mem.BaseRegNum))
724       return false;
725     // Immediate offset, multiple of 4 in range [0, 62].
726     if (!Mem.OffsetImm) return true;
727     int64_t Val = Mem.OffsetImm->getValue();
728     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
729   }
730   bool isMemThumbRIs1() const {
731     if (Kind != Memory || Mem.OffsetRegNum != 0 ||
732         !isARMLowRegister(Mem.BaseRegNum))
733       return false;
734     // Immediate offset in range [0, 31].
735     if (!Mem.OffsetImm) return true;
736     int64_t Val = Mem.OffsetImm->getValue();
737     return Val >= 0 && Val <= 31;
738   }
739   bool isMemThumbSPI() const {
740     if (Kind != Memory || Mem.OffsetRegNum != 0 || Mem.BaseRegNum != ARM::SP)
741       return false;
742     // Immediate offset, multiple of 4 in range [0, 1020].
743     if (!Mem.OffsetImm) return true;
744     int64_t Val = Mem.OffsetImm->getValue();
745     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
746   }
747   bool isMemImm8s4Offset() const {
748     if (Kind != Memory || Mem.OffsetRegNum != 0)
749       return false;
750     // Immediate offset a multiple of 4 in range [-1020, 1020].
751     if (!Mem.OffsetImm) return true;
752     int64_t Val = Mem.OffsetImm->getValue();
753     return Val >= -1020 && Val <= 1020 && (Val & 3) == 0;
754   }
755   bool isMemImm0_1020s4Offset() const {
756     if (Kind != Memory || Mem.OffsetRegNum != 0)
757       return false;
758     // Immediate offset a multiple of 4 in range [0, 1020].
759     if (!Mem.OffsetImm) return true;
760     int64_t Val = Mem.OffsetImm->getValue();
761     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
762   }
763   bool isMemImm8Offset() const {
764     if (Kind != Memory || Mem.OffsetRegNum != 0)
765       return false;
766     // Immediate offset in range [-255, 255].
767     if (!Mem.OffsetImm) return true;
768     int64_t Val = Mem.OffsetImm->getValue();
769     return Val > -256 && Val < 256;
770   }
771   bool isMemPosImm8Offset() const {
772     if (Kind != Memory || Mem.OffsetRegNum != 0)
773       return false;
774     // Immediate offset in range [0, 255].
775     if (!Mem.OffsetImm) return true;
776     int64_t Val = Mem.OffsetImm->getValue();
777     return Val >= 0 && Val < 256;
778   }
779   bool isMemNegImm8Offset() const {
780     if (Kind != Memory || Mem.OffsetRegNum != 0)
781       return false;
782     // Immediate offset in range [-255, -1].
783     if (!Mem.OffsetImm) return true;
784     int64_t Val = Mem.OffsetImm->getValue();
785     return Val > -256 && Val < 0;
786   }
787   bool isMemUImm12Offset() const {
788     // If we have an immediate that's not a constant, treat it as a label
789     // reference needing a fixup. If it is a constant, it's something else
790     // and we reject it.
791     if (Kind == Immediate && !isa<MCConstantExpr>(getImm()))
792       return true;
793
794     if (Kind != Memory || Mem.OffsetRegNum != 0)
795       return false;
796     // Immediate offset in range [0, 4095].
797     if (!Mem.OffsetImm) return true;
798     int64_t Val = Mem.OffsetImm->getValue();
799     return (Val >= 0 && Val < 4096);
800   }
801   bool isMemImm12Offset() const {
802     // If we have an immediate that's not a constant, treat it as a label
803     // reference needing a fixup. If it is a constant, it's something else
804     // and we reject it.
805     if (Kind == Immediate && !isa<MCConstantExpr>(getImm()))
806       return true;
807
808     if (Kind != Memory || Mem.OffsetRegNum != 0)
809       return false;
810     // Immediate offset in range [-4095, 4095].
811     if (!Mem.OffsetImm) return true;
812     int64_t Val = Mem.OffsetImm->getValue();
813     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
814   }
815   bool isPostIdxImm8() const {
816     if (Kind != Immediate)
817       return false;
818     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
819     if (!CE) return false;
820     int64_t Val = CE->getValue();
821     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
822   }
823
824   bool isMSRMask() const { return Kind == MSRMask; }
825   bool isProcIFlags() const { return Kind == ProcIFlags; }
826
827   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
828     // Add as immediates when possible.  Null MCExpr = 0.
829     if (Expr == 0)
830       Inst.addOperand(MCOperand::CreateImm(0));
831     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
832       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
833     else
834       Inst.addOperand(MCOperand::CreateExpr(Expr));
835   }
836
837   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
838     assert(N == 2 && "Invalid number of operands!");
839     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
840     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
841     Inst.addOperand(MCOperand::CreateReg(RegNum));
842   }
843
844   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
845     assert(N == 1 && "Invalid number of operands!");
846     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
847   }
848
849   void addITMaskOperands(MCInst &Inst, unsigned N) const {
850     assert(N == 1 && "Invalid number of operands!");
851     Inst.addOperand(MCOperand::CreateImm(ITMask.Mask));
852   }
853
854   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
855     assert(N == 1 && "Invalid number of operands!");
856     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
857   }
858
859   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
860     assert(N == 1 && "Invalid number of operands!");
861     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
862   }
863
864   void addCCOutOperands(MCInst &Inst, unsigned N) const {
865     assert(N == 1 && "Invalid number of operands!");
866     Inst.addOperand(MCOperand::CreateReg(getReg()));
867   }
868
869   void addRegOperands(MCInst &Inst, unsigned N) const {
870     assert(N == 1 && "Invalid number of operands!");
871     Inst.addOperand(MCOperand::CreateReg(getReg()));
872   }
873
874   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
875     assert(N == 3 && "Invalid number of operands!");
876     assert(isRegShiftedReg() && "addRegShiftedRegOperands() on non RegShiftedReg!");
877     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
878     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
879     Inst.addOperand(MCOperand::CreateImm(
880       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
881   }
882
883   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
884     assert(N == 2 && "Invalid number of operands!");
885     assert(isRegShiftedImm() && "addRegShiftedImmOperands() on non RegShiftedImm!");
886     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
887     Inst.addOperand(MCOperand::CreateImm(
888       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, RegShiftedImm.ShiftImm)));
889   }
890
891   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
892     assert(N == 1 && "Invalid number of operands!");
893     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
894                                          ShifterImm.Imm));
895   }
896
897   void addRegListOperands(MCInst &Inst, unsigned N) const {
898     assert(N == 1 && "Invalid number of operands!");
899     const SmallVectorImpl<unsigned> &RegList = getRegList();
900     for (SmallVectorImpl<unsigned>::const_iterator
901            I = RegList.begin(), E = RegList.end(); I != E; ++I)
902       Inst.addOperand(MCOperand::CreateReg(*I));
903   }
904
905   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
906     addRegListOperands(Inst, N);
907   }
908
909   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
910     addRegListOperands(Inst, N);
911   }
912
913   void addRotImmOperands(MCInst &Inst, unsigned N) const {
914     assert(N == 1 && "Invalid number of operands!");
915     // Encoded as val>>3. The printer handles display as 8, 16, 24.
916     Inst.addOperand(MCOperand::CreateImm(RotImm.Imm >> 3));
917   }
918
919   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
920     assert(N == 1 && "Invalid number of operands!");
921     // Munge the lsb/width into a bitfield mask.
922     unsigned lsb = Bitfield.LSB;
923     unsigned width = Bitfield.Width;
924     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
925     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
926                       (32 - (lsb + width)));
927     Inst.addOperand(MCOperand::CreateImm(Mask));
928   }
929
930   void addImmOperands(MCInst &Inst, unsigned N) const {
931     assert(N == 1 && "Invalid number of operands!");
932     addExpr(Inst, getImm());
933   }
934
935   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
936     assert(N == 1 && "Invalid number of operands!");
937     // FIXME: We really want to scale the value here, but the LDRD/STRD
938     // instruction don't encode operands that way yet.
939     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
940     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
941   }
942
943   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
944     assert(N == 1 && "Invalid number of operands!");
945     // The immediate is scaled by four in the encoding and is stored
946     // in the MCInst as such. Lop off the low two bits here.
947     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
948     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
949   }
950
951   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
952     assert(N == 1 && "Invalid number of operands!");
953     // The immediate is scaled by four in the encoding and is stored
954     // in the MCInst as such. Lop off the low two bits here.
955     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
956     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
957   }
958
959   void addImm0_255Operands(MCInst &Inst, unsigned N) const {
960     assert(N == 1 && "Invalid number of operands!");
961     addExpr(Inst, getImm());
962   }
963
964   void addImm0_7Operands(MCInst &Inst, unsigned N) const {
965     assert(N == 1 && "Invalid number of operands!");
966     addExpr(Inst, getImm());
967   }
968
969   void addImm0_15Operands(MCInst &Inst, unsigned N) const {
970     assert(N == 1 && "Invalid number of operands!");
971     addExpr(Inst, getImm());
972   }
973
974   void addImm0_31Operands(MCInst &Inst, unsigned N) const {
975     assert(N == 1 && "Invalid number of operands!");
976     addExpr(Inst, getImm());
977   }
978
979   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
980     assert(N == 1 && "Invalid number of operands!");
981     // The constant encodes as the immediate-1, and we store in the instruction
982     // the bits as encoded, so subtract off one here.
983     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
984     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
985   }
986
987   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
988     assert(N == 1 && "Invalid number of operands!");
989     // The constant encodes as the immediate-1, and we store in the instruction
990     // the bits as encoded, so subtract off one here.
991     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
992     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
993   }
994
995   void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
996     assert(N == 1 && "Invalid number of operands!");
997     addExpr(Inst, getImm());
998   }
999
1000   void addImm0_65535ExprOperands(MCInst &Inst, unsigned N) const {
1001     assert(N == 1 && "Invalid number of operands!");
1002     addExpr(Inst, getImm());
1003   }
1004
1005   void addImm24bitOperands(MCInst &Inst, unsigned N) const {
1006     assert(N == 1 && "Invalid number of operands!");
1007     addExpr(Inst, getImm());
1008   }
1009
1010   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1011     assert(N == 1 && "Invalid number of operands!");
1012     // The constant encodes as the immediate, except for 32, which encodes as
1013     // zero.
1014     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1015     unsigned Imm = CE->getValue();
1016     Inst.addOperand(MCOperand::CreateImm((Imm == 32 ? 0 : Imm)));
1017   }
1018
1019   void addPKHLSLImmOperands(MCInst &Inst, unsigned N) const {
1020     assert(N == 1 && "Invalid number of operands!");
1021     addExpr(Inst, getImm());
1022   }
1023
1024   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1025     assert(N == 1 && "Invalid number of operands!");
1026     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1027     // the instruction as well.
1028     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1029     int Val = CE->getValue();
1030     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
1031   }
1032
1033   void addARMSOImmOperands(MCInst &Inst, unsigned N) const {
1034     assert(N == 1 && "Invalid number of operands!");
1035     addExpr(Inst, getImm());
1036   }
1037
1038   void addT2SOImmOperands(MCInst &Inst, unsigned N) const {
1039     assert(N == 1 && "Invalid number of operands!");
1040     addExpr(Inst, getImm());
1041   }
1042
1043   void addSetEndImmOperands(MCInst &Inst, unsigned N) const {
1044     assert(N == 1 && "Invalid number of operands!");
1045     addExpr(Inst, getImm());
1046   }
1047
1048   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
1049     assert(N == 1 && "Invalid number of operands!");
1050     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
1051   }
1052
1053   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
1054     assert(N == 1 && "Invalid number of operands!");
1055     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1056   }
1057
1058   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
1059     assert(N == 3 && "Invalid number of operands!");
1060     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1061     if (!Mem.OffsetRegNum) {
1062       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1063       // Special case for #-0
1064       if (Val == INT32_MIN) Val = 0;
1065       if (Val < 0) Val = -Val;
1066       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1067     } else {
1068       // For register offset, we encode the shift type and negation flag
1069       // here.
1070       Val = ARM_AM::getAM2Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add,
1071                               Mem.ShiftImm, Mem.ShiftType);
1072     }
1073     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1074     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1075     Inst.addOperand(MCOperand::CreateImm(Val));
1076   }
1077
1078   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
1079     assert(N == 2 && "Invalid number of operands!");
1080     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1081     assert(CE && "non-constant AM2OffsetImm operand!");
1082     int32_t Val = CE->getValue();
1083     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1084     // Special case for #-0
1085     if (Val == INT32_MIN) Val = 0;
1086     if (Val < 0) Val = -Val;
1087     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1088     Inst.addOperand(MCOperand::CreateReg(0));
1089     Inst.addOperand(MCOperand::CreateImm(Val));
1090   }
1091
1092   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
1093     assert(N == 3 && "Invalid number of operands!");
1094     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1095     if (!Mem.OffsetRegNum) {
1096       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1097       // Special case for #-0
1098       if (Val == INT32_MIN) Val = 0;
1099       if (Val < 0) Val = -Val;
1100       Val = ARM_AM::getAM3Opc(AddSub, Val);
1101     } else {
1102       // For register offset, we encode the shift type and negation flag
1103       // here.
1104       Val = ARM_AM::getAM3Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
1105     }
1106     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1107     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1108     Inst.addOperand(MCOperand::CreateImm(Val));
1109   }
1110
1111   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
1112     assert(N == 2 && "Invalid number of operands!");
1113     if (Kind == PostIndexRegister) {
1114       int32_t Val =
1115         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
1116       Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1117       Inst.addOperand(MCOperand::CreateImm(Val));
1118       return;
1119     }
1120
1121     // Constant offset.
1122     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
1123     int32_t Val = CE->getValue();
1124     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1125     // Special case for #-0
1126     if (Val == INT32_MIN) Val = 0;
1127     if (Val < 0) Val = -Val;
1128     Val = ARM_AM::getAM3Opc(AddSub, Val);
1129     Inst.addOperand(MCOperand::CreateReg(0));
1130     Inst.addOperand(MCOperand::CreateImm(Val));
1131   }
1132
1133   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
1134     assert(N == 2 && "Invalid number of operands!");
1135     // The lower two bits are always zero and as such are not encoded.
1136     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() / 4 : 0;
1137     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1138     // Special case for #-0
1139     if (Val == INT32_MIN) Val = 0;
1140     if (Val < 0) Val = -Val;
1141     Val = ARM_AM::getAM5Opc(AddSub, Val);
1142     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1143     Inst.addOperand(MCOperand::CreateImm(Val));
1144   }
1145
1146   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
1147     assert(N == 2 && "Invalid number of operands!");
1148     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1149     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1150     Inst.addOperand(MCOperand::CreateImm(Val));
1151   }
1152
1153   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
1154     assert(N == 2 && "Invalid number of operands!");
1155     // The lower two bits are always zero and as such are not encoded.
1156     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() / 4 : 0;
1157     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1158     Inst.addOperand(MCOperand::CreateImm(Val));
1159   }
1160
1161   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1162     assert(N == 2 && "Invalid number of operands!");
1163     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1164     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1165     Inst.addOperand(MCOperand::CreateImm(Val));
1166   }
1167
1168   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1169     addMemImm8OffsetOperands(Inst, N);
1170   }
1171
1172   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1173     addMemImm8OffsetOperands(Inst, N);
1174   }
1175
1176   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1177     assert(N == 2 && "Invalid number of operands!");
1178     // If this is an immediate, it's a label reference.
1179     if (Kind == Immediate) {
1180       addExpr(Inst, getImm());
1181       Inst.addOperand(MCOperand::CreateImm(0));
1182       return;
1183     }
1184
1185     // Otherwise, it's a normal memory reg+offset.
1186     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1187     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1188     Inst.addOperand(MCOperand::CreateImm(Val));
1189   }
1190
1191   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1192     assert(N == 2 && "Invalid number of operands!");
1193     // If this is an immediate, it's a label reference.
1194     if (Kind == Immediate) {
1195       addExpr(Inst, getImm());
1196       Inst.addOperand(MCOperand::CreateImm(0));
1197       return;
1198     }
1199
1200     // Otherwise, it's a normal memory reg+offset.
1201     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1202     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1203     Inst.addOperand(MCOperand::CreateImm(Val));
1204   }
1205
1206   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1207     assert(N == 3 && "Invalid number of operands!");
1208     unsigned Val = ARM_AM::getAM2Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add,
1209                                      Mem.ShiftImm, Mem.ShiftType);
1210     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1211     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1212     Inst.addOperand(MCOperand::CreateImm(Val));
1213   }
1214
1215   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1216     assert(N == 3 && "Invalid number of operands!");
1217     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1218     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1219     Inst.addOperand(MCOperand::CreateImm(Mem.ShiftImm));
1220   }
1221
1222   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
1223     assert(N == 2 && "Invalid number of operands!");
1224     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1225     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1226   }
1227
1228   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
1229     assert(N == 2 && "Invalid number of operands!");
1230     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue() / 4) : 0;
1231     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1232     Inst.addOperand(MCOperand::CreateImm(Val));
1233   }
1234
1235   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
1236     assert(N == 2 && "Invalid number of operands!");
1237     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue() / 2) : 0;
1238     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1239     Inst.addOperand(MCOperand::CreateImm(Val));
1240   }
1241
1242   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
1243     assert(N == 2 && "Invalid number of operands!");
1244     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue()) : 0;
1245     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1246     Inst.addOperand(MCOperand::CreateImm(Val));
1247   }
1248
1249   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
1250     assert(N == 2 && "Invalid number of operands!");
1251     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue() / 4) : 0;
1252     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1253     Inst.addOperand(MCOperand::CreateImm(Val));
1254   }
1255
1256   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
1257     assert(N == 1 && "Invalid number of operands!");
1258     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1259     assert(CE && "non-constant post-idx-imm8 operand!");
1260     int Imm = CE->getValue();
1261     bool isAdd = Imm >= 0;
1262     if (Imm == INT32_MIN) Imm = 0;
1263     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
1264     Inst.addOperand(MCOperand::CreateImm(Imm));
1265   }
1266
1267   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
1268     assert(N == 2 && "Invalid number of operands!");
1269     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1270     Inst.addOperand(MCOperand::CreateImm(PostIdxReg.isAdd));
1271   }
1272
1273   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
1274     assert(N == 2 && "Invalid number of operands!");
1275     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1276     // The sign, shift type, and shift amount are encoded in a single operand
1277     // using the AM2 encoding helpers.
1278     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
1279     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
1280                                      PostIdxReg.ShiftTy);
1281     Inst.addOperand(MCOperand::CreateImm(Imm));
1282   }
1283
1284   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
1285     assert(N == 1 && "Invalid number of operands!");
1286     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
1287   }
1288
1289   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
1290     assert(N == 1 && "Invalid number of operands!");
1291     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
1292   }
1293
1294   virtual void print(raw_ostream &OS) const;
1295
1296   static ARMOperand *CreateITMask(unsigned Mask, SMLoc S) {
1297     ARMOperand *Op = new ARMOperand(ITCondMask);
1298     Op->ITMask.Mask = Mask;
1299     Op->StartLoc = S;
1300     Op->EndLoc = S;
1301     return Op;
1302   }
1303
1304   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
1305     ARMOperand *Op = new ARMOperand(CondCode);
1306     Op->CC.Val = CC;
1307     Op->StartLoc = S;
1308     Op->EndLoc = S;
1309     return Op;
1310   }
1311
1312   static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
1313     ARMOperand *Op = new ARMOperand(CoprocNum);
1314     Op->Cop.Val = CopVal;
1315     Op->StartLoc = S;
1316     Op->EndLoc = S;
1317     return Op;
1318   }
1319
1320   static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
1321     ARMOperand *Op = new ARMOperand(CoprocReg);
1322     Op->Cop.Val = CopVal;
1323     Op->StartLoc = S;
1324     Op->EndLoc = S;
1325     return Op;
1326   }
1327
1328   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
1329     ARMOperand *Op = new ARMOperand(CCOut);
1330     Op->Reg.RegNum = RegNum;
1331     Op->StartLoc = S;
1332     Op->EndLoc = S;
1333     return Op;
1334   }
1335
1336   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
1337     ARMOperand *Op = new ARMOperand(Token);
1338     Op->Tok.Data = Str.data();
1339     Op->Tok.Length = Str.size();
1340     Op->StartLoc = S;
1341     Op->EndLoc = S;
1342     return Op;
1343   }
1344
1345   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
1346     ARMOperand *Op = new ARMOperand(Register);
1347     Op->Reg.RegNum = RegNum;
1348     Op->StartLoc = S;
1349     Op->EndLoc = E;
1350     return Op;
1351   }
1352
1353   static ARMOperand *CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,
1354                                            unsigned SrcReg,
1355                                            unsigned ShiftReg,
1356                                            unsigned ShiftImm,
1357                                            SMLoc S, SMLoc E) {
1358     ARMOperand *Op = new ARMOperand(ShiftedRegister);
1359     Op->RegShiftedReg.ShiftTy = ShTy;
1360     Op->RegShiftedReg.SrcReg = SrcReg;
1361     Op->RegShiftedReg.ShiftReg = ShiftReg;
1362     Op->RegShiftedReg.ShiftImm = ShiftImm;
1363     Op->StartLoc = S;
1364     Op->EndLoc = E;
1365     return Op;
1366   }
1367
1368   static ARMOperand *CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,
1369                                             unsigned SrcReg,
1370                                             unsigned ShiftImm,
1371                                             SMLoc S, SMLoc E) {
1372     ARMOperand *Op = new ARMOperand(ShiftedImmediate);
1373     Op->RegShiftedImm.ShiftTy = ShTy;
1374     Op->RegShiftedImm.SrcReg = SrcReg;
1375     Op->RegShiftedImm.ShiftImm = ShiftImm;
1376     Op->StartLoc = S;
1377     Op->EndLoc = E;
1378     return Op;
1379   }
1380
1381   static ARMOperand *CreateShifterImm(bool isASR, unsigned Imm,
1382                                    SMLoc S, SMLoc E) {
1383     ARMOperand *Op = new ARMOperand(ShifterImmediate);
1384     Op->ShifterImm.isASR = isASR;
1385     Op->ShifterImm.Imm = Imm;
1386     Op->StartLoc = S;
1387     Op->EndLoc = E;
1388     return Op;
1389   }
1390
1391   static ARMOperand *CreateRotImm(unsigned Imm, SMLoc S, SMLoc E) {
1392     ARMOperand *Op = new ARMOperand(RotateImmediate);
1393     Op->RotImm.Imm = Imm;
1394     Op->StartLoc = S;
1395     Op->EndLoc = E;
1396     return Op;
1397   }
1398
1399   static ARMOperand *CreateBitfield(unsigned LSB, unsigned Width,
1400                                     SMLoc S, SMLoc E) {
1401     ARMOperand *Op = new ARMOperand(BitfieldDescriptor);
1402     Op->Bitfield.LSB = LSB;
1403     Op->Bitfield.Width = Width;
1404     Op->StartLoc = S;
1405     Op->EndLoc = E;
1406     return Op;
1407   }
1408
1409   static ARMOperand *
1410   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
1411                 SMLoc StartLoc, SMLoc EndLoc) {
1412     KindTy Kind = RegisterList;
1413
1414     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().first))
1415       Kind = DPRRegisterList;
1416     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
1417              contains(Regs.front().first))
1418       Kind = SPRRegisterList;
1419
1420     ARMOperand *Op = new ARMOperand(Kind);
1421     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1422            I = Regs.begin(), E = Regs.end(); I != E; ++I)
1423       Op->Registers.push_back(I->first);
1424     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
1425     Op->StartLoc = StartLoc;
1426     Op->EndLoc = EndLoc;
1427     return Op;
1428   }
1429
1430   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
1431     ARMOperand *Op = new ARMOperand(Immediate);
1432     Op->Imm.Val = Val;
1433     Op->StartLoc = S;
1434     Op->EndLoc = E;
1435     return Op;
1436   }
1437
1438   static ARMOperand *CreateMem(unsigned BaseRegNum,
1439                                const MCConstantExpr *OffsetImm,
1440                                unsigned OffsetRegNum,
1441                                ARM_AM::ShiftOpc ShiftType,
1442                                unsigned ShiftImm,
1443                                bool isNegative,
1444                                SMLoc S, SMLoc E) {
1445     ARMOperand *Op = new ARMOperand(Memory);
1446     Op->Mem.BaseRegNum = BaseRegNum;
1447     Op->Mem.OffsetImm = OffsetImm;
1448     Op->Mem.OffsetRegNum = OffsetRegNum;
1449     Op->Mem.ShiftType = ShiftType;
1450     Op->Mem.ShiftImm = ShiftImm;
1451     Op->Mem.isNegative = isNegative;
1452     Op->StartLoc = S;
1453     Op->EndLoc = E;
1454     return Op;
1455   }
1456
1457   static ARMOperand *CreatePostIdxReg(unsigned RegNum, bool isAdd,
1458                                       ARM_AM::ShiftOpc ShiftTy,
1459                                       unsigned ShiftImm,
1460                                       SMLoc S, SMLoc E) {
1461     ARMOperand *Op = new ARMOperand(PostIndexRegister);
1462     Op->PostIdxReg.RegNum = RegNum;
1463     Op->PostIdxReg.isAdd = isAdd;
1464     Op->PostIdxReg.ShiftTy = ShiftTy;
1465     Op->PostIdxReg.ShiftImm = ShiftImm;
1466     Op->StartLoc = S;
1467     Op->EndLoc = E;
1468     return Op;
1469   }
1470
1471   static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
1472     ARMOperand *Op = new ARMOperand(MemBarrierOpt);
1473     Op->MBOpt.Val = Opt;
1474     Op->StartLoc = S;
1475     Op->EndLoc = S;
1476     return Op;
1477   }
1478
1479   static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
1480     ARMOperand *Op = new ARMOperand(ProcIFlags);
1481     Op->IFlags.Val = IFlags;
1482     Op->StartLoc = S;
1483     Op->EndLoc = S;
1484     return Op;
1485   }
1486
1487   static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
1488     ARMOperand *Op = new ARMOperand(MSRMask);
1489     Op->MMask.Val = MMask;
1490     Op->StartLoc = S;
1491     Op->EndLoc = S;
1492     return Op;
1493   }
1494 };
1495
1496 } // end anonymous namespace.
1497
1498 void ARMOperand::print(raw_ostream &OS) const {
1499   switch (Kind) {
1500   case CondCode:
1501     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
1502     break;
1503   case CCOut:
1504     OS << "<ccout " << getReg() << ">";
1505     break;
1506   case ITCondMask: {
1507     static char MaskStr[][6] = { "()", "(t)", "(e)", "(tt)", "(et)", "(te)",
1508       "(ee)", "(ttt)", "(ett)", "(tet)", "(eet)", "(tte)", "(ete)",
1509       "(tee)", "(eee)" };
1510     assert((ITMask.Mask & 0xf) == ITMask.Mask);
1511     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
1512     break;
1513   }
1514   case CoprocNum:
1515     OS << "<coprocessor number: " << getCoproc() << ">";
1516     break;
1517   case CoprocReg:
1518     OS << "<coprocessor register: " << getCoproc() << ">";
1519     break;
1520   case MSRMask:
1521     OS << "<mask: " << getMSRMask() << ">";
1522     break;
1523   case Immediate:
1524     getImm()->print(OS);
1525     break;
1526   case MemBarrierOpt:
1527     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
1528     break;
1529   case Memory:
1530     OS << "<memory "
1531        << " base:" << Mem.BaseRegNum;
1532     OS << ">";
1533     break;
1534   case PostIndexRegister:
1535     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
1536        << PostIdxReg.RegNum;
1537     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
1538       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
1539          << PostIdxReg.ShiftImm;
1540     OS << ">";
1541     break;
1542   case ProcIFlags: {
1543     OS << "<ARM_PROC::";
1544     unsigned IFlags = getProcIFlags();
1545     for (int i=2; i >= 0; --i)
1546       if (IFlags & (1 << i))
1547         OS << ARM_PROC::IFlagsToString(1 << i);
1548     OS << ">";
1549     break;
1550   }
1551   case Register:
1552     OS << "<register " << getReg() << ">";
1553     break;
1554   case ShifterImmediate:
1555     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
1556        << " #" << ShifterImm.Imm << ">";
1557     break;
1558   case ShiftedRegister:
1559     OS << "<so_reg_reg "
1560        << RegShiftedReg.SrcReg
1561        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedReg.ShiftImm))
1562        << ", " << RegShiftedReg.ShiftReg << ", "
1563        << ARM_AM::getSORegOffset(RegShiftedReg.ShiftImm)
1564        << ">";
1565     break;
1566   case ShiftedImmediate:
1567     OS << "<so_reg_imm "
1568        << RegShiftedImm.SrcReg
1569        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedImm.ShiftImm))
1570        << ", " << ARM_AM::getSORegOffset(RegShiftedImm.ShiftImm)
1571        << ">";
1572     break;
1573   case RotateImmediate:
1574     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
1575     break;
1576   case BitfieldDescriptor:
1577     OS << "<bitfield " << "lsb: " << Bitfield.LSB
1578        << ", width: " << Bitfield.Width << ">";
1579     break;
1580   case RegisterList:
1581   case DPRRegisterList:
1582   case SPRRegisterList: {
1583     OS << "<register_list ";
1584
1585     const SmallVectorImpl<unsigned> &RegList = getRegList();
1586     for (SmallVectorImpl<unsigned>::const_iterator
1587            I = RegList.begin(), E = RegList.end(); I != E; ) {
1588       OS << *I;
1589       if (++I < E) OS << ", ";
1590     }
1591
1592     OS << ">";
1593     break;
1594   }
1595   case Token:
1596     OS << "'" << getToken() << "'";
1597     break;
1598   }
1599 }
1600
1601 /// @name Auto-generated Match Functions
1602 /// {
1603
1604 static unsigned MatchRegisterName(StringRef Name);
1605
1606 /// }
1607
1608 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
1609                                  SMLoc &StartLoc, SMLoc &EndLoc) {
1610   RegNo = tryParseRegister();
1611
1612   return (RegNo == (unsigned)-1);
1613 }
1614
1615 /// Try to parse a register name.  The token must be an Identifier when called,
1616 /// and if it is a register name the token is eaten and the register number is
1617 /// returned.  Otherwise return -1.
1618 ///
1619 int ARMAsmParser::tryParseRegister() {
1620   const AsmToken &Tok = Parser.getTok();
1621   if (Tok.isNot(AsmToken::Identifier)) return -1;
1622
1623   // FIXME: Validate register for the current architecture; we have to do
1624   // validation later, so maybe there is no need for this here.
1625   std::string upperCase = Tok.getString().str();
1626   std::string lowerCase = LowercaseString(upperCase);
1627   unsigned RegNum = MatchRegisterName(lowerCase);
1628   if (!RegNum) {
1629     RegNum = StringSwitch<unsigned>(lowerCase)
1630       .Case("r13", ARM::SP)
1631       .Case("r14", ARM::LR)
1632       .Case("r15", ARM::PC)
1633       .Case("ip", ARM::R12)
1634       .Default(0);
1635   }
1636   if (!RegNum) return -1;
1637
1638   Parser.Lex(); // Eat identifier token.
1639   return RegNum;
1640 }
1641
1642 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
1643 // If a recoverable error occurs, return 1. If an irrecoverable error
1644 // occurs, return -1. An irrecoverable error is one where tokens have been
1645 // consumed in the process of trying to parse the shifter (i.e., when it is
1646 // indeed a shifter operand, but malformed).
1647 int ARMAsmParser::tryParseShiftRegister(
1648                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1649   SMLoc S = Parser.getTok().getLoc();
1650   const AsmToken &Tok = Parser.getTok();
1651   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1652
1653   std::string upperCase = Tok.getString().str();
1654   std::string lowerCase = LowercaseString(upperCase);
1655   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
1656       .Case("lsl", ARM_AM::lsl)
1657       .Case("lsr", ARM_AM::lsr)
1658       .Case("asr", ARM_AM::asr)
1659       .Case("ror", ARM_AM::ror)
1660       .Case("rrx", ARM_AM::rrx)
1661       .Default(ARM_AM::no_shift);
1662
1663   if (ShiftTy == ARM_AM::no_shift)
1664     return 1;
1665
1666   Parser.Lex(); // Eat the operator.
1667
1668   // The source register for the shift has already been added to the
1669   // operand list, so we need to pop it off and combine it into the shifted
1670   // register operand instead.
1671   OwningPtr<ARMOperand> PrevOp((ARMOperand*)Operands.pop_back_val());
1672   if (!PrevOp->isReg())
1673     return Error(PrevOp->getStartLoc(), "shift must be of a register");
1674   int SrcReg = PrevOp->getReg();
1675   int64_t Imm = 0;
1676   int ShiftReg = 0;
1677   if (ShiftTy == ARM_AM::rrx) {
1678     // RRX Doesn't have an explicit shift amount. The encoder expects
1679     // the shift register to be the same as the source register. Seems odd,
1680     // but OK.
1681     ShiftReg = SrcReg;
1682   } else {
1683     // Figure out if this is shifted by a constant or a register (for non-RRX).
1684     if (Parser.getTok().is(AsmToken::Hash)) {
1685       Parser.Lex(); // Eat hash.
1686       SMLoc ImmLoc = Parser.getTok().getLoc();
1687       const MCExpr *ShiftExpr = 0;
1688       if (getParser().ParseExpression(ShiftExpr)) {
1689         Error(ImmLoc, "invalid immediate shift value");
1690         return -1;
1691       }
1692       // The expression must be evaluatable as an immediate.
1693       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
1694       if (!CE) {
1695         Error(ImmLoc, "invalid immediate shift value");
1696         return -1;
1697       }
1698       // Range check the immediate.
1699       // lsl, ror: 0 <= imm <= 31
1700       // lsr, asr: 0 <= imm <= 32
1701       Imm = CE->getValue();
1702       if (Imm < 0 ||
1703           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
1704           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
1705         Error(ImmLoc, "immediate shift value out of range");
1706         return -1;
1707       }
1708     } else if (Parser.getTok().is(AsmToken::Identifier)) {
1709       ShiftReg = tryParseRegister();
1710       SMLoc L = Parser.getTok().getLoc();
1711       if (ShiftReg == -1) {
1712         Error (L, "expected immediate or register in shift operand");
1713         return -1;
1714       }
1715     } else {
1716       Error (Parser.getTok().getLoc(),
1717                     "expected immediate or register in shift operand");
1718       return -1;
1719     }
1720   }
1721
1722   if (ShiftReg && ShiftTy != ARM_AM::rrx)
1723     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
1724                                                          ShiftReg, Imm,
1725                                                S, Parser.getTok().getLoc()));
1726   else
1727     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
1728                                                S, Parser.getTok().getLoc()));
1729
1730   return 0;
1731 }
1732
1733
1734 /// Try to parse a register name.  The token must be an Identifier when called.
1735 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
1736 /// if there is a "writeback". 'true' if it's not a register.
1737 ///
1738 /// TODO this is likely to change to allow different register types and or to
1739 /// parse for a specific register type.
1740 bool ARMAsmParser::
1741 tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1742   SMLoc S = Parser.getTok().getLoc();
1743   int RegNo = tryParseRegister();
1744   if (RegNo == -1)
1745     return true;
1746
1747   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
1748
1749   const AsmToken &ExclaimTok = Parser.getTok();
1750   if (ExclaimTok.is(AsmToken::Exclaim)) {
1751     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
1752                                                ExclaimTok.getLoc()));
1753     Parser.Lex(); // Eat exclaim token
1754   }
1755
1756   return false;
1757 }
1758
1759 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
1760 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
1761 /// "c5", ...
1762 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
1763   // Use the same layout as the tablegen'erated register name matcher. Ugly,
1764   // but efficient.
1765   switch (Name.size()) {
1766   default: break;
1767   case 2:
1768     if (Name[0] != CoprocOp)
1769       return -1;
1770     switch (Name[1]) {
1771     default:  return -1;
1772     case '0': return 0;
1773     case '1': return 1;
1774     case '2': return 2;
1775     case '3': return 3;
1776     case '4': return 4;
1777     case '5': return 5;
1778     case '6': return 6;
1779     case '7': return 7;
1780     case '8': return 8;
1781     case '9': return 9;
1782     }
1783     break;
1784   case 3:
1785     if (Name[0] != CoprocOp || Name[1] != '1')
1786       return -1;
1787     switch (Name[2]) {
1788     default:  return -1;
1789     case '0': return 10;
1790     case '1': return 11;
1791     case '2': return 12;
1792     case '3': return 13;
1793     case '4': return 14;
1794     case '5': return 15;
1795     }
1796     break;
1797   }
1798
1799   return -1;
1800 }
1801
1802 /// parseITCondCode - Try to parse a condition code for an IT instruction.
1803 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1804 parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1805   SMLoc S = Parser.getTok().getLoc();
1806   const AsmToken &Tok = Parser.getTok();
1807   if (!Tok.is(AsmToken::Identifier))
1808     return MatchOperand_NoMatch;
1809   unsigned CC = StringSwitch<unsigned>(Tok.getString())
1810     .Case("eq", ARMCC::EQ)
1811     .Case("ne", ARMCC::NE)
1812     .Case("hs", ARMCC::HS)
1813     .Case("cs", ARMCC::HS)
1814     .Case("lo", ARMCC::LO)
1815     .Case("cc", ARMCC::LO)
1816     .Case("mi", ARMCC::MI)
1817     .Case("pl", ARMCC::PL)
1818     .Case("vs", ARMCC::VS)
1819     .Case("vc", ARMCC::VC)
1820     .Case("hi", ARMCC::HI)
1821     .Case("ls", ARMCC::LS)
1822     .Case("ge", ARMCC::GE)
1823     .Case("lt", ARMCC::LT)
1824     .Case("gt", ARMCC::GT)
1825     .Case("le", ARMCC::LE)
1826     .Case("al", ARMCC::AL)
1827     .Default(~0U);
1828   if (CC == ~0U)
1829     return MatchOperand_NoMatch;
1830   Parser.Lex(); // Eat the token.
1831
1832   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
1833
1834   return MatchOperand_Success;
1835 }
1836
1837 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
1838 /// token must be an Identifier when called, and if it is a coprocessor
1839 /// number, the token is eaten and the operand is added to the operand list.
1840 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1841 parseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1842   SMLoc S = Parser.getTok().getLoc();
1843   const AsmToken &Tok = Parser.getTok();
1844   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1845
1846   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
1847   if (Num == -1)
1848     return MatchOperand_NoMatch;
1849
1850   Parser.Lex(); // Eat identifier token.
1851   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
1852   return MatchOperand_Success;
1853 }
1854
1855 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
1856 /// token must be an Identifier when called, and if it is a coprocessor
1857 /// number, the token is eaten and the operand is added to the operand list.
1858 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1859 parseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1860   SMLoc S = Parser.getTok().getLoc();
1861   const AsmToken &Tok = Parser.getTok();
1862   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1863
1864   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
1865   if (Reg == -1)
1866     return MatchOperand_NoMatch;
1867
1868   Parser.Lex(); // Eat identifier token.
1869   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
1870   return MatchOperand_Success;
1871 }
1872
1873 // For register list parsing, we need to map from raw GPR register numbering
1874 // to the enumeration values. The enumeration values aren't sorted by
1875 // register number due to our using "sp", "lr" and "pc" as canonical names.
1876 static unsigned getNextRegister(unsigned Reg) {
1877   // If this is a GPR, we need to do it manually, otherwise we can rely
1878   // on the sort ordering of the enumeration since the other reg-classes
1879   // are sane.
1880   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
1881     return Reg + 1;
1882   switch(Reg) {
1883   default: assert(0 && "Invalid GPR number!");
1884   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
1885   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
1886   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
1887   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
1888   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
1889   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
1890   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
1891   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
1892   }
1893 }
1894
1895 /// Parse a register list.
1896 bool ARMAsmParser::
1897 parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1898   assert(Parser.getTok().is(AsmToken::LCurly) &&
1899          "Token is not a Left Curly Brace");
1900   SMLoc S = Parser.getTok().getLoc();
1901   Parser.Lex(); // Eat '{' token.
1902   SMLoc RegLoc = Parser.getTok().getLoc();
1903
1904   // Check the first register in the list to see what register class
1905   // this is a list of.
1906   int Reg = tryParseRegister();
1907   if (Reg == -1)
1908     return Error(RegLoc, "register expected");
1909
1910   MCRegisterClass *RC;
1911   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
1912     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
1913   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
1914     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
1915   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
1916     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
1917   else
1918     return Error(RegLoc, "invalid register in register list");
1919
1920   // The reglist instructions have at most 16 registers, so reserve
1921   // space for that many.
1922   SmallVector<std::pair<unsigned, SMLoc>, 16> Registers;
1923   // Store the first register.
1924   Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
1925
1926   // This starts immediately after the first register token in the list,
1927   // so we can see either a comma or a minus (range separator) as a legal
1928   // next token.
1929   while (Parser.getTok().is(AsmToken::Comma) ||
1930          Parser.getTok().is(AsmToken::Minus)) {
1931     if (Parser.getTok().is(AsmToken::Minus)) {
1932       Parser.Lex(); // Eat the comma.
1933       SMLoc EndLoc = Parser.getTok().getLoc();
1934       int EndReg = tryParseRegister();
1935       if (EndReg == -1)
1936         return Error(EndLoc, "register expected");
1937       // If the register is the same as the start reg, there's nothing
1938       // more to do.
1939       if (Reg == EndReg)
1940         continue;
1941       // The register must be in the same register class as the first.
1942       if (!RC->contains(EndReg))
1943         return Error(EndLoc, "invalid register in register list");
1944       // Ranges must go from low to high.
1945       if (getARMRegisterNumbering(Reg) > getARMRegisterNumbering(EndReg))
1946         return Error(EndLoc, "bad range in register list");
1947
1948       // Add all the registers in the range to the register list.
1949       while (Reg != EndReg) {
1950         Reg = getNextRegister(Reg);
1951         Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
1952       }
1953       continue;
1954     }
1955     Parser.Lex(); // Eat the comma.
1956     RegLoc = Parser.getTok().getLoc();
1957     int OldReg = Reg;
1958     Reg = tryParseRegister();
1959     if (Reg == -1)
1960       return Error(RegLoc, "register expected");
1961     // The register must be in the same register class as the first.
1962     if (!RC->contains(Reg))
1963       return Error(RegLoc, "invalid register in register list");
1964     // List must be monotonically increasing.
1965     if (getARMRegisterNumbering(Reg) <= getARMRegisterNumbering(OldReg))
1966       return Error(RegLoc, "register list not in ascending order");
1967     // VFP register lists must also be contiguous.
1968     // It's OK to use the enumeration values directly here rather, as the
1969     // VFP register classes have the enum sorted properly.
1970     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
1971         Reg != OldReg + 1)
1972       return Error(RegLoc, "non-contiguous register range");
1973     Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
1974   }
1975
1976   SMLoc E = Parser.getTok().getLoc();
1977   if (Parser.getTok().isNot(AsmToken::RCurly))
1978     return Error(E, "'}' expected");
1979   Parser.Lex(); // Eat '}' token.
1980
1981   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
1982   return false;
1983 }
1984
1985 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
1986 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1987 parseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1988   SMLoc S = Parser.getTok().getLoc();
1989   const AsmToken &Tok = Parser.getTok();
1990   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1991   StringRef OptStr = Tok.getString();
1992
1993   unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
1994     .Case("sy",    ARM_MB::SY)
1995     .Case("st",    ARM_MB::ST)
1996     .Case("sh",    ARM_MB::ISH)
1997     .Case("ish",   ARM_MB::ISH)
1998     .Case("shst",  ARM_MB::ISHST)
1999     .Case("ishst", ARM_MB::ISHST)
2000     .Case("nsh",   ARM_MB::NSH)
2001     .Case("un",    ARM_MB::NSH)
2002     .Case("nshst", ARM_MB::NSHST)
2003     .Case("unst",  ARM_MB::NSHST)
2004     .Case("osh",   ARM_MB::OSH)
2005     .Case("oshst", ARM_MB::OSHST)
2006     .Default(~0U);
2007
2008   if (Opt == ~0U)
2009     return MatchOperand_NoMatch;
2010
2011   Parser.Lex(); // Eat identifier token.
2012   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
2013   return MatchOperand_Success;
2014 }
2015
2016 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
2017 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2018 parseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2019   SMLoc S = Parser.getTok().getLoc();
2020   const AsmToken &Tok = Parser.getTok();
2021   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2022   StringRef IFlagsStr = Tok.getString();
2023
2024   unsigned IFlags = 0;
2025   for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
2026     unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
2027     .Case("a", ARM_PROC::A)
2028     .Case("i", ARM_PROC::I)
2029     .Case("f", ARM_PROC::F)
2030     .Default(~0U);
2031
2032     // If some specific iflag is already set, it means that some letter is
2033     // present more than once, this is not acceptable.
2034     if (Flag == ~0U || (IFlags & Flag))
2035       return MatchOperand_NoMatch;
2036
2037     IFlags |= Flag;
2038   }
2039
2040   Parser.Lex(); // Eat identifier token.
2041   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
2042   return MatchOperand_Success;
2043 }
2044
2045 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
2046 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2047 parseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2048   SMLoc S = Parser.getTok().getLoc();
2049   const AsmToken &Tok = Parser.getTok();
2050   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2051   StringRef Mask = Tok.getString();
2052
2053   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
2054   size_t Start = 0, Next = Mask.find('_');
2055   StringRef Flags = "";
2056   std::string SpecReg = LowercaseString(Mask.slice(Start, Next));
2057   if (Next != StringRef::npos)
2058     Flags = Mask.slice(Next+1, Mask.size());
2059
2060   // FlagsVal contains the complete mask:
2061   // 3-0: Mask
2062   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
2063   unsigned FlagsVal = 0;
2064
2065   if (SpecReg == "apsr") {
2066     FlagsVal = StringSwitch<unsigned>(Flags)
2067     .Case("nzcvq",  0x8) // same as CPSR_f
2068     .Case("g",      0x4) // same as CPSR_s
2069     .Case("nzcvqg", 0xc) // same as CPSR_fs
2070     .Default(~0U);
2071
2072     if (FlagsVal == ~0U) {
2073       if (!Flags.empty())
2074         return MatchOperand_NoMatch;
2075       else
2076         FlagsVal = 8; // No flag
2077     }
2078   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
2079     if (Flags == "all") // cpsr_all is an alias for cpsr_fc
2080       Flags = "fc";
2081     for (int i = 0, e = Flags.size(); i != e; ++i) {
2082       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
2083       .Case("c", 1)
2084       .Case("x", 2)
2085       .Case("s", 4)
2086       .Case("f", 8)
2087       .Default(~0U);
2088
2089       // If some specific flag is already set, it means that some letter is
2090       // present more than once, this is not acceptable.
2091       if (FlagsVal == ~0U || (FlagsVal & Flag))
2092         return MatchOperand_NoMatch;
2093       FlagsVal |= Flag;
2094     }
2095   } else // No match for special register.
2096     return MatchOperand_NoMatch;
2097
2098   // Special register without flags are equivalent to "fc" flags.
2099   if (!FlagsVal)
2100     FlagsVal = 0x9;
2101
2102   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
2103   if (SpecReg == "spsr")
2104     FlagsVal |= 16;
2105
2106   Parser.Lex(); // Eat identifier token.
2107   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
2108   return MatchOperand_Success;
2109 }
2110
2111 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2112 parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands, StringRef Op,
2113             int Low, int High) {
2114   const AsmToken &Tok = Parser.getTok();
2115   if (Tok.isNot(AsmToken::Identifier)) {
2116     Error(Parser.getTok().getLoc(), Op + " operand expected.");
2117     return MatchOperand_ParseFail;
2118   }
2119   StringRef ShiftName = Tok.getString();
2120   std::string LowerOp = LowercaseString(Op);
2121   std::string UpperOp = UppercaseString(Op);
2122   if (ShiftName != LowerOp && ShiftName != UpperOp) {
2123     Error(Parser.getTok().getLoc(), Op + " operand expected.");
2124     return MatchOperand_ParseFail;
2125   }
2126   Parser.Lex(); // Eat shift type token.
2127
2128   // There must be a '#' and a shift amount.
2129   if (Parser.getTok().isNot(AsmToken::Hash)) {
2130     Error(Parser.getTok().getLoc(), "'#' expected");
2131     return MatchOperand_ParseFail;
2132   }
2133   Parser.Lex(); // Eat hash token.
2134
2135   const MCExpr *ShiftAmount;
2136   SMLoc Loc = Parser.getTok().getLoc();
2137   if (getParser().ParseExpression(ShiftAmount)) {
2138     Error(Loc, "illegal expression");
2139     return MatchOperand_ParseFail;
2140   }
2141   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2142   if (!CE) {
2143     Error(Loc, "constant expression expected");
2144     return MatchOperand_ParseFail;
2145   }
2146   int Val = CE->getValue();
2147   if (Val < Low || Val > High) {
2148     Error(Loc, "immediate value out of range");
2149     return MatchOperand_ParseFail;
2150   }
2151
2152   Operands.push_back(ARMOperand::CreateImm(CE, Loc, Parser.getTok().getLoc()));
2153
2154   return MatchOperand_Success;
2155 }
2156
2157 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2158 parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2159   const AsmToken &Tok = Parser.getTok();
2160   SMLoc S = Tok.getLoc();
2161   if (Tok.isNot(AsmToken::Identifier)) {
2162     Error(Tok.getLoc(), "'be' or 'le' operand expected");
2163     return MatchOperand_ParseFail;
2164   }
2165   int Val = StringSwitch<int>(Tok.getString())
2166     .Case("be", 1)
2167     .Case("le", 0)
2168     .Default(-1);
2169   Parser.Lex(); // Eat the token.
2170
2171   if (Val == -1) {
2172     Error(Tok.getLoc(), "'be' or 'le' operand expected");
2173     return MatchOperand_ParseFail;
2174   }
2175   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
2176                                                                   getContext()),
2177                                            S, Parser.getTok().getLoc()));
2178   return MatchOperand_Success;
2179 }
2180
2181 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
2182 /// instructions. Legal values are:
2183 ///     lsl #n  'n' in [0,31]
2184 ///     asr #n  'n' in [1,32]
2185 ///             n == 32 encoded as n == 0.
2186 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2187 parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2188   const AsmToken &Tok = Parser.getTok();
2189   SMLoc S = Tok.getLoc();
2190   if (Tok.isNot(AsmToken::Identifier)) {
2191     Error(S, "shift operator 'asr' or 'lsl' expected");
2192     return MatchOperand_ParseFail;
2193   }
2194   StringRef ShiftName = Tok.getString();
2195   bool isASR;
2196   if (ShiftName == "lsl" || ShiftName == "LSL")
2197     isASR = false;
2198   else if (ShiftName == "asr" || ShiftName == "ASR")
2199     isASR = true;
2200   else {
2201     Error(S, "shift operator 'asr' or 'lsl' expected");
2202     return MatchOperand_ParseFail;
2203   }
2204   Parser.Lex(); // Eat the operator.
2205
2206   // A '#' and a shift amount.
2207   if (Parser.getTok().isNot(AsmToken::Hash)) {
2208     Error(Parser.getTok().getLoc(), "'#' expected");
2209     return MatchOperand_ParseFail;
2210   }
2211   Parser.Lex(); // Eat hash token.
2212
2213   const MCExpr *ShiftAmount;
2214   SMLoc E = Parser.getTok().getLoc();
2215   if (getParser().ParseExpression(ShiftAmount)) {
2216     Error(E, "malformed shift expression");
2217     return MatchOperand_ParseFail;
2218   }
2219   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2220   if (!CE) {
2221     Error(E, "shift amount must be an immediate");
2222     return MatchOperand_ParseFail;
2223   }
2224
2225   int64_t Val = CE->getValue();
2226   if (isASR) {
2227     // Shift amount must be in [1,32]
2228     if (Val < 1 || Val > 32) {
2229       Error(E, "'asr' shift amount must be in range [1,32]");
2230       return MatchOperand_ParseFail;
2231     }
2232     // asr #32 encoded as asr #0.
2233     if (Val == 32) Val = 0;
2234   } else {
2235     // Shift amount must be in [1,32]
2236     if (Val < 0 || Val > 31) {
2237       Error(E, "'lsr' shift amount must be in range [0,31]");
2238       return MatchOperand_ParseFail;
2239     }
2240   }
2241
2242   E = Parser.getTok().getLoc();
2243   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, E));
2244
2245   return MatchOperand_Success;
2246 }
2247
2248 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
2249 /// of instructions. Legal values are:
2250 ///     ror #n  'n' in {0, 8, 16, 24}
2251 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2252 parseRotImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2253   const AsmToken &Tok = Parser.getTok();
2254   SMLoc S = Tok.getLoc();
2255   if (Tok.isNot(AsmToken::Identifier)) {
2256     Error(S, "rotate operator 'ror' expected");
2257     return MatchOperand_ParseFail;
2258   }
2259   StringRef ShiftName = Tok.getString();
2260   if (ShiftName != "ror" && ShiftName != "ROR") {
2261     Error(S, "rotate operator 'ror' expected");
2262     return MatchOperand_ParseFail;
2263   }
2264   Parser.Lex(); // Eat the operator.
2265
2266   // A '#' and a rotate amount.
2267   if (Parser.getTok().isNot(AsmToken::Hash)) {
2268     Error(Parser.getTok().getLoc(), "'#' expected");
2269     return MatchOperand_ParseFail;
2270   }
2271   Parser.Lex(); // Eat hash token.
2272
2273   const MCExpr *ShiftAmount;
2274   SMLoc E = Parser.getTok().getLoc();
2275   if (getParser().ParseExpression(ShiftAmount)) {
2276     Error(E, "malformed rotate expression");
2277     return MatchOperand_ParseFail;
2278   }
2279   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2280   if (!CE) {
2281     Error(E, "rotate amount must be an immediate");
2282     return MatchOperand_ParseFail;
2283   }
2284
2285   int64_t Val = CE->getValue();
2286   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
2287   // normally, zero is represented in asm by omitting the rotate operand
2288   // entirely.
2289   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
2290     Error(E, "'ror' rotate amount must be 8, 16, or 24");
2291     return MatchOperand_ParseFail;
2292   }
2293
2294   E = Parser.getTok().getLoc();
2295   Operands.push_back(ARMOperand::CreateRotImm(Val, S, E));
2296
2297   return MatchOperand_Success;
2298 }
2299
2300 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2301 parseBitfield(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2302   SMLoc S = Parser.getTok().getLoc();
2303   // The bitfield descriptor is really two operands, the LSB and the width.
2304   if (Parser.getTok().isNot(AsmToken::Hash)) {
2305     Error(Parser.getTok().getLoc(), "'#' expected");
2306     return MatchOperand_ParseFail;
2307   }
2308   Parser.Lex(); // Eat hash token.
2309
2310   const MCExpr *LSBExpr;
2311   SMLoc E = Parser.getTok().getLoc();
2312   if (getParser().ParseExpression(LSBExpr)) {
2313     Error(E, "malformed immediate expression");
2314     return MatchOperand_ParseFail;
2315   }
2316   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
2317   if (!CE) {
2318     Error(E, "'lsb' operand must be an immediate");
2319     return MatchOperand_ParseFail;
2320   }
2321
2322   int64_t LSB = CE->getValue();
2323   // The LSB must be in the range [0,31]
2324   if (LSB < 0 || LSB > 31) {
2325     Error(E, "'lsb' operand must be in the range [0,31]");
2326     return MatchOperand_ParseFail;
2327   }
2328   E = Parser.getTok().getLoc();
2329
2330   // Expect another immediate operand.
2331   if (Parser.getTok().isNot(AsmToken::Comma)) {
2332     Error(Parser.getTok().getLoc(), "too few operands");
2333     return MatchOperand_ParseFail;
2334   }
2335   Parser.Lex(); // Eat hash token.
2336   if (Parser.getTok().isNot(AsmToken::Hash)) {
2337     Error(Parser.getTok().getLoc(), "'#' expected");
2338     return MatchOperand_ParseFail;
2339   }
2340   Parser.Lex(); // Eat hash token.
2341
2342   const MCExpr *WidthExpr;
2343   if (getParser().ParseExpression(WidthExpr)) {
2344     Error(E, "malformed immediate expression");
2345     return MatchOperand_ParseFail;
2346   }
2347   CE = dyn_cast<MCConstantExpr>(WidthExpr);
2348   if (!CE) {
2349     Error(E, "'width' operand must be an immediate");
2350     return MatchOperand_ParseFail;
2351   }
2352
2353   int64_t Width = CE->getValue();
2354   // The LSB must be in the range [1,32-lsb]
2355   if (Width < 1 || Width > 32 - LSB) {
2356     Error(E, "'width' operand must be in the range [1,32-lsb]");
2357     return MatchOperand_ParseFail;
2358   }
2359   E = Parser.getTok().getLoc();
2360
2361   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, E));
2362
2363   return MatchOperand_Success;
2364 }
2365
2366 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2367 parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2368   // Check for a post-index addressing register operand. Specifically:
2369   // postidx_reg := '+' register {, shift}
2370   //              | '-' register {, shift}
2371   //              | register {, shift}
2372
2373   // This method must return MatchOperand_NoMatch without consuming any tokens
2374   // in the case where there is no match, as other alternatives take other
2375   // parse methods.
2376   AsmToken Tok = Parser.getTok();
2377   SMLoc S = Tok.getLoc();
2378   bool haveEaten = false;
2379   bool isAdd = true;
2380   int Reg = -1;
2381   if (Tok.is(AsmToken::Plus)) {
2382     Parser.Lex(); // Eat the '+' token.
2383     haveEaten = true;
2384   } else if (Tok.is(AsmToken::Minus)) {
2385     Parser.Lex(); // Eat the '-' token.
2386     isAdd = false;
2387     haveEaten = true;
2388   }
2389   if (Parser.getTok().is(AsmToken::Identifier))
2390     Reg = tryParseRegister();
2391   if (Reg == -1) {
2392     if (!haveEaten)
2393       return MatchOperand_NoMatch;
2394     Error(Parser.getTok().getLoc(), "register expected");
2395     return MatchOperand_ParseFail;
2396   }
2397   SMLoc E = Parser.getTok().getLoc();
2398
2399   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
2400   unsigned ShiftImm = 0;
2401   if (Parser.getTok().is(AsmToken::Comma)) {
2402     Parser.Lex(); // Eat the ','.
2403     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
2404       return MatchOperand_ParseFail;
2405   }
2406
2407   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
2408                                                   ShiftImm, S, E));
2409
2410   return MatchOperand_Success;
2411 }
2412
2413 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2414 parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2415   // Check for a post-index addressing register operand. Specifically:
2416   // am3offset := '+' register
2417   //              | '-' register
2418   //              | register
2419   //              | # imm
2420   //              | # + imm
2421   //              | # - imm
2422
2423   // This method must return MatchOperand_NoMatch without consuming any tokens
2424   // in the case where there is no match, as other alternatives take other
2425   // parse methods.
2426   AsmToken Tok = Parser.getTok();
2427   SMLoc S = Tok.getLoc();
2428
2429   // Do immediates first, as we always parse those if we have a '#'.
2430   if (Parser.getTok().is(AsmToken::Hash)) {
2431     Parser.Lex(); // Eat the '#'.
2432     // Explicitly look for a '-', as we need to encode negative zero
2433     // differently.
2434     bool isNegative = Parser.getTok().is(AsmToken::Minus);
2435     const MCExpr *Offset;
2436     if (getParser().ParseExpression(Offset))
2437       return MatchOperand_ParseFail;
2438     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2439     if (!CE) {
2440       Error(S, "constant expression expected");
2441       return MatchOperand_ParseFail;
2442     }
2443     SMLoc E = Tok.getLoc();
2444     // Negative zero is encoded as the flag value INT32_MIN.
2445     int32_t Val = CE->getValue();
2446     if (isNegative && Val == 0)
2447       Val = INT32_MIN;
2448
2449     Operands.push_back(
2450       ARMOperand::CreateImm(MCConstantExpr::Create(Val, getContext()), S, E));
2451
2452     return MatchOperand_Success;
2453   }
2454
2455
2456   bool haveEaten = false;
2457   bool isAdd = true;
2458   int Reg = -1;
2459   if (Tok.is(AsmToken::Plus)) {
2460     Parser.Lex(); // Eat the '+' token.
2461     haveEaten = true;
2462   } else if (Tok.is(AsmToken::Minus)) {
2463     Parser.Lex(); // Eat the '-' token.
2464     isAdd = false;
2465     haveEaten = true;
2466   }
2467   if (Parser.getTok().is(AsmToken::Identifier))
2468     Reg = tryParseRegister();
2469   if (Reg == -1) {
2470     if (!haveEaten)
2471       return MatchOperand_NoMatch;
2472     Error(Parser.getTok().getLoc(), "register expected");
2473     return MatchOperand_ParseFail;
2474   }
2475   SMLoc E = Parser.getTok().getLoc();
2476
2477   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
2478                                                   0, S, E));
2479
2480   return MatchOperand_Success;
2481 }
2482
2483 /// cvtT2LdrdPre - Convert parsed operands to MCInst.
2484 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2485 /// when they refer multiple MIOperands inside a single one.
2486 bool ARMAsmParser::
2487 cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
2488              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2489   // Rt, Rt2
2490   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2491   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2492   // Create a writeback register dummy placeholder.
2493   Inst.addOperand(MCOperand::CreateReg(0));
2494   // addr
2495   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2496   // pred
2497   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2498   return true;
2499 }
2500
2501 /// cvtT2StrdPre - Convert parsed operands to MCInst.
2502 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2503 /// when they refer multiple MIOperands inside a single one.
2504 bool ARMAsmParser::
2505 cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
2506              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2507   // Create a writeback register dummy placeholder.
2508   Inst.addOperand(MCOperand::CreateReg(0));
2509   // Rt, Rt2
2510   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2511   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2512   // addr
2513   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2514   // pred
2515   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2516   return true;
2517 }
2518
2519 /// cvtLdWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
2520 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2521 /// when they refer multiple MIOperands inside a single one.
2522 bool ARMAsmParser::
2523 cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
2524                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2525   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2526
2527   // Create a writeback register dummy placeholder.
2528   Inst.addOperand(MCOperand::CreateImm(0));
2529
2530   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
2531   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2532   return true;
2533 }
2534
2535 /// cvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2536 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2537 /// when they refer multiple MIOperands inside a single one.
2538 bool ARMAsmParser::
2539 cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2540                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2541   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2542
2543   // Create a writeback register dummy placeholder.
2544   Inst.addOperand(MCOperand::CreateImm(0));
2545
2546   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2547   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2548   return true;
2549 }
2550
2551 /// cvtLdWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2552 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2553 /// when they refer multiple MIOperands inside a single one.
2554 bool ARMAsmParser::
2555 cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2556                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2557   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2558
2559   // Create a writeback register dummy placeholder.
2560   Inst.addOperand(MCOperand::CreateImm(0));
2561
2562   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2563   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2564   return true;
2565 }
2566
2567
2568 /// cvtStWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2569 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2570 /// when they refer multiple MIOperands inside a single one.
2571 bool ARMAsmParser::
2572 cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2573                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2574   // Create a writeback register dummy placeholder.
2575   Inst.addOperand(MCOperand::CreateImm(0));
2576   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2577   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2578   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2579   return true;
2580 }
2581
2582 /// cvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2583 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2584 /// when they refer multiple MIOperands inside a single one.
2585 bool ARMAsmParser::
2586 cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2587                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2588   // Create a writeback register dummy placeholder.
2589   Inst.addOperand(MCOperand::CreateImm(0));
2590   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2591   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2592   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2593   return true;
2594 }
2595
2596 /// cvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2597 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2598 /// when they refer multiple MIOperands inside a single one.
2599 bool ARMAsmParser::
2600 cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2601                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2602   // Create a writeback register dummy placeholder.
2603   Inst.addOperand(MCOperand::CreateImm(0));
2604   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2605   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2606   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2607   return true;
2608 }
2609
2610 /// cvtLdExtTWriteBackImm - Convert parsed operands to MCInst.
2611 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2612 /// when they refer multiple MIOperands inside a single one.
2613 bool ARMAsmParser::
2614 cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2615                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2616   // Rt
2617   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2618   // Create a writeback register dummy placeholder.
2619   Inst.addOperand(MCOperand::CreateImm(0));
2620   // addr
2621   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2622   // offset
2623   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2624   // pred
2625   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2626   return true;
2627 }
2628
2629 /// cvtLdExtTWriteBackReg - Convert parsed operands to MCInst.
2630 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2631 /// when they refer multiple MIOperands inside a single one.
2632 bool ARMAsmParser::
2633 cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2634                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2635   // Rt
2636   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2637   // Create a writeback register dummy placeholder.
2638   Inst.addOperand(MCOperand::CreateImm(0));
2639   // addr
2640   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2641   // offset
2642   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2643   // pred
2644   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2645   return true;
2646 }
2647
2648 /// cvtStExtTWriteBackImm - Convert parsed operands to MCInst.
2649 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2650 /// when they refer multiple MIOperands inside a single one.
2651 bool ARMAsmParser::
2652 cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2653                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2654   // Create a writeback register dummy placeholder.
2655   Inst.addOperand(MCOperand::CreateImm(0));
2656   // Rt
2657   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2658   // addr
2659   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2660   // offset
2661   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2662   // pred
2663   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2664   return true;
2665 }
2666
2667 /// cvtStExtTWriteBackReg - Convert parsed operands to MCInst.
2668 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2669 /// when they refer multiple MIOperands inside a single one.
2670 bool ARMAsmParser::
2671 cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2672                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2673   // Create a writeback register dummy placeholder.
2674   Inst.addOperand(MCOperand::CreateImm(0));
2675   // Rt
2676   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2677   // addr
2678   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2679   // offset
2680   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2681   // pred
2682   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2683   return true;
2684 }
2685
2686 /// cvtLdrdPre - Convert parsed operands to MCInst.
2687 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2688 /// when they refer multiple MIOperands inside a single one.
2689 bool ARMAsmParser::
2690 cvtLdrdPre(MCInst &Inst, unsigned Opcode,
2691            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2692   // Rt, Rt2
2693   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2694   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2695   // Create a writeback register dummy placeholder.
2696   Inst.addOperand(MCOperand::CreateImm(0));
2697   // addr
2698   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2699   // pred
2700   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2701   return true;
2702 }
2703
2704 /// cvtStrdPre - Convert parsed operands to MCInst.
2705 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2706 /// when they refer multiple MIOperands inside a single one.
2707 bool ARMAsmParser::
2708 cvtStrdPre(MCInst &Inst, unsigned Opcode,
2709            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2710   // Create a writeback register dummy placeholder.
2711   Inst.addOperand(MCOperand::CreateImm(0));
2712   // Rt, Rt2
2713   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2714   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2715   // addr
2716   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2717   // pred
2718   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2719   return true;
2720 }
2721
2722 /// cvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2723 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2724 /// when they refer multiple MIOperands inside a single one.
2725 bool ARMAsmParser::
2726 cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2727                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2728   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2729   // Create a writeback register dummy placeholder.
2730   Inst.addOperand(MCOperand::CreateImm(0));
2731   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2732   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2733   return true;
2734 }
2735
2736 /// cvtThumbMultiple- Convert parsed operands to MCInst.
2737 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2738 /// when they refer multiple MIOperands inside a single one.
2739 bool ARMAsmParser::
2740 cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
2741            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2742   // The second source operand must be the same register as the destination
2743   // operand.
2744   if (Operands.size() == 6 &&
2745       (((ARMOperand*)Operands[3])->getReg() !=
2746        ((ARMOperand*)Operands[5])->getReg()) &&
2747       (((ARMOperand*)Operands[3])->getReg() !=
2748        ((ARMOperand*)Operands[4])->getReg())) {
2749     Error(Operands[3]->getStartLoc(),
2750           "destination register must match source register");
2751     return false;
2752   }
2753   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2754   ((ARMOperand*)Operands[1])->addCCOutOperands(Inst, 1);
2755   ((ARMOperand*)Operands[4])->addRegOperands(Inst, 1);
2756   // If we have a three-operand form, use that, else the second source operand
2757   // is just the destination operand again.
2758   if (Operands.size() == 6)
2759     ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
2760   else
2761     Inst.addOperand(Inst.getOperand(0));
2762   ((ARMOperand*)Operands[2])->addCondCodeOperands(Inst, 2);
2763
2764   return true;
2765 }
2766
2767 /// Parse an ARM memory expression, return false if successful else return true
2768 /// or an error.  The first token must be a '[' when called.
2769 bool ARMAsmParser::
2770 parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2771   SMLoc S, E;
2772   assert(Parser.getTok().is(AsmToken::LBrac) &&
2773          "Token is not a Left Bracket");
2774   S = Parser.getTok().getLoc();
2775   Parser.Lex(); // Eat left bracket token.
2776
2777   const AsmToken &BaseRegTok = Parser.getTok();
2778   int BaseRegNum = tryParseRegister();
2779   if (BaseRegNum == -1)
2780     return Error(BaseRegTok.getLoc(), "register expected");
2781
2782   // The next token must either be a comma or a closing bracket.
2783   const AsmToken &Tok = Parser.getTok();
2784   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
2785     return Error(Tok.getLoc(), "malformed memory operand");
2786
2787   if (Tok.is(AsmToken::RBrac)) {
2788     E = Tok.getLoc();
2789     Parser.Lex(); // Eat right bracket token.
2790
2791     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, 0, ARM_AM::no_shift,
2792                                              0, false, S, E));
2793
2794     return false;
2795   }
2796
2797   assert(Tok.is(AsmToken::Comma) && "Lost comma in memory operand?!");
2798   Parser.Lex(); // Eat the comma.
2799
2800   // If we have a '#' it's an immediate offset, else assume it's a register
2801   // offset.
2802   if (Parser.getTok().is(AsmToken::Hash)) {
2803     Parser.Lex(); // Eat the '#'.
2804     E = Parser.getTok().getLoc();
2805
2806     bool isNegative = getParser().getTok().is(AsmToken::Minus);
2807     const MCExpr *Offset;
2808     if (getParser().ParseExpression(Offset))
2809      return true;
2810
2811     // The expression has to be a constant. Memory references with relocations
2812     // don't come through here, as they use the <label> forms of the relevant
2813     // instructions.
2814     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2815     if (!CE)
2816       return Error (E, "constant expression expected");
2817
2818     // If the constant was #-0, represent it as INT32_MIN.
2819     int32_t Val = CE->getValue();
2820     if (isNegative && Val == 0)
2821       CE = MCConstantExpr::Create(INT32_MIN, getContext());
2822
2823     // Now we should have the closing ']'
2824     E = Parser.getTok().getLoc();
2825     if (Parser.getTok().isNot(AsmToken::RBrac))
2826       return Error(E, "']' expected");
2827     Parser.Lex(); // Eat right bracket token.
2828
2829     // Don't worry about range checking the value here. That's handled by
2830     // the is*() predicates.
2831     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
2832                                              ARM_AM::no_shift, 0, false, S,E));
2833
2834     // If there's a pre-indexing writeback marker, '!', just add it as a token
2835     // operand.
2836     if (Parser.getTok().is(AsmToken::Exclaim)) {
2837       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2838       Parser.Lex(); // Eat the '!'.
2839     }
2840
2841     return false;
2842   }
2843
2844   // The register offset is optionally preceded by a '+' or '-'
2845   bool isNegative = false;
2846   if (Parser.getTok().is(AsmToken::Minus)) {
2847     isNegative = true;
2848     Parser.Lex(); // Eat the '-'.
2849   } else if (Parser.getTok().is(AsmToken::Plus)) {
2850     // Nothing to do.
2851     Parser.Lex(); // Eat the '+'.
2852   }
2853
2854   E = Parser.getTok().getLoc();
2855   int OffsetRegNum = tryParseRegister();
2856   if (OffsetRegNum == -1)
2857     return Error(E, "register expected");
2858
2859   // If there's a shift operator, handle it.
2860   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
2861   unsigned ShiftImm = 0;
2862   if (Parser.getTok().is(AsmToken::Comma)) {
2863     Parser.Lex(); // Eat the ','.
2864     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
2865       return true;
2866   }
2867
2868   // Now we should have the closing ']'
2869   E = Parser.getTok().getLoc();
2870   if (Parser.getTok().isNot(AsmToken::RBrac))
2871     return Error(E, "']' expected");
2872   Parser.Lex(); // Eat right bracket token.
2873
2874   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, OffsetRegNum,
2875                                            ShiftType, ShiftImm, isNegative,
2876                                            S, E));
2877
2878   // If there's a pre-indexing writeback marker, '!', just add it as a token
2879   // operand.
2880   if (Parser.getTok().is(AsmToken::Exclaim)) {
2881     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2882     Parser.Lex(); // Eat the '!'.
2883   }
2884
2885   return false;
2886 }
2887
2888 /// parseMemRegOffsetShift - one of these two:
2889 ///   ( lsl | lsr | asr | ror ) , # shift_amount
2890 ///   rrx
2891 /// return true if it parses a shift otherwise it returns false.
2892 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
2893                                           unsigned &Amount) {
2894   SMLoc Loc = Parser.getTok().getLoc();
2895   const AsmToken &Tok = Parser.getTok();
2896   if (Tok.isNot(AsmToken::Identifier))
2897     return true;
2898   StringRef ShiftName = Tok.getString();
2899   if (ShiftName == "lsl" || ShiftName == "LSL")
2900     St = ARM_AM::lsl;
2901   else if (ShiftName == "lsr" || ShiftName == "LSR")
2902     St = ARM_AM::lsr;
2903   else if (ShiftName == "asr" || ShiftName == "ASR")
2904     St = ARM_AM::asr;
2905   else if (ShiftName == "ror" || ShiftName == "ROR")
2906     St = ARM_AM::ror;
2907   else if (ShiftName == "rrx" || ShiftName == "RRX")
2908     St = ARM_AM::rrx;
2909   else
2910     return Error(Loc, "illegal shift operator");
2911   Parser.Lex(); // Eat shift type token.
2912
2913   // rrx stands alone.
2914   Amount = 0;
2915   if (St != ARM_AM::rrx) {
2916     Loc = Parser.getTok().getLoc();
2917     // A '#' and a shift amount.
2918     const AsmToken &HashTok = Parser.getTok();
2919     if (HashTok.isNot(AsmToken::Hash))
2920       return Error(HashTok.getLoc(), "'#' expected");
2921     Parser.Lex(); // Eat hash token.
2922
2923     const MCExpr *Expr;
2924     if (getParser().ParseExpression(Expr))
2925       return true;
2926     // Range check the immediate.
2927     // lsl, ror: 0 <= imm <= 31
2928     // lsr, asr: 0 <= imm <= 32
2929     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
2930     if (!CE)
2931       return Error(Loc, "shift amount must be an immediate");
2932     int64_t Imm = CE->getValue();
2933     if (Imm < 0 ||
2934         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
2935         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
2936       return Error(Loc, "immediate shift value out of range");
2937     Amount = Imm;
2938   }
2939
2940   return false;
2941 }
2942
2943 /// Parse a arm instruction operand.  For now this parses the operand regardless
2944 /// of the mnemonic.
2945 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2946                                 StringRef Mnemonic) {
2947   SMLoc S, E;
2948
2949   // Check if the current operand has a custom associated parser, if so, try to
2950   // custom parse the operand, or fallback to the general approach.
2951   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
2952   if (ResTy == MatchOperand_Success)
2953     return false;
2954   // If there wasn't a custom match, try the generic matcher below. Otherwise,
2955   // there was a match, but an error occurred, in which case, just return that
2956   // the operand parsing failed.
2957   if (ResTy == MatchOperand_ParseFail)
2958     return true;
2959
2960   switch (getLexer().getKind()) {
2961   default:
2962     Error(Parser.getTok().getLoc(), "unexpected token in operand");
2963     return true;
2964   case AsmToken::Identifier: {
2965     if (!tryParseRegisterWithWriteBack(Operands))
2966       return false;
2967     int Res = tryParseShiftRegister(Operands);
2968     if (Res == 0) // success
2969       return false;
2970     else if (Res == -1) // irrecoverable error
2971       return true;
2972
2973     // Fall though for the Identifier case that is not a register or a
2974     // special name.
2975   }
2976   case AsmToken::Integer: // things like 1f and 2b as a branch targets
2977   case AsmToken::Dot: {   // . as a branch target
2978     // This was not a register so parse other operands that start with an
2979     // identifier (like labels) as expressions and create them as immediates.
2980     const MCExpr *IdVal;
2981     S = Parser.getTok().getLoc();
2982     if (getParser().ParseExpression(IdVal))
2983       return true;
2984     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2985     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
2986     return false;
2987   }
2988   case AsmToken::LBrac:
2989     return parseMemory(Operands);
2990   case AsmToken::LCurly:
2991     return parseRegisterList(Operands);
2992   case AsmToken::Hash: {
2993     // #42 -> immediate.
2994     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
2995     S = Parser.getTok().getLoc();
2996     Parser.Lex();
2997     bool isNegative = Parser.getTok().is(AsmToken::Minus);
2998     const MCExpr *ImmVal;
2999     if (getParser().ParseExpression(ImmVal))
3000       return true;
3001     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
3002     if (!CE) {
3003       Error(S, "constant expression expected");
3004       return MatchOperand_ParseFail;
3005     }
3006     int32_t Val = CE->getValue();
3007     if (isNegative && Val == 0)
3008       ImmVal = MCConstantExpr::Create(INT32_MIN, getContext());
3009     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3010     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
3011     return false;
3012   }
3013   case AsmToken::Colon: {
3014     // ":lower16:" and ":upper16:" expression prefixes
3015     // FIXME: Check it's an expression prefix,
3016     // e.g. (FOO - :lower16:BAR) isn't legal.
3017     ARMMCExpr::VariantKind RefKind;
3018     if (parsePrefix(RefKind))
3019       return true;
3020
3021     const MCExpr *SubExprVal;
3022     if (getParser().ParseExpression(SubExprVal))
3023       return true;
3024
3025     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
3026                                                    getContext());
3027     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3028     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
3029     return false;
3030   }
3031   }
3032 }
3033
3034 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
3035 //  :lower16: and :upper16:.
3036 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
3037   RefKind = ARMMCExpr::VK_ARM_None;
3038
3039   // :lower16: and :upper16: modifiers
3040   assert(getLexer().is(AsmToken::Colon) && "expected a :");
3041   Parser.Lex(); // Eat ':'
3042
3043   if (getLexer().isNot(AsmToken::Identifier)) {
3044     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
3045     return true;
3046   }
3047
3048   StringRef IDVal = Parser.getTok().getIdentifier();
3049   if (IDVal == "lower16") {
3050     RefKind = ARMMCExpr::VK_ARM_LO16;
3051   } else if (IDVal == "upper16") {
3052     RefKind = ARMMCExpr::VK_ARM_HI16;
3053   } else {
3054     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
3055     return true;
3056   }
3057   Parser.Lex();
3058
3059   if (getLexer().isNot(AsmToken::Colon)) {
3060     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
3061     return true;
3062   }
3063   Parser.Lex(); // Eat the last ':'
3064   return false;
3065 }
3066
3067 /// \brief Given a mnemonic, split out possible predication code and carry
3068 /// setting letters to form a canonical mnemonic and flags.
3069 //
3070 // FIXME: Would be nice to autogen this.
3071 // FIXME: This is a bit of a maze of special cases.
3072 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
3073                                       unsigned &PredicationCode,
3074                                       bool &CarrySetting,
3075                                       unsigned &ProcessorIMod,
3076                                       StringRef &ITMask) {
3077   PredicationCode = ARMCC::AL;
3078   CarrySetting = false;
3079   ProcessorIMod = 0;
3080
3081   // Ignore some mnemonics we know aren't predicated forms.
3082   //
3083   // FIXME: Would be nice to autogen this.
3084   if ((Mnemonic == "movs" && isThumb()) ||
3085       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
3086       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
3087       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
3088       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
3089       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
3090       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
3091       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal")
3092     return Mnemonic;
3093
3094   // First, split out any predication code. Ignore mnemonics we know aren't
3095   // predicated but do have a carry-set and so weren't caught above.
3096   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
3097       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
3098       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
3099       Mnemonic != "sbcs" && Mnemonic != "rscs") {
3100     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
3101       .Case("eq", ARMCC::EQ)
3102       .Case("ne", ARMCC::NE)
3103       .Case("hs", ARMCC::HS)
3104       .Case("cs", ARMCC::HS)
3105       .Case("lo", ARMCC::LO)
3106       .Case("cc", ARMCC::LO)
3107       .Case("mi", ARMCC::MI)
3108       .Case("pl", ARMCC::PL)
3109       .Case("vs", ARMCC::VS)
3110       .Case("vc", ARMCC::VC)
3111       .Case("hi", ARMCC::HI)
3112       .Case("ls", ARMCC::LS)
3113       .Case("ge", ARMCC::GE)
3114       .Case("lt", ARMCC::LT)
3115       .Case("gt", ARMCC::GT)
3116       .Case("le", ARMCC::LE)
3117       .Case("al", ARMCC::AL)
3118       .Default(~0U);
3119     if (CC != ~0U) {
3120       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
3121       PredicationCode = CC;
3122     }
3123   }
3124
3125   // Next, determine if we have a carry setting bit. We explicitly ignore all
3126   // the instructions we know end in 's'.
3127   if (Mnemonic.endswith("s") &&
3128       !(Mnemonic == "cps" || Mnemonic == "mls" ||
3129         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
3130         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
3131         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
3132         Mnemonic == "vrsqrts" || Mnemonic == "srs" ||
3133         (Mnemonic == "movs" && isThumb()))) {
3134     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
3135     CarrySetting = true;
3136   }
3137
3138   // The "cps" instruction can have a interrupt mode operand which is glued into
3139   // the mnemonic. Check if this is the case, split it and parse the imod op
3140   if (Mnemonic.startswith("cps")) {
3141     // Split out any imod code.
3142     unsigned IMod =
3143       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
3144       .Case("ie", ARM_PROC::IE)
3145       .Case("id", ARM_PROC::ID)
3146       .Default(~0U);
3147     if (IMod != ~0U) {
3148       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
3149       ProcessorIMod = IMod;
3150     }
3151   }
3152
3153   // The "it" instruction has the condition mask on the end of the mnemonic.
3154   if (Mnemonic.startswith("it")) {
3155     ITMask = Mnemonic.slice(2, Mnemonic.size());
3156     Mnemonic = Mnemonic.slice(0, 2);
3157   }
3158
3159   return Mnemonic;
3160 }
3161
3162 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
3163 /// inclusion of carry set or predication code operands.
3164 //
3165 // FIXME: It would be nice to autogen this.
3166 void ARMAsmParser::
3167 getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
3168                       bool &CanAcceptPredicationCode) {
3169   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
3170       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
3171       Mnemonic == "add" || Mnemonic == "adc" ||
3172       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
3173       Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mvn" ||
3174       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
3175       Mnemonic == "sbc" || Mnemonic == "umull" || Mnemonic == "eor" ||
3176       Mnemonic == "neg" ||
3177       (!isThumb() && (Mnemonic == "smull" || Mnemonic == "mov" ||
3178                       Mnemonic == "mla" || Mnemonic == "smlal"))) {
3179     CanAcceptCarrySet = true;
3180   } else
3181     CanAcceptCarrySet = false;
3182
3183   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
3184       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
3185       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
3186       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
3187       Mnemonic == "dsb" || Mnemonic == "isb" || Mnemonic == "setend" ||
3188       (Mnemonic == "clrex" && !isThumb()) ||
3189       (Mnemonic == "nop" && isThumbOne()) ||
3190       ((Mnemonic == "pld" || Mnemonic == "pli" || Mnemonic == "pldw") &&
3191        !isThumb()) ||
3192       ((Mnemonic.startswith("rfe") || Mnemonic.startswith("srs")) &&
3193        !isThumb()) ||
3194       Mnemonic.startswith("cps") || (Mnemonic == "movs" && isThumbOne())) {
3195     CanAcceptPredicationCode = false;
3196   } else
3197     CanAcceptPredicationCode = true;
3198
3199   if (isThumb()) {
3200     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
3201         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
3202       CanAcceptPredicationCode = false;
3203   }
3204 }
3205
3206 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
3207                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3208   // FIXME: This is all horribly hacky. We really need a better way to deal
3209   // with optional operands like this in the matcher table.
3210
3211   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
3212   // another does not. Specifically, the MOVW instruction does not. So we
3213   // special case it here and remove the defaulted (non-setting) cc_out
3214   // operand if that's the instruction we're trying to match.
3215   //
3216   // We do this as post-processing of the explicit operands rather than just
3217   // conditionally adding the cc_out in the first place because we need
3218   // to check the type of the parsed immediate operand.
3219   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
3220       !static_cast<ARMOperand*>(Operands[4])->isARMSOImm() &&
3221       static_cast<ARMOperand*>(Operands[4])->isImm0_65535Expr() &&
3222       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3223     return true;
3224
3225   // Register-register 'add' for thumb does not have a cc_out operand
3226   // when there are only two register operands.
3227   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
3228       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3229       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3230       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3231     return true;
3232   // Register-register 'add' for thumb does not have a cc_out operand
3233   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
3234   // have to check the immediate range here since Thumb2 has a variant
3235   // that can handle a different range and has a cc_out operand.
3236   if (isThumb() && Mnemonic == "add" && Operands.size() == 6 &&
3237       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3238       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3239       static_cast<ARMOperand*>(Operands[4])->getReg() == ARM::SP &&
3240       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3241       (static_cast<ARMOperand*>(Operands[5])->isReg() ||
3242        static_cast<ARMOperand*>(Operands[5])->isImm0_1020s4()))
3243     return true;
3244   // For Thumb2, add immediate does not have a cc_out operand for the
3245   // imm0_4096 variant. That's the least-preferred variant when
3246   // selecting via the generic "add" mnemonic, so to know that we
3247   // should remove the cc_out operand, we have to explicitly check that
3248   // it's not one of the other variants. Ugh.
3249   if (isThumbTwo() && Mnemonic == "add" && Operands.size() == 6 &&
3250       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3251       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3252       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3253     // Nest conditions rather than one big 'if' statement for readability.
3254     //
3255     // If either register is a high reg, it's either one of the SP
3256     // variants (handled above) or a 32-bit encoding, so we just
3257     // check against T3.
3258     if ((!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3259          !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg())) &&
3260         static_cast<ARMOperand*>(Operands[5])->isT2SOImm())
3261       return false;
3262     // If both registers are low, we're in an IT block, and the immediate is
3263     // in range, we should use encoding T1 instead, which has a cc_out.
3264     if (inITBlock() &&
3265         isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) &&
3266         isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) &&
3267         static_cast<ARMOperand*>(Operands[5])->isImm0_7())
3268       return false;
3269
3270     // Otherwise, we use encoding T4, which does not have a cc_out
3271     // operand.
3272     return true;
3273   }
3274
3275   // The thumb2 multiply instruction doesn't have a CCOut register, so
3276   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
3277   // use the 16-bit encoding or not.
3278   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
3279       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3280       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3281       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3282       static_cast<ARMOperand*>(Operands[5])->isReg() &&
3283       // If the registers aren't low regs, the destination reg isn't the
3284       // same as one of the source regs, or the cc_out operand is zero
3285       // outside of an IT block, we have to use the 32-bit encoding, so
3286       // remove the cc_out operand.
3287       (!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3288        !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) ||
3289        !inITBlock() ||
3290        (static_cast<ARMOperand*>(Operands[3])->getReg() !=
3291         static_cast<ARMOperand*>(Operands[5])->getReg() &&
3292         static_cast<ARMOperand*>(Operands[3])->getReg() !=
3293         static_cast<ARMOperand*>(Operands[4])->getReg())))
3294     return true;
3295
3296
3297
3298   // Register-register 'add/sub' for thumb does not have a cc_out operand
3299   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
3300   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
3301   // right, this will result in better diagnostics (which operand is off)
3302   // anyway.
3303   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
3304       (Operands.size() == 5 || Operands.size() == 6) &&
3305       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3306       static_cast<ARMOperand*>(Operands[3])->getReg() == ARM::SP &&
3307       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3308     return true;
3309
3310   return false;
3311 }
3312
3313 /// Parse an arm instruction mnemonic followed by its operands.
3314 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
3315                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3316   // Create the leading tokens for the mnemonic, split by '.' characters.
3317   size_t Start = 0, Next = Name.find('.');
3318   StringRef Mnemonic = Name.slice(Start, Next);
3319
3320   // Split out the predication code and carry setting flag from the mnemonic.
3321   unsigned PredicationCode;
3322   unsigned ProcessorIMod;
3323   bool CarrySetting;
3324   StringRef ITMask;
3325   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
3326                            ProcessorIMod, ITMask);
3327
3328   // In Thumb1, only the branch (B) instruction can be predicated.
3329   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
3330     Parser.EatToEndOfStatement();
3331     return Error(NameLoc, "conditional execution not supported in Thumb1");
3332   }
3333
3334   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
3335
3336   // Handle the IT instruction ITMask. Convert it to a bitmask. This
3337   // is the mask as it will be for the IT encoding if the conditional
3338   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
3339   // where the conditional bit0 is zero, the instruction post-processing
3340   // will adjust the mask accordingly.
3341   if (Mnemonic == "it") {
3342     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
3343     if (ITMask.size() > 3) {
3344       Parser.EatToEndOfStatement();
3345       return Error(Loc, "too many conditions on IT instruction");
3346     }
3347     unsigned Mask = 8;
3348     for (unsigned i = ITMask.size(); i != 0; --i) {
3349       char pos = ITMask[i - 1];
3350       if (pos != 't' && pos != 'e') {
3351         Parser.EatToEndOfStatement();
3352         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
3353       }
3354       Mask >>= 1;
3355       if (ITMask[i - 1] == 't')
3356         Mask |= 8;
3357     }
3358     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
3359   }
3360
3361   // FIXME: This is all a pretty gross hack. We should automatically handle
3362   // optional operands like this via tblgen.
3363
3364   // Next, add the CCOut and ConditionCode operands, if needed.
3365   //
3366   // For mnemonics which can ever incorporate a carry setting bit or predication
3367   // code, our matching model involves us always generating CCOut and
3368   // ConditionCode operands to match the mnemonic "as written" and then we let
3369   // the matcher deal with finding the right instruction or generating an
3370   // appropriate error.
3371   bool CanAcceptCarrySet, CanAcceptPredicationCode;
3372   getMnemonicAcceptInfo(Mnemonic, CanAcceptCarrySet, CanAcceptPredicationCode);
3373
3374   // If we had a carry-set on an instruction that can't do that, issue an
3375   // error.
3376   if (!CanAcceptCarrySet && CarrySetting) {
3377     Parser.EatToEndOfStatement();
3378     return Error(NameLoc, "instruction '" + Mnemonic +
3379                  "' can not set flags, but 's' suffix specified");
3380   }
3381   // If we had a predication code on an instruction that can't do that, issue an
3382   // error.
3383   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
3384     Parser.EatToEndOfStatement();
3385     return Error(NameLoc, "instruction '" + Mnemonic +
3386                  "' is not predicable, but condition code specified");
3387   }
3388
3389   // Add the carry setting operand, if necessary.
3390   if (CanAcceptCarrySet) {
3391     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
3392     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
3393                                                Loc));
3394   }
3395
3396   // Add the predication code operand, if necessary.
3397   if (CanAcceptPredicationCode) {
3398     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
3399                                       CarrySetting);
3400     Operands.push_back(ARMOperand::CreateCondCode(
3401                          ARMCC::CondCodes(PredicationCode), Loc));
3402   }
3403
3404   // Add the processor imod operand, if necessary.
3405   if (ProcessorIMod) {
3406     Operands.push_back(ARMOperand::CreateImm(
3407           MCConstantExpr::Create(ProcessorIMod, getContext()),
3408                                  NameLoc, NameLoc));
3409   }
3410
3411   // Add the remaining tokens in the mnemonic.
3412   while (Next != StringRef::npos) {
3413     Start = Next;
3414     Next = Name.find('.', Start + 1);
3415     StringRef ExtraToken = Name.slice(Start, Next);
3416
3417     // For now, we're only parsing Thumb1 (for the most part), so
3418     // just ignore ".n" qualifiers. We'll use them to restrict
3419     // matching when we do Thumb2.
3420     if (ExtraToken != ".n") {
3421       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
3422       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
3423     }
3424   }
3425
3426   // Read the remaining operands.
3427   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3428     // Read the first operand.
3429     if (parseOperand(Operands, Mnemonic)) {
3430       Parser.EatToEndOfStatement();
3431       return true;
3432     }
3433
3434     while (getLexer().is(AsmToken::Comma)) {
3435       Parser.Lex();  // Eat the comma.
3436
3437       // Parse and remember the operand.
3438       if (parseOperand(Operands, Mnemonic)) {
3439         Parser.EatToEndOfStatement();
3440         return true;
3441       }
3442     }
3443   }
3444
3445   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3446     Parser.EatToEndOfStatement();
3447     return TokError("unexpected token in argument list");
3448   }
3449
3450   Parser.Lex(); // Consume the EndOfStatement
3451
3452   // Some instructions, mostly Thumb, have forms for the same mnemonic that
3453   // do and don't have a cc_out optional-def operand. With some spot-checks
3454   // of the operand list, we can figure out which variant we're trying to
3455   // parse and adjust accordingly before actually matching. We shouldn't ever
3456   // try to remove a cc_out operand that was explicitly set on the the
3457   // mnemonic, of course (CarrySetting == true). Reason number #317 the
3458   // table driven matcher doesn't fit well with the ARM instruction set.
3459   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands)) {
3460     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3461     Operands.erase(Operands.begin() + 1);
3462     delete Op;
3463   }
3464
3465   // ARM mode 'blx' need special handling, as the register operand version
3466   // is predicable, but the label operand version is not. So, we can't rely
3467   // on the Mnemonic based checking to correctly figure out when to put
3468   // a CondCode operand in the list. If we're trying to match the label
3469   // version, remove the CondCode operand here.
3470   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
3471       static_cast<ARMOperand*>(Operands[2])->isImm()) {
3472     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3473     Operands.erase(Operands.begin() + 1);
3474     delete Op;
3475   }
3476
3477   // The vector-compare-to-zero instructions have a literal token "#0" at
3478   // the end that comes to here as an immediate operand. Convert it to a
3479   // token to play nicely with the matcher.
3480   if ((Mnemonic == "vceq" || Mnemonic == "vcge" || Mnemonic == "vcgt" ||
3481       Mnemonic == "vcle" || Mnemonic == "vclt") && Operands.size() == 6 &&
3482       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3483     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
3484     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3485     if (CE && CE->getValue() == 0) {
3486       Operands.erase(Operands.begin() + 5);
3487       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3488       delete Op;
3489     }
3490   }
3491   // Similarly, the Thumb1 "RSB" instruction has a literal "#0" on the
3492   // end. Convert it to a token here.
3493   if (Mnemonic == "rsb" && isThumb() && Operands.size() == 6 &&
3494       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3495     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
3496     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3497     if (CE && CE->getValue() == 0) {
3498       Operands.erase(Operands.begin() + 5);
3499       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3500       delete Op;
3501     }
3502   }
3503
3504   return false;
3505 }
3506
3507 // Validate context-sensitive operand constraints.
3508
3509 // return 'true' if register list contains non-low GPR registers,
3510 // 'false' otherwise. If Reg is in the register list or is HiReg, set
3511 // 'containsReg' to true.
3512 static bool checkLowRegisterList(MCInst Inst, unsigned OpNo, unsigned Reg,
3513                                  unsigned HiReg, bool &containsReg) {
3514   containsReg = false;
3515   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
3516     unsigned OpReg = Inst.getOperand(i).getReg();
3517     if (OpReg == Reg)
3518       containsReg = true;
3519     // Anything other than a low register isn't legal here.
3520     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
3521       return true;
3522   }
3523   return false;
3524 }
3525
3526 // Check if the specified regisgter is in the register list of the inst,
3527 // starting at the indicated operand number.
3528 static bool listContainsReg(MCInst &Inst, unsigned OpNo, unsigned Reg) {
3529   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
3530     unsigned OpReg = Inst.getOperand(i).getReg();
3531     if (OpReg == Reg)
3532       return true;
3533   }
3534   return false;
3535 }
3536
3537 // FIXME: We would really prefer to have MCInstrInfo (the wrapper around
3538 // the ARMInsts array) instead. Getting that here requires awkward
3539 // API changes, though. Better way?
3540 namespace llvm {
3541 extern MCInstrDesc ARMInsts[];
3542 }
3543 static MCInstrDesc &getInstDesc(unsigned Opcode) {
3544   return ARMInsts[Opcode];
3545 }
3546
3547 // FIXME: We would really like to be able to tablegen'erate this.
3548 bool ARMAsmParser::
3549 validateInstruction(MCInst &Inst,
3550                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3551   MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
3552   SMLoc Loc = Operands[0]->getStartLoc();
3553   // Check the IT block state first.
3554   // NOTE: In Thumb mode, the BKPT instruction has the interesting property of
3555   // being allowed in IT blocks, but not being predicable.  It just always
3556   // executes.
3557   if (inITBlock() && Inst.getOpcode() != ARM::tBKPT) {
3558     unsigned bit = 1;
3559     if (ITState.FirstCond)
3560       ITState.FirstCond = false;
3561     else
3562       bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
3563     // The instruction must be predicable.
3564     if (!MCID.isPredicable())
3565       return Error(Loc, "instructions in IT block must be predicable");
3566     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
3567     unsigned ITCond = bit ? ITState.Cond :
3568       ARMCC::getOppositeCondition(ITState.Cond);
3569     if (Cond != ITCond) {
3570       // Find the condition code Operand to get its SMLoc information.
3571       SMLoc CondLoc;
3572       for (unsigned i = 1; i < Operands.size(); ++i)
3573         if (static_cast<ARMOperand*>(Operands[i])->isCondCode())
3574           CondLoc = Operands[i]->getStartLoc();
3575       return Error(CondLoc, "incorrect condition in IT block; got '" +
3576                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
3577                    "', but expected '" +
3578                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
3579     }
3580   // Check for non-'al' condition codes outside of the IT block.
3581   } else if (isThumbTwo() && MCID.isPredicable() &&
3582              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
3583              ARMCC::AL && Inst.getOpcode() != ARM::tB &&
3584              Inst.getOpcode() != ARM::t2B)
3585     return Error(Loc, "predicated instructions must be in IT block");
3586
3587   switch (Inst.getOpcode()) {
3588   case ARM::LDRD:
3589   case ARM::LDRD_PRE:
3590   case ARM::LDRD_POST:
3591   case ARM::LDREXD: {
3592     // Rt2 must be Rt + 1.
3593     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
3594     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3595     if (Rt2 != Rt + 1)
3596       return Error(Operands[3]->getStartLoc(),
3597                    "destination operands must be sequential");
3598     return false;
3599   }
3600   case ARM::STRD: {
3601     // Rt2 must be Rt + 1.
3602     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
3603     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3604     if (Rt2 != Rt + 1)
3605       return Error(Operands[3]->getStartLoc(),
3606                    "source operands must be sequential");
3607     return false;
3608   }
3609   case ARM::STRD_PRE:
3610   case ARM::STRD_POST:
3611   case ARM::STREXD: {
3612     // Rt2 must be Rt + 1.
3613     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3614     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(2).getReg());
3615     if (Rt2 != Rt + 1)
3616       return Error(Operands[3]->getStartLoc(),
3617                    "source operands must be sequential");
3618     return false;
3619   }
3620   case ARM::SBFX:
3621   case ARM::UBFX: {
3622     // width must be in range [1, 32-lsb]
3623     unsigned lsb = Inst.getOperand(2).getImm();
3624     unsigned widthm1 = Inst.getOperand(3).getImm();
3625     if (widthm1 >= 32 - lsb)
3626       return Error(Operands[5]->getStartLoc(),
3627                    "bitfield width must be in range [1,32-lsb]");
3628     return false;
3629   }
3630   case ARM::tLDMIA: {
3631     // If we're parsing Thumb2, the .w variant is available and handles
3632     // most cases that are normally illegal for a Thumb1 LDM
3633     // instruction. We'll make the transformation in processInstruction()
3634     // if necessary.
3635     //
3636     // Thumb LDM instructions are writeback iff the base register is not
3637     // in the register list.
3638     unsigned Rn = Inst.getOperand(0).getReg();
3639     bool hasWritebackToken =
3640       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
3641        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
3642     bool listContainsBase;
3643     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) && !isThumbTwo())
3644       return Error(Operands[3 + hasWritebackToken]->getStartLoc(),
3645                    "registers must be in range r0-r7");
3646     // If we should have writeback, then there should be a '!' token.
3647     if (!listContainsBase && !hasWritebackToken && !isThumbTwo())
3648       return Error(Operands[2]->getStartLoc(),
3649                    "writeback operator '!' expected");
3650     // If we should not have writeback, there must not be a '!'. This is
3651     // true even for the 32-bit wide encodings.
3652     if (listContainsBase && hasWritebackToken)
3653       return Error(Operands[3]->getStartLoc(),
3654                    "writeback operator '!' not allowed when base register "
3655                    "in register list");
3656
3657     break;
3658   }
3659   case ARM::t2LDMIA_UPD: {
3660     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
3661       return Error(Operands[4]->getStartLoc(),
3662                    "writeback operator '!' not allowed when base register "
3663                    "in register list");
3664     break;
3665   }
3666   case ARM::tPOP: {
3667     bool listContainsBase;
3668     if (checkLowRegisterList(Inst, 3, 0, ARM::PC, listContainsBase))
3669       return Error(Operands[2]->getStartLoc(),
3670                    "registers must be in range r0-r7 or pc");
3671     break;
3672   }
3673   case ARM::tPUSH: {
3674     bool listContainsBase;
3675     if (checkLowRegisterList(Inst, 3, 0, ARM::LR, listContainsBase))
3676       return Error(Operands[2]->getStartLoc(),
3677                    "registers must be in range r0-r7 or lr");
3678     break;
3679   }
3680   case ARM::tSTMIA_UPD: {
3681     bool listContainsBase;
3682     if (checkLowRegisterList(Inst, 4, 0, 0, listContainsBase) && !isThumbTwo())
3683       return Error(Operands[4]->getStartLoc(),
3684                    "registers must be in range r0-r7");
3685     break;
3686   }
3687   }
3688
3689   return false;
3690 }
3691
3692 void ARMAsmParser::
3693 processInstruction(MCInst &Inst,
3694                    const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3695   switch (Inst.getOpcode()) {
3696   case ARM::LDMIA_UPD:
3697     // If this is a load of a single register via a 'pop', then we should use
3698     // a post-indexed LDR instruction instead, per the ARM ARM.
3699     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "pop" &&
3700         Inst.getNumOperands() == 5) {
3701       MCInst TmpInst;
3702       TmpInst.setOpcode(ARM::LDR_POST_IMM);
3703       TmpInst.addOperand(Inst.getOperand(4)); // Rt
3704       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
3705       TmpInst.addOperand(Inst.getOperand(1)); // Rn
3706       TmpInst.addOperand(MCOperand::CreateReg(0));  // am2offset
3707       TmpInst.addOperand(MCOperand::CreateImm(4));
3708       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
3709       TmpInst.addOperand(Inst.getOperand(3));
3710       Inst = TmpInst;
3711     }
3712     break;
3713   case ARM::STMDB_UPD:
3714     // If this is a store of a single register via a 'push', then we should use
3715     // a pre-indexed STR instruction instead, per the ARM ARM.
3716     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "push" &&
3717         Inst.getNumOperands() == 5) {
3718       MCInst TmpInst;
3719       TmpInst.setOpcode(ARM::STR_PRE_IMM);
3720       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
3721       TmpInst.addOperand(Inst.getOperand(4)); // Rt
3722       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
3723       TmpInst.addOperand(MCOperand::CreateImm(-4));
3724       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
3725       TmpInst.addOperand(Inst.getOperand(3));
3726       Inst = TmpInst;
3727     }
3728     break;
3729   case ARM::tADDi8:
3730     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
3731     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
3732     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
3733     // to encoding T1 if <Rd> is omitted."
3734     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6)
3735       Inst.setOpcode(ARM::tADDi3);
3736     break;
3737   case ARM::tB:
3738     // A Thumb conditional branch outside of an IT block is a tBcc.
3739     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
3740       Inst.setOpcode(ARM::tBcc);
3741     break;
3742   case ARM::t2B:
3743     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
3744     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
3745       Inst.setOpcode(ARM::t2Bcc);
3746     break;
3747   case ARM::t2Bcc:
3748     // If the conditional is AL or we're in an IT block, we really want t2B.
3749     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock())
3750       Inst.setOpcode(ARM::t2B);
3751     break;
3752   case ARM::tBcc:
3753     // If the conditional is AL, we really want tB.
3754     if (Inst.getOperand(1).getImm() == ARMCC::AL)
3755       Inst.setOpcode(ARM::tB);
3756     break;
3757   case ARM::tLDMIA: {
3758     // If the register list contains any high registers, or if the writeback
3759     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
3760     // instead if we're in Thumb2. Otherwise, this should have generated
3761     // an error in validateInstruction().
3762     unsigned Rn = Inst.getOperand(0).getReg();
3763     bool hasWritebackToken =
3764       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
3765        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
3766     bool listContainsBase;
3767     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
3768         (!listContainsBase && !hasWritebackToken) ||
3769         (listContainsBase && hasWritebackToken)) {
3770       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
3771       assert (isThumbTwo());
3772       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
3773       // If we're switching to the updating version, we need to insert
3774       // the writeback tied operand.
3775       if (hasWritebackToken)
3776         Inst.insert(Inst.begin(),
3777                     MCOperand::CreateReg(Inst.getOperand(0).getReg()));
3778     }
3779     break;
3780   }
3781   case ARM::tSTMIA_UPD: {
3782     // If the register list contains any high registers, we need to use
3783     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
3784     // should have generated an error in validateInstruction().
3785     unsigned Rn = Inst.getOperand(0).getReg();
3786     bool listContainsBase;
3787     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
3788       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
3789       assert (isThumbTwo());
3790       Inst.setOpcode(ARM::t2STMIA_UPD);
3791     }
3792     break;
3793   }
3794   case ARM::t2MOVi: {
3795     // If we can use the 16-bit encoding and the user didn't explicitly
3796     // request the 32-bit variant, transform it here.
3797     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3798         Inst.getOperand(1).getImm() <= 255 &&
3799         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
3800          Inst.getOperand(4).getReg() == ARM::CPSR) ||
3801         (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
3802         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3803          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3804       // The operands aren't in the same order for tMOVi8...
3805       MCInst TmpInst;
3806       TmpInst.setOpcode(ARM::tMOVi8);
3807       TmpInst.addOperand(Inst.getOperand(0));
3808       TmpInst.addOperand(Inst.getOperand(4));
3809       TmpInst.addOperand(Inst.getOperand(1));
3810       TmpInst.addOperand(Inst.getOperand(2));
3811       TmpInst.addOperand(Inst.getOperand(3));
3812       Inst = TmpInst;
3813     }
3814     break;
3815   }
3816   case ARM::t2MOVr: {
3817     // If we can use the 16-bit encoding and the user didn't explicitly
3818     // request the 32-bit variant, transform it here.
3819     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3820         isARMLowRegister(Inst.getOperand(1).getReg()) &&
3821         Inst.getOperand(2).getImm() == ARMCC::AL &&
3822         Inst.getOperand(4).getReg() == ARM::CPSR &&
3823         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3824          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3825       // The operands aren't the same for tMOV[S]r... (no cc_out)
3826       MCInst TmpInst;
3827       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
3828       TmpInst.addOperand(Inst.getOperand(0));
3829       TmpInst.addOperand(Inst.getOperand(1));
3830       TmpInst.addOperand(Inst.getOperand(2));
3831       TmpInst.addOperand(Inst.getOperand(3));
3832       Inst = TmpInst;
3833     }
3834     break;
3835   }
3836   case ARM::t2IT: {
3837     // The mask bits for all but the first condition are represented as
3838     // the low bit of the condition code value implies 't'. We currently
3839     // always have 1 implies 't', so XOR toggle the bits if the low bit
3840     // of the condition code is zero. The encoding also expects the low
3841     // bit of the condition to be encoded as bit 4 of the mask operand,
3842     // so mask that in if needed
3843     MCOperand &MO = Inst.getOperand(1);
3844     unsigned Mask = MO.getImm();
3845     unsigned OrigMask = Mask;
3846     unsigned TZ = CountTrailingZeros_32(Mask);
3847     if ((Inst.getOperand(0).getImm() & 1) == 0) {
3848       assert(Mask && TZ <= 3 && "illegal IT mask value!");
3849       for (unsigned i = 3; i != TZ; --i)
3850         Mask ^= 1 << i;
3851     } else
3852       Mask |= 0x10;
3853     MO.setImm(Mask);
3854
3855     // Set up the IT block state according to the IT instruction we just
3856     // matched.
3857     assert(!inITBlock() && "nested IT blocks?!");
3858     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
3859     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
3860     ITState.CurPosition = 0;
3861     ITState.FirstCond = true;
3862     break;
3863   }
3864   }
3865 }
3866
3867 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3868   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
3869   // suffix depending on whether they're in an IT block or not.
3870   unsigned Opc = Inst.getOpcode();
3871   MCInstrDesc &MCID = getInstDesc(Opc);
3872   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
3873     assert(MCID.hasOptionalDef() &&
3874            "optionally flag setting instruction missing optional def operand");
3875     assert(MCID.NumOperands == Inst.getNumOperands() &&
3876            "operand count mismatch!");
3877     // Find the optional-def operand (cc_out).
3878     unsigned OpNo;
3879     for (OpNo = 0;
3880          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
3881          ++OpNo)
3882       ;
3883     // If we're parsing Thumb1, reject it completely.
3884     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
3885       return Match_MnemonicFail;
3886     // If we're parsing Thumb2, which form is legal depends on whether we're
3887     // in an IT block.
3888     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
3889         !inITBlock())
3890       return Match_RequiresITBlock;
3891     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
3892         inITBlock())
3893       return Match_RequiresNotITBlock;
3894   }
3895   // Some high-register supporting Thumb1 encodings only allow both registers
3896   // to be from r0-r7 when in Thumb2.
3897   else if (Opc == ARM::tADDhirr && isThumbOne() &&
3898            isARMLowRegister(Inst.getOperand(1).getReg()) &&
3899            isARMLowRegister(Inst.getOperand(2).getReg()))
3900     return Match_RequiresThumb2;
3901   // Others only require ARMv6 or later.
3902   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
3903            isARMLowRegister(Inst.getOperand(0).getReg()) &&
3904            isARMLowRegister(Inst.getOperand(1).getReg()))
3905     return Match_RequiresV6;
3906   return Match_Success;
3907 }
3908
3909 bool ARMAsmParser::
3910 MatchAndEmitInstruction(SMLoc IDLoc,
3911                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
3912                         MCStreamer &Out) {
3913   MCInst Inst;
3914   unsigned ErrorInfo;
3915   unsigned MatchResult;
3916   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
3917   switch (MatchResult) {
3918   default: break;
3919   case Match_Success:
3920     // Context sensitive operand constraints aren't handled by the matcher,
3921     // so check them here.
3922     if (validateInstruction(Inst, Operands)) {
3923       // Still progress the IT block, otherwise one wrong condition causes
3924       // nasty cascading errors.
3925       forwardITPosition();
3926       return true;
3927     }
3928
3929     // Some instructions need post-processing to, for example, tweak which
3930     // encoding is selected.
3931     processInstruction(Inst, Operands);
3932
3933     // Only move forward at the very end so that everything in validate
3934     // and process gets a consistent answer about whether we're in an IT
3935     // block.
3936     forwardITPosition();
3937
3938     Out.EmitInstruction(Inst);
3939     return false;
3940   case Match_MissingFeature:
3941     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
3942     return true;
3943   case Match_InvalidOperand: {
3944     SMLoc ErrorLoc = IDLoc;
3945     if (ErrorInfo != ~0U) {
3946       if (ErrorInfo >= Operands.size())
3947         return Error(IDLoc, "too few operands for instruction");
3948
3949       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
3950       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
3951     }
3952
3953     return Error(ErrorLoc, "invalid operand for instruction");
3954   }
3955   case Match_MnemonicFail:
3956     return Error(IDLoc, "invalid instruction");
3957   case Match_ConversionFail:
3958     // The converter function will have already emited a diagnostic.
3959     return true;
3960   case Match_RequiresNotITBlock:
3961     return Error(IDLoc, "flag setting instruction only valid outside IT block");
3962   case Match_RequiresITBlock:
3963     return Error(IDLoc, "instruction only valid inside IT block");
3964   case Match_RequiresV6:
3965     return Error(IDLoc, "instruction variant requires ARMv6 or later");
3966   case Match_RequiresThumb2:
3967     return Error(IDLoc, "instruction variant requires Thumb2");
3968   }
3969
3970   llvm_unreachable("Implement any new match types added!");
3971   return true;
3972 }
3973
3974 /// parseDirective parses the arm specific directives
3975 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
3976   StringRef IDVal = DirectiveID.getIdentifier();
3977   if (IDVal == ".word")
3978     return parseDirectiveWord(4, DirectiveID.getLoc());
3979   else if (IDVal == ".thumb")
3980     return parseDirectiveThumb(DirectiveID.getLoc());
3981   else if (IDVal == ".thumb_func")
3982     return parseDirectiveThumbFunc(DirectiveID.getLoc());
3983   else if (IDVal == ".code")
3984     return parseDirectiveCode(DirectiveID.getLoc());
3985   else if (IDVal == ".syntax")
3986     return parseDirectiveSyntax(DirectiveID.getLoc());
3987   return true;
3988 }
3989
3990 /// parseDirectiveWord
3991 ///  ::= .word [ expression (, expression)* ]
3992 bool ARMAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
3993   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3994     for (;;) {
3995       const MCExpr *Value;
3996       if (getParser().ParseExpression(Value))
3997         return true;
3998
3999       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
4000
4001       if (getLexer().is(AsmToken::EndOfStatement))
4002         break;
4003
4004       // FIXME: Improve diagnostic.
4005       if (getLexer().isNot(AsmToken::Comma))
4006         return Error(L, "unexpected token in directive");
4007       Parser.Lex();
4008     }
4009   }
4010
4011   Parser.Lex();
4012   return false;
4013 }
4014
4015 /// parseDirectiveThumb
4016 ///  ::= .thumb
4017 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
4018   if (getLexer().isNot(AsmToken::EndOfStatement))
4019     return Error(L, "unexpected token in directive");
4020   Parser.Lex();
4021
4022   // TODO: set thumb mode
4023   // TODO: tell the MC streamer the mode
4024   // getParser().getStreamer().Emit???();
4025   return false;
4026 }
4027
4028 /// parseDirectiveThumbFunc
4029 ///  ::= .thumbfunc symbol_name
4030 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
4031   const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
4032   bool isMachO = MAI.hasSubsectionsViaSymbols();
4033   StringRef Name;
4034
4035   // Darwin asm has function name after .thumb_func direction
4036   // ELF doesn't
4037   if (isMachO) {
4038     const AsmToken &Tok = Parser.getTok();
4039     if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
4040       return Error(L, "unexpected token in .thumb_func directive");
4041     Name = Tok.getString();
4042     Parser.Lex(); // Consume the identifier token.
4043   }
4044
4045   if (getLexer().isNot(AsmToken::EndOfStatement))
4046     return Error(L, "unexpected token in directive");
4047   Parser.Lex();
4048
4049   // FIXME: assuming function name will be the line following .thumb_func
4050   if (!isMachO) {
4051     Name = Parser.getTok().getString();
4052   }
4053
4054   // Mark symbol as a thumb symbol.
4055   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
4056   getParser().getStreamer().EmitThumbFunc(Func);
4057   return false;
4058 }
4059
4060 /// parseDirectiveSyntax
4061 ///  ::= .syntax unified | divided
4062 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
4063   const AsmToken &Tok = Parser.getTok();
4064   if (Tok.isNot(AsmToken::Identifier))
4065     return Error(L, "unexpected token in .syntax directive");
4066   StringRef Mode = Tok.getString();
4067   if (Mode == "unified" || Mode == "UNIFIED")
4068     Parser.Lex();
4069   else if (Mode == "divided" || Mode == "DIVIDED")
4070     return Error(L, "'.syntax divided' arm asssembly not supported");
4071   else
4072     return Error(L, "unrecognized syntax mode in .syntax directive");
4073
4074   if (getLexer().isNot(AsmToken::EndOfStatement))
4075     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4076   Parser.Lex();
4077
4078   // TODO tell the MC streamer the mode
4079   // getParser().getStreamer().Emit???();
4080   return false;
4081 }
4082
4083 /// parseDirectiveCode
4084 ///  ::= .code 16 | 32
4085 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
4086   const AsmToken &Tok = Parser.getTok();
4087   if (Tok.isNot(AsmToken::Integer))
4088     return Error(L, "unexpected token in .code directive");
4089   int64_t Val = Parser.getTok().getIntVal();
4090   if (Val == 16)
4091     Parser.Lex();
4092   else if (Val == 32)
4093     Parser.Lex();
4094   else
4095     return Error(L, "invalid operand to .code directive");
4096
4097   if (getLexer().isNot(AsmToken::EndOfStatement))
4098     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4099   Parser.Lex();
4100
4101   if (Val == 16) {
4102     if (!isThumb())
4103       SwitchMode();
4104     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
4105   } else {
4106     if (isThumb())
4107       SwitchMode();
4108     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
4109   }
4110
4111   return false;
4112 }
4113
4114 extern "C" void LLVMInitializeARMAsmLexer();
4115
4116 /// Force static initialization.
4117 extern "C" void LLVMInitializeARMAsmParser() {
4118   RegisterMCAsmParser<ARMAsmParser> X(TheARMTarget);
4119   RegisterMCAsmParser<ARMAsmParser> Y(TheThumbTarget);
4120   LLVMInitializeARMAsmLexer();
4121 }
4122
4123 #define GET_REGISTER_MATCHER
4124 #define GET_MATCHER_IMPLEMENTATION
4125 #include "ARMGenAsmMatcher.inc"