1 //===-- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "ARMAddressingModes.h"
12 #include "ARMMCExpr.h"
13 #include "ARMBaseRegisterInfo.h"
14 #include "ARMSubtarget.h"
15 #include "llvm/MC/MCParser/MCAsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmParser.h"
17 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/Target/TargetRegistry.h"
24 #include "llvm/Target/TargetAsmParser.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Twine.h"
37 class ARMAsmParser : public TargetAsmParser {
41 MCAsmParser &getParser() const { return Parser; }
42 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
44 void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
45 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
47 int TryParseRegister();
48 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
49 bool TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
50 bool TryParseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
51 bool ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
52 bool ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &,
53 ARMII::AddrMode AddrMode);
54 bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
55 bool ParsePrefix(ARMMCExpr::VariantKind &RefKind);
56 const MCExpr *ApplyPrefixToExpr(const MCExpr *E,
57 MCSymbolRefExpr::VariantKind Variant);
60 bool ParseMemoryOffsetReg(bool &Negative,
61 bool &OffsetRegShifted,
62 enum ARM_AM::ShiftOpc &ShiftType,
63 const MCExpr *&ShiftAmount,
64 const MCExpr *&Offset,
68 bool ParseShift(enum ARM_AM::ShiftOpc &St,
69 const MCExpr *&ShiftAmount, SMLoc &E);
70 bool ParseDirectiveWord(unsigned Size, SMLoc L);
71 bool ParseDirectiveThumb(SMLoc L);
72 bool ParseDirectiveThumbFunc(SMLoc L);
73 bool ParseDirectiveCode(SMLoc L);
74 bool ParseDirectiveSyntax(SMLoc L);
76 bool MatchAndEmitInstruction(SMLoc IDLoc,
77 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
79 void GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
80 bool &CanAcceptPredicationCode);
82 /// @name Auto-generated Match Functions
85 #define GET_ASSEMBLER_HEADER
86 #include "ARMGenAsmMatcher.inc"
90 OperandMatchResultTy tryParseCoprocNumOperand(
91 SmallVectorImpl<MCParsedAsmOperand*>&);
92 OperandMatchResultTy tryParseCoprocRegOperand(
93 SmallVectorImpl<MCParsedAsmOperand*>&);
94 OperandMatchResultTy tryParseMemBarrierOptOperand(
95 SmallVectorImpl<MCParsedAsmOperand*>&);
96 OperandMatchResultTy tryParseProcIFlagsOperand(
97 SmallVectorImpl<MCParsedAsmOperand*>&);
98 OperandMatchResultTy tryParseMSRMaskOperand(
99 SmallVectorImpl<MCParsedAsmOperand*>&);
100 OperandMatchResultTy tryParseMemMode2Operand(
101 SmallVectorImpl<MCParsedAsmOperand*>&);
102 OperandMatchResultTy tryParseMemMode3Operand(
103 SmallVectorImpl<MCParsedAsmOperand*>&);
105 // Asm Match Converter Methods
106 bool CvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
107 const SmallVectorImpl<MCParsedAsmOperand*> &);
108 bool CvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
109 const SmallVectorImpl<MCParsedAsmOperand*> &);
110 bool CvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
111 const SmallVectorImpl<MCParsedAsmOperand*> &);
112 bool CvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
113 const SmallVectorImpl<MCParsedAsmOperand*> &);
116 ARMAsmParser(const Target &T, MCAsmParser &_Parser, TargetMachine &_TM)
117 : TargetAsmParser(T), Parser(_Parser), TM(_TM) {
118 MCAsmParserExtension::Initialize(_Parser);
119 // Initialize the set of available features.
120 setAvailableFeatures(ComputeAvailableFeatures(
121 &TM.getSubtarget<ARMSubtarget>()));
124 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
125 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
126 virtual bool ParseDirective(AsmToken DirectiveID);
128 } // end anonymous namespace
132 /// ARMOperand - Instances of this class represent a parsed ARM machine
134 class ARMOperand : public MCParsedAsmOperand {
153 SMLoc StartLoc, EndLoc;
154 SmallVector<unsigned, 8> Registers;
158 ARMCC::CondCodes Val;
170 ARM_PROC::IFlags Val;
190 /// Combined record for all forms of ARM address expressions.
192 ARMII::AddrMode AddrMode;
195 unsigned RegNum; ///< Offset register num, when OffsetIsReg.
196 const MCExpr *Value; ///< Offset value, when !OffsetIsReg.
198 const MCExpr *ShiftAmount; // used when OffsetRegShifted is true
199 enum ARM_AM::ShiftOpc ShiftType; // used when OffsetRegShifted is true
200 unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
201 unsigned Preindexed : 1;
202 unsigned Postindexed : 1;
203 unsigned OffsetIsReg : 1;
204 unsigned Negative : 1; // only used when OffsetIsReg is true
205 unsigned Writeback : 1;
209 ARM_AM::ShiftOpc ShiftTy;
214 ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
216 ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
218 StartLoc = o.StartLoc;
232 case DPRRegisterList:
233 case SPRRegisterList:
234 Registers = o.Registers;
261 /// getStartLoc - Get the location of the first token of this operand.
262 SMLoc getStartLoc() const { return StartLoc; }
263 /// getEndLoc - Get the location of the last token of this operand.
264 SMLoc getEndLoc() const { return EndLoc; }
266 ARMCC::CondCodes getCondCode() const {
267 assert(Kind == CondCode && "Invalid access!");
271 unsigned getCoproc() const {
272 assert((Kind == CoprocNum || Kind == CoprocReg) && "Invalid access!");
276 StringRef getToken() const {
277 assert(Kind == Token && "Invalid access!");
278 return StringRef(Tok.Data, Tok.Length);
281 unsigned getReg() const {
282 assert((Kind == Register || Kind == CCOut) && "Invalid access!");
286 const SmallVectorImpl<unsigned> &getRegList() const {
287 assert((Kind == RegisterList || Kind == DPRRegisterList ||
288 Kind == SPRRegisterList) && "Invalid access!");
292 const MCExpr *getImm() const {
293 assert(Kind == Immediate && "Invalid access!");
297 ARM_MB::MemBOpt getMemBarrierOpt() const {
298 assert(Kind == MemBarrierOpt && "Invalid access!");
302 ARM_PROC::IFlags getProcIFlags() const {
303 assert(Kind == ProcIFlags && "Invalid access!");
307 unsigned getMSRMask() const {
308 assert(Kind == MSRMask && "Invalid access!");
312 /// @name Memory Operand Accessors
314 ARMII::AddrMode getMemAddrMode() const {
317 unsigned getMemBaseRegNum() const {
318 return Mem.BaseRegNum;
320 unsigned getMemOffsetRegNum() const {
321 assert(Mem.OffsetIsReg && "Invalid access!");
322 return Mem.Offset.RegNum;
324 const MCExpr *getMemOffset() const {
325 assert(!Mem.OffsetIsReg && "Invalid access!");
326 return Mem.Offset.Value;
328 unsigned getMemOffsetRegShifted() const {
329 assert(Mem.OffsetIsReg && "Invalid access!");
330 return Mem.OffsetRegShifted;
332 const MCExpr *getMemShiftAmount() const {
333 assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
334 return Mem.ShiftAmount;
336 enum ARM_AM::ShiftOpc getMemShiftType() const {
337 assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
338 return Mem.ShiftType;
340 bool getMemPreindexed() const { return Mem.Preindexed; }
341 bool getMemPostindexed() const { return Mem.Postindexed; }
342 bool getMemOffsetIsReg() const { return Mem.OffsetIsReg; }
343 bool getMemNegative() const { return Mem.Negative; }
344 bool getMemWriteback() const { return Mem.Writeback; }
348 bool isCoprocNum() const { return Kind == CoprocNum; }
349 bool isCoprocReg() const { return Kind == CoprocReg; }
350 bool isCondCode() const { return Kind == CondCode; }
351 bool isCCOut() const { return Kind == CCOut; }
352 bool isImm() const { return Kind == Immediate; }
353 bool isImm0_255() const {
354 if (Kind != Immediate)
356 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
357 if (!CE) return false;
358 int64_t Value = CE->getValue();
359 return Value >= 0 && Value < 256;
361 bool isT2SOImm() const {
362 if (Kind != Immediate)
364 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
365 if (!CE) return false;
366 int64_t Value = CE->getValue();
367 return ARM_AM::getT2SOImmVal(Value) != -1;
369 bool isReg() const { return Kind == Register; }
370 bool isRegList() const { return Kind == RegisterList; }
371 bool isDPRRegList() const { return Kind == DPRRegisterList; }
372 bool isSPRRegList() const { return Kind == SPRRegisterList; }
373 bool isToken() const { return Kind == Token; }
374 bool isMemBarrierOpt() const { return Kind == MemBarrierOpt; }
375 bool isMemory() const { return Kind == Memory; }
376 bool isShifter() const { return Kind == Shifter; }
377 bool isMemMode2() const {
378 if (getMemAddrMode() != ARMII::AddrMode2)
381 if (getMemOffsetIsReg())
384 if (getMemNegative() &&
385 !(getMemPostindexed() || getMemPreindexed()))
388 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
389 if (!CE) return false;
390 int64_t Value = CE->getValue();
392 // The offset must be in the range 0-4095 (imm12).
393 if (Value > 4095 || Value < -4095)
398 bool isMemMode3() const {
399 if (getMemAddrMode() != ARMII::AddrMode3)
402 if (getMemOffsetIsReg()) {
403 if (getMemOffsetRegShifted())
404 return false; // No shift with offset reg allowed
408 if (getMemNegative() &&
409 !(getMemPostindexed() || getMemPreindexed()))
412 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
413 if (!CE) return false;
414 int64_t Value = CE->getValue();
416 // The offset must be in the range 0-255 (imm8).
417 if (Value > 255 || Value < -255)
422 bool isMemMode5() const {
423 if (!isMemory() || getMemOffsetIsReg() || getMemWriteback() ||
427 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
428 if (!CE) return false;
430 // The offset must be a multiple of 4 in the range 0-1020.
431 int64_t Value = CE->getValue();
432 return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
434 bool isMemMode7() const {
436 getMemPreindexed() ||
437 getMemPostindexed() ||
438 getMemOffsetIsReg() ||
443 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
444 if (!CE) return false;
451 bool isMemModeRegThumb() const {
452 if (!isMemory() || !getMemOffsetIsReg() || getMemWriteback())
456 bool isMemModeImmThumb() const {
457 if (!isMemory() || getMemOffsetIsReg() || getMemWriteback())
460 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
461 if (!CE) return false;
463 // The offset must be a multiple of 4 in the range 0-124.
464 uint64_t Value = CE->getValue();
465 return ((Value & 0x3) == 0 && Value <= 124);
467 bool isMSRMask() const { return Kind == MSRMask; }
468 bool isProcIFlags() const { return Kind == ProcIFlags; }
470 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
471 // Add as immediates when possible. Null MCExpr = 0.
473 Inst.addOperand(MCOperand::CreateImm(0));
474 else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
475 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
477 Inst.addOperand(MCOperand::CreateExpr(Expr));
480 void addCondCodeOperands(MCInst &Inst, unsigned N) const {
481 assert(N == 2 && "Invalid number of operands!");
482 Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
483 unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
484 Inst.addOperand(MCOperand::CreateReg(RegNum));
487 void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
488 assert(N == 1 && "Invalid number of operands!");
489 Inst.addOperand(MCOperand::CreateImm(getCoproc()));
492 void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
493 assert(N == 1 && "Invalid number of operands!");
494 Inst.addOperand(MCOperand::CreateImm(getCoproc()));
497 void addCCOutOperands(MCInst &Inst, unsigned N) const {
498 assert(N == 1 && "Invalid number of operands!");
499 Inst.addOperand(MCOperand::CreateReg(getReg()));
502 void addRegOperands(MCInst &Inst, unsigned N) const {
503 assert(N == 1 && "Invalid number of operands!");
504 Inst.addOperand(MCOperand::CreateReg(getReg()));
507 void addShifterOperands(MCInst &Inst, unsigned N) const {
508 assert(N == 1 && "Invalid number of operands!");
509 Inst.addOperand(MCOperand::CreateImm(
510 ARM_AM::getSORegOpc(Shift.ShiftTy, 0)));
513 void addRegListOperands(MCInst &Inst, unsigned N) const {
514 assert(N == 1 && "Invalid number of operands!");
515 const SmallVectorImpl<unsigned> &RegList = getRegList();
516 for (SmallVectorImpl<unsigned>::const_iterator
517 I = RegList.begin(), E = RegList.end(); I != E; ++I)
518 Inst.addOperand(MCOperand::CreateReg(*I));
521 void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
522 addRegListOperands(Inst, N);
525 void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
526 addRegListOperands(Inst, N);
529 void addImmOperands(MCInst &Inst, unsigned N) const {
530 assert(N == 1 && "Invalid number of operands!");
531 addExpr(Inst, getImm());
534 void addImm0_255Operands(MCInst &Inst, unsigned N) const {
535 assert(N == 1 && "Invalid number of operands!");
536 addExpr(Inst, getImm());
539 void addT2SOImmOperands(MCInst &Inst, unsigned N) const {
540 assert(N == 1 && "Invalid number of operands!");
541 addExpr(Inst, getImm());
544 void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
545 assert(N == 1 && "Invalid number of operands!");
546 Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
549 void addMemMode7Operands(MCInst &Inst, unsigned N) const {
550 assert(N == 1 && isMemMode7() && "Invalid number of operands!");
551 Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
553 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
555 assert((CE || CE->getValue() == 0) &&
556 "No offset operand support in mode 7");
559 void addMemMode2Operands(MCInst &Inst, unsigned N) const {
560 assert(isMemMode2() && "Invalid mode or number of operands!");
561 Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
562 unsigned IdxMode = (getMemPreindexed() | getMemPostindexed() << 1);
564 if (getMemOffsetIsReg()) {
565 Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
567 ARM_AM::AddrOpc AMOpc = getMemNegative() ? ARM_AM::sub : ARM_AM::add;
568 ARM_AM::ShiftOpc ShOpc = ARM_AM::no_shift;
569 int64_t ShiftAmount = 0;
571 if (getMemOffsetRegShifted()) {
572 ShOpc = getMemShiftType();
573 const MCConstantExpr *CE =
574 dyn_cast<MCConstantExpr>(getMemShiftAmount());
575 ShiftAmount = CE->getValue();
578 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(AMOpc, ShiftAmount,
583 // Create a operand placeholder to always yield the same number of operands.
584 Inst.addOperand(MCOperand::CreateReg(0));
586 // FIXME: #-0 is encoded differently than #0. Does the parser preserve
588 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
589 assert(CE && "Non-constant mode 2 offset operand!");
590 int64_t Offset = CE->getValue();
593 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(ARM_AM::add,
594 Offset, ARM_AM::no_shift, IdxMode)));
596 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(ARM_AM::sub,
597 -Offset, ARM_AM::no_shift, IdxMode)));
600 void addMemMode3Operands(MCInst &Inst, unsigned N) const {
601 assert(isMemMode3() && "Invalid mode or number of operands!");
602 Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
603 unsigned IdxMode = (getMemPreindexed() | getMemPostindexed() << 1);
605 if (getMemOffsetIsReg()) {
606 Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
608 ARM_AM::AddrOpc AMOpc = getMemNegative() ? ARM_AM::sub : ARM_AM::add;
609 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM3Opc(AMOpc, 0,
614 // Create a operand placeholder to always yield the same number of operands.
615 Inst.addOperand(MCOperand::CreateReg(0));
617 // FIXME: #-0 is encoded differently than #0. Does the parser preserve
619 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
620 assert(CE && "Non-constant mode 3 offset operand!");
621 int64_t Offset = CE->getValue();
624 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM3Opc(ARM_AM::add,
627 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM3Opc(ARM_AM::sub,
631 void addMemMode5Operands(MCInst &Inst, unsigned N) const {
632 assert(N == 2 && isMemMode5() && "Invalid number of operands!");
634 Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
635 assert(!getMemOffsetIsReg() && "Invalid mode 5 operand");
637 // FIXME: #-0 is encoded differently than #0. Does the parser preserve
639 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
640 assert(CE && "Non-constant mode 5 offset operand!");
642 // The MCInst offset operand doesn't include the low two bits (like
643 // the instruction encoding).
644 int64_t Offset = CE->getValue() / 4;
646 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
649 Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
653 void addMemModeRegThumbOperands(MCInst &Inst, unsigned N) const {
654 assert(N == 2 && isMemModeRegThumb() && "Invalid number of operands!");
655 Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
656 Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
659 void addMemModeImmThumbOperands(MCInst &Inst, unsigned N) const {
660 assert(N == 2 && isMemModeImmThumb() && "Invalid number of operands!");
661 Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
662 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
663 assert(CE && "Non-constant mode offset operand!");
664 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
667 void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
668 assert(N == 1 && "Invalid number of operands!");
669 Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
672 void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
673 assert(N == 1 && "Invalid number of operands!");
674 Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
677 virtual void dump(raw_ostream &OS) const;
679 static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
680 ARMOperand *Op = new ARMOperand(CondCode);
687 static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
688 ARMOperand *Op = new ARMOperand(CoprocNum);
689 Op->Cop.Val = CopVal;
695 static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
696 ARMOperand *Op = new ARMOperand(CoprocReg);
697 Op->Cop.Val = CopVal;
703 static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
704 ARMOperand *Op = new ARMOperand(CCOut);
705 Op->Reg.RegNum = RegNum;
711 static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
712 ARMOperand *Op = new ARMOperand(Token);
713 Op->Tok.Data = Str.data();
714 Op->Tok.Length = Str.size();
720 static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
721 ARMOperand *Op = new ARMOperand(Register);
722 Op->Reg.RegNum = RegNum;
728 static ARMOperand *CreateShifter(ARM_AM::ShiftOpc ShTy,
730 ARMOperand *Op = new ARMOperand(Shifter);
731 Op->Shift.ShiftTy = ShTy;
738 CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
739 SMLoc StartLoc, SMLoc EndLoc) {
740 KindTy Kind = RegisterList;
742 if (ARM::DPRRegClass.contains(Regs.front().first))
743 Kind = DPRRegisterList;
744 else if (ARM::SPRRegClass.contains(Regs.front().first))
745 Kind = SPRRegisterList;
747 ARMOperand *Op = new ARMOperand(Kind);
748 for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
749 I = Regs.begin(), E = Regs.end(); I != E; ++I)
750 Op->Registers.push_back(I->first);
751 array_pod_sort(Op->Registers.begin(), Op->Registers.end());
752 Op->StartLoc = StartLoc;
757 static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
758 ARMOperand *Op = new ARMOperand(Immediate);
765 static ARMOperand *CreateMem(ARMII::AddrMode AddrMode, unsigned BaseRegNum,
766 bool OffsetIsReg, const MCExpr *Offset,
767 int OffsetRegNum, bool OffsetRegShifted,
768 enum ARM_AM::ShiftOpc ShiftType,
769 const MCExpr *ShiftAmount, bool Preindexed,
770 bool Postindexed, bool Negative, bool Writeback,
772 assert((OffsetRegNum == -1 || OffsetIsReg) &&
773 "OffsetRegNum must imply OffsetIsReg!");
774 assert((!OffsetRegShifted || OffsetIsReg) &&
775 "OffsetRegShifted must imply OffsetIsReg!");
776 assert((Offset || OffsetIsReg) &&
777 "Offset must exists unless register offset is used!");
778 assert((!ShiftAmount || (OffsetIsReg && OffsetRegShifted)) &&
779 "Cannot have shift amount without shifted register offset!");
780 assert((!Offset || !OffsetIsReg) &&
781 "Cannot have expression offset and register offset!");
783 ARMOperand *Op = new ARMOperand(Memory);
784 Op->Mem.AddrMode = AddrMode;
785 Op->Mem.BaseRegNum = BaseRegNum;
786 Op->Mem.OffsetIsReg = OffsetIsReg;
788 Op->Mem.Offset.RegNum = OffsetRegNum;
790 Op->Mem.Offset.Value = Offset;
791 Op->Mem.OffsetRegShifted = OffsetRegShifted;
792 Op->Mem.ShiftType = ShiftType;
793 Op->Mem.ShiftAmount = ShiftAmount;
794 Op->Mem.Preindexed = Preindexed;
795 Op->Mem.Postindexed = Postindexed;
796 Op->Mem.Negative = Negative;
797 Op->Mem.Writeback = Writeback;
804 static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
805 ARMOperand *Op = new ARMOperand(MemBarrierOpt);
812 static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
813 ARMOperand *Op = new ARMOperand(ProcIFlags);
814 Op->IFlags.Val = IFlags;
820 static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
821 ARMOperand *Op = new ARMOperand(MSRMask);
822 Op->MMask.Val = MMask;
829 } // end anonymous namespace.
831 void ARMOperand::dump(raw_ostream &OS) const {
834 OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
837 OS << "<ccout " << getReg() << ">";
840 OS << "<coprocessor number: " << getCoproc() << ">";
843 OS << "<coprocessor register: " << getCoproc() << ">";
846 OS << "<mask: " << getMSRMask() << ">";
852 OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
856 << "am:" << ARMII::AddrModeToString(getMemAddrMode())
857 << " base:" << getMemBaseRegNum();
858 if (getMemOffsetIsReg()) {
859 OS << " offset:<register " << getMemOffsetRegNum();
860 if (getMemOffsetRegShifted()) {
861 OS << " offset-shift-type:" << getMemShiftType();
862 OS << " offset-shift-amount:" << *getMemShiftAmount();
865 OS << " offset:" << *getMemOffset();
867 if (getMemOffsetIsReg())
868 OS << " (offset-is-reg)";
869 if (getMemPreindexed())
870 OS << " (pre-indexed)";
871 if (getMemPostindexed())
872 OS << " (post-indexed)";
873 if (getMemNegative())
875 if (getMemWriteback())
876 OS << " (writeback)";
881 unsigned IFlags = getProcIFlags();
882 for (int i=2; i >= 0; --i)
883 if (IFlags & (1 << i))
884 OS << ARM_PROC::IFlagsToString(1 << i);
889 OS << "<register " << getReg() << ">";
892 OS << "<shifter " << getShiftOpcStr(Shift.ShiftTy) << ">";
895 case DPRRegisterList:
896 case SPRRegisterList: {
897 OS << "<register_list ";
899 const SmallVectorImpl<unsigned> &RegList = getRegList();
900 for (SmallVectorImpl<unsigned>::const_iterator
901 I = RegList.begin(), E = RegList.end(); I != E; ) {
903 if (++I < E) OS << ", ";
910 OS << "'" << getToken() << "'";
915 /// @name Auto-generated Match Functions
918 static unsigned MatchRegisterName(StringRef Name);
922 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
923 SMLoc &StartLoc, SMLoc &EndLoc) {
924 RegNo = TryParseRegister();
926 return (RegNo == (unsigned)-1);
929 /// Try to parse a register name. The token must be an Identifier when called,
930 /// and if it is a register name the token is eaten and the register number is
931 /// returned. Otherwise return -1.
933 int ARMAsmParser::TryParseRegister() {
934 const AsmToken &Tok = Parser.getTok();
935 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
937 // FIXME: Validate register for the current architecture; we have to do
938 // validation later, so maybe there is no need for this here.
939 std::string upperCase = Tok.getString().str();
940 std::string lowerCase = LowercaseString(upperCase);
941 unsigned RegNum = MatchRegisterName(lowerCase);
943 RegNum = StringSwitch<unsigned>(lowerCase)
944 .Case("r13", ARM::SP)
945 .Case("r14", ARM::LR)
946 .Case("r15", ARM::PC)
947 .Case("ip", ARM::R12)
950 if (!RegNum) return -1;
952 Parser.Lex(); // Eat identifier token.
956 /// Try to parse a register name. The token must be an Identifier when called,
957 /// and if it is a register name the token is eaten and the register number is
958 /// returned. Otherwise return -1.
960 bool ARMAsmParser::TryParseShiftRegister(
961 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
962 SMLoc S = Parser.getTok().getLoc();
963 const AsmToken &Tok = Parser.getTok();
964 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
966 std::string upperCase = Tok.getString().str();
967 std::string lowerCase = LowercaseString(upperCase);
968 ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
969 .Case("lsl", ARM_AM::lsl)
970 .Case("lsr", ARM_AM::lsr)
971 .Case("asr", ARM_AM::asr)
972 .Case("ror", ARM_AM::ror)
973 .Case("rrx", ARM_AM::rrx)
974 .Default(ARM_AM::no_shift);
976 if (ShiftTy == ARM_AM::no_shift)
979 Parser.Lex(); // Eat shift-type operand;
980 int RegNum = TryParseRegister();
982 return Error(Parser.getTok().getLoc(), "register expected");
984 Operands.push_back(ARMOperand::CreateReg(RegNum,S, Parser.getTok().getLoc()));
985 Operands.push_back(ARMOperand::CreateShifter(ShiftTy,
986 S, Parser.getTok().getLoc()));
992 /// Try to parse a register name. The token must be an Identifier when called.
993 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
994 /// if there is a "writeback". 'true' if it's not a register.
996 /// TODO this is likely to change to allow different register types and or to
997 /// parse for a specific register type.
999 TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1000 SMLoc S = Parser.getTok().getLoc();
1001 int RegNo = TryParseRegister();
1005 Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
1007 const AsmToken &ExclaimTok = Parser.getTok();
1008 if (ExclaimTok.is(AsmToken::Exclaim)) {
1009 Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
1010 ExclaimTok.getLoc()));
1011 Parser.Lex(); // Eat exclaim token
1017 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
1018 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
1020 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
1021 // Use the same layout as the tablegen'erated register name matcher. Ugly,
1023 switch (Name.size()) {
1026 if (Name[0] != CoprocOp)
1043 if (Name[0] != CoprocOp || Name[1] != '1')
1047 case '0': return 10;
1048 case '1': return 11;
1049 case '2': return 12;
1050 case '3': return 13;
1051 case '4': return 14;
1052 case '5': return 15;
1060 /// tryParseCoprocNumOperand - Try to parse an coprocessor number operand. The
1061 /// token must be an Identifier when called, and if it is a coprocessor
1062 /// number, the token is eaten and the operand is added to the operand list.
1063 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1064 tryParseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1065 SMLoc S = Parser.getTok().getLoc();
1066 const AsmToken &Tok = Parser.getTok();
1067 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1069 int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
1071 return MatchOperand_NoMatch;
1073 Parser.Lex(); // Eat identifier token.
1074 Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
1075 return MatchOperand_Success;
1078 /// tryParseCoprocRegOperand - Try to parse an coprocessor register operand. The
1079 /// token must be an Identifier when called, and if it is a coprocessor
1080 /// number, the token is eaten and the operand is added to the operand list.
1081 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1082 tryParseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1083 SMLoc S = Parser.getTok().getLoc();
1084 const AsmToken &Tok = Parser.getTok();
1085 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1087 int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
1089 return MatchOperand_NoMatch;
1091 Parser.Lex(); // Eat identifier token.
1092 Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
1093 return MatchOperand_Success;
1096 /// Parse a register list, return it if successful else return null. The first
1097 /// token must be a '{' when called.
1099 ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1100 assert(Parser.getTok().is(AsmToken::LCurly) &&
1101 "Token is not a Left Curly Brace");
1102 SMLoc S = Parser.getTok().getLoc();
1104 // Read the rest of the registers in the list.
1105 unsigned PrevRegNum = 0;
1106 SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
1109 bool IsRange = Parser.getTok().is(AsmToken::Minus);
1110 Parser.Lex(); // Eat non-identifier token.
1112 const AsmToken &RegTok = Parser.getTok();
1113 SMLoc RegLoc = RegTok.getLoc();
1114 if (RegTok.isNot(AsmToken::Identifier)) {
1115 Error(RegLoc, "register expected");
1119 int RegNum = TryParseRegister();
1121 Error(RegLoc, "register expected");
1126 int Reg = PrevRegNum;
1129 Registers.push_back(std::make_pair(Reg, RegLoc));
1130 } while (Reg != RegNum);
1132 Registers.push_back(std::make_pair(RegNum, RegLoc));
1135 PrevRegNum = RegNum;
1136 } while (Parser.getTok().is(AsmToken::Comma) ||
1137 Parser.getTok().is(AsmToken::Minus));
1139 // Process the right curly brace of the list.
1140 const AsmToken &RCurlyTok = Parser.getTok();
1141 if (RCurlyTok.isNot(AsmToken::RCurly)) {
1142 Error(RCurlyTok.getLoc(), "'}' expected");
1146 SMLoc E = RCurlyTok.getLoc();
1147 Parser.Lex(); // Eat right curly brace token.
1149 // Verify the register list.
1150 SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1151 RI = Registers.begin(), RE = Registers.end();
1153 unsigned HighRegNum = getARMRegisterNumbering(RI->first);
1154 bool EmittedWarning = false;
1156 DenseMap<unsigned, bool> RegMap;
1157 RegMap[HighRegNum] = true;
1159 for (++RI; RI != RE; ++RI) {
1160 const std::pair<unsigned, SMLoc> &RegInfo = *RI;
1161 unsigned Reg = getARMRegisterNumbering(RegInfo.first);
1164 Error(RegInfo.second, "register duplicated in register list");
1168 if (!EmittedWarning && Reg < HighRegNum)
1169 Warning(RegInfo.second,
1170 "register not in ascending order in register list");
1173 HighRegNum = std::max(Reg, HighRegNum);
1176 Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
1180 /// tryParseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
1181 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1182 tryParseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1183 SMLoc S = Parser.getTok().getLoc();
1184 const AsmToken &Tok = Parser.getTok();
1185 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1186 StringRef OptStr = Tok.getString();
1188 unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
1189 .Case("sy", ARM_MB::SY)
1190 .Case("st", ARM_MB::ST)
1191 .Case("ish", ARM_MB::ISH)
1192 .Case("ishst", ARM_MB::ISHST)
1193 .Case("nsh", ARM_MB::NSH)
1194 .Case("nshst", ARM_MB::NSHST)
1195 .Case("osh", ARM_MB::OSH)
1196 .Case("oshst", ARM_MB::OSHST)
1200 return MatchOperand_NoMatch;
1202 Parser.Lex(); // Eat identifier token.
1203 Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
1204 return MatchOperand_Success;
1207 /// tryParseProcIFlagsOperand - Try to parse iflags from CPS instruction.
1208 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1209 tryParseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1210 SMLoc S = Parser.getTok().getLoc();
1211 const AsmToken &Tok = Parser.getTok();
1212 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1213 StringRef IFlagsStr = Tok.getString();
1215 unsigned IFlags = 0;
1216 for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
1217 unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
1218 .Case("a", ARM_PROC::A)
1219 .Case("i", ARM_PROC::I)
1220 .Case("f", ARM_PROC::F)
1223 // If some specific iflag is already set, it means that some letter is
1224 // present more than once, this is not acceptable.
1225 if (Flag == ~0U || (IFlags & Flag))
1226 return MatchOperand_NoMatch;
1231 Parser.Lex(); // Eat identifier token.
1232 Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
1233 return MatchOperand_Success;
1236 /// tryParseMSRMaskOperand - Try to parse mask flags from MSR instruction.
1237 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1238 tryParseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1239 SMLoc S = Parser.getTok().getLoc();
1240 const AsmToken &Tok = Parser.getTok();
1241 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1242 StringRef Mask = Tok.getString();
1244 // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
1245 size_t Start = 0, Next = Mask.find('_');
1246 StringRef Flags = "";
1247 StringRef SpecReg = Mask.slice(Start, Next);
1248 if (Next != StringRef::npos)
1249 Flags = Mask.slice(Next+1, Mask.size());
1251 // FlagsVal contains the complete mask:
1253 // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1254 unsigned FlagsVal = 0;
1256 if (SpecReg == "apsr") {
1257 FlagsVal = StringSwitch<unsigned>(Flags)
1258 .Case("nzcvq", 0x8) // same as CPSR_c
1259 .Case("g", 0x4) // same as CPSR_s
1260 .Case("nzcvqg", 0xc) // same as CPSR_fs
1263 if (FlagsVal == ~0U) {
1265 return MatchOperand_NoMatch;
1267 FlagsVal = 0; // No flag
1269 } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
1270 if (Flags == "all") // cpsr_all is an alias for cpsr_fc
1272 for (int i = 0, e = Flags.size(); i != e; ++i) {
1273 unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
1280 // If some specific flag is already set, it means that some letter is
1281 // present more than once, this is not acceptable.
1282 if (FlagsVal == ~0U || (FlagsVal & Flag))
1283 return MatchOperand_NoMatch;
1286 } else // No match for special register.
1287 return MatchOperand_NoMatch;
1289 // Special register without flags are equivalent to "fc" flags.
1293 // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1294 if (SpecReg == "spsr")
1297 Parser.Lex(); // Eat identifier token.
1298 Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
1299 return MatchOperand_Success;
1302 /// tryParseMemMode2Operand - Try to parse memory addressing mode 2 operand.
1303 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1304 tryParseMemMode2Operand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1305 assert(Parser.getTok().is(AsmToken::LBrac) && "Token is not a \"[\"");
1307 if (ParseMemory(Operands, ARMII::AddrMode2))
1308 return MatchOperand_NoMatch;
1310 return MatchOperand_Success;
1313 /// tryParseMemMode3Operand - Try to parse memory addressing mode 3 operand.
1314 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1315 tryParseMemMode3Operand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1316 assert(Parser.getTok().is(AsmToken::LBrac) && "Token is not a \"[\"");
1318 if (ParseMemory(Operands, ARMII::AddrMode3))
1319 return MatchOperand_NoMatch;
1321 return MatchOperand_Success;
1324 /// CvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
1325 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1326 /// when they refer multiple MIOperands inside a single one.
1328 CvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
1329 const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1330 ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1332 // Create a writeback register dummy placeholder.
1333 Inst.addOperand(MCOperand::CreateImm(0));
1335 ((ARMOperand*)Operands[3])->addMemMode2Operands(Inst, 3);
1336 ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1340 /// CvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
1341 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1342 /// when they refer multiple MIOperands inside a single one.
1344 CvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
1345 const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1346 // Create a writeback register dummy placeholder.
1347 Inst.addOperand(MCOperand::CreateImm(0));
1348 ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1349 ((ARMOperand*)Operands[3])->addMemMode2Operands(Inst, 3);
1350 ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1354 /// CvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
1355 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1356 /// when they refer multiple MIOperands inside a single one.
1358 CvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
1359 const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1360 ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1362 // Create a writeback register dummy placeholder.
1363 Inst.addOperand(MCOperand::CreateImm(0));
1365 ((ARMOperand*)Operands[3])->addMemMode3Operands(Inst, 3);
1366 ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1370 /// CvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
1371 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1372 /// when they refer multiple MIOperands inside a single one.
1374 CvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
1375 const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1376 // Create a writeback register dummy placeholder.
1377 Inst.addOperand(MCOperand::CreateImm(0));
1378 ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1379 ((ARMOperand*)Operands[3])->addMemMode3Operands(Inst, 3);
1380 ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1384 /// Parse an ARM memory expression, return false if successful else return true
1385 /// or an error. The first token must be a '[' when called.
1387 /// TODO Only preindexing and postindexing addressing are started, unindexed
1388 /// with option, etc are still to do.
1390 ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1391 ARMII::AddrMode AddrMode = ARMII::AddrModeNone) {
1393 assert(Parser.getTok().is(AsmToken::LBrac) &&
1394 "Token is not a Left Bracket");
1395 S = Parser.getTok().getLoc();
1396 Parser.Lex(); // Eat left bracket token.
1398 const AsmToken &BaseRegTok = Parser.getTok();
1399 if (BaseRegTok.isNot(AsmToken::Identifier)) {
1400 Error(BaseRegTok.getLoc(), "register expected");
1403 int BaseRegNum = TryParseRegister();
1404 if (BaseRegNum == -1) {
1405 Error(BaseRegTok.getLoc(), "register expected");
1409 // The next token must either be a comma or a closing bracket.
1410 const AsmToken &Tok = Parser.getTok();
1411 if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
1414 bool Preindexed = false;
1415 bool Postindexed = false;
1416 bool OffsetIsReg = false;
1417 bool Negative = false;
1418 bool Writeback = false;
1419 ARMOperand *WBOp = 0;
1420 int OffsetRegNum = -1;
1421 bool OffsetRegShifted = false;
1422 enum ARM_AM::ShiftOpc ShiftType = ARM_AM::lsl;
1423 const MCExpr *ShiftAmount = 0;
1424 const MCExpr *Offset = 0;
1426 // First look for preindexed address forms, that is after the "[Rn" we now
1427 // have to see if the next token is a comma.
1428 if (Tok.is(AsmToken::Comma)) {
1430 Parser.Lex(); // Eat comma token.
1432 if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
1433 Offset, OffsetIsReg, OffsetRegNum, E))
1435 const AsmToken &RBracTok = Parser.getTok();
1436 if (RBracTok.isNot(AsmToken::RBrac)) {
1437 Error(RBracTok.getLoc(), "']' expected");
1440 E = RBracTok.getLoc();
1441 Parser.Lex(); // Eat right bracket token.
1443 const AsmToken &ExclaimTok = Parser.getTok();
1444 if (ExclaimTok.is(AsmToken::Exclaim)) {
1445 // None of addrmode3 instruction uses "!"
1446 if (AddrMode == ARMII::AddrMode3)
1449 WBOp = ARMOperand::CreateToken(ExclaimTok.getString(),
1450 ExclaimTok.getLoc());
1452 Parser.Lex(); // Eat exclaim token
1453 } else { // In addressing mode 2, pre-indexed mode always end with "!"
1454 if (AddrMode == ARMII::AddrMode2)
1458 // The "[Rn" we have so far was not followed by a comma.
1460 // If there's anything other than the right brace, this is a post indexing
1463 Parser.Lex(); // Eat right bracket token.
1465 const AsmToken &NextTok = Parser.getTok();
1467 if (NextTok.isNot(AsmToken::EndOfStatement)) {
1471 if (NextTok.isNot(AsmToken::Comma)) {
1472 Error(NextTok.getLoc(), "',' expected");
1476 Parser.Lex(); // Eat comma token.
1478 if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
1479 ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
1485 // Force Offset to exist if used.
1488 Offset = MCConstantExpr::Create(0, getContext());
1490 if (AddrMode == ARMII::AddrMode3 && OffsetRegShifted) {
1491 Error(E, "shift amount not supported");
1496 Operands.push_back(ARMOperand::CreateMem(AddrMode, BaseRegNum, OffsetIsReg,
1497 Offset, OffsetRegNum, OffsetRegShifted,
1498 ShiftType, ShiftAmount, Preindexed,
1499 Postindexed, Negative, Writeback, S, E));
1501 Operands.push_back(WBOp);
1506 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
1507 /// we will parse the following (were +/- means that a plus or minus is
1512 /// we return false on success or an error otherwise.
1513 bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
1514 bool &OffsetRegShifted,
1515 enum ARM_AM::ShiftOpc &ShiftType,
1516 const MCExpr *&ShiftAmount,
1517 const MCExpr *&Offset,
1522 OffsetRegShifted = false;
1523 OffsetIsReg = false;
1525 const AsmToken &NextTok = Parser.getTok();
1526 E = NextTok.getLoc();
1527 if (NextTok.is(AsmToken::Plus))
1528 Parser.Lex(); // Eat plus token.
1529 else if (NextTok.is(AsmToken::Minus)) {
1531 Parser.Lex(); // Eat minus token
1533 // See if there is a register following the "[Rn," or "[Rn]," we have so far.
1534 const AsmToken &OffsetRegTok = Parser.getTok();
1535 if (OffsetRegTok.is(AsmToken::Identifier)) {
1536 SMLoc CurLoc = OffsetRegTok.getLoc();
1537 OffsetRegNum = TryParseRegister();
1538 if (OffsetRegNum != -1) {
1544 // If we parsed a register as the offset then there can be a shift after that.
1545 if (OffsetRegNum != -1) {
1546 // Look for a comma then a shift
1547 const AsmToken &Tok = Parser.getTok();
1548 if (Tok.is(AsmToken::Comma)) {
1549 Parser.Lex(); // Eat comma token.
1551 const AsmToken &Tok = Parser.getTok();
1552 if (ParseShift(ShiftType, ShiftAmount, E))
1553 return Error(Tok.getLoc(), "shift expected");
1554 OffsetRegShifted = true;
1557 else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
1558 // Look for #offset following the "[Rn," or "[Rn],"
1559 const AsmToken &HashTok = Parser.getTok();
1560 if (HashTok.isNot(AsmToken::Hash))
1561 return Error(HashTok.getLoc(), "'#' expected");
1563 Parser.Lex(); // Eat hash token.
1565 if (getParser().ParseExpression(Offset))
1567 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1572 /// ParseShift as one of these two:
1573 /// ( lsl | lsr | asr | ror ) , # shift_amount
1575 /// and returns true if it parses a shift otherwise it returns false.
1576 bool ARMAsmParser::ParseShift(ARM_AM::ShiftOpc &St,
1577 const MCExpr *&ShiftAmount, SMLoc &E) {
1578 const AsmToken &Tok = Parser.getTok();
1579 if (Tok.isNot(AsmToken::Identifier))
1581 StringRef ShiftName = Tok.getString();
1582 if (ShiftName == "lsl" || ShiftName == "LSL")
1584 else if (ShiftName == "lsr" || ShiftName == "LSR")
1586 else if (ShiftName == "asr" || ShiftName == "ASR")
1588 else if (ShiftName == "ror" || ShiftName == "ROR")
1590 else if (ShiftName == "rrx" || ShiftName == "RRX")
1594 Parser.Lex(); // Eat shift type token.
1596 // Rrx stands alone.
1597 if (St == ARM_AM::rrx)
1600 // Otherwise, there must be a '#' and a shift amount.
1601 const AsmToken &HashTok = Parser.getTok();
1602 if (HashTok.isNot(AsmToken::Hash))
1603 return Error(HashTok.getLoc(), "'#' expected");
1604 Parser.Lex(); // Eat hash token.
1606 if (getParser().ParseExpression(ShiftAmount))
1612 /// Parse a arm instruction operand. For now this parses the operand regardless
1613 /// of the mnemonic.
1614 bool ARMAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1615 StringRef Mnemonic) {
1618 // Check if the current operand has a custom associated parser, if so, try to
1619 // custom parse the operand, or fallback to the general approach.
1620 OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
1621 if (ResTy == MatchOperand_Success)
1623 // If there wasn't a custom match, try the generic matcher below. Otherwise,
1624 // there was a match, but an error occurred, in which case, just return that
1625 // the operand parsing failed.
1626 if (ResTy == MatchOperand_ParseFail)
1629 switch (getLexer().getKind()) {
1631 Error(Parser.getTok().getLoc(), "unexpected token in operand");
1633 case AsmToken::Identifier:
1634 if (!TryParseRegisterWithWriteBack(Operands))
1636 if (!TryParseShiftRegister(Operands))
1640 // Fall though for the Identifier case that is not a register or a
1642 case AsmToken::Integer: // things like 1f and 2b as a branch targets
1643 case AsmToken::Dot: { // . as a branch target
1644 // This was not a register so parse other operands that start with an
1645 // identifier (like labels) as expressions and create them as immediates.
1646 const MCExpr *IdVal;
1647 S = Parser.getTok().getLoc();
1648 if (getParser().ParseExpression(IdVal))
1650 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1651 Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
1654 case AsmToken::LBrac:
1655 return ParseMemory(Operands);
1656 case AsmToken::LCurly:
1657 return ParseRegisterList(Operands);
1658 case AsmToken::Hash:
1659 // #42 -> immediate.
1660 // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
1661 S = Parser.getTok().getLoc();
1663 const MCExpr *ImmVal;
1664 if (getParser().ParseExpression(ImmVal))
1666 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1667 Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
1669 case AsmToken::Colon: {
1670 // ":lower16:" and ":upper16:" expression prefixes
1671 // FIXME: Check it's an expression prefix,
1672 // e.g. (FOO - :lower16:BAR) isn't legal.
1673 ARMMCExpr::VariantKind RefKind;
1674 if (ParsePrefix(RefKind))
1677 const MCExpr *SubExprVal;
1678 if (getParser().ParseExpression(SubExprVal))
1681 const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
1683 E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1684 Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
1690 // ParsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
1691 // :lower16: and :upper16:.
1692 bool ARMAsmParser::ParsePrefix(ARMMCExpr::VariantKind &RefKind) {
1693 RefKind = ARMMCExpr::VK_ARM_None;
1695 // :lower16: and :upper16: modifiers
1696 assert(getLexer().is(AsmToken::Colon) && "expected a :");
1697 Parser.Lex(); // Eat ':'
1699 if (getLexer().isNot(AsmToken::Identifier)) {
1700 Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
1704 StringRef IDVal = Parser.getTok().getIdentifier();
1705 if (IDVal == "lower16") {
1706 RefKind = ARMMCExpr::VK_ARM_LO16;
1707 } else if (IDVal == "upper16") {
1708 RefKind = ARMMCExpr::VK_ARM_HI16;
1710 Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
1715 if (getLexer().isNot(AsmToken::Colon)) {
1716 Error(Parser.getTok().getLoc(), "unexpected token after prefix");
1719 Parser.Lex(); // Eat the last ':'
1724 ARMAsmParser::ApplyPrefixToExpr(const MCExpr *E,
1725 MCSymbolRefExpr::VariantKind Variant) {
1726 // Recurse over the given expression, rebuilding it to apply the given variant
1727 // to the leftmost symbol.
1728 if (Variant == MCSymbolRefExpr::VK_None)
1731 switch (E->getKind()) {
1732 case MCExpr::Target:
1733 llvm_unreachable("Can't handle target expr yet");
1734 case MCExpr::Constant:
1735 llvm_unreachable("Can't handle lower16/upper16 of constant yet");
1737 case MCExpr::SymbolRef: {
1738 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1740 if (SRE->getKind() != MCSymbolRefExpr::VK_None)
1743 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
1747 llvm_unreachable("Can't handle unary expressions yet");
1749 case MCExpr::Binary: {
1750 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1751 const MCExpr *LHS = ApplyPrefixToExpr(BE->getLHS(), Variant);
1752 const MCExpr *RHS = BE->getRHS();
1756 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1760 assert(0 && "Invalid expression kind!");
1764 /// \brief Given a mnemonic, split out possible predication code and carry
1765 /// setting letters to form a canonical mnemonic and flags.
1767 // FIXME: Would be nice to autogen this.
1768 static StringRef SplitMnemonic(StringRef Mnemonic,
1769 unsigned &PredicationCode,
1771 unsigned &ProcessorIMod) {
1772 PredicationCode = ARMCC::AL;
1773 CarrySetting = false;
1776 // Ignore some mnemonics we know aren't predicated forms.
1778 // FIXME: Would be nice to autogen this.
1779 if (Mnemonic == "teq" || Mnemonic == "vceq" ||
1780 Mnemonic == "movs" ||
1781 Mnemonic == "svc" ||
1782 (Mnemonic == "mls" || Mnemonic == "smmls" || Mnemonic == "vcls" ||
1783 Mnemonic == "vmls" || Mnemonic == "vnmls") ||
1784 Mnemonic == "vacge" || Mnemonic == "vcge" ||
1785 Mnemonic == "vclt" ||
1786 Mnemonic == "vacgt" || Mnemonic == "vcgt" ||
1787 Mnemonic == "vcle" ||
1788 (Mnemonic == "smlal" || Mnemonic == "umaal" || Mnemonic == "umlal" ||
1789 Mnemonic == "vabal" || Mnemonic == "vmlal" || Mnemonic == "vpadal" ||
1790 Mnemonic == "vqdmlal" || Mnemonic == "bics"))
1793 // First, split out any predication code.
1794 unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
1795 .Case("eq", ARMCC::EQ)
1796 .Case("ne", ARMCC::NE)
1797 .Case("hs", ARMCC::HS)
1798 .Case("cs", ARMCC::HS)
1799 .Case("lo", ARMCC::LO)
1800 .Case("cc", ARMCC::LO)
1801 .Case("mi", ARMCC::MI)
1802 .Case("pl", ARMCC::PL)
1803 .Case("vs", ARMCC::VS)
1804 .Case("vc", ARMCC::VC)
1805 .Case("hi", ARMCC::HI)
1806 .Case("ls", ARMCC::LS)
1807 .Case("ge", ARMCC::GE)
1808 .Case("lt", ARMCC::LT)
1809 .Case("gt", ARMCC::GT)
1810 .Case("le", ARMCC::LE)
1811 .Case("al", ARMCC::AL)
1814 Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
1815 PredicationCode = CC;
1818 // Next, determine if we have a carry setting bit. We explicitly ignore all
1819 // the instructions we know end in 's'.
1820 if (Mnemonic.endswith("s") &&
1821 !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" ||
1822 Mnemonic == "movs" || Mnemonic == "mrs" || Mnemonic == "smmls" ||
1823 Mnemonic == "vabs" || Mnemonic == "vcls" || Mnemonic == "vmls" ||
1824 Mnemonic == "vmrs" || Mnemonic == "vnmls" || Mnemonic == "vqabs" ||
1825 Mnemonic == "vrecps" || Mnemonic == "vrsqrts")) {
1826 Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
1827 CarrySetting = true;
1830 // The "cps" instruction can have a interrupt mode operand which is glued into
1831 // the mnemonic. Check if this is the case, split it and parse the imod op
1832 if (Mnemonic.startswith("cps")) {
1833 // Split out any imod code.
1835 StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
1836 .Case("ie", ARM_PROC::IE)
1837 .Case("id", ARM_PROC::ID)
1840 Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
1841 ProcessorIMod = IMod;
1848 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
1849 /// inclusion of carry set or predication code operands.
1851 // FIXME: It would be nice to autogen this.
1853 GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
1854 bool &CanAcceptPredicationCode) {
1855 bool isThumbOne = TM.getSubtarget<ARMSubtarget>().isThumb1Only();
1856 bool isThumb = TM.getSubtarget<ARMSubtarget>().isThumb();
1858 if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
1859 Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
1860 Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" ||
1861 Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
1862 Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mvn" ||
1863 Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
1864 Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" ||
1865 Mnemonic == "eor" || Mnemonic == "smlal" ||
1866 (Mnemonic == "mov" && !isThumbOne)) {
1867 CanAcceptCarrySet = true;
1869 CanAcceptCarrySet = false;
1872 if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
1873 Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
1874 Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
1875 Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
1876 Mnemonic == "dsb" || Mnemonic == "movs" || Mnemonic == "isb" ||
1877 Mnemonic == "clrex" || Mnemonic.startswith("cps")) {
1878 CanAcceptPredicationCode = false;
1880 CanAcceptPredicationCode = true;
1884 if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
1885 Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp" ||
1886 (Mnemonic == "mov" && isThumbOne))
1887 CanAcceptPredicationCode = false;
1890 /// Parse an arm instruction mnemonic followed by its operands.
1891 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
1892 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1893 // Create the leading tokens for the mnemonic, split by '.' characters.
1894 size_t Start = 0, Next = Name.find('.');
1895 StringRef Head = Name.slice(Start, Next);
1897 // Split out the predication code and carry setting flag from the mnemonic.
1898 unsigned PredicationCode;
1899 unsigned ProcessorIMod;
1901 Head = SplitMnemonic(Head, PredicationCode, CarrySetting,
1904 Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1906 // Next, add the CCOut and ConditionCode operands, if needed.
1908 // For mnemonics which can ever incorporate a carry setting bit or predication
1909 // code, our matching model involves us always generating CCOut and
1910 // ConditionCode operands to match the mnemonic "as written" and then we let
1911 // the matcher deal with finding the right instruction or generating an
1912 // appropriate error.
1913 bool CanAcceptCarrySet, CanAcceptPredicationCode;
1914 GetMnemonicAcceptInfo(Head, CanAcceptCarrySet, CanAcceptPredicationCode);
1916 // Add the carry setting operand, if necessary.
1918 // FIXME: It would be awesome if we could somehow invent a location such that
1919 // match errors on this operand would print a nice diagnostic about how the
1920 // 's' character in the mnemonic resulted in a CCOut operand.
1921 if (CanAcceptCarrySet) {
1922 Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
1925 // This mnemonic can't ever accept a carry set, but the user wrote one (or
1926 // misspelled another mnemonic).
1928 // FIXME: Issue a nice error.
1931 // Add the predication code operand, if necessary.
1932 if (CanAcceptPredicationCode) {
1933 Operands.push_back(ARMOperand::CreateCondCode(
1934 ARMCC::CondCodes(PredicationCode), NameLoc));
1936 // This mnemonic can't ever accept a predication code, but the user wrote
1937 // one (or misspelled another mnemonic).
1939 // FIXME: Issue a nice error.
1942 // Add the processor imod operand, if necessary.
1943 if (ProcessorIMod) {
1944 Operands.push_back(ARMOperand::CreateImm(
1945 MCConstantExpr::Create(ProcessorIMod, getContext()),
1948 // This mnemonic can't ever accept a imod, but the user wrote
1949 // one (or misspelled another mnemonic).
1951 // FIXME: Issue a nice error.
1954 // Add the remaining tokens in the mnemonic.
1955 while (Next != StringRef::npos) {
1957 Next = Name.find('.', Start + 1);
1958 StringRef ExtraToken = Name.slice(Start, Next);
1960 Operands.push_back(ARMOperand::CreateToken(ExtraToken, NameLoc));
1963 // Read the remaining operands.
1964 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1965 // Read the first operand.
1966 if (ParseOperand(Operands, Head)) {
1967 Parser.EatToEndOfStatement();
1971 while (getLexer().is(AsmToken::Comma)) {
1972 Parser.Lex(); // Eat the comma.
1974 // Parse and remember the operand.
1975 if (ParseOperand(Operands, Head)) {
1976 Parser.EatToEndOfStatement();
1982 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1983 Parser.EatToEndOfStatement();
1984 return TokError("unexpected token in argument list");
1987 Parser.Lex(); // Consume the EndOfStatement
1992 MatchAndEmitInstruction(SMLoc IDLoc,
1993 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1997 MatchResultTy MatchResult, MatchResult2;
1998 MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1999 if (MatchResult != Match_Success) {
2000 // If we get a Match_InvalidOperand it might be some arithmetic instruction
2001 // that does not update the condition codes. So try adding a CCOut operand
2002 // with a value of reg0.
2003 if (MatchResult == Match_InvalidOperand) {
2004 Operands.insert(Operands.begin() + 1,
2005 ARMOperand::CreateCCOut(0,
2006 ((ARMOperand*)Operands[0])->getStartLoc()));
2007 MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
2008 if (MatchResult2 == Match_Success)
2009 MatchResult = Match_Success;
2011 ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
2012 Operands.erase(Operands.begin() + 1);
2016 // If we get a Match_MnemonicFail it might be some arithmetic instruction
2017 // that updates the condition codes if it ends in 's'. So see if the
2018 // mnemonic ends in 's' and if so try removing the 's' and adding a CCOut
2019 // operand with a value of CPSR.
2020 else if(MatchResult == Match_MnemonicFail) {
2021 // Get the instruction mnemonic, which is the first token.
2022 StringRef Mnemonic = ((ARMOperand*)Operands[0])->getToken();
2023 if (Mnemonic.substr(Mnemonic.size()-1) == "s") {
2024 // removed the 's' from the mnemonic for matching.
2025 StringRef MnemonicNoS = Mnemonic.slice(0, Mnemonic.size() - 1);
2026 SMLoc NameLoc = ((ARMOperand*)Operands[0])->getStartLoc();
2027 ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
2028 Operands.erase(Operands.begin());
2030 Operands.insert(Operands.begin(),
2031 ARMOperand::CreateToken(MnemonicNoS, NameLoc));
2032 Operands.insert(Operands.begin() + 1,
2033 ARMOperand::CreateCCOut(ARM::CPSR, NameLoc));
2034 MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
2035 if (MatchResult2 == Match_Success)
2036 MatchResult = Match_Success;
2038 ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
2039 Operands.erase(Operands.begin());
2041 Operands.insert(Operands.begin(),
2042 ARMOperand::CreateToken(Mnemonic, NameLoc));
2043 ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
2044 Operands.erase(Operands.begin() + 1);
2050 switch (MatchResult) {
2052 Out.EmitInstruction(Inst);
2054 case Match_MissingFeature:
2055 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
2057 case Match_InvalidOperand: {
2058 SMLoc ErrorLoc = IDLoc;
2059 if (ErrorInfo != ~0U) {
2060 if (ErrorInfo >= Operands.size())
2061 return Error(IDLoc, "too few operands for instruction");
2063 ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
2064 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
2067 return Error(ErrorLoc, "invalid operand for instruction");
2069 case Match_MnemonicFail:
2070 return Error(IDLoc, "unrecognized instruction mnemonic");
2071 case Match_ConversionFail:
2072 return Error(IDLoc, "unable to convert operands to instruction");
2075 llvm_unreachable("Implement any new match types added!");
2079 /// ParseDirective parses the arm specific directives
2080 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
2081 StringRef IDVal = DirectiveID.getIdentifier();
2082 if (IDVal == ".word")
2083 return ParseDirectiveWord(4, DirectiveID.getLoc());
2084 else if (IDVal == ".thumb")
2085 return ParseDirectiveThumb(DirectiveID.getLoc());
2086 else if (IDVal == ".thumb_func")
2087 return ParseDirectiveThumbFunc(DirectiveID.getLoc());
2088 else if (IDVal == ".code")
2089 return ParseDirectiveCode(DirectiveID.getLoc());
2090 else if (IDVal == ".syntax")
2091 return ParseDirectiveSyntax(DirectiveID.getLoc());
2095 /// ParseDirectiveWord
2096 /// ::= .word [ expression (, expression)* ]
2097 bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2098 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2100 const MCExpr *Value;
2101 if (getParser().ParseExpression(Value))
2104 getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
2106 if (getLexer().is(AsmToken::EndOfStatement))
2109 // FIXME: Improve diagnostic.
2110 if (getLexer().isNot(AsmToken::Comma))
2111 return Error(L, "unexpected token in directive");
2120 /// ParseDirectiveThumb
2122 bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
2123 if (getLexer().isNot(AsmToken::EndOfStatement))
2124 return Error(L, "unexpected token in directive");
2127 // TODO: set thumb mode
2128 // TODO: tell the MC streamer the mode
2129 // getParser().getStreamer().Emit???();
2133 /// ParseDirectiveThumbFunc
2134 /// ::= .thumbfunc symbol_name
2135 bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
2136 const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
2137 bool isMachO = MAI.hasSubsectionsViaSymbols();
2140 // Darwin asm has function name after .thumb_func direction
2143 const AsmToken &Tok = Parser.getTok();
2144 if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
2145 return Error(L, "unexpected token in .thumb_func directive");
2146 Name = Tok.getString();
2147 Parser.Lex(); // Consume the identifier token.
2150 if (getLexer().isNot(AsmToken::EndOfStatement))
2151 return Error(L, "unexpected token in directive");
2154 // FIXME: assuming function name will be the line following .thumb_func
2156 Name = Parser.getTok().getString();
2159 // Mark symbol as a thumb symbol.
2160 MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
2161 getParser().getStreamer().EmitThumbFunc(Func);
2165 /// ParseDirectiveSyntax
2166 /// ::= .syntax unified | divided
2167 bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
2168 const AsmToken &Tok = Parser.getTok();
2169 if (Tok.isNot(AsmToken::Identifier))
2170 return Error(L, "unexpected token in .syntax directive");
2171 StringRef Mode = Tok.getString();
2172 if (Mode == "unified" || Mode == "UNIFIED")
2174 else if (Mode == "divided" || Mode == "DIVIDED")
2175 return Error(L, "'.syntax divided' arm asssembly not supported");
2177 return Error(L, "unrecognized syntax mode in .syntax directive");
2179 if (getLexer().isNot(AsmToken::EndOfStatement))
2180 return Error(Parser.getTok().getLoc(), "unexpected token in directive");
2183 // TODO tell the MC streamer the mode
2184 // getParser().getStreamer().Emit???();
2188 /// ParseDirectiveCode
2189 /// ::= .code 16 | 32
2190 bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
2191 const AsmToken &Tok = Parser.getTok();
2192 if (Tok.isNot(AsmToken::Integer))
2193 return Error(L, "unexpected token in .code directive");
2194 int64_t Val = Parser.getTok().getIntVal();
2200 return Error(L, "invalid operand to .code directive");
2202 if (getLexer().isNot(AsmToken::EndOfStatement))
2203 return Error(Parser.getTok().getLoc(), "unexpected token in directive");
2206 // FIXME: We need to be able switch subtargets at this point so that
2207 // MatchInstructionImpl() will work when it gets the AvailableFeatures which
2208 // includes Feature_IsThumb or not to match the right instructions. This is
2209 // blocked on the FIXME in llvm-mc.cpp when creating the TargetMachine.
2211 assert(TM.getSubtarget<ARMSubtarget>().isThumb() &&
2212 "switching between arm/thumb not yet suppported via .code 16)");
2213 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
2216 assert(!TM.getSubtarget<ARMSubtarget>().isThumb() &&
2217 "switching between thumb/arm not yet suppported via .code 32)");
2218 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2224 extern "C" void LLVMInitializeARMAsmLexer();
2226 /// Force static initialization.
2227 extern "C" void LLVMInitializeARMAsmParser() {
2228 RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
2229 RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);
2230 LLVMInitializeARMAsmLexer();
2233 #define GET_REGISTER_MATCHER
2234 #define GET_MATCHER_IMPLEMENTATION
2235 #include "ARMGenAsmMatcher.inc"