ARM thumb assembly parsing for arithmetic flag setting instructions.
[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/MCRegisterInfo.h"
22 #include "llvm/MC/MCSubtargetInfo.h"
23 #include "llvm/MC/MCTargetAsmParser.h"
24 #include "llvm/Target/TargetRegistry.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/ADT/OwningPtr.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33
34 using namespace llvm;
35
36 namespace {
37
38 class ARMOperand;
39
40 class ARMAsmParser : public MCTargetAsmParser {
41   MCSubtargetInfo &STI;
42   MCAsmParser &Parser;
43
44   MCAsmParser &getParser() const { return Parser; }
45   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
46
47   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
48   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
49
50   int tryParseRegister();
51   bool tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
52   int tryParseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
53   bool parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
54   bool parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
55   bool parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
56   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
57   const MCExpr *applyPrefixToExpr(const MCExpr *E,
58                                   MCSymbolRefExpr::VariantKind Variant);
59
60
61   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
62                               unsigned &ShiftAmount);
63   bool parseDirectiveWord(unsigned Size, SMLoc L);
64   bool parseDirectiveThumb(SMLoc L);
65   bool parseDirectiveThumbFunc(SMLoc L);
66   bool parseDirectiveCode(SMLoc L);
67   bool parseDirectiveSyntax(SMLoc L);
68
69   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
70                           bool &CarrySetting, unsigned &ProcessorIMod);
71   void getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
72                              bool &CanAcceptPredicationCode);
73
74   bool isThumb() const {
75     // FIXME: Can tablegen auto-generate this?
76     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
77   }
78   bool isThumbOne() const {
79     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
80   }
81   bool isThumbTwo() const {
82     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2);
83   }
84   void SwitchMode() {
85     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
86     setAvailableFeatures(FB);
87   }
88
89   /// @name Auto-generated Match Functions
90   /// {
91
92 #define GET_ASSEMBLER_HEADER
93 #include "ARMGenAsmMatcher.inc"
94
95   /// }
96
97   OperandMatchResultTy parseCoprocNumOperand(
98     SmallVectorImpl<MCParsedAsmOperand*>&);
99   OperandMatchResultTy parseCoprocRegOperand(
100     SmallVectorImpl<MCParsedAsmOperand*>&);
101   OperandMatchResultTy parseMemBarrierOptOperand(
102     SmallVectorImpl<MCParsedAsmOperand*>&);
103   OperandMatchResultTy parseProcIFlagsOperand(
104     SmallVectorImpl<MCParsedAsmOperand*>&);
105   OperandMatchResultTy parseMSRMaskOperand(
106     SmallVectorImpl<MCParsedAsmOperand*>&);
107   OperandMatchResultTy parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &O,
108                                    StringRef Op, int Low, int High);
109   OperandMatchResultTy parsePKHLSLImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
110     return parsePKHImm(O, "lsl", 0, 31);
111   }
112   OperandMatchResultTy parsePKHASRImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
113     return parsePKHImm(O, "asr", 1, 32);
114   }
115   OperandMatchResultTy parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*>&);
116   OperandMatchResultTy parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*>&);
117   OperandMatchResultTy parseRotImm(SmallVectorImpl<MCParsedAsmOperand*>&);
118   OperandMatchResultTy parseBitfield(SmallVectorImpl<MCParsedAsmOperand*>&);
119   OperandMatchResultTy parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*>&);
120   OperandMatchResultTy parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*>&);
121
122   // Asm Match Converter Methods
123   bool cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
124                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
125   bool cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
126                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
127   bool cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
128                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
129   bool cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
130                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
131   bool cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
132                              const SmallVectorImpl<MCParsedAsmOperand*> &);
133   bool cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
134                              const SmallVectorImpl<MCParsedAsmOperand*> &);
135   bool cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
136                              const SmallVectorImpl<MCParsedAsmOperand*> &);
137   bool cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
138                              const SmallVectorImpl<MCParsedAsmOperand*> &);
139   bool cvtLdrdPre(MCInst &Inst, unsigned Opcode,
140                   const SmallVectorImpl<MCParsedAsmOperand*> &);
141   bool cvtStrdPre(MCInst &Inst, unsigned Opcode,
142                   const SmallVectorImpl<MCParsedAsmOperand*> &);
143   bool cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
144                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
145
146   bool validateInstruction(MCInst &Inst,
147                            const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
148   void processInstruction(MCInst &Inst,
149                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
150
151 public:
152   enum ARMMatchResultTy {
153     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY
154   };
155
156   ARMAsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser)
157     : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
158     MCAsmParserExtension::Initialize(_Parser);
159
160     // Initialize the set of available features.
161     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
162   }
163
164   // Implementation of the MCTargetAsmParser interface:
165   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
166   bool ParseInstruction(StringRef Name, SMLoc NameLoc,
167                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
168   bool ParseDirective(AsmToken DirectiveID);
169
170   unsigned checkTargetMatchPredicate(MCInst &Inst);
171
172   bool MatchAndEmitInstruction(SMLoc IDLoc,
173                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
174                                MCStreamer &Out);
175 };
176 } // end anonymous namespace
177
178 namespace {
179
180 /// ARMOperand - Instances of this class represent a parsed ARM machine
181 /// instruction.
182 class ARMOperand : public MCParsedAsmOperand {
183   enum KindTy {
184     CondCode,
185     CCOut,
186     CoprocNum,
187     CoprocReg,
188     Immediate,
189     MemBarrierOpt,
190     Memory,
191     PostIndexRegister,
192     MSRMask,
193     ProcIFlags,
194     Register,
195     RegisterList,
196     DPRRegisterList,
197     SPRRegisterList,
198     ShiftedRegister,
199     ShiftedImmediate,
200     ShifterImmediate,
201     RotateImmediate,
202     BitfieldDescriptor,
203     Token
204   } Kind;
205
206   SMLoc StartLoc, EndLoc;
207   SmallVector<unsigned, 8> Registers;
208
209   union {
210     struct {
211       ARMCC::CondCodes Val;
212     } CC;
213
214     struct {
215       ARM_MB::MemBOpt Val;
216     } MBOpt;
217
218     struct {
219       unsigned Val;
220     } Cop;
221
222     struct {
223       ARM_PROC::IFlags Val;
224     } IFlags;
225
226     struct {
227       unsigned Val;
228     } MMask;
229
230     struct {
231       const char *Data;
232       unsigned Length;
233     } Tok;
234
235     struct {
236       unsigned RegNum;
237     } Reg;
238
239     struct {
240       const MCExpr *Val;
241     } Imm;
242
243     /// Combined record for all forms of ARM address expressions.
244     struct {
245       unsigned BaseRegNum;
246       // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
247       // was specified.
248       const MCConstantExpr *OffsetImm;  // Offset immediate value
249       unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
250       ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
251       unsigned ShiftImm;      // shift for OffsetReg.
252       unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
253     } Mem;
254
255     struct {
256       unsigned RegNum;
257       bool isAdd;
258       ARM_AM::ShiftOpc ShiftTy;
259       unsigned ShiftImm;
260     } PostIdxReg;
261
262     struct {
263       bool isASR;
264       unsigned Imm;
265     } ShifterImm;
266     struct {
267       ARM_AM::ShiftOpc ShiftTy;
268       unsigned SrcReg;
269       unsigned ShiftReg;
270       unsigned ShiftImm;
271     } RegShiftedReg;
272     struct {
273       ARM_AM::ShiftOpc ShiftTy;
274       unsigned SrcReg;
275       unsigned ShiftImm;
276     } RegShiftedImm;
277     struct {
278       unsigned Imm;
279     } RotImm;
280     struct {
281       unsigned LSB;
282       unsigned Width;
283     } Bitfield;
284   };
285
286   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
287 public:
288   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
289     Kind = o.Kind;
290     StartLoc = o.StartLoc;
291     EndLoc = o.EndLoc;
292     switch (Kind) {
293     case CondCode:
294       CC = o.CC;
295       break;
296     case Token:
297       Tok = o.Tok;
298       break;
299     case CCOut:
300     case Register:
301       Reg = o.Reg;
302       break;
303     case RegisterList:
304     case DPRRegisterList:
305     case SPRRegisterList:
306       Registers = o.Registers;
307       break;
308     case CoprocNum:
309     case CoprocReg:
310       Cop = o.Cop;
311       break;
312     case Immediate:
313       Imm = o.Imm;
314       break;
315     case MemBarrierOpt:
316       MBOpt = o.MBOpt;
317       break;
318     case Memory:
319       Mem = o.Mem;
320       break;
321     case PostIndexRegister:
322       PostIdxReg = o.PostIdxReg;
323       break;
324     case MSRMask:
325       MMask = o.MMask;
326       break;
327     case ProcIFlags:
328       IFlags = o.IFlags;
329       break;
330     case ShifterImmediate:
331       ShifterImm = o.ShifterImm;
332       break;
333     case ShiftedRegister:
334       RegShiftedReg = o.RegShiftedReg;
335       break;
336     case ShiftedImmediate:
337       RegShiftedImm = o.RegShiftedImm;
338       break;
339     case RotateImmediate:
340       RotImm = o.RotImm;
341       break;
342     case BitfieldDescriptor:
343       Bitfield = o.Bitfield;
344       break;
345     }
346   }
347
348   /// getStartLoc - Get the location of the first token of this operand.
349   SMLoc getStartLoc() const { return StartLoc; }
350   /// getEndLoc - Get the location of the last token of this operand.
351   SMLoc getEndLoc() const { return EndLoc; }
352
353   ARMCC::CondCodes getCondCode() const {
354     assert(Kind == CondCode && "Invalid access!");
355     return CC.Val;
356   }
357
358   unsigned getCoproc() const {
359     assert((Kind == CoprocNum || Kind == CoprocReg) && "Invalid access!");
360     return Cop.Val;
361   }
362
363   StringRef getToken() const {
364     assert(Kind == Token && "Invalid access!");
365     return StringRef(Tok.Data, Tok.Length);
366   }
367
368   unsigned getReg() const {
369     assert((Kind == Register || Kind == CCOut) && "Invalid access!");
370     return Reg.RegNum;
371   }
372
373   const SmallVectorImpl<unsigned> &getRegList() const {
374     assert((Kind == RegisterList || Kind == DPRRegisterList ||
375             Kind == SPRRegisterList) && "Invalid access!");
376     return Registers;
377   }
378
379   const MCExpr *getImm() const {
380     assert(Kind == Immediate && "Invalid access!");
381     return Imm.Val;
382   }
383
384   ARM_MB::MemBOpt getMemBarrierOpt() const {
385     assert(Kind == MemBarrierOpt && "Invalid access!");
386     return MBOpt.Val;
387   }
388
389   ARM_PROC::IFlags getProcIFlags() const {
390     assert(Kind == ProcIFlags && "Invalid access!");
391     return IFlags.Val;
392   }
393
394   unsigned getMSRMask() const {
395     assert(Kind == MSRMask && "Invalid access!");
396     return MMask.Val;
397   }
398
399   bool isCoprocNum() const { return Kind == CoprocNum; }
400   bool isCoprocReg() const { return Kind == CoprocReg; }
401   bool isCondCode() const { return Kind == CondCode; }
402   bool isCCOut() const { return Kind == CCOut; }
403   bool isImm() const { return Kind == Immediate; }
404   bool isImm0_255() const {
405     if (Kind != Immediate)
406       return false;
407     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
408     if (!CE) return false;
409     int64_t Value = CE->getValue();
410     return Value >= 0 && Value < 256;
411   }
412   bool isImm0_7() const {
413     if (Kind != Immediate)
414       return false;
415     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
416     if (!CE) return false;
417     int64_t Value = CE->getValue();
418     return Value >= 0 && Value < 8;
419   }
420   bool isImm0_15() const {
421     if (Kind != Immediate)
422       return false;
423     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
424     if (!CE) return false;
425     int64_t Value = CE->getValue();
426     return Value >= 0 && Value < 16;
427   }
428   bool isImm0_31() const {
429     if (Kind != Immediate)
430       return false;
431     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
432     if (!CE) return false;
433     int64_t Value = CE->getValue();
434     return Value >= 0 && Value < 32;
435   }
436   bool isImm1_16() const {
437     if (Kind != Immediate)
438       return false;
439     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
440     if (!CE) return false;
441     int64_t Value = CE->getValue();
442     return Value > 0 && Value < 17;
443   }
444   bool isImm1_32() const {
445     if (Kind != Immediate)
446       return false;
447     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
448     if (!CE) return false;
449     int64_t Value = CE->getValue();
450     return Value > 0 && Value < 33;
451   }
452   bool isImm0_65535() const {
453     if (Kind != Immediate)
454       return false;
455     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
456     if (!CE) return false;
457     int64_t Value = CE->getValue();
458     return Value >= 0 && Value < 65536;
459   }
460   bool isImm0_65535Expr() const {
461     if (Kind != Immediate)
462       return false;
463     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
464     // If it's not a constant expression, it'll generate a fixup and be
465     // handled later.
466     if (!CE) return true;
467     int64_t Value = CE->getValue();
468     return Value >= 0 && Value < 65536;
469   }
470   bool isImm24bit() const {
471     if (Kind != Immediate)
472       return false;
473     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
474     if (!CE) return false;
475     int64_t Value = CE->getValue();
476     return Value >= 0 && Value <= 0xffffff;
477   }
478   bool isPKHLSLImm() const {
479     if (Kind != Immediate)
480       return false;
481     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
482     if (!CE) return false;
483     int64_t Value = CE->getValue();
484     return Value >= 0 && Value < 32;
485   }
486   bool isPKHASRImm() const {
487     if (Kind != Immediate)
488       return false;
489     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
490     if (!CE) return false;
491     int64_t Value = CE->getValue();
492     return Value > 0 && Value <= 32;
493   }
494   bool isARMSOImm() const {
495     if (Kind != Immediate)
496       return false;
497     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
498     if (!CE) return false;
499     int64_t Value = CE->getValue();
500     return ARM_AM::getSOImmVal(Value) != -1;
501   }
502   bool isT2SOImm() const {
503     if (Kind != Immediate)
504       return false;
505     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
506     if (!CE) return false;
507     int64_t Value = CE->getValue();
508     return ARM_AM::getT2SOImmVal(Value) != -1;
509   }
510   bool isSetEndImm() const {
511     if (Kind != Immediate)
512       return false;
513     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
514     if (!CE) return false;
515     int64_t Value = CE->getValue();
516     return Value == 1 || Value == 0;
517   }
518   bool isReg() const { return Kind == Register; }
519   bool isRegList() const { return Kind == RegisterList; }
520   bool isDPRRegList() const { return Kind == DPRRegisterList; }
521   bool isSPRRegList() const { return Kind == SPRRegisterList; }
522   bool isToken() const { return Kind == Token; }
523   bool isMemBarrierOpt() const { return Kind == MemBarrierOpt; }
524   bool isMemory() const { return Kind == Memory; }
525   bool isShifterImm() const { return Kind == ShifterImmediate; }
526   bool isRegShiftedReg() const { return Kind == ShiftedRegister; }
527   bool isRegShiftedImm() const { return Kind == ShiftedImmediate; }
528   bool isRotImm() const { return Kind == RotateImmediate; }
529   bool isBitfield() const { return Kind == BitfieldDescriptor; }
530   bool isPostIdxRegShifted() const { return Kind == PostIndexRegister; }
531   bool isPostIdxReg() const {
532     return Kind == PostIndexRegister && PostIdxReg.ShiftTy == ARM_AM::no_shift;
533   }
534   bool isMemNoOffset() const {
535     if (Kind != Memory)
536       return false;
537     // No offset of any kind.
538     return Mem.OffsetRegNum == 0 && Mem.OffsetImm == 0;
539   }
540   bool isAddrMode2() const {
541     if (Kind != Memory)
542       return false;
543     // Check for register offset.
544     if (Mem.OffsetRegNum) return true;
545     // Immediate offset in range [-4095, 4095].
546     if (!Mem.OffsetImm) return true;
547     int64_t Val = Mem.OffsetImm->getValue();
548     return Val > -4096 && Val < 4096;
549   }
550   bool isAM2OffsetImm() const {
551     if (Kind != Immediate)
552       return false;
553     // Immediate offset in range [-4095, 4095].
554     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
555     if (!CE) return false;
556     int64_t Val = CE->getValue();
557     return Val > -4096 && Val < 4096;
558   }
559   bool isAddrMode3() const {
560     if (Kind != Memory)
561       return false;
562     // No shifts are legal for AM3.
563     if (Mem.ShiftType != ARM_AM::no_shift) return false;
564     // Check for register offset.
565     if (Mem.OffsetRegNum) return true;
566     // Immediate offset in range [-255, 255].
567     if (!Mem.OffsetImm) return true;
568     int64_t Val = Mem.OffsetImm->getValue();
569     return Val > -256 && Val < 256;
570   }
571   bool isAM3Offset() const {
572     if (Kind != Immediate && Kind != PostIndexRegister)
573       return false;
574     if (Kind == PostIndexRegister)
575       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
576     // Immediate offset in range [-255, 255].
577     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
578     if (!CE) return false;
579     int64_t Val = CE->getValue();
580     // Special case, #-0 is INT32_MIN.
581     return (Val > -256 && Val < 256) || Val == INT32_MIN;
582   }
583   bool isAddrMode5() const {
584     if (Kind != Memory)
585       return false;
586     // Check for register offset.
587     if (Mem.OffsetRegNum) return false;
588     // Immediate offset in range [-1020, 1020] and a multiple of 4.
589     if (!Mem.OffsetImm) return true;
590     int64_t Val = Mem.OffsetImm->getValue();
591     return Val >= -1020 && Val <= 1020 && ((Val & 3) == 0);
592   }
593   bool isMemRegOffset() const {
594     if (Kind != Memory || !Mem.OffsetRegNum)
595       return false;
596     return true;
597   }
598   bool isMemThumbRR() const {
599     // Thumb reg+reg addressing is simple. Just two registers, a base and
600     // an offset. No shifts, negations or any other complicating factors.
601     if (Kind != Memory || !Mem.OffsetRegNum || Mem.isNegative ||
602         Mem.ShiftType != ARM_AM::no_shift)
603       return false;
604     return true;
605   }
606   bool isMemImm8Offset() const {
607     if (Kind != Memory || Mem.OffsetRegNum != 0)
608       return false;
609     // Immediate offset in range [-255, 255].
610     if (!Mem.OffsetImm) return true;
611     int64_t Val = Mem.OffsetImm->getValue();
612     return Val > -256 && Val < 256;
613   }
614   bool isMemImm12Offset() const {
615     // If we have an immediate that's not a constant, treat it as a label
616     // reference needing a fixup. If it is a constant, it's something else
617     // and we reject it.
618     if (Kind == Immediate && !isa<MCConstantExpr>(getImm()))
619       return true;
620
621     if (Kind != Memory || Mem.OffsetRegNum != 0)
622       return false;
623     // Immediate offset in range [-4095, 4095].
624     if (!Mem.OffsetImm) return true;
625     int64_t Val = Mem.OffsetImm->getValue();
626     return Val > -4096 && Val < 4096;
627   }
628   bool isPostIdxImm8() const {
629     if (Kind != Immediate)
630       return false;
631     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
632     if (!CE) return false;
633     int64_t Val = CE->getValue();
634     return Val > -256 && Val < 256;
635   }
636
637   bool isMSRMask() const { return Kind == MSRMask; }
638   bool isProcIFlags() const { return Kind == ProcIFlags; }
639
640   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
641     // Add as immediates when possible.  Null MCExpr = 0.
642     if (Expr == 0)
643       Inst.addOperand(MCOperand::CreateImm(0));
644     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
645       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
646     else
647       Inst.addOperand(MCOperand::CreateExpr(Expr));
648   }
649
650   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
651     assert(N == 2 && "Invalid number of operands!");
652     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
653     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
654     Inst.addOperand(MCOperand::CreateReg(RegNum));
655   }
656
657   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
658     assert(N == 1 && "Invalid number of operands!");
659     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
660   }
661
662   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
663     assert(N == 1 && "Invalid number of operands!");
664     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
665   }
666
667   void addCCOutOperands(MCInst &Inst, unsigned N) const {
668     assert(N == 1 && "Invalid number of operands!");
669     Inst.addOperand(MCOperand::CreateReg(getReg()));
670   }
671
672   void addRegOperands(MCInst &Inst, unsigned N) const {
673     assert(N == 1 && "Invalid number of operands!");
674     Inst.addOperand(MCOperand::CreateReg(getReg()));
675   }
676
677   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
678     assert(N == 3 && "Invalid number of operands!");
679     assert(isRegShiftedReg() && "addRegShiftedRegOperands() on non RegShiftedReg!");
680     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
681     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
682     Inst.addOperand(MCOperand::CreateImm(
683       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
684   }
685
686   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
687     assert(N == 2 && "Invalid number of operands!");
688     assert(isRegShiftedImm() && "addRegShiftedImmOperands() on non RegShiftedImm!");
689     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
690     Inst.addOperand(MCOperand::CreateImm(
691       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, RegShiftedImm.ShiftImm)));
692   }
693
694
695   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
696     assert(N == 1 && "Invalid number of operands!");
697     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
698                                          ShifterImm.Imm));
699   }
700
701   void addRegListOperands(MCInst &Inst, unsigned N) const {
702     assert(N == 1 && "Invalid number of operands!");
703     const SmallVectorImpl<unsigned> &RegList = getRegList();
704     for (SmallVectorImpl<unsigned>::const_iterator
705            I = RegList.begin(), E = RegList.end(); I != E; ++I)
706       Inst.addOperand(MCOperand::CreateReg(*I));
707   }
708
709   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
710     addRegListOperands(Inst, N);
711   }
712
713   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
714     addRegListOperands(Inst, N);
715   }
716
717   void addRotImmOperands(MCInst &Inst, unsigned N) const {
718     assert(N == 1 && "Invalid number of operands!");
719     // Encoded as val>>3. The printer handles display as 8, 16, 24.
720     Inst.addOperand(MCOperand::CreateImm(RotImm.Imm >> 3));
721   }
722
723   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
724     assert(N == 1 && "Invalid number of operands!");
725     // Munge the lsb/width into a bitfield mask.
726     unsigned lsb = Bitfield.LSB;
727     unsigned width = Bitfield.Width;
728     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
729     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
730                       (32 - (lsb + width)));
731     Inst.addOperand(MCOperand::CreateImm(Mask));
732   }
733
734   void addImmOperands(MCInst &Inst, unsigned N) const {
735     assert(N == 1 && "Invalid number of operands!");
736     addExpr(Inst, getImm());
737   }
738
739   void addImm0_255Operands(MCInst &Inst, unsigned N) const {
740     assert(N == 1 && "Invalid number of operands!");
741     addExpr(Inst, getImm());
742   }
743
744   void addImm0_7Operands(MCInst &Inst, unsigned N) const {
745     assert(N == 1 && "Invalid number of operands!");
746     addExpr(Inst, getImm());
747   }
748
749   void addImm0_15Operands(MCInst &Inst, unsigned N) const {
750     assert(N == 1 && "Invalid number of operands!");
751     addExpr(Inst, getImm());
752   }
753
754   void addImm0_31Operands(MCInst &Inst, unsigned N) const {
755     assert(N == 1 && "Invalid number of operands!");
756     addExpr(Inst, getImm());
757   }
758
759   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
760     assert(N == 1 && "Invalid number of operands!");
761     // The constant encodes as the immediate-1, and we store in the instruction
762     // the bits as encoded, so subtract off one here.
763     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
764     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
765   }
766
767   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
768     assert(N == 1 && "Invalid number of operands!");
769     // The constant encodes as the immediate-1, and we store in the instruction
770     // the bits as encoded, so subtract off one here.
771     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
772     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
773   }
774
775   void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
776     assert(N == 1 && "Invalid number of operands!");
777     addExpr(Inst, getImm());
778   }
779
780   void addImm0_65535ExprOperands(MCInst &Inst, unsigned N) const {
781     assert(N == 1 && "Invalid number of operands!");
782     addExpr(Inst, getImm());
783   }
784
785   void addImm24bitOperands(MCInst &Inst, unsigned N) const {
786     assert(N == 1 && "Invalid number of operands!");
787     addExpr(Inst, getImm());
788   }
789
790   void addPKHLSLImmOperands(MCInst &Inst, unsigned N) const {
791     assert(N == 1 && "Invalid number of operands!");
792     addExpr(Inst, getImm());
793   }
794
795   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
796     assert(N == 1 && "Invalid number of operands!");
797     // An ASR value of 32 encodes as 0, so that's how we want to add it to
798     // the instruction as well.
799     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
800     int Val = CE->getValue();
801     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
802   }
803
804   void addARMSOImmOperands(MCInst &Inst, unsigned N) const {
805     assert(N == 1 && "Invalid number of operands!");
806     addExpr(Inst, getImm());
807   }
808
809   void addT2SOImmOperands(MCInst &Inst, unsigned N) const {
810     assert(N == 1 && "Invalid number of operands!");
811     addExpr(Inst, getImm());
812   }
813
814   void addSetEndImmOperands(MCInst &Inst, unsigned N) const {
815     assert(N == 1 && "Invalid number of operands!");
816     addExpr(Inst, getImm());
817   }
818
819   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
820     assert(N == 1 && "Invalid number of operands!");
821     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
822   }
823
824   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
825     assert(N == 1 && "Invalid number of operands!");
826     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
827   }
828
829   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
830     assert(N == 3 && "Invalid number of operands!");
831     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
832     if (!Mem.OffsetRegNum) {
833       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
834       // Special case for #-0
835       if (Val == INT32_MIN) Val = 0;
836       if (Val < 0) Val = -Val;
837       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
838     } else {
839       // For register offset, we encode the shift type and negation flag
840       // here.
841       Val = ARM_AM::getAM2Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add,
842                               Mem.ShiftImm, Mem.ShiftType);
843     }
844     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
845     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
846     Inst.addOperand(MCOperand::CreateImm(Val));
847   }
848
849   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
850     assert(N == 2 && "Invalid number of operands!");
851     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
852     assert(CE && "non-constant AM2OffsetImm operand!");
853     int32_t Val = CE->getValue();
854     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
855     // Special case for #-0
856     if (Val == INT32_MIN) Val = 0;
857     if (Val < 0) Val = -Val;
858     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
859     Inst.addOperand(MCOperand::CreateReg(0));
860     Inst.addOperand(MCOperand::CreateImm(Val));
861   }
862
863   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
864     assert(N == 3 && "Invalid number of operands!");
865     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
866     if (!Mem.OffsetRegNum) {
867       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
868       // Special case for #-0
869       if (Val == INT32_MIN) Val = 0;
870       if (Val < 0) Val = -Val;
871       Val = ARM_AM::getAM3Opc(AddSub, Val);
872     } else {
873       // For register offset, we encode the shift type and negation flag
874       // here.
875       Val = ARM_AM::getAM3Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
876     }
877     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
878     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
879     Inst.addOperand(MCOperand::CreateImm(Val));
880   }
881
882   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
883     assert(N == 2 && "Invalid number of operands!");
884     if (Kind == PostIndexRegister) {
885       int32_t Val =
886         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
887       Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
888       Inst.addOperand(MCOperand::CreateImm(Val));
889       return;
890     }
891
892     // Constant offset.
893     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
894     int32_t Val = CE->getValue();
895     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
896     // Special case for #-0
897     if (Val == INT32_MIN) Val = 0;
898     if (Val < 0) Val = -Val;
899     Val = ARM_AM::getAM3Opc(AddSub, Val);
900     Inst.addOperand(MCOperand::CreateReg(0));
901     Inst.addOperand(MCOperand::CreateImm(Val));
902   }
903
904   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
905     assert(N == 2 && "Invalid number of operands!");
906     // The lower two bits are always zero and as such are not encoded.
907     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() / 4 : 0;
908     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
909     // Special case for #-0
910     if (Val == INT32_MIN) Val = 0;
911     if (Val < 0) Val = -Val;
912     Val = ARM_AM::getAM5Opc(AddSub, Val);
913     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
914     Inst.addOperand(MCOperand::CreateImm(Val));
915   }
916
917   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
918     assert(N == 2 && "Invalid number of operands!");
919     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
920     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
921     Inst.addOperand(MCOperand::CreateImm(Val));
922   }
923
924   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
925     assert(N == 2 && "Invalid number of operands!");
926     // If this is an immediate, it's a label reference.
927     if (Kind == Immediate) {
928       addExpr(Inst, getImm());
929       Inst.addOperand(MCOperand::CreateImm(0));
930       return;
931     }
932
933     // Otherwise, it's a normal memory reg+offset.
934     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
935     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
936     Inst.addOperand(MCOperand::CreateImm(Val));
937   }
938
939   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
940     assert(N == 3 && "Invalid number of operands!");
941     unsigned Val = ARM_AM::getAM2Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add,
942                                      Mem.ShiftImm, Mem.ShiftType);
943     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
944     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
945     Inst.addOperand(MCOperand::CreateImm(Val));
946   }
947
948   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
949     assert(N == 2 && "Invalid number of operands!");
950     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
951     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
952   }
953
954   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
955     assert(N == 1 && "Invalid number of operands!");
956     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
957     assert(CE && "non-constant post-idx-imm8 operand!");
958     int Imm = CE->getValue();
959     bool isAdd = Imm >= 0;
960     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
961     Inst.addOperand(MCOperand::CreateImm(Imm));
962   }
963
964   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
965     assert(N == 2 && "Invalid number of operands!");
966     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
967     Inst.addOperand(MCOperand::CreateImm(PostIdxReg.isAdd));
968   }
969
970   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
971     assert(N == 2 && "Invalid number of operands!");
972     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
973     // The sign, shift type, and shift amount are encoded in a single operand
974     // using the AM2 encoding helpers.
975     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
976     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
977                                      PostIdxReg.ShiftTy);
978     Inst.addOperand(MCOperand::CreateImm(Imm));
979   }
980
981   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
982     assert(N == 1 && "Invalid number of operands!");
983     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
984   }
985
986   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
987     assert(N == 1 && "Invalid number of operands!");
988     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
989   }
990
991   virtual void print(raw_ostream &OS) const;
992
993   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
994     ARMOperand *Op = new ARMOperand(CondCode);
995     Op->CC.Val = CC;
996     Op->StartLoc = S;
997     Op->EndLoc = S;
998     return Op;
999   }
1000
1001   static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
1002     ARMOperand *Op = new ARMOperand(CoprocNum);
1003     Op->Cop.Val = CopVal;
1004     Op->StartLoc = S;
1005     Op->EndLoc = S;
1006     return Op;
1007   }
1008
1009   static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
1010     ARMOperand *Op = new ARMOperand(CoprocReg);
1011     Op->Cop.Val = CopVal;
1012     Op->StartLoc = S;
1013     Op->EndLoc = S;
1014     return Op;
1015   }
1016
1017   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
1018     ARMOperand *Op = new ARMOperand(CCOut);
1019     Op->Reg.RegNum = RegNum;
1020     Op->StartLoc = S;
1021     Op->EndLoc = S;
1022     return Op;
1023   }
1024
1025   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
1026     ARMOperand *Op = new ARMOperand(Token);
1027     Op->Tok.Data = Str.data();
1028     Op->Tok.Length = Str.size();
1029     Op->StartLoc = S;
1030     Op->EndLoc = S;
1031     return Op;
1032   }
1033
1034   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
1035     ARMOperand *Op = new ARMOperand(Register);
1036     Op->Reg.RegNum = RegNum;
1037     Op->StartLoc = S;
1038     Op->EndLoc = E;
1039     return Op;
1040   }
1041
1042   static ARMOperand *CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,
1043                                            unsigned SrcReg,
1044                                            unsigned ShiftReg,
1045                                            unsigned ShiftImm,
1046                                            SMLoc S, SMLoc E) {
1047     ARMOperand *Op = new ARMOperand(ShiftedRegister);
1048     Op->RegShiftedReg.ShiftTy = ShTy;
1049     Op->RegShiftedReg.SrcReg = SrcReg;
1050     Op->RegShiftedReg.ShiftReg = ShiftReg;
1051     Op->RegShiftedReg.ShiftImm = ShiftImm;
1052     Op->StartLoc = S;
1053     Op->EndLoc = E;
1054     return Op;
1055   }
1056
1057   static ARMOperand *CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,
1058                                             unsigned SrcReg,
1059                                             unsigned ShiftImm,
1060                                             SMLoc S, SMLoc E) {
1061     ARMOperand *Op = new ARMOperand(ShiftedImmediate);
1062     Op->RegShiftedImm.ShiftTy = ShTy;
1063     Op->RegShiftedImm.SrcReg = SrcReg;
1064     Op->RegShiftedImm.ShiftImm = ShiftImm;
1065     Op->StartLoc = S;
1066     Op->EndLoc = E;
1067     return Op;
1068   }
1069
1070   static ARMOperand *CreateShifterImm(bool isASR, unsigned Imm,
1071                                    SMLoc S, SMLoc E) {
1072     ARMOperand *Op = new ARMOperand(ShifterImmediate);
1073     Op->ShifterImm.isASR = isASR;
1074     Op->ShifterImm.Imm = Imm;
1075     Op->StartLoc = S;
1076     Op->EndLoc = E;
1077     return Op;
1078   }
1079
1080   static ARMOperand *CreateRotImm(unsigned Imm, SMLoc S, SMLoc E) {
1081     ARMOperand *Op = new ARMOperand(RotateImmediate);
1082     Op->RotImm.Imm = Imm;
1083     Op->StartLoc = S;
1084     Op->EndLoc = E;
1085     return Op;
1086   }
1087
1088   static ARMOperand *CreateBitfield(unsigned LSB, unsigned Width,
1089                                     SMLoc S, SMLoc E) {
1090     ARMOperand *Op = new ARMOperand(BitfieldDescriptor);
1091     Op->Bitfield.LSB = LSB;
1092     Op->Bitfield.Width = Width;
1093     Op->StartLoc = S;
1094     Op->EndLoc = E;
1095     return Op;
1096   }
1097
1098   static ARMOperand *
1099   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
1100                 SMLoc StartLoc, SMLoc EndLoc) {
1101     KindTy Kind = RegisterList;
1102
1103     if (llvm::ARMMCRegisterClasses[ARM::DPRRegClassID].
1104         contains(Regs.front().first))
1105       Kind = DPRRegisterList;
1106     else if (llvm::ARMMCRegisterClasses[ARM::SPRRegClassID].
1107              contains(Regs.front().first))
1108       Kind = SPRRegisterList;
1109
1110     ARMOperand *Op = new ARMOperand(Kind);
1111     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1112            I = Regs.begin(), E = Regs.end(); I != E; ++I)
1113       Op->Registers.push_back(I->first);
1114     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
1115     Op->StartLoc = StartLoc;
1116     Op->EndLoc = EndLoc;
1117     return Op;
1118   }
1119
1120   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
1121     ARMOperand *Op = new ARMOperand(Immediate);
1122     Op->Imm.Val = Val;
1123     Op->StartLoc = S;
1124     Op->EndLoc = E;
1125     return Op;
1126   }
1127
1128   static ARMOperand *CreateMem(unsigned BaseRegNum,
1129                                const MCConstantExpr *OffsetImm,
1130                                unsigned OffsetRegNum,
1131                                ARM_AM::ShiftOpc ShiftType,
1132                                unsigned ShiftImm,
1133                                bool isNegative,
1134                                SMLoc S, SMLoc E) {
1135     ARMOperand *Op = new ARMOperand(Memory);
1136     Op->Mem.BaseRegNum = BaseRegNum;
1137     Op->Mem.OffsetImm = OffsetImm;
1138     Op->Mem.OffsetRegNum = OffsetRegNum;
1139     Op->Mem.ShiftType = ShiftType;
1140     Op->Mem.ShiftImm = ShiftImm;
1141     Op->Mem.isNegative = isNegative;
1142     Op->StartLoc = S;
1143     Op->EndLoc = E;
1144     return Op;
1145   }
1146
1147   static ARMOperand *CreatePostIdxReg(unsigned RegNum, bool isAdd,
1148                                       ARM_AM::ShiftOpc ShiftTy,
1149                                       unsigned ShiftImm,
1150                                       SMLoc S, SMLoc E) {
1151     ARMOperand *Op = new ARMOperand(PostIndexRegister);
1152     Op->PostIdxReg.RegNum = RegNum;
1153     Op->PostIdxReg.isAdd = isAdd;
1154     Op->PostIdxReg.ShiftTy = ShiftTy;
1155     Op->PostIdxReg.ShiftImm = ShiftImm;
1156     Op->StartLoc = S;
1157     Op->EndLoc = E;
1158     return Op;
1159   }
1160
1161   static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
1162     ARMOperand *Op = new ARMOperand(MemBarrierOpt);
1163     Op->MBOpt.Val = Opt;
1164     Op->StartLoc = S;
1165     Op->EndLoc = S;
1166     return Op;
1167   }
1168
1169   static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
1170     ARMOperand *Op = new ARMOperand(ProcIFlags);
1171     Op->IFlags.Val = IFlags;
1172     Op->StartLoc = S;
1173     Op->EndLoc = S;
1174     return Op;
1175   }
1176
1177   static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
1178     ARMOperand *Op = new ARMOperand(MSRMask);
1179     Op->MMask.Val = MMask;
1180     Op->StartLoc = S;
1181     Op->EndLoc = S;
1182     return Op;
1183   }
1184 };
1185
1186 } // end anonymous namespace.
1187
1188 void ARMOperand::print(raw_ostream &OS) const {
1189   switch (Kind) {
1190   case CondCode:
1191     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
1192     break;
1193   case CCOut:
1194     OS << "<ccout " << getReg() << ">";
1195     break;
1196   case CoprocNum:
1197     OS << "<coprocessor number: " << getCoproc() << ">";
1198     break;
1199   case CoprocReg:
1200     OS << "<coprocessor register: " << getCoproc() << ">";
1201     break;
1202   case MSRMask:
1203     OS << "<mask: " << getMSRMask() << ">";
1204     break;
1205   case Immediate:
1206     getImm()->print(OS);
1207     break;
1208   case MemBarrierOpt:
1209     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
1210     break;
1211   case Memory:
1212     OS << "<memory "
1213        << " base:" << Mem.BaseRegNum;
1214     OS << ">";
1215     break;
1216   case PostIndexRegister:
1217     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
1218        << PostIdxReg.RegNum;
1219     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
1220       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
1221          << PostIdxReg.ShiftImm;
1222     OS << ">";
1223     break;
1224   case ProcIFlags: {
1225     OS << "<ARM_PROC::";
1226     unsigned IFlags = getProcIFlags();
1227     for (int i=2; i >= 0; --i)
1228       if (IFlags & (1 << i))
1229         OS << ARM_PROC::IFlagsToString(1 << i);
1230     OS << ">";
1231     break;
1232   }
1233   case Register:
1234     OS << "<register " << getReg() << ">";
1235     break;
1236   case ShifterImmediate:
1237     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
1238        << " #" << ShifterImm.Imm << ">";
1239     break;
1240   case ShiftedRegister:
1241     OS << "<so_reg_reg "
1242        << RegShiftedReg.SrcReg
1243        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedReg.ShiftImm))
1244        << ", " << RegShiftedReg.ShiftReg << ", "
1245        << ARM_AM::getSORegOffset(RegShiftedReg.ShiftImm)
1246        << ">";
1247     break;
1248   case ShiftedImmediate:
1249     OS << "<so_reg_imm "
1250        << RegShiftedImm.SrcReg
1251        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedImm.ShiftImm))
1252        << ", " << ARM_AM::getSORegOffset(RegShiftedImm.ShiftImm)
1253        << ">";
1254     break;
1255   case RotateImmediate:
1256     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
1257     break;
1258   case BitfieldDescriptor:
1259     OS << "<bitfield " << "lsb: " << Bitfield.LSB
1260        << ", width: " << Bitfield.Width << ">";
1261     break;
1262   case RegisterList:
1263   case DPRRegisterList:
1264   case SPRRegisterList: {
1265     OS << "<register_list ";
1266
1267     const SmallVectorImpl<unsigned> &RegList = getRegList();
1268     for (SmallVectorImpl<unsigned>::const_iterator
1269            I = RegList.begin(), E = RegList.end(); I != E; ) {
1270       OS << *I;
1271       if (++I < E) OS << ", ";
1272     }
1273
1274     OS << ">";
1275     break;
1276   }
1277   case Token:
1278     OS << "'" << getToken() << "'";
1279     break;
1280   }
1281 }
1282
1283 /// @name Auto-generated Match Functions
1284 /// {
1285
1286 static unsigned MatchRegisterName(StringRef Name);
1287
1288 /// }
1289
1290 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
1291                                  SMLoc &StartLoc, SMLoc &EndLoc) {
1292   RegNo = tryParseRegister();
1293
1294   return (RegNo == (unsigned)-1);
1295 }
1296
1297 /// Try to parse a register name.  The token must be an Identifier when called,
1298 /// and if it is a register name the token is eaten and the register number is
1299 /// returned.  Otherwise return -1.
1300 ///
1301 int ARMAsmParser::tryParseRegister() {
1302   const AsmToken &Tok = Parser.getTok();
1303   if (Tok.isNot(AsmToken::Identifier)) return -1;
1304
1305   // FIXME: Validate register for the current architecture; we have to do
1306   // validation later, so maybe there is no need for this here.
1307   std::string upperCase = Tok.getString().str();
1308   std::string lowerCase = LowercaseString(upperCase);
1309   unsigned RegNum = MatchRegisterName(lowerCase);
1310   if (!RegNum) {
1311     RegNum = StringSwitch<unsigned>(lowerCase)
1312       .Case("r13", ARM::SP)
1313       .Case("r14", ARM::LR)
1314       .Case("r15", ARM::PC)
1315       .Case("ip", ARM::R12)
1316       .Default(0);
1317   }
1318   if (!RegNum) return -1;
1319
1320   Parser.Lex(); // Eat identifier token.
1321   return RegNum;
1322 }
1323
1324 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
1325 // If a recoverable error occurs, return 1. If an irrecoverable error
1326 // occurs, return -1. An irrecoverable error is one where tokens have been
1327 // consumed in the process of trying to parse the shifter (i.e., when it is
1328 // indeed a shifter operand, but malformed).
1329 int ARMAsmParser::tryParseShiftRegister(
1330                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1331   SMLoc S = Parser.getTok().getLoc();
1332   const AsmToken &Tok = Parser.getTok();
1333   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1334
1335   std::string upperCase = Tok.getString().str();
1336   std::string lowerCase = LowercaseString(upperCase);
1337   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
1338       .Case("lsl", ARM_AM::lsl)
1339       .Case("lsr", ARM_AM::lsr)
1340       .Case("asr", ARM_AM::asr)
1341       .Case("ror", ARM_AM::ror)
1342       .Case("rrx", ARM_AM::rrx)
1343       .Default(ARM_AM::no_shift);
1344
1345   if (ShiftTy == ARM_AM::no_shift)
1346     return 1;
1347
1348   Parser.Lex(); // Eat the operator.
1349
1350   // The source register for the shift has already been added to the
1351   // operand list, so we need to pop it off and combine it into the shifted
1352   // register operand instead.
1353   OwningPtr<ARMOperand> PrevOp((ARMOperand*)Operands.pop_back_val());
1354   if (!PrevOp->isReg())
1355     return Error(PrevOp->getStartLoc(), "shift must be of a register");
1356   int SrcReg = PrevOp->getReg();
1357   int64_t Imm = 0;
1358   int ShiftReg = 0;
1359   if (ShiftTy == ARM_AM::rrx) {
1360     // RRX Doesn't have an explicit shift amount. The encoder expects
1361     // the shift register to be the same as the source register. Seems odd,
1362     // but OK.
1363     ShiftReg = SrcReg;
1364   } else {
1365     // Figure out if this is shifted by a constant or a register (for non-RRX).
1366     if (Parser.getTok().is(AsmToken::Hash)) {
1367       Parser.Lex(); // Eat hash.
1368       SMLoc ImmLoc = Parser.getTok().getLoc();
1369       const MCExpr *ShiftExpr = 0;
1370       if (getParser().ParseExpression(ShiftExpr)) {
1371         Error(ImmLoc, "invalid immediate shift value");
1372         return -1;
1373       }
1374       // The expression must be evaluatable as an immediate.
1375       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
1376       if (!CE) {
1377         Error(ImmLoc, "invalid immediate shift value");
1378         return -1;
1379       }
1380       // Range check the immediate.
1381       // lsl, ror: 0 <= imm <= 31
1382       // lsr, asr: 0 <= imm <= 32
1383       Imm = CE->getValue();
1384       if (Imm < 0 ||
1385           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
1386           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
1387         Error(ImmLoc, "immediate shift value out of range");
1388         return -1;
1389       }
1390     } else if (Parser.getTok().is(AsmToken::Identifier)) {
1391       ShiftReg = tryParseRegister();
1392       SMLoc L = Parser.getTok().getLoc();
1393       if (ShiftReg == -1) {
1394         Error (L, "expected immediate or register in shift operand");
1395         return -1;
1396       }
1397     } else {
1398       Error (Parser.getTok().getLoc(),
1399                     "expected immediate or register in shift operand");
1400       return -1;
1401     }
1402   }
1403
1404   if (ShiftReg && ShiftTy != ARM_AM::rrx)
1405     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
1406                                                          ShiftReg, Imm,
1407                                                S, Parser.getTok().getLoc()));
1408   else
1409     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
1410                                                S, Parser.getTok().getLoc()));
1411
1412   return 0;
1413 }
1414
1415
1416 /// Try to parse a register name.  The token must be an Identifier when called.
1417 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
1418 /// if there is a "writeback". 'true' if it's not a register.
1419 ///
1420 /// TODO this is likely to change to allow different register types and or to
1421 /// parse for a specific register type.
1422 bool ARMAsmParser::
1423 tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1424   SMLoc S = Parser.getTok().getLoc();
1425   int RegNo = tryParseRegister();
1426   if (RegNo == -1)
1427     return true;
1428
1429   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
1430
1431   const AsmToken &ExclaimTok = Parser.getTok();
1432   if (ExclaimTok.is(AsmToken::Exclaim)) {
1433     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
1434                                                ExclaimTok.getLoc()));
1435     Parser.Lex(); // Eat exclaim token
1436   }
1437
1438   return false;
1439 }
1440
1441 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
1442 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
1443 /// "c5", ...
1444 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
1445   // Use the same layout as the tablegen'erated register name matcher. Ugly,
1446   // but efficient.
1447   switch (Name.size()) {
1448   default: break;
1449   case 2:
1450     if (Name[0] != CoprocOp)
1451       return -1;
1452     switch (Name[1]) {
1453     default:  return -1;
1454     case '0': return 0;
1455     case '1': return 1;
1456     case '2': return 2;
1457     case '3': return 3;
1458     case '4': return 4;
1459     case '5': return 5;
1460     case '6': return 6;
1461     case '7': return 7;
1462     case '8': return 8;
1463     case '9': return 9;
1464     }
1465     break;
1466   case 3:
1467     if (Name[0] != CoprocOp || Name[1] != '1')
1468       return -1;
1469     switch (Name[2]) {
1470     default:  return -1;
1471     case '0': return 10;
1472     case '1': return 11;
1473     case '2': return 12;
1474     case '3': return 13;
1475     case '4': return 14;
1476     case '5': return 15;
1477     }
1478     break;
1479   }
1480
1481   return -1;
1482 }
1483
1484 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
1485 /// token must be an Identifier when called, and if it is a coprocessor
1486 /// number, the token is eaten and the operand is added to the operand list.
1487 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1488 parseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1489   SMLoc S = Parser.getTok().getLoc();
1490   const AsmToken &Tok = Parser.getTok();
1491   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1492
1493   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
1494   if (Num == -1)
1495     return MatchOperand_NoMatch;
1496
1497   Parser.Lex(); // Eat identifier token.
1498   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
1499   return MatchOperand_Success;
1500 }
1501
1502 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
1503 /// token must be an Identifier when called, and if it is a coprocessor
1504 /// number, the token is eaten and the operand is added to the operand list.
1505 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1506 parseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1507   SMLoc S = Parser.getTok().getLoc();
1508   const AsmToken &Tok = Parser.getTok();
1509   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1510
1511   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
1512   if (Reg == -1)
1513     return MatchOperand_NoMatch;
1514
1515   Parser.Lex(); // Eat identifier token.
1516   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
1517   return MatchOperand_Success;
1518 }
1519
1520 /// Parse a register list, return it if successful else return null.  The first
1521 /// token must be a '{' when called.
1522 bool ARMAsmParser::
1523 parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1524   assert(Parser.getTok().is(AsmToken::LCurly) &&
1525          "Token is not a Left Curly Brace");
1526   SMLoc S = Parser.getTok().getLoc();
1527
1528   // Read the rest of the registers in the list.
1529   unsigned PrevRegNum = 0;
1530   SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
1531
1532   do {
1533     bool IsRange = Parser.getTok().is(AsmToken::Minus);
1534     Parser.Lex(); // Eat non-identifier token.
1535
1536     const AsmToken &RegTok = Parser.getTok();
1537     SMLoc RegLoc = RegTok.getLoc();
1538     if (RegTok.isNot(AsmToken::Identifier)) {
1539       Error(RegLoc, "register expected");
1540       return true;
1541     }
1542
1543     int RegNum = tryParseRegister();
1544     if (RegNum == -1) {
1545       Error(RegLoc, "register expected");
1546       return true;
1547     }
1548
1549     if (IsRange) {
1550       int Reg = PrevRegNum;
1551       do {
1552         ++Reg;
1553         Registers.push_back(std::make_pair(Reg, RegLoc));
1554       } while (Reg != RegNum);
1555     } else {
1556       Registers.push_back(std::make_pair(RegNum, RegLoc));
1557     }
1558
1559     PrevRegNum = RegNum;
1560   } while (Parser.getTok().is(AsmToken::Comma) ||
1561            Parser.getTok().is(AsmToken::Minus));
1562
1563   // Process the right curly brace of the list.
1564   const AsmToken &RCurlyTok = Parser.getTok();
1565   if (RCurlyTok.isNot(AsmToken::RCurly)) {
1566     Error(RCurlyTok.getLoc(), "'}' expected");
1567     return true;
1568   }
1569
1570   SMLoc E = RCurlyTok.getLoc();
1571   Parser.Lex(); // Eat right curly brace token.
1572
1573   // Verify the register list.
1574   SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1575     RI = Registers.begin(), RE = Registers.end();
1576
1577   unsigned HighRegNum = getARMRegisterNumbering(RI->first);
1578   bool EmittedWarning = false;
1579
1580   DenseMap<unsigned, bool> RegMap;
1581   RegMap[HighRegNum] = true;
1582
1583   for (++RI; RI != RE; ++RI) {
1584     const std::pair<unsigned, SMLoc> &RegInfo = *RI;
1585     unsigned Reg = getARMRegisterNumbering(RegInfo.first);
1586
1587     if (RegMap[Reg]) {
1588       Error(RegInfo.second, "register duplicated in register list");
1589       return true;
1590     }
1591
1592     if (!EmittedWarning && Reg < HighRegNum)
1593       Warning(RegInfo.second,
1594               "register not in ascending order in register list");
1595
1596     RegMap[Reg] = true;
1597     HighRegNum = std::max(Reg, HighRegNum);
1598   }
1599
1600   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
1601   return false;
1602 }
1603
1604 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
1605 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1606 parseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1607   SMLoc S = Parser.getTok().getLoc();
1608   const AsmToken &Tok = Parser.getTok();
1609   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1610   StringRef OptStr = Tok.getString();
1611
1612   unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
1613     .Case("sy",    ARM_MB::SY)
1614     .Case("st",    ARM_MB::ST)
1615     .Case("sh",    ARM_MB::ISH)
1616     .Case("ish",   ARM_MB::ISH)
1617     .Case("shst",  ARM_MB::ISHST)
1618     .Case("ishst", ARM_MB::ISHST)
1619     .Case("nsh",   ARM_MB::NSH)
1620     .Case("un",    ARM_MB::NSH)
1621     .Case("nshst", ARM_MB::NSHST)
1622     .Case("unst",  ARM_MB::NSHST)
1623     .Case("osh",   ARM_MB::OSH)
1624     .Case("oshst", ARM_MB::OSHST)
1625     .Default(~0U);
1626
1627   if (Opt == ~0U)
1628     return MatchOperand_NoMatch;
1629
1630   Parser.Lex(); // Eat identifier token.
1631   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
1632   return MatchOperand_Success;
1633 }
1634
1635 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
1636 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1637 parseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1638   SMLoc S = Parser.getTok().getLoc();
1639   const AsmToken &Tok = Parser.getTok();
1640   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1641   StringRef IFlagsStr = Tok.getString();
1642
1643   unsigned IFlags = 0;
1644   for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
1645     unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
1646     .Case("a", ARM_PROC::A)
1647     .Case("i", ARM_PROC::I)
1648     .Case("f", ARM_PROC::F)
1649     .Default(~0U);
1650
1651     // If some specific iflag is already set, it means that some letter is
1652     // present more than once, this is not acceptable.
1653     if (Flag == ~0U || (IFlags & Flag))
1654       return MatchOperand_NoMatch;
1655
1656     IFlags |= Flag;
1657   }
1658
1659   Parser.Lex(); // Eat identifier token.
1660   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
1661   return MatchOperand_Success;
1662 }
1663
1664 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
1665 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1666 parseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1667   SMLoc S = Parser.getTok().getLoc();
1668   const AsmToken &Tok = Parser.getTok();
1669   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1670   StringRef Mask = Tok.getString();
1671
1672   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
1673   size_t Start = 0, Next = Mask.find('_');
1674   StringRef Flags = "";
1675   std::string SpecReg = LowercaseString(Mask.slice(Start, Next));
1676   if (Next != StringRef::npos)
1677     Flags = Mask.slice(Next+1, Mask.size());
1678
1679   // FlagsVal contains the complete mask:
1680   // 3-0: Mask
1681   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1682   unsigned FlagsVal = 0;
1683
1684   if (SpecReg == "apsr") {
1685     FlagsVal = StringSwitch<unsigned>(Flags)
1686     .Case("nzcvq",  0x8) // same as CPSR_f
1687     .Case("g",      0x4) // same as CPSR_s
1688     .Case("nzcvqg", 0xc) // same as CPSR_fs
1689     .Default(~0U);
1690
1691     if (FlagsVal == ~0U) {
1692       if (!Flags.empty())
1693         return MatchOperand_NoMatch;
1694       else
1695         FlagsVal = 0; // No flag
1696     }
1697   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
1698     if (Flags == "all") // cpsr_all is an alias for cpsr_fc
1699       Flags = "fc";
1700     for (int i = 0, e = Flags.size(); i != e; ++i) {
1701       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
1702       .Case("c", 1)
1703       .Case("x", 2)
1704       .Case("s", 4)
1705       .Case("f", 8)
1706       .Default(~0U);
1707
1708       // If some specific flag is already set, it means that some letter is
1709       // present more than once, this is not acceptable.
1710       if (FlagsVal == ~0U || (FlagsVal & Flag))
1711         return MatchOperand_NoMatch;
1712       FlagsVal |= Flag;
1713     }
1714   } else // No match for special register.
1715     return MatchOperand_NoMatch;
1716
1717   // Special register without flags are equivalent to "fc" flags.
1718   if (!FlagsVal)
1719     FlagsVal = 0x9;
1720
1721   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1722   if (SpecReg == "spsr")
1723     FlagsVal |= 16;
1724
1725   Parser.Lex(); // Eat identifier token.
1726   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
1727   return MatchOperand_Success;
1728 }
1729
1730 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1731 parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands, StringRef Op,
1732             int Low, int High) {
1733   const AsmToken &Tok = Parser.getTok();
1734   if (Tok.isNot(AsmToken::Identifier)) {
1735     Error(Parser.getTok().getLoc(), Op + " operand expected.");
1736     return MatchOperand_ParseFail;
1737   }
1738   StringRef ShiftName = Tok.getString();
1739   std::string LowerOp = LowercaseString(Op);
1740   std::string UpperOp = UppercaseString(Op);
1741   if (ShiftName != LowerOp && ShiftName != UpperOp) {
1742     Error(Parser.getTok().getLoc(), Op + " operand expected.");
1743     return MatchOperand_ParseFail;
1744   }
1745   Parser.Lex(); // Eat shift type token.
1746
1747   // There must be a '#' and a shift amount.
1748   if (Parser.getTok().isNot(AsmToken::Hash)) {
1749     Error(Parser.getTok().getLoc(), "'#' expected");
1750     return MatchOperand_ParseFail;
1751   }
1752   Parser.Lex(); // Eat hash token.
1753
1754   const MCExpr *ShiftAmount;
1755   SMLoc Loc = Parser.getTok().getLoc();
1756   if (getParser().ParseExpression(ShiftAmount)) {
1757     Error(Loc, "illegal expression");
1758     return MatchOperand_ParseFail;
1759   }
1760   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
1761   if (!CE) {
1762     Error(Loc, "constant expression expected");
1763     return MatchOperand_ParseFail;
1764   }
1765   int Val = CE->getValue();
1766   if (Val < Low || Val > High) {
1767     Error(Loc, "immediate value out of range");
1768     return MatchOperand_ParseFail;
1769   }
1770
1771   Operands.push_back(ARMOperand::CreateImm(CE, Loc, Parser.getTok().getLoc()));
1772
1773   return MatchOperand_Success;
1774 }
1775
1776 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1777 parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1778   const AsmToken &Tok = Parser.getTok();
1779   SMLoc S = Tok.getLoc();
1780   if (Tok.isNot(AsmToken::Identifier)) {
1781     Error(Tok.getLoc(), "'be' or 'le' operand expected");
1782     return MatchOperand_ParseFail;
1783   }
1784   int Val = StringSwitch<int>(Tok.getString())
1785     .Case("be", 1)
1786     .Case("le", 0)
1787     .Default(-1);
1788   Parser.Lex(); // Eat the token.
1789
1790   if (Val == -1) {
1791     Error(Tok.getLoc(), "'be' or 'le' operand expected");
1792     return MatchOperand_ParseFail;
1793   }
1794   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
1795                                                                   getContext()),
1796                                            S, Parser.getTok().getLoc()));
1797   return MatchOperand_Success;
1798 }
1799
1800 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
1801 /// instructions. Legal values are:
1802 ///     lsl #n  'n' in [0,31]
1803 ///     asr #n  'n' in [1,32]
1804 ///             n == 32 encoded as n == 0.
1805 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1806 parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1807   const AsmToken &Tok = Parser.getTok();
1808   SMLoc S = Tok.getLoc();
1809   if (Tok.isNot(AsmToken::Identifier)) {
1810     Error(S, "shift operator 'asr' or 'lsl' expected");
1811     return MatchOperand_ParseFail;
1812   }
1813   StringRef ShiftName = Tok.getString();
1814   bool isASR;
1815   if (ShiftName == "lsl" || ShiftName == "LSL")
1816     isASR = false;
1817   else if (ShiftName == "asr" || ShiftName == "ASR")
1818     isASR = true;
1819   else {
1820     Error(S, "shift operator 'asr' or 'lsl' expected");
1821     return MatchOperand_ParseFail;
1822   }
1823   Parser.Lex(); // Eat the operator.
1824
1825   // A '#' and a shift amount.
1826   if (Parser.getTok().isNot(AsmToken::Hash)) {
1827     Error(Parser.getTok().getLoc(), "'#' expected");
1828     return MatchOperand_ParseFail;
1829   }
1830   Parser.Lex(); // Eat hash token.
1831
1832   const MCExpr *ShiftAmount;
1833   SMLoc E = Parser.getTok().getLoc();
1834   if (getParser().ParseExpression(ShiftAmount)) {
1835     Error(E, "malformed shift expression");
1836     return MatchOperand_ParseFail;
1837   }
1838   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
1839   if (!CE) {
1840     Error(E, "shift amount must be an immediate");
1841     return MatchOperand_ParseFail;
1842   }
1843
1844   int64_t Val = CE->getValue();
1845   if (isASR) {
1846     // Shift amount must be in [1,32]
1847     if (Val < 1 || Val > 32) {
1848       Error(E, "'asr' shift amount must be in range [1,32]");
1849       return MatchOperand_ParseFail;
1850     }
1851     // asr #32 encoded as asr #0.
1852     if (Val == 32) Val = 0;
1853   } else {
1854     // Shift amount must be in [1,32]
1855     if (Val < 0 || Val > 31) {
1856       Error(E, "'lsr' shift amount must be in range [0,31]");
1857       return MatchOperand_ParseFail;
1858     }
1859   }
1860
1861   E = Parser.getTok().getLoc();
1862   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, E));
1863
1864   return MatchOperand_Success;
1865 }
1866
1867 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
1868 /// of instructions. Legal values are:
1869 ///     ror #n  'n' in {0, 8, 16, 24}
1870 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1871 parseRotImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1872   const AsmToken &Tok = Parser.getTok();
1873   SMLoc S = Tok.getLoc();
1874   if (Tok.isNot(AsmToken::Identifier)) {
1875     Error(S, "rotate operator 'ror' expected");
1876     return MatchOperand_ParseFail;
1877   }
1878   StringRef ShiftName = Tok.getString();
1879   if (ShiftName != "ror" && ShiftName != "ROR") {
1880     Error(S, "rotate operator 'ror' expected");
1881     return MatchOperand_ParseFail;
1882   }
1883   Parser.Lex(); // Eat the operator.
1884
1885   // A '#' and a rotate amount.
1886   if (Parser.getTok().isNot(AsmToken::Hash)) {
1887     Error(Parser.getTok().getLoc(), "'#' expected");
1888     return MatchOperand_ParseFail;
1889   }
1890   Parser.Lex(); // Eat hash token.
1891
1892   const MCExpr *ShiftAmount;
1893   SMLoc E = Parser.getTok().getLoc();
1894   if (getParser().ParseExpression(ShiftAmount)) {
1895     Error(E, "malformed rotate expression");
1896     return MatchOperand_ParseFail;
1897   }
1898   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
1899   if (!CE) {
1900     Error(E, "rotate amount must be an immediate");
1901     return MatchOperand_ParseFail;
1902   }
1903
1904   int64_t Val = CE->getValue();
1905   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
1906   // normally, zero is represented in asm by omitting the rotate operand
1907   // entirely.
1908   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
1909     Error(E, "'ror' rotate amount must be 8, 16, or 24");
1910     return MatchOperand_ParseFail;
1911   }
1912
1913   E = Parser.getTok().getLoc();
1914   Operands.push_back(ARMOperand::CreateRotImm(Val, S, E));
1915
1916   return MatchOperand_Success;
1917 }
1918
1919 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1920 parseBitfield(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1921   SMLoc S = Parser.getTok().getLoc();
1922   // The bitfield descriptor is really two operands, the LSB and the width.
1923   if (Parser.getTok().isNot(AsmToken::Hash)) {
1924     Error(Parser.getTok().getLoc(), "'#' expected");
1925     return MatchOperand_ParseFail;
1926   }
1927   Parser.Lex(); // Eat hash token.
1928
1929   const MCExpr *LSBExpr;
1930   SMLoc E = Parser.getTok().getLoc();
1931   if (getParser().ParseExpression(LSBExpr)) {
1932     Error(E, "malformed immediate expression");
1933     return MatchOperand_ParseFail;
1934   }
1935   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
1936   if (!CE) {
1937     Error(E, "'lsb' operand must be an immediate");
1938     return MatchOperand_ParseFail;
1939   }
1940
1941   int64_t LSB = CE->getValue();
1942   // The LSB must be in the range [0,31]
1943   if (LSB < 0 || LSB > 31) {
1944     Error(E, "'lsb' operand must be in the range [0,31]");
1945     return MatchOperand_ParseFail;
1946   }
1947   E = Parser.getTok().getLoc();
1948
1949   // Expect another immediate operand.
1950   if (Parser.getTok().isNot(AsmToken::Comma)) {
1951     Error(Parser.getTok().getLoc(), "too few operands");
1952     return MatchOperand_ParseFail;
1953   }
1954   Parser.Lex(); // Eat hash token.
1955   if (Parser.getTok().isNot(AsmToken::Hash)) {
1956     Error(Parser.getTok().getLoc(), "'#' expected");
1957     return MatchOperand_ParseFail;
1958   }
1959   Parser.Lex(); // Eat hash token.
1960
1961   const MCExpr *WidthExpr;
1962   if (getParser().ParseExpression(WidthExpr)) {
1963     Error(E, "malformed immediate expression");
1964     return MatchOperand_ParseFail;
1965   }
1966   CE = dyn_cast<MCConstantExpr>(WidthExpr);
1967   if (!CE) {
1968     Error(E, "'width' operand must be an immediate");
1969     return MatchOperand_ParseFail;
1970   }
1971
1972   int64_t Width = CE->getValue();
1973   // The LSB must be in the range [1,32-lsb]
1974   if (Width < 1 || Width > 32 - LSB) {
1975     Error(E, "'width' operand must be in the range [1,32-lsb]");
1976     return MatchOperand_ParseFail;
1977   }
1978   E = Parser.getTok().getLoc();
1979
1980   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, E));
1981
1982   return MatchOperand_Success;
1983 }
1984
1985 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1986 parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1987   // Check for a post-index addressing register operand. Specifically:
1988   // postidx_reg := '+' register {, shift}
1989   //              | '-' register {, shift}
1990   //              | register {, shift}
1991
1992   // This method must return MatchOperand_NoMatch without consuming any tokens
1993   // in the case where there is no match, as other alternatives take other
1994   // parse methods.
1995   AsmToken Tok = Parser.getTok();
1996   SMLoc S = Tok.getLoc();
1997   bool haveEaten = false;
1998   bool isAdd = true;
1999   int Reg = -1;
2000   if (Tok.is(AsmToken::Plus)) {
2001     Parser.Lex(); // Eat the '+' token.
2002     haveEaten = true;
2003   } else if (Tok.is(AsmToken::Minus)) {
2004     Parser.Lex(); // Eat the '-' token.
2005     isAdd = false;
2006     haveEaten = true;
2007   }
2008   if (Parser.getTok().is(AsmToken::Identifier))
2009     Reg = tryParseRegister();
2010   if (Reg == -1) {
2011     if (!haveEaten)
2012       return MatchOperand_NoMatch;
2013     Error(Parser.getTok().getLoc(), "register expected");
2014     return MatchOperand_ParseFail;
2015   }
2016   SMLoc E = Parser.getTok().getLoc();
2017
2018   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
2019   unsigned ShiftImm = 0;
2020   if (Parser.getTok().is(AsmToken::Comma)) {
2021     Parser.Lex(); // Eat the ','.
2022     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
2023       return MatchOperand_ParseFail;
2024   }
2025
2026   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
2027                                                   ShiftImm, S, E));
2028
2029   return MatchOperand_Success;
2030 }
2031
2032 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2033 parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2034   // Check for a post-index addressing register operand. Specifically:
2035   // am3offset := '+' register
2036   //              | '-' register
2037   //              | register
2038   //              | # imm
2039   //              | # + imm
2040   //              | # - imm
2041
2042   // This method must return MatchOperand_NoMatch without consuming any tokens
2043   // in the case where there is no match, as other alternatives take other
2044   // parse methods.
2045   AsmToken Tok = Parser.getTok();
2046   SMLoc S = Tok.getLoc();
2047
2048   // Do immediates first, as we always parse those if we have a '#'.
2049   if (Parser.getTok().is(AsmToken::Hash)) {
2050     Parser.Lex(); // Eat the '#'.
2051     // Explicitly look for a '-', as we need to encode negative zero
2052     // differently.
2053     bool isNegative = Parser.getTok().is(AsmToken::Minus);
2054     const MCExpr *Offset;
2055     if (getParser().ParseExpression(Offset))
2056       return MatchOperand_ParseFail;
2057     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2058     if (!CE) {
2059       Error(S, "constant expression expected");
2060       return MatchOperand_ParseFail;
2061     }
2062     SMLoc E = Tok.getLoc();
2063     // Negative zero is encoded as the flag value INT32_MIN.
2064     int32_t Val = CE->getValue();
2065     if (isNegative && Val == 0)
2066       Val = INT32_MIN;
2067
2068     Operands.push_back(
2069       ARMOperand::CreateImm(MCConstantExpr::Create(Val, getContext()), S, E));
2070
2071     return MatchOperand_Success;
2072   }
2073
2074
2075   bool haveEaten = false;
2076   bool isAdd = true;
2077   int Reg = -1;
2078   if (Tok.is(AsmToken::Plus)) {
2079     Parser.Lex(); // Eat the '+' token.
2080     haveEaten = true;
2081   } else if (Tok.is(AsmToken::Minus)) {
2082     Parser.Lex(); // Eat the '-' token.
2083     isAdd = false;
2084     haveEaten = true;
2085   }
2086   if (Parser.getTok().is(AsmToken::Identifier))
2087     Reg = tryParseRegister();
2088   if (Reg == -1) {
2089     if (!haveEaten)
2090       return MatchOperand_NoMatch;
2091     Error(Parser.getTok().getLoc(), "register expected");
2092     return MatchOperand_ParseFail;
2093   }
2094   SMLoc E = Parser.getTok().getLoc();
2095
2096   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
2097                                                   0, S, E));
2098
2099   return MatchOperand_Success;
2100 }
2101
2102 /// cvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2103 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2104 /// when they refer multiple MIOperands inside a single one.
2105 bool ARMAsmParser::
2106 cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2107                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2108   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2109
2110   // Create a writeback register dummy placeholder.
2111   Inst.addOperand(MCOperand::CreateImm(0));
2112
2113   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2114   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2115   return true;
2116 }
2117
2118 /// cvtStWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2119 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2120 /// when they refer multiple MIOperands inside a single one.
2121 bool ARMAsmParser::
2122 cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2123                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2124   // Create a writeback register dummy placeholder.
2125   Inst.addOperand(MCOperand::CreateImm(0));
2126   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2127   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2128   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2129   return true;
2130 }
2131
2132 /// cvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2133 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2134 /// when they refer multiple MIOperands inside a single one.
2135 bool ARMAsmParser::
2136 cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2137                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2138   // Create a writeback register dummy placeholder.
2139   Inst.addOperand(MCOperand::CreateImm(0));
2140   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2141   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2142   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2143   return true;
2144 }
2145
2146 /// cvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2147 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2148 /// when they refer multiple MIOperands inside a single one.
2149 bool ARMAsmParser::
2150 cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2151                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2152   // Create a writeback register dummy placeholder.
2153   Inst.addOperand(MCOperand::CreateImm(0));
2154   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2155   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2156   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2157   return true;
2158 }
2159
2160 /// cvtLdExtTWriteBackImm - Convert parsed operands to MCInst.
2161 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2162 /// when they refer multiple MIOperands inside a single one.
2163 bool ARMAsmParser::
2164 cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2165                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2166   // Rt
2167   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2168   // Create a writeback register dummy placeholder.
2169   Inst.addOperand(MCOperand::CreateImm(0));
2170   // addr
2171   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2172   // offset
2173   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2174   // pred
2175   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2176   return true;
2177 }
2178
2179 /// cvtLdExtTWriteBackReg - Convert parsed operands to MCInst.
2180 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2181 /// when they refer multiple MIOperands inside a single one.
2182 bool ARMAsmParser::
2183 cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2184                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2185   // Rt
2186   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2187   // Create a writeback register dummy placeholder.
2188   Inst.addOperand(MCOperand::CreateImm(0));
2189   // addr
2190   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2191   // offset
2192   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2193   // pred
2194   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2195   return true;
2196 }
2197
2198 /// cvtStExtTWriteBackImm - Convert parsed operands to MCInst.
2199 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2200 /// when they refer multiple MIOperands inside a single one.
2201 bool ARMAsmParser::
2202 cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2203                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2204   // Create a writeback register dummy placeholder.
2205   Inst.addOperand(MCOperand::CreateImm(0));
2206   // Rt
2207   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2208   // addr
2209   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2210   // offset
2211   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2212   // pred
2213   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2214   return true;
2215 }
2216
2217 /// cvtStExtTWriteBackReg - Convert parsed operands to MCInst.
2218 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2219 /// when they refer multiple MIOperands inside a single one.
2220 bool ARMAsmParser::
2221 cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2222                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2223   // Create a writeback register dummy placeholder.
2224   Inst.addOperand(MCOperand::CreateImm(0));
2225   // Rt
2226   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2227   // addr
2228   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2229   // offset
2230   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2231   // pred
2232   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2233   return true;
2234 }
2235
2236 /// cvtLdrdPre - Convert parsed operands to MCInst.
2237 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2238 /// when they refer multiple MIOperands inside a single one.
2239 bool ARMAsmParser::
2240 cvtLdrdPre(MCInst &Inst, unsigned Opcode,
2241            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2242   // Rt, Rt2
2243   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2244   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2245   // Create a writeback register dummy placeholder.
2246   Inst.addOperand(MCOperand::CreateImm(0));
2247   // addr
2248   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2249   // pred
2250   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2251   return true;
2252 }
2253
2254 /// cvtStrdPre - Convert parsed operands to MCInst.
2255 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2256 /// when they refer multiple MIOperands inside a single one.
2257 bool ARMAsmParser::
2258 cvtStrdPre(MCInst &Inst, unsigned Opcode,
2259            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2260   // Create a writeback register dummy placeholder.
2261   Inst.addOperand(MCOperand::CreateImm(0));
2262   // Rt, Rt2
2263   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2264   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2265   // addr
2266   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2267   // pred
2268   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2269   return true;
2270 }
2271
2272 /// cvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2273 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2274 /// when they refer multiple MIOperands inside a single one.
2275 bool ARMAsmParser::
2276 cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2277                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2278   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2279   // Create a writeback register dummy placeholder.
2280   Inst.addOperand(MCOperand::CreateImm(0));
2281   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2282   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2283   return true;
2284 }
2285
2286
2287 /// Parse an ARM memory expression, return false if successful else return true
2288 /// or an error.  The first token must be a '[' when called.
2289 bool ARMAsmParser::
2290 parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2291   SMLoc S, E;
2292   assert(Parser.getTok().is(AsmToken::LBrac) &&
2293          "Token is not a Left Bracket");
2294   S = Parser.getTok().getLoc();
2295   Parser.Lex(); // Eat left bracket token.
2296
2297   const AsmToken &BaseRegTok = Parser.getTok();
2298   int BaseRegNum = tryParseRegister();
2299   if (BaseRegNum == -1)
2300     return Error(BaseRegTok.getLoc(), "register expected");
2301
2302   // The next token must either be a comma or a closing bracket.
2303   const AsmToken &Tok = Parser.getTok();
2304   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
2305     return Error(Tok.getLoc(), "malformed memory operand");
2306
2307   if (Tok.is(AsmToken::RBrac)) {
2308     E = Tok.getLoc();
2309     Parser.Lex(); // Eat right bracket token.
2310
2311     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, 0, ARM_AM::no_shift,
2312                                              0, false, S, E));
2313
2314     return false;
2315   }
2316
2317   assert(Tok.is(AsmToken::Comma) && "Lost comma in memory operand?!");
2318   Parser.Lex(); // Eat the comma.
2319
2320   // If we have a '#' it's an immediate offset, else assume it's a register
2321   // offset.
2322   if (Parser.getTok().is(AsmToken::Hash)) {
2323     Parser.Lex(); // Eat the '#'.
2324     E = Parser.getTok().getLoc();
2325
2326     // FIXME: Special case #-0 so we can correctly set the U bit.
2327
2328     const MCExpr *Offset;
2329     if (getParser().ParseExpression(Offset))
2330      return true;
2331
2332     // The expression has to be a constant. Memory references with relocations
2333     // don't come through here, as they use the <label> forms of the relevant
2334     // instructions.
2335     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2336     if (!CE)
2337       return Error (E, "constant expression expected");
2338
2339     // Now we should have the closing ']'
2340     E = Parser.getTok().getLoc();
2341     if (Parser.getTok().isNot(AsmToken::RBrac))
2342       return Error(E, "']' expected");
2343     Parser.Lex(); // Eat right bracket token.
2344
2345     // Don't worry about range checking the value here. That's handled by
2346     // the is*() predicates.
2347     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
2348                                              ARM_AM::no_shift, 0, false, S,E));
2349
2350     // If there's a pre-indexing writeback marker, '!', just add it as a token
2351     // operand.
2352     if (Parser.getTok().is(AsmToken::Exclaim)) {
2353       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2354       Parser.Lex(); // Eat the '!'.
2355     }
2356
2357     return false;
2358   }
2359
2360   // The register offset is optionally preceded by a '+' or '-'
2361   bool isNegative = false;
2362   if (Parser.getTok().is(AsmToken::Minus)) {
2363     isNegative = true;
2364     Parser.Lex(); // Eat the '-'.
2365   } else if (Parser.getTok().is(AsmToken::Plus)) {
2366     // Nothing to do.
2367     Parser.Lex(); // Eat the '+'.
2368   }
2369
2370   E = Parser.getTok().getLoc();
2371   int OffsetRegNum = tryParseRegister();
2372   if (OffsetRegNum == -1)
2373     return Error(E, "register expected");
2374
2375   // If there's a shift operator, handle it.
2376   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
2377   unsigned ShiftImm = 0;
2378   if (Parser.getTok().is(AsmToken::Comma)) {
2379     Parser.Lex(); // Eat the ','.
2380     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
2381       return true;
2382   }
2383
2384   // Now we should have the closing ']'
2385   E = Parser.getTok().getLoc();
2386   if (Parser.getTok().isNot(AsmToken::RBrac))
2387     return Error(E, "']' expected");
2388   Parser.Lex(); // Eat right bracket token.
2389
2390   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, OffsetRegNum,
2391                                            ShiftType, ShiftImm, isNegative,
2392                                            S, E));
2393
2394   // If there's a pre-indexing writeback marker, '!', just add it as a token
2395   // operand.
2396   if (Parser.getTok().is(AsmToken::Exclaim)) {
2397     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2398     Parser.Lex(); // Eat the '!'.
2399   }
2400
2401   return false;
2402 }
2403
2404 /// parseMemRegOffsetShift - one of these two:
2405 ///   ( lsl | lsr | asr | ror ) , # shift_amount
2406 ///   rrx
2407 /// return true if it parses a shift otherwise it returns false.
2408 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
2409                                           unsigned &Amount) {
2410   SMLoc Loc = Parser.getTok().getLoc();
2411   const AsmToken &Tok = Parser.getTok();
2412   if (Tok.isNot(AsmToken::Identifier))
2413     return true;
2414   StringRef ShiftName = Tok.getString();
2415   if (ShiftName == "lsl" || ShiftName == "LSL")
2416     St = ARM_AM::lsl;
2417   else if (ShiftName == "lsr" || ShiftName == "LSR")
2418     St = ARM_AM::lsr;
2419   else if (ShiftName == "asr" || ShiftName == "ASR")
2420     St = ARM_AM::asr;
2421   else if (ShiftName == "ror" || ShiftName == "ROR")
2422     St = ARM_AM::ror;
2423   else if (ShiftName == "rrx" || ShiftName == "RRX")
2424     St = ARM_AM::rrx;
2425   else
2426     return Error(Loc, "illegal shift operator");
2427   Parser.Lex(); // Eat shift type token.
2428
2429   // rrx stands alone.
2430   Amount = 0;
2431   if (St != ARM_AM::rrx) {
2432     Loc = Parser.getTok().getLoc();
2433     // A '#' and a shift amount.
2434     const AsmToken &HashTok = Parser.getTok();
2435     if (HashTok.isNot(AsmToken::Hash))
2436       return Error(HashTok.getLoc(), "'#' expected");
2437     Parser.Lex(); // Eat hash token.
2438
2439     const MCExpr *Expr;
2440     if (getParser().ParseExpression(Expr))
2441       return true;
2442     // Range check the immediate.
2443     // lsl, ror: 0 <= imm <= 31
2444     // lsr, asr: 0 <= imm <= 32
2445     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
2446     if (!CE)
2447       return Error(Loc, "shift amount must be an immediate");
2448     int64_t Imm = CE->getValue();
2449     if (Imm < 0 ||
2450         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
2451         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
2452       return Error(Loc, "immediate shift value out of range");
2453     Amount = Imm;
2454   }
2455
2456   return false;
2457 }
2458
2459 /// Parse a arm instruction operand.  For now this parses the operand regardless
2460 /// of the mnemonic.
2461 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2462                                 StringRef Mnemonic) {
2463   SMLoc S, E;
2464
2465   // Check if the current operand has a custom associated parser, if so, try to
2466   // custom parse the operand, or fallback to the general approach.
2467   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
2468   if (ResTy == MatchOperand_Success)
2469     return false;
2470   // If there wasn't a custom match, try the generic matcher below. Otherwise,
2471   // there was a match, but an error occurred, in which case, just return that
2472   // the operand parsing failed.
2473   if (ResTy == MatchOperand_ParseFail)
2474     return true;
2475
2476   switch (getLexer().getKind()) {
2477   default:
2478     Error(Parser.getTok().getLoc(), "unexpected token in operand");
2479     return true;
2480   case AsmToken::Identifier: {
2481     if (!tryParseRegisterWithWriteBack(Operands))
2482       return false;
2483     int Res = tryParseShiftRegister(Operands);
2484     if (Res == 0) // success
2485       return false;
2486     else if (Res == -1) // irrecoverable error
2487       return true;
2488
2489     // Fall though for the Identifier case that is not a register or a
2490     // special name.
2491   }
2492   case AsmToken::Integer: // things like 1f and 2b as a branch targets
2493   case AsmToken::Dot: {   // . as a branch target
2494     // This was not a register so parse other operands that start with an
2495     // identifier (like labels) as expressions and create them as immediates.
2496     const MCExpr *IdVal;
2497     S = Parser.getTok().getLoc();
2498     if (getParser().ParseExpression(IdVal))
2499       return true;
2500     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2501     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
2502     return false;
2503   }
2504   case AsmToken::LBrac:
2505     return parseMemory(Operands);
2506   case AsmToken::LCurly:
2507     return parseRegisterList(Operands);
2508   case AsmToken::Hash:
2509     // #42 -> immediate.
2510     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
2511     S = Parser.getTok().getLoc();
2512     Parser.Lex();
2513     const MCExpr *ImmVal;
2514     if (getParser().ParseExpression(ImmVal))
2515       return true;
2516     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2517     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
2518     return false;
2519   case AsmToken::Colon: {
2520     // ":lower16:" and ":upper16:" expression prefixes
2521     // FIXME: Check it's an expression prefix,
2522     // e.g. (FOO - :lower16:BAR) isn't legal.
2523     ARMMCExpr::VariantKind RefKind;
2524     if (parsePrefix(RefKind))
2525       return true;
2526
2527     const MCExpr *SubExprVal;
2528     if (getParser().ParseExpression(SubExprVal))
2529       return true;
2530
2531     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
2532                                                    getContext());
2533     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2534     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
2535     return false;
2536   }
2537   }
2538 }
2539
2540 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
2541 //  :lower16: and :upper16:.
2542 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
2543   RefKind = ARMMCExpr::VK_ARM_None;
2544
2545   // :lower16: and :upper16: modifiers
2546   assert(getLexer().is(AsmToken::Colon) && "expected a :");
2547   Parser.Lex(); // Eat ':'
2548
2549   if (getLexer().isNot(AsmToken::Identifier)) {
2550     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
2551     return true;
2552   }
2553
2554   StringRef IDVal = Parser.getTok().getIdentifier();
2555   if (IDVal == "lower16") {
2556     RefKind = ARMMCExpr::VK_ARM_LO16;
2557   } else if (IDVal == "upper16") {
2558     RefKind = ARMMCExpr::VK_ARM_HI16;
2559   } else {
2560     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
2561     return true;
2562   }
2563   Parser.Lex();
2564
2565   if (getLexer().isNot(AsmToken::Colon)) {
2566     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
2567     return true;
2568   }
2569   Parser.Lex(); // Eat the last ':'
2570   return false;
2571 }
2572
2573 const MCExpr *
2574 ARMAsmParser::applyPrefixToExpr(const MCExpr *E,
2575                                 MCSymbolRefExpr::VariantKind Variant) {
2576   // Recurse over the given expression, rebuilding it to apply the given variant
2577   // to the leftmost symbol.
2578   if (Variant == MCSymbolRefExpr::VK_None)
2579     return E;
2580
2581   switch (E->getKind()) {
2582   case MCExpr::Target:
2583     llvm_unreachable("Can't handle target expr yet");
2584   case MCExpr::Constant:
2585     llvm_unreachable("Can't handle lower16/upper16 of constant yet");
2586
2587   case MCExpr::SymbolRef: {
2588     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
2589
2590     if (SRE->getKind() != MCSymbolRefExpr::VK_None)
2591       return 0;
2592
2593     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
2594   }
2595
2596   case MCExpr::Unary:
2597     llvm_unreachable("Can't handle unary expressions yet");
2598
2599   case MCExpr::Binary: {
2600     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
2601     const MCExpr *LHS = applyPrefixToExpr(BE->getLHS(), Variant);
2602     const MCExpr *RHS = BE->getRHS();
2603     if (!LHS)
2604       return 0;
2605
2606     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
2607   }
2608   }
2609
2610   assert(0 && "Invalid expression kind!");
2611   return 0;
2612 }
2613
2614 /// \brief Given a mnemonic, split out possible predication code and carry
2615 /// setting letters to form a canonical mnemonic and flags.
2616 //
2617 // FIXME: Would be nice to autogen this.
2618 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
2619                                       unsigned &PredicationCode,
2620                                       bool &CarrySetting,
2621                                       unsigned &ProcessorIMod) {
2622   PredicationCode = ARMCC::AL;
2623   CarrySetting = false;
2624   ProcessorIMod = 0;
2625
2626   // Ignore some mnemonics we know aren't predicated forms.
2627   //
2628   // FIXME: Would be nice to autogen this.
2629   if ((Mnemonic == "movs" && isThumb()) ||
2630       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
2631       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
2632       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
2633       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
2634       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
2635       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
2636       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal")
2637     return Mnemonic;
2638
2639   // First, split out any predication code. Ignore mnemonics we know aren't
2640   // predicated but do have a carry-set and so weren't caught above.
2641   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
2642       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
2643       Mnemonic != "umlals" && Mnemonic != "umulls") {
2644     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
2645       .Case("eq", ARMCC::EQ)
2646       .Case("ne", ARMCC::NE)
2647       .Case("hs", ARMCC::HS)
2648       .Case("cs", ARMCC::HS)
2649       .Case("lo", ARMCC::LO)
2650       .Case("cc", ARMCC::LO)
2651       .Case("mi", ARMCC::MI)
2652       .Case("pl", ARMCC::PL)
2653       .Case("vs", ARMCC::VS)
2654       .Case("vc", ARMCC::VC)
2655       .Case("hi", ARMCC::HI)
2656       .Case("ls", ARMCC::LS)
2657       .Case("ge", ARMCC::GE)
2658       .Case("lt", ARMCC::LT)
2659       .Case("gt", ARMCC::GT)
2660       .Case("le", ARMCC::LE)
2661       .Case("al", ARMCC::AL)
2662       .Default(~0U);
2663     if (CC != ~0U) {
2664       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
2665       PredicationCode = CC;
2666     }
2667   }
2668
2669   // Next, determine if we have a carry setting bit. We explicitly ignore all
2670   // the instructions we know end in 's'.
2671   if (Mnemonic.endswith("s") &&
2672       !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" ||
2673         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
2674         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
2675         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
2676         Mnemonic == "vrsqrts" || Mnemonic == "srs" ||
2677         (Mnemonic == "movs" && isThumb()))) {
2678     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
2679     CarrySetting = true;
2680   }
2681
2682   // The "cps" instruction can have a interrupt mode operand which is glued into
2683   // the mnemonic. Check if this is the case, split it and parse the imod op
2684   if (Mnemonic.startswith("cps")) {
2685     // Split out any imod code.
2686     unsigned IMod =
2687       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
2688       .Case("ie", ARM_PROC::IE)
2689       .Case("id", ARM_PROC::ID)
2690       .Default(~0U);
2691     if (IMod != ~0U) {
2692       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
2693       ProcessorIMod = IMod;
2694     }
2695   }
2696
2697   return Mnemonic;
2698 }
2699
2700 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
2701 /// inclusion of carry set or predication code operands.
2702 //
2703 // FIXME: It would be nice to autogen this.
2704 void ARMAsmParser::
2705 getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
2706                       bool &CanAcceptPredicationCode) {
2707   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
2708       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
2709       Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" ||
2710       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
2711       Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mvn" ||
2712       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
2713       Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" ||
2714       Mnemonic == "eor" || Mnemonic == "smlal" ||
2715       (Mnemonic == "mov" && !isThumbOne())) {
2716     CanAcceptCarrySet = true;
2717   } else {
2718     CanAcceptCarrySet = false;
2719   }
2720
2721   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
2722       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
2723       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
2724       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
2725       Mnemonic == "dsb" || Mnemonic == "isb" || Mnemonic == "clrex" ||
2726       Mnemonic == "setend" ||
2727       ((Mnemonic == "pld" || Mnemonic == "pli") && !isThumb()) ||
2728       ((Mnemonic.startswith("rfe") || Mnemonic.startswith("srs"))
2729         && !isThumb()) ||
2730       Mnemonic.startswith("cps") || (Mnemonic == "movs" && isThumb())) {
2731     CanAcceptPredicationCode = false;
2732   } else {
2733     CanAcceptPredicationCode = true;
2734   }
2735
2736   if (isThumb())
2737     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
2738         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
2739       CanAcceptPredicationCode = false;
2740 }
2741
2742 /// Parse an arm instruction mnemonic followed by its operands.
2743 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
2744                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2745   // Create the leading tokens for the mnemonic, split by '.' characters.
2746   size_t Start = 0, Next = Name.find('.');
2747   StringRef Mnemonic = Name.slice(Start, Next);
2748
2749   // Split out the predication code and carry setting flag from the mnemonic.
2750   unsigned PredicationCode;
2751   unsigned ProcessorIMod;
2752   bool CarrySetting;
2753   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
2754                            ProcessorIMod);
2755
2756   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
2757
2758   // FIXME: This is all a pretty gross hack. We should automatically handle
2759   // optional operands like this via tblgen.
2760
2761   // Next, add the CCOut and ConditionCode operands, if needed.
2762   //
2763   // For mnemonics which can ever incorporate a carry setting bit or predication
2764   // code, our matching model involves us always generating CCOut and
2765   // ConditionCode operands to match the mnemonic "as written" and then we let
2766   // the matcher deal with finding the right instruction or generating an
2767   // appropriate error.
2768   bool CanAcceptCarrySet, CanAcceptPredicationCode;
2769   getMnemonicAcceptInfo(Mnemonic, CanAcceptCarrySet, CanAcceptPredicationCode);
2770
2771   // If we had a carry-set on an instruction that can't do that, issue an
2772   // error.
2773   if (!CanAcceptCarrySet && CarrySetting) {
2774     Parser.EatToEndOfStatement();
2775     return Error(NameLoc, "instruction '" + Mnemonic +
2776                  "' can not set flags, but 's' suffix specified");
2777   }
2778   // If we had a predication code on an instruction that can't do that, issue an
2779   // error.
2780   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
2781     Parser.EatToEndOfStatement();
2782     return Error(NameLoc, "instruction '" + Mnemonic +
2783                  "' is not predicable, but condition code specified");
2784   }
2785
2786   // Add the carry setting operand, if necessary.
2787   //
2788   // FIXME: It would be awesome if we could somehow invent a location such that
2789   // match errors on this operand would print a nice diagnostic about how the
2790   // 's' character in the mnemonic resulted in a CCOut operand.
2791   if (CanAcceptCarrySet)
2792     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
2793                                                NameLoc));
2794
2795   // Add the predication code operand, if necessary.
2796   if (CanAcceptPredicationCode) {
2797     Operands.push_back(ARMOperand::CreateCondCode(
2798                          ARMCC::CondCodes(PredicationCode), NameLoc));
2799   }
2800
2801   // Add the processor imod operand, if necessary.
2802   if (ProcessorIMod) {
2803     Operands.push_back(ARMOperand::CreateImm(
2804           MCConstantExpr::Create(ProcessorIMod, getContext()),
2805                                  NameLoc, NameLoc));
2806   } else {
2807     // This mnemonic can't ever accept a imod, but the user wrote
2808     // one (or misspelled another mnemonic).
2809
2810     // FIXME: Issue a nice error.
2811   }
2812
2813   // Add the remaining tokens in the mnemonic.
2814   while (Next != StringRef::npos) {
2815     Start = Next;
2816     Next = Name.find('.', Start + 1);
2817     StringRef ExtraToken = Name.slice(Start, Next);
2818
2819     Operands.push_back(ARMOperand::CreateToken(ExtraToken, NameLoc));
2820   }
2821
2822   // Read the remaining operands.
2823   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2824     // Read the first operand.
2825     if (parseOperand(Operands, Mnemonic)) {
2826       Parser.EatToEndOfStatement();
2827       return true;
2828     }
2829
2830     while (getLexer().is(AsmToken::Comma)) {
2831       Parser.Lex();  // Eat the comma.
2832
2833       // Parse and remember the operand.
2834       if (parseOperand(Operands, Mnemonic)) {
2835         Parser.EatToEndOfStatement();
2836         return true;
2837       }
2838     }
2839   }
2840
2841   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2842     Parser.EatToEndOfStatement();
2843     return TokError("unexpected token in argument list");
2844   }
2845
2846   Parser.Lex(); // Consume the EndOfStatement
2847
2848
2849   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
2850   // another does not. Specifically, the MOVW instruction does not. So we
2851   // special case it here and remove the defaulted (non-setting) cc_out
2852   // operand if that's the instruction we're trying to match.
2853   //
2854   // We do this post-processing of the explicit operands rather than just
2855   // conditionally adding the cc_out in the first place because we need
2856   // to check the type of the parsed immediate operand.
2857   if (Mnemonic == "mov" && Operands.size() > 4 &&
2858       !static_cast<ARMOperand*>(Operands[4])->isARMSOImm() &&
2859       static_cast<ARMOperand*>(Operands[4])->isImm0_65535Expr() &&
2860       static_cast<ARMOperand*>(Operands[1])->getReg() == 0) {
2861     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
2862     Operands.erase(Operands.begin() + 1);
2863     delete Op;
2864   }
2865
2866   // ARM mode 'blx' need special handling, as the register operand version
2867   // is predicable, but the label operand version is not. So, we can't rely
2868   // on the Mnemonic based checking to correctly figure out when to put
2869   // a CondCode operand in the list. If we're trying to match the label
2870   // version, remove the CondCode operand here.
2871   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
2872       static_cast<ARMOperand*>(Operands[2])->isImm()) {
2873     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
2874     Operands.erase(Operands.begin() + 1);
2875     delete Op;
2876   }
2877
2878   // The vector-compare-to-zero instructions have a literal token "#0" at
2879   // the end that comes to here as an immediate operand. Convert it to a
2880   // token to play nicely with the matcher.
2881   if ((Mnemonic == "vceq" || Mnemonic == "vcge" || Mnemonic == "vcgt" ||
2882       Mnemonic == "vcle" || Mnemonic == "vclt") && Operands.size() == 6 &&
2883       static_cast<ARMOperand*>(Operands[5])->isImm()) {
2884     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
2885     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
2886     if (CE && CE->getValue() == 0) {
2887       Operands.erase(Operands.begin() + 5);
2888       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
2889       delete Op;
2890     }
2891   }
2892   return false;
2893 }
2894
2895 // Validate context-sensitive operand constraints.
2896 // FIXME: We would really like to be able to tablegen'erate this.
2897 bool ARMAsmParser::
2898 validateInstruction(MCInst &Inst,
2899                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2900   switch (Inst.getOpcode()) {
2901   case ARM::LDRD:
2902   case ARM::LDRD_PRE:
2903   case ARM::LDRD_POST:
2904   case ARM::LDREXD: {
2905     // Rt2 must be Rt + 1.
2906     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
2907     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
2908     if (Rt2 != Rt + 1)
2909       return Error(Operands[3]->getStartLoc(),
2910                    "destination operands must be sequential");
2911     return false;
2912   }
2913   case ARM::STRD: {
2914     // Rt2 must be Rt + 1.
2915     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
2916     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
2917     if (Rt2 != Rt + 1)
2918       return Error(Operands[3]->getStartLoc(),
2919                    "source operands must be sequential");
2920     return false;
2921   }
2922   case ARM::STRD_PRE:
2923   case ARM::STRD_POST:
2924   case ARM::STREXD: {
2925     // Rt2 must be Rt + 1.
2926     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(1).getReg());
2927     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(2).getReg());
2928     if (Rt2 != Rt + 1)
2929       return Error(Operands[3]->getStartLoc(),
2930                    "source operands must be sequential");
2931     return false;
2932   }
2933   case ARM::SBFX:
2934   case ARM::UBFX: {
2935     // width must be in range [1, 32-lsb]
2936     unsigned lsb = Inst.getOperand(2).getImm();
2937     unsigned widthm1 = Inst.getOperand(3).getImm();
2938     if (widthm1 >= 32 - lsb)
2939       return Error(Operands[5]->getStartLoc(),
2940                    "bitfield width must be in range [1,32-lsb]");
2941   }
2942   }
2943
2944   return false;
2945 }
2946
2947 void ARMAsmParser::
2948 processInstruction(MCInst &Inst,
2949                    const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2950   switch (Inst.getOpcode()) {
2951   case ARM::LDMIA_UPD:
2952     // If this is a load of a single register via a 'pop', then we should use
2953     // a post-indexed LDR instruction instead, per the ARM ARM.
2954     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "pop" &&
2955         Inst.getNumOperands() == 5) {
2956       MCInst TmpInst;
2957       TmpInst.setOpcode(ARM::LDR_POST_IMM);
2958       TmpInst.addOperand(Inst.getOperand(4)); // Rt
2959       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
2960       TmpInst.addOperand(Inst.getOperand(1)); // Rn
2961       TmpInst.addOperand(MCOperand::CreateReg(0));  // am2offset
2962       TmpInst.addOperand(MCOperand::CreateImm(4));
2963       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
2964       TmpInst.addOperand(Inst.getOperand(3));
2965       Inst = TmpInst;
2966     }
2967     break;
2968   case ARM::STMDB_UPD:
2969     // If this is a store of a single register via a 'push', then we should use
2970     // a pre-indexed STR instruction instead, per the ARM ARM.
2971     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "push" &&
2972         Inst.getNumOperands() == 5) {
2973       MCInst TmpInst;
2974       TmpInst.setOpcode(ARM::STR_PRE_IMM);
2975       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
2976       TmpInst.addOperand(Inst.getOperand(4)); // Rt
2977       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
2978       TmpInst.addOperand(MCOperand::CreateImm(-4));
2979       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
2980       TmpInst.addOperand(Inst.getOperand(3));
2981       Inst = TmpInst;
2982     }
2983     break;
2984   }
2985 }
2986
2987 // FIXME: We would really prefer to have MCInstrInfo (the wrapper around
2988 // the ARMInsts array) instead. Getting that here requires awkward
2989 // API changes, though. Better way?
2990 namespace llvm {
2991 extern MCInstrDesc ARMInsts[];
2992 }
2993 static MCInstrDesc &getInstDesc(unsigned Opcode) {
2994   return ARMInsts[Opcode];
2995 }
2996
2997 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
2998   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
2999   // suffix depending on whether they're in an IT block or not.
3000   MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
3001   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
3002     assert(MCID.hasOptionalDef() &&
3003            "optionally flag setting instruction missing optional def operand");
3004     assert(MCID.NumOperands == Inst.getNumOperands() &&
3005            "operand count mismatch!");
3006     // Find the optional-def operand (cc_out).
3007     unsigned OpNo;
3008     for (OpNo = 0;
3009          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
3010          ++OpNo)
3011       ;
3012     // If we're parsing Thumb1, reject it completely.
3013     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
3014       return Match_MnemonicFail;
3015     // If we're parsing Thumb2, which form is legal depends on whether we're
3016     // in an IT block.
3017     // FIXME: We don't yet do IT blocks, so just always consider it to be
3018     // that we aren't in one until we do.
3019     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
3020       return Match_RequiresITBlock;
3021   }
3022   return Match_Success;
3023 }
3024
3025 bool ARMAsmParser::
3026 MatchAndEmitInstruction(SMLoc IDLoc,
3027                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
3028                         MCStreamer &Out) {
3029   MCInst Inst;
3030   unsigned ErrorInfo;
3031   unsigned MatchResult;
3032   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
3033   switch (MatchResult) {
3034   default: break;
3035   case Match_Success:
3036     // Context sensitive operand constraints aren't handled by the matcher,
3037     // so check them here.
3038     if (validateInstruction(Inst, Operands))
3039       return true;
3040
3041     // Some instructions need post-processing to, for example, tweak which
3042     // encoding is selected.
3043     processInstruction(Inst, Operands);
3044
3045     Out.EmitInstruction(Inst);
3046     return false;
3047   case Match_MissingFeature:
3048     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
3049     return true;
3050   case Match_InvalidOperand: {
3051     SMLoc ErrorLoc = IDLoc;
3052     if (ErrorInfo != ~0U) {
3053       if (ErrorInfo >= Operands.size())
3054         return Error(IDLoc, "too few operands for instruction");
3055
3056       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
3057       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
3058     }
3059
3060     return Error(ErrorLoc, "invalid operand for instruction");
3061   }
3062   case Match_MnemonicFail:
3063     return Error(IDLoc, "invalid instruction");
3064   case Match_ConversionFail:
3065     return Error(IDLoc, "unable to convert operands to instruction");
3066   case Match_RequiresITBlock:
3067     return Error(IDLoc, "instruction only valid inside IT block");
3068   }
3069
3070   llvm_unreachable("Implement any new match types added!");
3071   return true;
3072 }
3073
3074 /// parseDirective parses the arm specific directives
3075 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
3076   StringRef IDVal = DirectiveID.getIdentifier();
3077   if (IDVal == ".word")
3078     return parseDirectiveWord(4, DirectiveID.getLoc());
3079   else if (IDVal == ".thumb")
3080     return parseDirectiveThumb(DirectiveID.getLoc());
3081   else if (IDVal == ".thumb_func")
3082     return parseDirectiveThumbFunc(DirectiveID.getLoc());
3083   else if (IDVal == ".code")
3084     return parseDirectiveCode(DirectiveID.getLoc());
3085   else if (IDVal == ".syntax")
3086     return parseDirectiveSyntax(DirectiveID.getLoc());
3087   return true;
3088 }
3089
3090 /// parseDirectiveWord
3091 ///  ::= .word [ expression (, expression)* ]
3092 bool ARMAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
3093   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3094     for (;;) {
3095       const MCExpr *Value;
3096       if (getParser().ParseExpression(Value))
3097         return true;
3098
3099       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
3100
3101       if (getLexer().is(AsmToken::EndOfStatement))
3102         break;
3103
3104       // FIXME: Improve diagnostic.
3105       if (getLexer().isNot(AsmToken::Comma))
3106         return Error(L, "unexpected token in directive");
3107       Parser.Lex();
3108     }
3109   }
3110
3111   Parser.Lex();
3112   return false;
3113 }
3114
3115 /// parseDirectiveThumb
3116 ///  ::= .thumb
3117 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
3118   if (getLexer().isNot(AsmToken::EndOfStatement))
3119     return Error(L, "unexpected token in directive");
3120   Parser.Lex();
3121
3122   // TODO: set thumb mode
3123   // TODO: tell the MC streamer the mode
3124   // getParser().getStreamer().Emit???();
3125   return false;
3126 }
3127
3128 /// parseDirectiveThumbFunc
3129 ///  ::= .thumbfunc symbol_name
3130 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
3131   const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
3132   bool isMachO = MAI.hasSubsectionsViaSymbols();
3133   StringRef Name;
3134
3135   // Darwin asm has function name after .thumb_func direction
3136   // ELF doesn't
3137   if (isMachO) {
3138     const AsmToken &Tok = Parser.getTok();
3139     if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
3140       return Error(L, "unexpected token in .thumb_func directive");
3141     Name = Tok.getString();
3142     Parser.Lex(); // Consume the identifier token.
3143   }
3144
3145   if (getLexer().isNot(AsmToken::EndOfStatement))
3146     return Error(L, "unexpected token in directive");
3147   Parser.Lex();
3148
3149   // FIXME: assuming function name will be the line following .thumb_func
3150   if (!isMachO) {
3151     Name = Parser.getTok().getString();
3152   }
3153
3154   // Mark symbol as a thumb symbol.
3155   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
3156   getParser().getStreamer().EmitThumbFunc(Func);
3157   return false;
3158 }
3159
3160 /// parseDirectiveSyntax
3161 ///  ::= .syntax unified | divided
3162 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
3163   const AsmToken &Tok = Parser.getTok();
3164   if (Tok.isNot(AsmToken::Identifier))
3165     return Error(L, "unexpected token in .syntax directive");
3166   StringRef Mode = Tok.getString();
3167   if (Mode == "unified" || Mode == "UNIFIED")
3168     Parser.Lex();
3169   else if (Mode == "divided" || Mode == "DIVIDED")
3170     return Error(L, "'.syntax divided' arm asssembly not supported");
3171   else
3172     return Error(L, "unrecognized syntax mode in .syntax directive");
3173
3174   if (getLexer().isNot(AsmToken::EndOfStatement))
3175     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
3176   Parser.Lex();
3177
3178   // TODO tell the MC streamer the mode
3179   // getParser().getStreamer().Emit???();
3180   return false;
3181 }
3182
3183 /// parseDirectiveCode
3184 ///  ::= .code 16 | 32
3185 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
3186   const AsmToken &Tok = Parser.getTok();
3187   if (Tok.isNot(AsmToken::Integer))
3188     return Error(L, "unexpected token in .code directive");
3189   int64_t Val = Parser.getTok().getIntVal();
3190   if (Val == 16)
3191     Parser.Lex();
3192   else if (Val == 32)
3193     Parser.Lex();
3194   else
3195     return Error(L, "invalid operand to .code directive");
3196
3197   if (getLexer().isNot(AsmToken::EndOfStatement))
3198     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
3199   Parser.Lex();
3200
3201   if (Val == 16) {
3202     if (!isThumb()) {
3203       SwitchMode();
3204       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
3205     }
3206   } else {
3207     if (isThumb()) {
3208       SwitchMode();
3209       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
3210     }
3211   }
3212
3213   return false;
3214 }
3215
3216 extern "C" void LLVMInitializeARMAsmLexer();
3217
3218 /// Force static initialization.
3219 extern "C" void LLVMInitializeARMAsmParser() {
3220   RegisterMCAsmParser<ARMAsmParser> X(TheARMTarget);
3221   RegisterMCAsmParser<ARMAsmParser> Y(TheThumbTarget);
3222   LLVMInitializeARMAsmLexer();
3223 }
3224
3225 #define GET_REGISTER_MATCHER
3226 #define GET_MATCHER_IMPLEMENTATION
3227 #include "ARMGenAsmMatcher.inc"