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