blob: 43c872b809859a2e60fcf8983e9954a96a012ca0 [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
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// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000017#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000019#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000020#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000022#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000024#include "llvm/MC/MCParser/AsmCond.h"
25#include "llvm/MC/MCParser/AsmLexer.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
27#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000028#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000029#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000030#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000031#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000032#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000033#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000034#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000035#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000037#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000038#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000039#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000040#include <set>
41#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000042#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000043using namespace llvm;
44
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000045static cl::opt<bool>
46FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
48
Eric Christopher2318ba12012-12-18 00:30:54 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000050
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000051namespace {
52
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000053/// \brief Helper class for storing information about an active macro
54/// instantiation.
55struct MacroInstantiation {
56 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000057 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000058
59 /// The macro instantiation with substitutions.
60 MemoryBuffer *Instantiation;
61
62 /// The location of the instantiation.
63 SMLoc InstantiationLoc;
64
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000065 /// The buffer where parsing should resume upon instantiation completion.
66 int ExitBuffer;
67
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000068 /// The location where parsing should resume upon instantiation completion.
69 SMLoc ExitLoc;
70
71public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000072 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000073 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000074};
75
Chad Rosier6a020a72012-10-25 20:41:34 +000076//struct AsmRewrite;
Eli Friedman2128aae2012-10-22 23:58:19 +000077struct ParseStatementInfo {
78 /// ParsedOperands - The parsed operands from the last parsed statement.
79 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
80
81 /// Opcode - The opcode from the last parsed instruction.
82 unsigned Opcode;
83
Chad Rosier57498012012-12-12 22:45:52 +000084 /// Error - Was there an error parsing the inline assembly?
85 bool ParseError;
86
Eli Friedman2128aae2012-10-22 23:58:19 +000087 SmallVectorImpl<AsmRewrite> *AsmRewrites;
88
Chad Rosier57498012012-12-12 22:45:52 +000089 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +000090 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +000091 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +000092
93 ~ParseStatementInfo() {
94 // Free any parsed operands.
95 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
96 delete ParsedOperands[i];
97 ParsedOperands.clear();
98 }
99};
100
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000101/// \brief The concrete assembly parser instance.
102class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000103 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
104 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000105private:
106 AsmLexer Lexer;
107 MCContext &Ctx;
108 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000109 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000110 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000111 SourceMgr::DiagHandlerTy SavedDiagHandler;
112 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000113 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000114
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000115 /// This is the current buffer index we're lexing from as managed by the
116 /// SourceMgr object.
117 int CurBuffer;
118
119 AsmCond TheCondState;
120 std::vector<AsmCond> TheCondStack;
121
Eli Bendersky6ee13082013-01-15 22:59:42 +0000122 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
123 /// extensions. Extensions register themselves in this map by calling
124 /// AddDirectiveHandler.
125 typedef std::pair<MCAsmParserExtension*, DirectiveHandler>
126 ExtensionDirectiveHandler;
127 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000128
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000129 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000130 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000131
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000132 /// ActiveMacros - Stack of active macro instantiations.
133 std::vector<MacroInstantiation*> ActiveMacros;
134
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000135 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000136 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000137
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000138 /// Flag tracking whether any errors have been encountered.
139 unsigned HadError : 1;
140
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000141 /// The values from the last parsed cpp hash file line comment if any.
142 StringRef CppHashFilename;
143 int64_t CppHashLineNumber;
144 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000145 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000146
Devang Patel0db58bf2012-01-31 18:14:05 +0000147 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
148 unsigned AssemblerDialect;
149
Preston Gurd7b6f2032012-09-19 20:36:12 +0000150 /// IsDarwin - is Darwin compatibility enabled?
151 bool IsDarwin;
152
Chad Rosier8f138d12012-10-15 17:19:13 +0000153 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000154 bool ParsingInlineAsm;
155
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000156public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000157 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000158 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000159 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000160
161 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
162
Craig Topper345d16d2012-08-29 05:48:09 +0000163 virtual void AddDirectiveHandler(MCAsmParserExtension *Object,
164 StringRef Directive,
165 DirectiveHandler Handler) {
Eli Bendersky6ee13082013-01-15 22:59:42 +0000166 ExtensionDirectiveMap[Directive] = std::make_pair(Object, Handler);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000167 }
168
169public:
170 /// @name MCAsmParser Interface
171 /// {
172
173 virtual SourceMgr &getSourceManager() { return SrcMgr; }
174 virtual MCAsmLexer &getLexer() { return Lexer; }
175 virtual MCContext &getContext() { return Ctx; }
176 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000177 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000178 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000179 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000180 else
181 return AssemblerDialect;
182 }
183 virtual void setAssemblerDialect(unsigned i) {
184 AssemblerDialect = i;
185 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000186
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000187 virtual bool Warning(SMLoc L, const Twine &Msg,
188 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
189 virtual bool Error(SMLoc L, const Twine &Msg,
190 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000191
Craig Topper345d16d2012-08-29 05:48:09 +0000192 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000193
Chad Rosier84125ca2012-10-13 00:26:04 +0000194 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000195 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000196
197 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
198 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000199 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000200 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000201 SmallVectorImpl<std::string> &Clobbers,
202 const MCInstrInfo *MII,
203 const MCInstPrinter *IP,
204 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000205
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000206 bool ParseExpression(const MCExpr *&Res);
207 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
208 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
209 virtual bool ParseAbsoluteExpression(int64_t &Res);
210
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000211 bool ParseMacroArgument(MCAsmMacroArgument &MA,
212 AsmToken::TokenKind &ArgumentDelimiter);
213
Eli Benderskybf706b32013-01-12 00:05:00 +0000214 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
215 /// and set \p Res to the identifier contents.
216 virtual bool ParseIdentifier(StringRef &Res);
Eli Benderskyb2f0b592013-01-12 00:23:24 +0000217 virtual void EatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000218
Eli Bendersky733c3362013-01-14 18:08:41 +0000219 virtual bool MacrosEnabled() {return MacrosEnabledFlag;}
220 virtual void SetMacrosEnabled(bool flag) {MacrosEnabledFlag = flag;}
221
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000222 virtual const MCAsmMacro* LookupMacro(StringRef Name);
223 virtual void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
224 virtual void UndefineMacro(StringRef Name);
225
226 virtual bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
227 virtual bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
228 void HandleMacroExit();
229
Eli Bendersky318cad32013-01-14 19:15:01 +0000230 virtual void CheckForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000231 /// }
232
233private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000234
Eli Friedman2128aae2012-10-22 23:58:19 +0000235 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000236 void EatToEndOfLine();
237 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000238
Rafael Espindola761cb062012-06-03 23:57:14 +0000239 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000240 const MCAsmMacroParameters &Parameters,
241 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000242 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000243
244 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000245 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000246 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
247 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000248 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000249 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000250
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000251 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
252 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000253 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
254 /// This returns true on failure.
255 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000256
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000257 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000258 /// current token is not set; clients should ensure Lex() is called
259 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000260 ///
261 /// \param InBuffer If not -1, should be the known buffer id that contains the
262 /// location.
263 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000264
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000265 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000266
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000267 /// \brief Parse up to the end of statement and a return the contents from the
268 /// current token until the end of the statement; the current token on exit
269 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000270 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000271
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000272 /// \brief Parse until the end of a statement or a comma is encountered,
273 /// return the contents from the current token up to the end or comma.
274 StringRef ParseStringToComma();
275
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000276 bool ParseAssignment(StringRef Name, bool allow_redef,
277 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000278
279 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
280 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
281 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000282 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000283
Eli Bendersky6ee13082013-01-15 22:59:42 +0000284 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000285
Eli Bendersky6ee13082013-01-15 22:59:42 +0000286 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000287 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000288 DK_NO_DIRECTIVE, // Placeholder
289 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
290 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
291 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000292 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000293 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
294 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
295 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
296 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
297 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
298 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
299 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000300 DK_ELSEIF, DK_ELSE, DK_ENDIF,
301 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
302 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
303 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
304 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
305 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
306 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
307 DK_CFI_REGISTER,
308 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
309 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000310 };
311
Eli Bendersky6ee13082013-01-15 22:59:42 +0000312 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
313 /// directives parsed by this class.
314 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000315
316 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000317 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000318 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000319 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000320 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000321 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000322 // ".set", ".equ", ".equiv"
323 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000324 bool ParseDirectiveOrg(); // ".org"
325 // ".align{,32}", ".p2align{,w,l}"
326 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
327
Eli Bendersky6ee13082013-01-15 22:59:42 +0000328 // ".file", ".line", ".loc", ".stabs"
329 bool ParseDirectiveFile(SMLoc DirectiveLoc);
330 bool ParseDirectiveLine();
331 bool ParseDirectiveLoc();
332 bool ParseDirectiveStabs();
333
334 // .cfi directives
335 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
336 bool ParseDirectiveCFISections();
337 bool ParseDirectiveCFIStartProc();
338 bool ParseDirectiveCFIEndProc();
339 bool ParseDirectiveCFIDefCfaOffset();
340 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
341 bool ParseDirectiveCFIAdjustCfaOffset();
342 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
343 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
344 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
345 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
346 bool ParseDirectiveCFIRememberState();
347 bool ParseDirectiveCFIRestoreState();
348 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
349 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
350 bool ParseDirectiveCFIEscape();
351 bool ParseDirectiveCFISignalFrame();
352 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
353
354 // macro directives
355 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
356 bool ParseDirectiveEndMacro(StringRef Directive);
357 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
358 bool ParseDirectiveMacrosOnOff(StringRef Directive);
359
Eli Bendersky4766ef42012-12-20 19:05:53 +0000360 // ".bundle_align_mode"
361 bool ParseDirectiveBundleAlignMode();
362 // ".bundle_lock"
363 bool ParseDirectiveBundleLock();
364 // ".bundle_unlock"
365 bool ParseDirectiveBundleUnlock();
366
Eli Bendersky6ee13082013-01-15 22:59:42 +0000367 // ".space", ".skip"
368 bool ParseDirectiveSpace(StringRef IDVal);
369
370 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
371 bool ParseDirectiveLEB128(bool Signed);
372
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000373 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
374 /// accepts a single symbol (which should be a label or an external).
375 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000376
377 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
378
379 bool ParseDirectiveAbort(); // ".abort"
380 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000381 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000382
383 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000384 // ".ifb" or ".ifnb", depending on ExpectBlank.
385 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000386 // ".ifc" or ".ifnc", depending on ExpectEqual.
387 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000388 // ".ifdef" or ".ifndef", depending on expect_defined
389 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000390 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
391 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
392 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
393
394 /// ParseEscapedString - Parse the current token as a string which may include
395 /// escaped characters and return the string contents.
396 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000397
398 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
399 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000400
Rafael Espindola761cb062012-06-03 23:57:14 +0000401 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000402 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
403 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000404 raw_svector_ostream &OS);
405 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000406 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000407 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000408 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000409
Eli Friedman2128aae2012-10-22 23:58:19 +0000410 // "_emit"
411 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000412
Eli Bendersky6ee13082013-01-15 22:59:42 +0000413 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000414};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000415}
416
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000417namespace llvm {
418
419extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000420extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000421extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000422
423}
424
Chris Lattneraaec2052010-01-19 19:46:13 +0000425enum { DEFAULT_ADDRSPACE = 0 };
426
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000427AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000428 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000429 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000430 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000431 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000432 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000433 // Save the old handler.
434 SavedDiagHandler = SrcMgr.getDiagHandler();
435 SavedDiagContext = SrcMgr.getDiagContext();
436 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000437 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000438 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000439
Daniel Dunbare4749702010-07-12 18:12:02 +0000440 // Initialize the platform / file format parser.
441 //
442 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
443 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000444 if (_MAI.hasMicrosoftFastStdCallMangling()) {
445 PlatformParser = createCOFFAsmParser();
446 PlatformParser->Initialize(*this);
447 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000448 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000449 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000450 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000451 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000452 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000453 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000454 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000455
Eli Bendersky6ee13082013-01-15 22:59:42 +0000456 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000457}
458
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000459AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000460 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
461
462 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000463 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000464 ie = MacroMap.end(); it != ie; ++it)
465 delete it->getValue();
466
Daniel Dunbare4749702010-07-12 18:12:02 +0000467 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000468}
469
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000470void AsmParser::PrintMacroInstantiations() {
471 // Print the active macro instantiation stack.
472 for (std::vector<MacroInstantiation*>::const_reverse_iterator
473 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000474 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
475 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000476}
477
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000478bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000479 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000480 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000481 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000482 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000483 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000484}
485
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000486bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000487 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000488 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000489 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000490 return true;
491}
492
Sean Callananfd0b0282010-01-21 00:19:58 +0000493bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000494 std::string IncludedFile;
495 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000496 if (NewBuf == -1)
497 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000498
Sean Callananfd0b0282010-01-21 00:19:58 +0000499 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000500
Sean Callananfd0b0282010-01-21 00:19:58 +0000501 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000502
Sean Callananfd0b0282010-01-21 00:19:58 +0000503 return false;
504}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000505
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000506/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000507/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000508/// returns true on failure.
509bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
510 std::string IncludedFile;
511 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
512 if (NewBuf == -1)
513 return true;
514
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000515 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000516 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
517 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000518 return false;
519}
520
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000521void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
522 if (InBuffer != -1) {
523 CurBuffer = InBuffer;
524 } else {
525 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
526 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000527 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
528}
529
Sean Callananfd0b0282010-01-21 00:19:58 +0000530const AsmToken &AsmParser::Lex() {
531 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000532
Sean Callananfd0b0282010-01-21 00:19:58 +0000533 if (tok->is(AsmToken::Eof)) {
534 // If this is the end of an included file, pop the parent file off the
535 // include stack.
536 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
537 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000538 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000539 tok = &Lexer.Lex();
540 }
541 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000542
Sean Callananfd0b0282010-01-21 00:19:58 +0000543 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000544 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000545
Sean Callananfd0b0282010-01-21 00:19:58 +0000546 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000547}
548
Chris Lattner79180e22010-04-05 23:15:42 +0000549bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000550 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000551 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000552 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000553
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000554 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000555 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000556
557 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000558 AsmCond StartingCondState = TheCondState;
559
Kevin Enderby613b7572011-11-01 22:27:22 +0000560 // If we are generating dwarf for assembly source files save the initial text
561 // section and generate a .file directive.
562 if (getContext().getGenDwarfForAssembly()) {
563 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000564 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
565 getStreamer().EmitLabel(SectionStartSym);
566 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000567 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000568 StringRef(),
569 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000570 }
571
Chris Lattnerb717fb02009-07-02 21:53:43 +0000572 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000573 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000574 ParseStatementInfo Info;
575 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000576
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000577 // We had an error, validate that one was emitted and recover by skipping to
578 // the next line.
579 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000580 EatToEndOfStatement();
581 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000582
583 if (TheCondState.TheCond != StartingCondState.TheCond ||
584 TheCondState.Ignore != StartingCondState.Ignore)
585 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000586
587 // Check to see there are no empty DwarfFile slots.
588 const std::vector<MCDwarfFile *> &MCDwarfFiles =
589 getContext().getMCDwarfFiles();
590 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000591 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000592 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000593 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000594
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000595 // Check to see that all assembler local symbols were actually defined.
596 // Targets that don't do subsections via symbols may not want this, though,
597 // so conservatively exclude them. Only do this if we're finalizing, though,
598 // as otherwise we won't necessarilly have seen everything yet.
599 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
600 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
601 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
602 e = Symbols.end();
603 i != e; ++i) {
604 MCSymbol *Sym = i->getValue();
605 // Variable symbols may not be marked as defined, so check those
606 // explicitly. If we know it's a variable, we have a definition for
607 // the purposes of this check.
608 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
609 // FIXME: We would really like to refer back to where the symbol was
610 // first referenced for a source location. We need to add something
611 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000612 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
613 "assembler local symbol '" + Sym->getName() +
614 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000615 }
616 }
617
618
Chris Lattner79180e22010-04-05 23:15:42 +0000619 // Finalize the output stream if there are no errors and if the client wants
620 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000621 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000622 Out.Finish();
623
Chris Lattnerb717fb02009-07-02 21:53:43 +0000624 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000625}
626
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000627void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000628 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000629 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000630 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000631 }
632}
633
Chris Lattner2cf5f142009-06-22 01:29:09 +0000634/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
635void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000636 while (Lexer.isNot(AsmToken::EndOfStatement) &&
637 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000638 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000639
Chris Lattner2cf5f142009-06-22 01:29:09 +0000640 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000641 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000642 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000643}
644
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000645StringRef AsmParser::ParseStringToEndOfStatement() {
646 const char *Start = getTok().getLoc().getPointer();
647
648 while (Lexer.isNot(AsmToken::EndOfStatement) &&
649 Lexer.isNot(AsmToken::Eof))
650 Lex();
651
652 const char *End = getTok().getLoc().getPointer();
653 return StringRef(Start, End - Start);
654}
Chris Lattnerc4193832009-06-22 05:51:26 +0000655
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000656StringRef AsmParser::ParseStringToComma() {
657 const char *Start = getTok().getLoc().getPointer();
658
659 while (Lexer.isNot(AsmToken::EndOfStatement) &&
660 Lexer.isNot(AsmToken::Comma) &&
661 Lexer.isNot(AsmToken::Eof))
662 Lex();
663
664 const char *End = getTok().getLoc().getPointer();
665 return StringRef(Start, End - Start);
666}
667
Chris Lattner74ec1a32009-06-22 06:32:03 +0000668/// ParseParenExpr - Parse a paren expression and return it.
669/// NOTE: This assumes the leading '(' has already been consumed.
670///
671/// parenexpr ::= expr)
672///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000673bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000674 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000675 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000676 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000677 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000678 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000679 return false;
680}
Chris Lattnerc4193832009-06-22 05:51:26 +0000681
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000682/// ParseBracketExpr - Parse a bracket expression and return it.
683/// NOTE: This assumes the leading '[' has already been consumed.
684///
685/// bracketexpr ::= expr]
686///
687bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
688 if (ParseExpression(Res)) return true;
689 if (Lexer.isNot(AsmToken::RBrac))
690 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000691 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000692 Lex();
693 return false;
694}
695
Chris Lattner74ec1a32009-06-22 06:32:03 +0000696/// ParsePrimaryExpr - Parse a primary expression and return it.
697/// primaryexpr ::= (parenexpr
698/// primaryexpr ::= symbol
699/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000700/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000701/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000702bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000703 switch (Lexer.getKind()) {
704 default:
705 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000706 // If we have an error assume that we've already handled it.
707 case AsmToken::Error:
708 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000709 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000710 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000711 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000712 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000713 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000714 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000715 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000716 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000717 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000718 StringRef Identifier;
719 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000720 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000721
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000722 EndLoc = SMLoc::getFromPointer(Identifier.end());
723
Daniel Dunbarfffff912009-10-16 01:34:54 +0000724 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000725 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000726 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000727
728 // Lookup the symbol variant if used.
729 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000730 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000731 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000732 if (Variant == MCSymbolRefExpr::VK_Invalid) {
733 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000734 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000735 }
736 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000737
Daniel Dunbarfffff912009-10-16 01:34:54 +0000738 // If this is an absolute variable reference, substitute it now to preserve
739 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000740 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000741 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000742 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000743
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000744 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000745 return false;
746 }
747
748 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000749 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000750 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000751 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000752 case AsmToken::Integer: {
753 SMLoc Loc = getTok().getLoc();
754 int64_t IntVal = getTok().getIntVal();
755 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000756 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000757 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000758 // Look for 'b' or 'f' following an Integer as a directional label
759 if (Lexer.getKind() == AsmToken::Identifier) {
760 StringRef IDVal = getTok().getString();
761 if (IDVal == "f" || IDVal == "b"){
762 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
763 IDVal == "f" ? 1 : 0);
764 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
765 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000766 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000767 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000768 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000769 Lex(); // Eat identifier.
770 }
771 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000772 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000773 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000774 case AsmToken::Real: {
775 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000776 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000777 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000778 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000779 Lex(); // Eat token.
780 return false;
781 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000782 case AsmToken::Dot: {
783 // This is a '.' reference, which references the current PC. Emit a
784 // temporary label to the streamer and refer to it.
785 MCSymbol *Sym = Ctx.CreateTempSymbol();
786 Out.EmitLabel(Sym);
787 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000788 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000789 Lex(); // Eat identifier.
790 return false;
791 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000792 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000793 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000794 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000795 case AsmToken::LBrac:
796 if (!PlatformParser->HasBracketExpressions())
797 return TokError("brackets expression not supported on this target");
798 Lex(); // Eat the '['.
799 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000800 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000801 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000802 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000803 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000804 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000805 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000806 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000807 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000808 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000809 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000810 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000811 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000812 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000813 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000814 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000815 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000816 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000817 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000818 }
819}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000820
Chris Lattnerb4307b32010-01-15 19:28:38 +0000821bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000822 SMLoc EndLoc;
823 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000824}
825
Daniel Dunbarcceba832010-09-17 02:47:07 +0000826const MCExpr *
827AsmParser::ApplyModifierToExpr(const MCExpr *E,
828 MCSymbolRefExpr::VariantKind Variant) {
829 // Recurse over the given expression, rebuilding it to apply the given variant
830 // if there is exactly one symbol.
831 switch (E->getKind()) {
832 case MCExpr::Target:
833 case MCExpr::Constant:
834 return 0;
835
836 case MCExpr::SymbolRef: {
837 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
838
839 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
840 TokError("invalid variant on expression '" +
841 getTok().getIdentifier() + "' (already modified)");
842 return E;
843 }
844
845 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
846 }
847
848 case MCExpr::Unary: {
849 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
850 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
851 if (!Sub)
852 return 0;
853 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
854 }
855
856 case MCExpr::Binary: {
857 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
858 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
859 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
860
861 if (!LHS && !RHS)
862 return 0;
863
864 if (!LHS) LHS = BE->getLHS();
865 if (!RHS) RHS = BE->getRHS();
866
867 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
868 }
869 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000870
Craig Topper85814382012-02-07 05:05:23 +0000871 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000872}
873
Chris Lattner74ec1a32009-06-22 06:32:03 +0000874/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000875///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000876/// expr ::= expr &&,|| expr -> lowest.
877/// expr ::= expr |,^,&,! expr
878/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
879/// expr ::= expr <<,>> expr
880/// expr ::= expr +,- expr
881/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000882/// expr ::= primaryexpr
883///
Chris Lattner54482b42010-01-15 19:39:23 +0000884bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000885 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000886 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000887 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
888 return true;
889
Daniel Dunbarcceba832010-09-17 02:47:07 +0000890 // As a special case, we support 'a op b @ modifier' by rewriting the
891 // expression to include the modifier. This is inefficient, but in general we
892 // expect users to use 'a@modifier op b'.
893 if (Lexer.getKind() == AsmToken::At) {
894 Lex();
895
896 if (Lexer.isNot(AsmToken::Identifier))
897 return TokError("unexpected symbol modifier following '@'");
898
899 MCSymbolRefExpr::VariantKind Variant =
900 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
901 if (Variant == MCSymbolRefExpr::VK_Invalid)
902 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
903
904 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
905 if (!ModifiedRes) {
906 return TokError("invalid modifier '" + getTok().getIdentifier() +
907 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000908 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000909
Daniel Dunbarcceba832010-09-17 02:47:07 +0000910 Res = ModifiedRes;
911 Lex();
912 }
913
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000914 // Try to constant fold it up front, if possible.
915 int64_t Value;
916 if (Res->EvaluateAsAbsolute(Value))
917 Res = MCConstantExpr::Create(Value, getContext());
918
919 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000920}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000921
Chris Lattnerb4307b32010-01-15 19:28:38 +0000922bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000923 Res = 0;
924 return ParseParenExpr(Res, EndLoc) ||
925 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000926}
927
Daniel Dunbar475839e2009-06-29 20:37:27 +0000928bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000929 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000930
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000931 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000932 if (ParseExpression(Expr))
933 return true;
934
Daniel Dunbare00b0112009-10-16 01:57:52 +0000935 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000936 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000937
938 return false;
939}
940
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000941static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000942 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000943 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000944 default:
945 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000946
Jim Grosbachfbe16812011-08-20 16:24:13 +0000947 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000948 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000949 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000950 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000951 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000952 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000953 return 1;
954
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000955
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000956 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000957 //
958 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000959 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000960 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000961 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000962 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000963 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000964 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000965 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000966 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000967 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000968
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000969 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000970 case AsmToken::EqualEqual:
971 Kind = MCBinaryExpr::EQ;
972 return 3;
973 case AsmToken::ExclaimEqual:
974 case AsmToken::LessGreater:
975 Kind = MCBinaryExpr::NE;
976 return 3;
977 case AsmToken::Less:
978 Kind = MCBinaryExpr::LT;
979 return 3;
980 case AsmToken::LessEqual:
981 Kind = MCBinaryExpr::LTE;
982 return 3;
983 case AsmToken::Greater:
984 Kind = MCBinaryExpr::GT;
985 return 3;
986 case AsmToken::GreaterEqual:
987 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000988 return 3;
989
Jim Grosbachfbe16812011-08-20 16:24:13 +0000990 // Intermediate Precedence: <<, >>
991 case AsmToken::LessLess:
992 Kind = MCBinaryExpr::Shl;
993 return 4;
994 case AsmToken::GreaterGreater:
995 Kind = MCBinaryExpr::Shr;
996 return 4;
997
Daniel Dunbarb1e0f762010-10-25 20:18:56 +0000998 // High Intermediate Precedence: +, -
999 case AsmToken::Plus:
1000 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001001 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001002 case AsmToken::Minus:
1003 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001004 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001005
Jim Grosbachfbe16812011-08-20 16:24:13 +00001006 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001007 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001008 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001009 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001010 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001011 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001012 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001013 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001014 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001015 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001016 }
1017}
1018
1019
1020/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1021/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001022bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1023 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001024 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001025 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001026 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001027
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001028 // If the next token is lower precedence than we are allowed to eat, return
1029 // successfully with what we ate already.
1030 if (TokPrec < Precedence)
1031 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001032
Sean Callanan79ed1a82010-01-19 20:22:31 +00001033 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001034
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001035 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001036 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001037 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001038
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001039 // If BinOp binds less tightly with RHS than the operator after RHS, let
1040 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001041 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001042 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001043 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001044 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001045 }
1046
Daniel Dunbar475839e2009-06-29 20:37:27 +00001047 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001048 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001049 }
1050}
1051
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001052/// ParseStatement:
1053/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001054/// ::= Label* Directive ...Operands... EndOfStatement
1055/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001056bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001057 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001058 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001059 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001060 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001061 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001062
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001063 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001064 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001065 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001066 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001067 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001068 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001069 if (Lexer.is(AsmToken::Hash))
1070 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001071
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001072 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001073 if (Lexer.is(AsmToken::Integer)) {
1074 LocalLabelVal = getTok().getIntVal();
1075 if (LocalLabelVal < 0) {
1076 if (!TheCondState.Ignore)
1077 return TokError("unexpected token at start of statement");
1078 IDVal = "";
1079 }
1080 else {
1081 IDVal = getTok().getString();
1082 Lex(); // Consume the integer token to be used as an identifier token.
1083 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001084 if (!TheCondState.Ignore)
1085 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001086 }
1087 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001088
1089 } else if (Lexer.is(AsmToken::Dot)) {
1090 // Treat '.' as a valid identifier in this context.
1091 Lex();
1092 IDVal = ".";
1093
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001094 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001095 if (!TheCondState.Ignore)
1096 return TokError("unexpected token at start of statement");
1097 IDVal = "";
1098 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001099
Chris Lattner7834fac2010-04-17 18:14:27 +00001100 // Handle conditional assembly here before checking for skipping. We
1101 // have to do this so that .endif isn't skipped in a ".if 0" block for
1102 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001103 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001104 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001105 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001106 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1107 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001108 switch (DirKind) {
1109 default:
1110 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001111 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001112 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001113 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001114 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001115 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001116 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001117 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001118 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001119 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001120 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001121 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001122 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001123 case DK_IFNDEF:
1124 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001125 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001126 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001127 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001128 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001129 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001130 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001131 return ParseDirectiveEndIf(IDLoc);
1132 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001133
Chris Lattner7834fac2010-04-17 18:14:27 +00001134 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001135 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001136 EatToEndOfStatement();
1137 return false;
1138 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001139
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001140 // FIXME: Recurse on local labels?
1141
1142 // See what kind of statement we have.
1143 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001144 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001145 CheckForValidSection();
1146
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001147 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001148 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001149
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001150 // Diagnose attempt to use '.' as a label.
1151 if (IDVal == ".")
1152 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1153
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001154 // Diagnose attempt to use a variable as a label.
1155 //
1156 // FIXME: Diagnostics. Note the location of the definition as a label.
1157 // FIXME: This doesn't diagnose assignment to a symbol which has been
1158 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001159 MCSymbol *Sym;
1160 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001161 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001162 else
1163 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001164 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001165 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001166
Daniel Dunbar959fd882009-08-26 22:13:22 +00001167 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001168 if (!ParsingInlineAsm)
1169 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001170
Kevin Enderby94c2e852011-12-09 18:09:40 +00001171 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001172 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001173 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001174 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1175 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001176
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001177 // Consume any end of statement token, if present, to avoid spurious
1178 // AddBlankLine calls().
1179 if (Lexer.is(AsmToken::EndOfStatement)) {
1180 Lex();
1181 if (Lexer.is(AsmToken::Eof))
1182 return false;
1183 }
1184
Eli Friedman2128aae2012-10-22 23:58:19 +00001185 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001186 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001187
Daniel Dunbar3f872332009-07-28 16:08:33 +00001188 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001189 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001190 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001191
Nico Weber4c4c7322011-01-28 03:04:41 +00001192 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001193
1194 default: // Normal instruction or directive.
1195 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001196 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001197
1198 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001199 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001200 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1201 return HandleMacroEntry(M, IDLoc);
1202 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001203
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001204 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001205
1206 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001207 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001208 // There are several entities interested in parsing directives:
1209 //
1210 // 1. The target-specific assembly parser. Some directives are target
1211 // specific or may potentially behave differently on certain targets.
1212 // 2. Asm parser extensions. For example, platform-specific parsers
1213 // (like the ELF parser) register themselves as extensions.
1214 // 3. The generic directive parser implemented by this class. These are
1215 // all the directives that behave in a target and platform independent
1216 // manner, or at least have a default behavior that's shared between
1217 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001218
Eli Bendersky6ee13082013-01-15 22:59:42 +00001219 // First query the target-specific parser. It will return 'true' if it
1220 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001221 if (!getTargetParser().ParseDirective(ID))
1222 return false;
1223
Eli Bendersky6ee13082013-01-15 22:59:42 +00001224 // Next, check the extention directive map to see if any extension has
1225 // registered itself to parse this directive.
1226 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1227 ExtensionDirectiveMap.lookup(IDVal);
1228 if (Handler.first)
1229 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1230
1231 // Finally, if no one else is interested in this directive, it must be
1232 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001233 switch (DirKind) {
1234 default:
1235 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001236 case DK_SET:
1237 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001238 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001239 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001240 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001241 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001242 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001243 case DK_ASCIZ:
1244 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001245 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001246 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001247 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001248 case DK_SHORT:
1249 case DK_VALUE:
1250 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001251 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001252 case DK_LONG:
1253 case DK_INT:
1254 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001255 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001256 case DK_QUAD:
1257 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001258 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001259 case DK_SINGLE:
1260 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001261 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001262 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001263 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001264 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001265 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1266 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1267 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001268 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001269 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1270 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1271 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001272 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001273 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001274 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001275 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001276 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001277 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001278 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001279 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001280 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001281 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001282 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001283 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001284 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001285 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001286 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001287 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001288 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001289 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001290 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001291 EatToEndOfStatement(); // .extern is the default, ignore it.
1292 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001293 case DK_GLOBL:
1294 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001295 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001296 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001297 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001298 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001299 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001300 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001301 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001302 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001303 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001304 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001305 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001306 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001307 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001308 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001309 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001310 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001311 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001312 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001313 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001314 case DK_COMM:
1315 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001316 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001317 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001318 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001319 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001320 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001322 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001323 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_CODE16:
1326 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001327 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001328 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001329 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001330 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001331 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001332 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001333 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001334 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001335 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001336 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001337 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001338 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001339 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001340 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001341 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001342 case DK_SLEB128:
1343 return ParseDirectiveLEB128(true);
1344 case DK_ULEB128:
1345 return ParseDirectiveLEB128(false);
1346 case DK_SPACE:
1347 case DK_SKIP:
1348 return ParseDirectiveSpace(IDVal);
1349 case DK_FILE:
1350 return ParseDirectiveFile(IDLoc);
1351 case DK_LINE:
1352 return ParseDirectiveLine();
1353 case DK_LOC:
1354 return ParseDirectiveLoc();
1355 case DK_STABS:
1356 return ParseDirectiveStabs();
1357 case DK_CFI_SECTIONS:
1358 return ParseDirectiveCFISections();
1359 case DK_CFI_STARTPROC:
1360 return ParseDirectiveCFIStartProc();
1361 case DK_CFI_ENDPROC:
1362 return ParseDirectiveCFIEndProc();
1363 case DK_CFI_DEF_CFA:
1364 return ParseDirectiveCFIDefCfa(IDLoc);
1365 case DK_CFI_DEF_CFA_OFFSET:
1366 return ParseDirectiveCFIDefCfaOffset();
1367 case DK_CFI_ADJUST_CFA_OFFSET:
1368 return ParseDirectiveCFIAdjustCfaOffset();
1369 case DK_CFI_DEF_CFA_REGISTER:
1370 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1371 case DK_CFI_OFFSET:
1372 return ParseDirectiveCFIOffset(IDLoc);
1373 case DK_CFI_REL_OFFSET:
1374 return ParseDirectiveCFIRelOffset(IDLoc);
1375 case DK_CFI_PERSONALITY:
1376 return ParseDirectiveCFIPersonalityOrLsda(true);
1377 case DK_CFI_LSDA:
1378 return ParseDirectiveCFIPersonalityOrLsda(false);
1379 case DK_CFI_REMEMBER_STATE:
1380 return ParseDirectiveCFIRememberState();
1381 case DK_CFI_RESTORE_STATE:
1382 return ParseDirectiveCFIRestoreState();
1383 case DK_CFI_SAME_VALUE:
1384 return ParseDirectiveCFISameValue(IDLoc);
1385 case DK_CFI_RESTORE:
1386 return ParseDirectiveCFIRestore(IDLoc);
1387 case DK_CFI_ESCAPE:
1388 return ParseDirectiveCFIEscape();
1389 case DK_CFI_SIGNAL_FRAME:
1390 return ParseDirectiveCFISignalFrame();
1391 case DK_CFI_UNDEFINED:
1392 return ParseDirectiveCFIUndefined(IDLoc);
1393 case DK_CFI_REGISTER:
1394 return ParseDirectiveCFIRegister(IDLoc);
1395 case DK_MACROS_ON:
1396 case DK_MACROS_OFF:
1397 return ParseDirectiveMacrosOnOff(IDVal);
1398 case DK_MACRO:
1399 return ParseDirectiveMacro(IDLoc);
1400 case DK_ENDM:
1401 case DK_ENDMACRO:
1402 return ParseDirectiveEndMacro(IDVal);
1403 case DK_PURGEM:
1404 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001405 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001406
Jim Grosbach686c0182012-05-01 18:38:27 +00001407 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001408 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001409
Eli Friedman2128aae2012-10-22 23:58:19 +00001410 // _emit
1411 if (ParsingInlineAsm && IDVal == "_emit")
1412 return ParseDirectiveEmit(IDLoc, Info);
1413
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001414 CheckForValidSection();
1415
Chris Lattnera7f13542010-05-19 23:34:33 +00001416 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001417 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001418 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001419 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001420
Chad Rosier6a020a72012-10-25 20:41:34 +00001421 ParseInstructionInfo IInfo(Info.AsmRewrites);
1422 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1423 IDLoc,Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001424 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001425
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001426 // Dump the parsed representation, if requested.
1427 if (getShowParsedOperands()) {
1428 SmallString<256> Str;
1429 raw_svector_ostream OS(Str);
1430 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001431 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001432 if (i != 0)
1433 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001434 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001435 }
1436 OS << "]";
1437
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001438 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001439 }
1440
Kevin Enderby613b7572011-11-01 22:27:22 +00001441 // If we are generating dwarf for assembly source files and the current
1442 // section is the initial text section then generate a .loc directive for
1443 // the instruction.
1444 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001445 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001446
1447 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1448
1449 // If we previously parsed a cpp hash file line comment then make sure the
1450 // current Dwarf File is for the CppHashFilename if not then emit the
1451 // Dwarf File table for it and adjust the line number for the .loc.
1452 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1453 getContext().getMCDwarfFiles();
1454 if (CppHashFilename.size() != 0) {
1455 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1456 CppHashFilename)
Eric Christopher2318ba12012-12-18 00:30:54 +00001457 getStreamer().EmitDwarfFileDirective(
1458 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001459
Kevin Enderby32c1a822012-11-05 21:55:41 +00001460 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001461 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1462 }
1463
Kevin Enderby613b7572011-11-01 22:27:22 +00001464 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001465 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001466 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001467 StringRef());
1468 }
1469
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001470 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001471 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001472 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001473 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1474 Info.ParsedOperands,
1475 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001476 ParsingInlineAsm);
1477 }
Chris Lattner98986712010-01-14 22:21:20 +00001478
Chris Lattnercbf8a982010-09-11 16:18:25 +00001479 // Don't skip the rest of the line, the instruction parser is responsible for
1480 // that.
1481 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001482}
Chris Lattner9a023f72009-06-24 04:43:34 +00001483
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001484/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1485/// since they may not be able to be tokenized to get to the end of line token.
1486void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001487 if (!Lexer.is(AsmToken::EndOfStatement))
1488 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001489 // Eat EOL.
1490 Lex();
1491}
1492
1493/// ParseCppHashLineFilenameComment as this:
1494/// ::= # number "filename"
1495/// or just as a full line comment if it doesn't have a number and a string.
1496bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1497 Lex(); // Eat the hash token.
1498
1499 if (getLexer().isNot(AsmToken::Integer)) {
1500 // Consume the line since in cases it is not a well-formed line directive,
1501 // as if were simply a full line comment.
1502 EatToEndOfLine();
1503 return false;
1504 }
1505
1506 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001507 Lex();
1508
1509 if (getLexer().isNot(AsmToken::String)) {
1510 EatToEndOfLine();
1511 return false;
1512 }
1513
1514 StringRef Filename = getTok().getString();
1515 // Get rid of the enclosing quotes.
1516 Filename = Filename.substr(1, Filename.size()-2);
1517
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001518 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1519 CppHashLoc = L;
1520 CppHashFilename = Filename;
1521 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001522 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001523
1524 // Ignore any trailing characters, they're just comment.
1525 EatToEndOfLine();
1526 return false;
1527}
1528
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001529/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001530/// for the Filename and LineNo if any in the diagnostic.
1531void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1532 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1533 raw_ostream &OS = errs();
1534
1535 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1536 const SMLoc &DiagLoc = Diag.getLoc();
1537 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1538 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1539
1540 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1541 // before printing the message.
1542 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001543 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001544 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1545 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1546 }
1547
Eric Christopher2318ba12012-12-18 00:30:54 +00001548 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001549 // manager changed or buffer changed (like in a nested include) then just
1550 // print the normal diagnostic using its Filename and LineNo.
1551 if (!Parser->CppHashLineNumber ||
1552 &DiagSrcMgr != &Parser->SrcMgr ||
1553 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001554 if (Parser->SavedDiagHandler)
1555 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1556 else
1557 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001558 return;
1559 }
1560
Eric Christopher2318ba12012-12-18 00:30:54 +00001561 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001562 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1563 // the diagnostic.
1564 const std::string Filename = Parser->CppHashFilename;
1565
1566 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1567 int CppHashLocLineNo =
1568 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1569 int LineNo = Parser->CppHashLineNumber - 1 +
1570 (DiagLocLineNo - CppHashLocLineNo);
1571
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001572 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1573 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001574 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001575 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001576
Benjamin Kramer04a04262011-10-16 10:48:29 +00001577 if (Parser->SavedDiagHandler)
1578 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1579 else
1580 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001581}
1582
Rafael Espindola799aacf2012-08-21 18:29:30 +00001583// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1584// difference being that that function accepts '@' as part of identifiers and
1585// we can't do that. AsmLexer.cpp should probably be changed to handle
1586// '@' as a special case when needed.
1587static bool isIdentifierChar(char c) {
1588 return isalnum(c) || c == '_' || c == '$' || c == '.';
1589}
1590
Rafael Espindola761cb062012-06-03 23:57:14 +00001591bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001592 const MCAsmMacroParameters &Parameters,
1593 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001594 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001595 unsigned NParameters = Parameters.size();
1596 if (NParameters != 0 && NParameters != A.size())
1597 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001598
Preston Gurd7b6f2032012-09-19 20:36:12 +00001599 // A macro without parameters is handled differently on Darwin:
1600 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001601 while (!Body.empty()) {
1602 // Scan for the next substitution.
1603 std::size_t End = Body.size(), Pos = 0;
1604 for (; Pos != End; ++Pos) {
1605 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001606 if (!NParameters) {
1607 // This macro has no parameters, look for $0, $1, etc.
1608 if (Body[Pos] != '$' || Pos + 1 == End)
1609 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001610
Rafael Espindola65366442011-06-05 02:43:45 +00001611 char Next = Body[Pos + 1];
1612 if (Next == '$' || Next == 'n' || isdigit(Next))
1613 break;
1614 } else {
1615 // This macro has parameters, look for \foo, \bar, etc.
1616 if (Body[Pos] == '\\' && Pos + 1 != End)
1617 break;
1618 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001619 }
1620
1621 // Add the prefix.
1622 OS << Body.slice(0, Pos);
1623
1624 // Check if we reached the end.
1625 if (Pos == End)
1626 break;
1627
Rafael Espindola65366442011-06-05 02:43:45 +00001628 if (!NParameters) {
1629 switch (Body[Pos+1]) {
1630 // $$ => $
1631 case '$':
1632 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001633 break;
1634
Rafael Espindola65366442011-06-05 02:43:45 +00001635 // $n => number of arguments
1636 case 'n':
1637 OS << A.size();
1638 break;
1639
1640 // $[0-9] => argument
1641 default: {
1642 // Missing arguments are ignored.
1643 unsigned Index = Body[Pos+1] - '0';
1644 if (Index >= A.size())
1645 break;
1646
1647 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001648 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001649 ie = A[Index].end(); it != ie; ++it)
1650 OS << it->getString();
1651 break;
1652 }
1653 }
1654 Pos += 2;
1655 } else {
1656 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001657 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001658 ++I;
1659
1660 const char *Begin = Body.data() + Pos +1;
1661 StringRef Argument(Begin, I - (Pos +1));
1662 unsigned Index = 0;
1663 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001664 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001665 break;
1666
Preston Gurd7b6f2032012-09-19 20:36:12 +00001667 if (Index == NParameters) {
1668 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1669 Pos += 3;
1670 else {
1671 OS << '\\' << Argument;
1672 Pos = I;
1673 }
1674 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001675 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001676 ie = A[Index].end(); it != ie; ++it)
1677 if (it->getKind() == AsmToken::String)
1678 OS << it->getStringContents();
1679 else
1680 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001681
Preston Gurd7b6f2032012-09-19 20:36:12 +00001682 Pos += 1 + Argument.size();
1683 }
Rafael Espindola65366442011-06-05 02:43:45 +00001684 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001685 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001686 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001687 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001688
Rafael Espindola65366442011-06-05 02:43:45 +00001689 return false;
1690}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001691
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001692MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001693 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001694 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001695 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1696 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001697{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001698}
1699
Preston Gurd7b6f2032012-09-19 20:36:12 +00001700static bool IsOperator(AsmToken::TokenKind kind)
1701{
1702 switch (kind)
1703 {
1704 default:
1705 return false;
1706 case AsmToken::Plus:
1707 case AsmToken::Minus:
1708 case AsmToken::Tilde:
1709 case AsmToken::Slash:
1710 case AsmToken::Star:
1711 case AsmToken::Dot:
1712 case AsmToken::Equal:
1713 case AsmToken::EqualEqual:
1714 case AsmToken::Pipe:
1715 case AsmToken::PipePipe:
1716 case AsmToken::Caret:
1717 case AsmToken::Amp:
1718 case AsmToken::AmpAmp:
1719 case AsmToken::Exclaim:
1720 case AsmToken::ExclaimEqual:
1721 case AsmToken::Percent:
1722 case AsmToken::Less:
1723 case AsmToken::LessEqual:
1724 case AsmToken::LessLess:
1725 case AsmToken::LessGreater:
1726 case AsmToken::Greater:
1727 case AsmToken::GreaterEqual:
1728 case AsmToken::GreaterGreater:
1729 return true;
1730 }
1731}
1732
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001733bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001734 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001735 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001736 unsigned AddTokens = 0;
1737
1738 // gas accepts arguments separated by whitespace, except on Darwin
1739 if (!IsDarwin)
1740 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001741
1742 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001743 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1744 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001745 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001746 }
1747
1748 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1749 // Spaces and commas cannot be mixed to delimit parameters
1750 if (ArgumentDelimiter == AsmToken::Eof)
1751 ArgumentDelimiter = AsmToken::Comma;
1752 else if (ArgumentDelimiter != AsmToken::Comma) {
1753 Lexer.setSkipSpace(true);
1754 return TokError("expected ' ' for macro argument separator");
1755 }
1756 break;
1757 }
1758
1759 if (Lexer.is(AsmToken::Space)) {
1760 Lex(); // Eat spaces
1761
1762 // Spaces can delimit parameters, but could also be part an expression.
1763 // If the token after a space is an operator, add the token and the next
1764 // one into this argument
1765 if (ArgumentDelimiter == AsmToken::Space ||
1766 ArgumentDelimiter == AsmToken::Eof) {
1767 if (IsOperator(Lexer.getKind())) {
1768 // Check to see whether the token is used as an operator,
1769 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001770 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001771 if (*NextChar == ' ')
1772 AddTokens = 2;
1773 }
1774
1775 if (!AddTokens && ParenLevel == 0) {
1776 if (ArgumentDelimiter == AsmToken::Eof &&
1777 !IsOperator(Lexer.getKind()))
1778 ArgumentDelimiter = AsmToken::Space;
1779 break;
1780 }
1781 }
1782 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001783
1784 // HandleMacroEntry relies on not advancing the lexer here
1785 // to be able to fill in the remaining default parameter values
1786 if (Lexer.is(AsmToken::EndOfStatement))
1787 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001788
1789 // Adjust the current parentheses level.
1790 if (Lexer.is(AsmToken::LParen))
1791 ++ParenLevel;
1792 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1793 --ParenLevel;
1794
1795 // Append the token to the current argument list.
1796 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001797 if (AddTokens)
1798 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001799 Lex();
1800 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001801
1802 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001803 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001804 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001805 return false;
1806}
1807
1808// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001809bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001810 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001811 // Argument delimiter is initially unknown. It will be set by
1812 // ParseMacroArgument()
1813 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001814
1815 // Parse two kinds of macro invocations:
1816 // - macros defined without any parameters accept an arbitrary number of them
1817 // - macros defined with parameters accept at most that many of them
1818 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1819 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001820 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001821
Preston Gurd7b6f2032012-09-19 20:36:12 +00001822 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001823 return true;
1824
Preston Gurd6c9176a2012-09-19 20:29:04 +00001825 if (!MA.empty() || !NParameters)
1826 A.push_back(MA);
1827 else if (NParameters) {
1828 if (!M->Parameters[Parameter].second.empty())
1829 A.push_back(M->Parameters[Parameter].second);
1830 }
Jim Grosbach97146442012-07-30 22:44:17 +00001831
Preston Gurd6c9176a2012-09-19 20:29:04 +00001832 // At the end of the statement, fill in remaining arguments that have
1833 // default values. If there aren't any, then the next argument is
1834 // required but missing
1835 if (Lexer.is(AsmToken::EndOfStatement)) {
1836 if (NParameters && Parameter < NParameters - 1) {
1837 if (M->Parameters[Parameter + 1].second.empty())
1838 return TokError("macro argument '" +
1839 Twine(M->Parameters[Parameter + 1].first) +
1840 "' is missing");
1841 else
1842 continue;
1843 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001844 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001845 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001846
1847 if (Lexer.is(AsmToken::Comma))
1848 Lex();
1849 }
1850 return TokError("Too many arguments");
1851}
1852
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001853const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1854 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1855 return (I == MacroMap.end()) ? NULL : I->getValue();
1856}
1857
1858void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1859 MacroMap[Name] = new MCAsmMacro(Macro);
1860}
1861
1862void AsmParser::UndefineMacro(StringRef Name) {
1863 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1864 if (I != MacroMap.end()) {
1865 delete I->getValue();
1866 MacroMap.erase(I);
1867 }
1868}
1869
1870bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001871 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1872 // this, although we should protect against infinite loops.
1873 if (ActiveMacros.size() == 20)
1874 return TokError("macros cannot be nested more than 20 levels deep");
1875
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001876 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001877 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001878 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001879
Jim Grosbach97146442012-07-30 22:44:17 +00001880 // Remove any trailing empty arguments. Do this after-the-fact as we have
1881 // to keep empty arguments in the middle of the list or positionality
1882 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001883 while (!A.empty() && A.back().empty())
1884 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001885
Rafael Espindola65366442011-06-05 02:43:45 +00001886 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1887 // to hold the macro body with substitutions.
1888 SmallString<256> Buf;
1889 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001890 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001891
Rafael Espindola8a403d32012-08-08 14:51:03 +00001892 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001893 return true;
1894
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001895 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001896 // instantiation.
1897 OS << ".endmacro\n";
1898
Rafael Espindola65366442011-06-05 02:43:45 +00001899 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001900 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001901
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001902 // Create the macro instantiation object and add to the current macro
1903 // instantiation stack.
1904 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001905 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001906 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001907 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001908 ActiveMacros.push_back(MI);
1909
1910 // Jump to the macro instantiation and prime the lexer.
1911 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1912 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1913 Lex();
1914
1915 return false;
1916}
1917
1918void AsmParser::HandleMacroExit() {
1919 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001920 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001921 Lex();
1922
1923 // Pop the instantiation entry.
1924 delete ActiveMacros.back();
1925 ActiveMacros.pop_back();
1926}
1927
Rafael Espindolae71cc862012-01-28 05:57:00 +00001928static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001929 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001930 case MCExpr::Binary: {
1931 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1932 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001933 break;
1934 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001935 case MCExpr::Target:
1936 case MCExpr::Constant:
1937 return false;
1938 case MCExpr::SymbolRef: {
1939 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001940 if (S.isVariable())
1941 return IsUsedIn(Sym, S.getVariableValue());
1942 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001943 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001944 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001945 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001946 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001947
1948 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001949}
1950
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001951bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1952 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001953 // FIXME: Use better location, we should use proper tokens.
1954 SMLoc EqualLoc = Lexer.getLoc();
1955
Daniel Dunbar821e3332009-08-31 08:09:28 +00001956 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001957 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001958 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001959
Rafael Espindolae71cc862012-01-28 05:57:00 +00001960 // Note: we don't count b as used in "a = b". This is to allow
1961 // a = b
1962 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001963
Daniel Dunbar3f872332009-07-28 16:08:33 +00001964 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001965 return TokError("unexpected token in assignment");
1966
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001967 // Error on assignment to '.'.
1968 if (Name == ".") {
1969 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1970 "(use '.space' or '.org').)"));
1971 }
1972
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001973 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001974 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001975
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001976 // Validate that the LHS is allowed to be a variable (either it has not been
1977 // used as a symbol, or it is an absolute symbol).
1978 MCSymbol *Sym = getContext().LookupSymbol(Name);
1979 if (Sym) {
1980 // Diagnose assignment to a label.
1981 //
1982 // FIXME: Diagnostics. Note the location of the definition as a label.
1983 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00001984 if (IsUsedIn(Sym, Value))
1985 return Error(EqualLoc, "Recursive use of '" + Name + "'");
1986 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00001987 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00001988 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
1989 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00001990 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001991 return Error(EqualLoc, "redefinition of '" + Name + "'");
1992 else if (!Sym->isVariable())
1993 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00001994 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00001995 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
1996 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001997
1998 // Don't count these checks as uses.
1999 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002000 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002001 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002002
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002003 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002004
2005 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002006 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002007 if (NoDeadStrip)
2008 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2009
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002010
2011 return false;
2012}
2013
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002014/// ParseIdentifier:
2015/// ::= identifier
2016/// ::= string
2017bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002018 // The assembler has relaxed rules for accepting identifiers, in particular we
2019 // allow things like '.globl $foo', which would normally be separate
2020 // tokens. At this level, we have already lexed so we cannot (currently)
2021 // handle this as a context dependent token, instead we detect adjacent tokens
2022 // and return the combined identifier.
2023 if (Lexer.is(AsmToken::Dollar)) {
2024 SMLoc DollarLoc = getLexer().getLoc();
2025
2026 // Consume the dollar sign, and check for a following identifier.
2027 Lex();
2028 if (Lexer.isNot(AsmToken::Identifier))
2029 return true;
2030
2031 // We have a '$' followed by an identifier, make sure they are adjacent.
2032 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2033 return true;
2034
2035 // Construct the joined identifier and consume the token.
2036 Res = StringRef(DollarLoc.getPointer(),
2037 getTok().getIdentifier().size() + 1);
2038 Lex();
2039 return false;
2040 }
2041
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002042 if (Lexer.isNot(AsmToken::Identifier) &&
2043 Lexer.isNot(AsmToken::String))
2044 return true;
2045
Sean Callanan18b83232010-01-19 21:44:56 +00002046 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002047
Sean Callanan79ed1a82010-01-19 20:22:31 +00002048 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002049
2050 return false;
2051}
2052
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002053/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002054/// ::= .equ identifier ',' expression
2055/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002056/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002057bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002058 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002059
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002060 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002061 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002062
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002063 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002064 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002065 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002066
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002067 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002068}
2069
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002070bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002071 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002072
2073 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002074 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002075 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2076 if (Str[i] != '\\') {
2077 Data += Str[i];
2078 continue;
2079 }
2080
2081 // Recognize escaped characters. Note that this escape semantics currently
2082 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2083 ++i;
2084 if (i == e)
2085 return TokError("unexpected backslash at end of string");
2086
2087 // Recognize octal sequences.
2088 if ((unsigned) (Str[i] - '0') <= 7) {
2089 // Consume up to three octal characters.
2090 unsigned Value = Str[i] - '0';
2091
2092 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2093 ++i;
2094 Value = Value * 8 + (Str[i] - '0');
2095
2096 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2097 ++i;
2098 Value = Value * 8 + (Str[i] - '0');
2099 }
2100 }
2101
2102 if (Value > 255)
2103 return TokError("invalid octal escape sequence (out of range)");
2104
2105 Data += (unsigned char) Value;
2106 continue;
2107 }
2108
2109 // Otherwise recognize individual escapes.
2110 switch (Str[i]) {
2111 default:
2112 // Just reject invalid escape sequences for now.
2113 return TokError("invalid escape sequence (unrecognized character)");
2114
2115 case 'b': Data += '\b'; break;
2116 case 'f': Data += '\f'; break;
2117 case 'n': Data += '\n'; break;
2118 case 'r': Data += '\r'; break;
2119 case 't': Data += '\t'; break;
2120 case '"': Data += '"'; break;
2121 case '\\': Data += '\\'; break;
2122 }
2123 }
2124
2125 return false;
2126}
2127
Daniel Dunbara0d14262009-06-24 23:30:00 +00002128/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002129/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2130bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002131 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002132 CheckForValidSection();
2133
Daniel Dunbara0d14262009-06-24 23:30:00 +00002134 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002135 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002136 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002137
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002138 std::string Data;
2139 if (ParseEscapedString(Data))
2140 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002141
2142 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002143 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002144 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2145
Sean Callanan79ed1a82010-01-19 20:22:31 +00002146 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002147
2148 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002149 break;
2150
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002151 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002152 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002153 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002154 }
2155 }
2156
Sean Callanan79ed1a82010-01-19 20:22:31 +00002157 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002158 return false;
2159}
2160
2161/// ParseDirectiveValue
2162/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2163bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002164 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002165 CheckForValidSection();
2166
Daniel Dunbara0d14262009-06-24 23:30:00 +00002167 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002168 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002169 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002170 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002171 return true;
2172
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002173 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002174 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2175 assert(Size <= 8 && "Invalid size");
2176 uint64_t IntValue = MCE->getValue();
2177 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2178 return Error(ExprLoc, "literal value out of range for directive");
2179 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2180 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002181 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002182
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002183 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002184 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002185
Daniel Dunbara0d14262009-06-24 23:30:00 +00002186 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002187 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002188 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002189 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002190 }
2191 }
2192
Sean Callanan79ed1a82010-01-19 20:22:31 +00002193 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002194 return false;
2195}
2196
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002197/// ParseDirectiveRealValue
2198/// ::= (.single | .double) [ expression (, expression)* ]
2199bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2200 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2201 CheckForValidSection();
2202
2203 for (;;) {
2204 // We don't truly support arithmetic on floating point expressions, so we
2205 // have to manually parse unary prefixes.
2206 bool IsNeg = false;
2207 if (getLexer().is(AsmToken::Minus)) {
2208 Lex();
2209 IsNeg = true;
2210 } else if (getLexer().is(AsmToken::Plus))
2211 Lex();
2212
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002213 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002214 getLexer().isNot(AsmToken::Real) &&
2215 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002216 return TokError("unexpected token in directive");
2217
2218 // Convert to an APFloat.
2219 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002220 StringRef IDVal = getTok().getString();
2221 if (getLexer().is(AsmToken::Identifier)) {
2222 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2223 Value = APFloat::getInf(Semantics);
2224 else if (!IDVal.compare_lower("nan"))
2225 Value = APFloat::getNaN(Semantics, false, ~0);
2226 else
2227 return TokError("invalid floating point literal");
2228 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002229 APFloat::opInvalidOp)
2230 return TokError("invalid floating point literal");
2231 if (IsNeg)
2232 Value.changeSign();
2233
2234 // Consume the numeric token.
2235 Lex();
2236
2237 // Emit the value as an integer.
2238 APInt AsInt = Value.bitcastToAPInt();
2239 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2240 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2241
2242 if (getLexer().is(AsmToken::EndOfStatement))
2243 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002244
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002245 if (getLexer().isNot(AsmToken::Comma))
2246 return TokError("unexpected token in directive");
2247 Lex();
2248 }
2249 }
2250
2251 Lex();
2252 return false;
2253}
2254
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002255/// ParseDirectiveZero
2256/// ::= .zero expression
2257bool AsmParser::ParseDirectiveZero() {
2258 CheckForValidSection();
2259
2260 int64_t NumBytes;
2261 if (ParseAbsoluteExpression(NumBytes))
2262 return true;
2263
Rafael Espindolae452b172010-10-05 19:42:57 +00002264 int64_t Val = 0;
2265 if (getLexer().is(AsmToken::Comma)) {
2266 Lex();
2267 if (ParseAbsoluteExpression(Val))
2268 return true;
2269 }
2270
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002271 if (getLexer().isNot(AsmToken::EndOfStatement))
2272 return TokError("unexpected token in '.zero' directive");
2273
2274 Lex();
2275
Rafael Espindolae452b172010-10-05 19:42:57 +00002276 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002277
2278 return false;
2279}
2280
Daniel Dunbara0d14262009-06-24 23:30:00 +00002281/// ParseDirectiveFill
2282/// ::= .fill expression , expression , expression
2283bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002284 CheckForValidSection();
2285
Daniel Dunbara0d14262009-06-24 23:30:00 +00002286 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002287 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002288 return true;
2289
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002290 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002291 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002292 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002293
Daniel Dunbara0d14262009-06-24 23:30:00 +00002294 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002295 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002296 return true;
2297
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002298 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002299 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002300 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002301
Daniel Dunbara0d14262009-06-24 23:30:00 +00002302 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002303 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002304 return true;
2305
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002306 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002307 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002308
Sean Callanan79ed1a82010-01-19 20:22:31 +00002309 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002310
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002311 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2312 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002313
2314 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002315 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002316
2317 return false;
2318}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002319
2320/// ParseDirectiveOrg
2321/// ::= .org expression [ , expression ]
2322bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002323 CheckForValidSection();
2324
Daniel Dunbar821e3332009-08-31 08:09:28 +00002325 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002326 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002327 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002328 return true;
2329
2330 // Parse optional fill expression.
2331 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002332 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2333 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002334 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002335 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002336
Daniel Dunbar475839e2009-06-29 20:37:27 +00002337 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002338 return true;
2339
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002340 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002341 return TokError("unexpected token in '.org' directive");
2342 }
2343
Sean Callanan79ed1a82010-01-19 20:22:31 +00002344 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002345
Jim Grosbachebd4c052012-01-27 00:37:08 +00002346 // Only limited forms of relocatable expressions are accepted here, it
2347 // has to be relative to the current section. The streamer will return
2348 // 'true' if the expression wasn't evaluatable.
2349 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2350 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002351
2352 return false;
2353}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002354
2355/// ParseDirectiveAlign
2356/// ::= {.align, ...} expression [ , expression [ , expression ]]
2357bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002358 CheckForValidSection();
2359
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002360 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002361 int64_t Alignment;
2362 if (ParseAbsoluteExpression(Alignment))
2363 return true;
2364
2365 SMLoc MaxBytesLoc;
2366 bool HasFillExpr = false;
2367 int64_t FillExpr = 0;
2368 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002369 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2370 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002371 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002372 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002373
2374 // The fill expression can be omitted while specifying a maximum number of
2375 // alignment bytes, e.g:
2376 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002377 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002378 HasFillExpr = true;
2379 if (ParseAbsoluteExpression(FillExpr))
2380 return true;
2381 }
2382
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002383 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2384 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002385 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002386 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002387
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002388 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002389 if (ParseAbsoluteExpression(MaxBytesToFill))
2390 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002391
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002392 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002393 return TokError("unexpected token in directive");
2394 }
2395 }
2396
Sean Callanan79ed1a82010-01-19 20:22:31 +00002397 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002398
Daniel Dunbar648ac512010-05-17 21:54:30 +00002399 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002400 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002401
2402 // Compute alignment in bytes.
2403 if (IsPow2) {
2404 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002405 if (Alignment >= 32) {
2406 Error(AlignmentLoc, "invalid alignment value");
2407 Alignment = 31;
2408 }
2409
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002410 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002411 }
2412
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002413 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002414 if (MaxBytesLoc.isValid()) {
2415 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002416 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2417 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002418 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002419 }
2420
2421 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002422 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2423 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002424 MaxBytesToFill = 0;
2425 }
2426 }
2427
Daniel Dunbar648ac512010-05-17 21:54:30 +00002428 // Check whether we should use optimal code alignment for this .align
2429 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002430 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002431 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2432 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002433 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002434 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002435 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002436 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2437 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002438 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002439
2440 return false;
2441}
2442
Eli Bendersky6ee13082013-01-15 22:59:42 +00002443/// ParseDirectiveFile
2444/// ::= .file [number] filename
2445/// ::= .file number directory filename
2446bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2447 // FIXME: I'm not sure what this is.
2448 int64_t FileNumber = -1;
2449 SMLoc FileNumberLoc = getLexer().getLoc();
2450 if (getLexer().is(AsmToken::Integer)) {
2451 FileNumber = getTok().getIntVal();
2452 Lex();
2453
2454 if (FileNumber < 1)
2455 return TokError("file number less than one");
2456 }
2457
2458 if (getLexer().isNot(AsmToken::String))
2459 return TokError("unexpected token in '.file' directive");
2460
2461 // Usually the directory and filename together, otherwise just the directory.
2462 StringRef Path = getTok().getString();
2463 Path = Path.substr(1, Path.size()-2);
2464 Lex();
2465
2466 StringRef Directory;
2467 StringRef Filename;
2468 if (getLexer().is(AsmToken::String)) {
2469 if (FileNumber == -1)
2470 return TokError("explicit path specified, but no file number");
2471 Filename = getTok().getString();
2472 Filename = Filename.substr(1, Filename.size()-2);
2473 Directory = Path;
2474 Lex();
2475 } else {
2476 Filename = Path;
2477 }
2478
2479 if (getLexer().isNot(AsmToken::EndOfStatement))
2480 return TokError("unexpected token in '.file' directive");
2481
2482 if (FileNumber == -1)
2483 getStreamer().EmitFileDirective(Filename);
2484 else {
2485 if (getContext().getGenDwarfForAssembly() == true)
2486 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2487 "used to generate dwarf debug info for assembly code");
2488
2489 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2490 Error(FileNumberLoc, "file number already allocated");
2491 }
2492
2493 return false;
2494}
2495
2496/// ParseDirectiveLine
2497/// ::= .line [number]
2498bool AsmParser::ParseDirectiveLine() {
2499 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2500 if (getLexer().isNot(AsmToken::Integer))
2501 return TokError("unexpected token in '.line' directive");
2502
2503 int64_t LineNumber = getTok().getIntVal();
2504 (void) LineNumber;
2505 Lex();
2506
2507 // FIXME: Do something with the .line.
2508 }
2509
2510 if (getLexer().isNot(AsmToken::EndOfStatement))
2511 return TokError("unexpected token in '.line' directive");
2512
2513 return false;
2514}
2515
2516/// ParseDirectiveLoc
2517/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2518/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2519/// The first number is a file number, must have been previously assigned with
2520/// a .file directive, the second number is the line number and optionally the
2521/// third number is a column position (zero if not specified). The remaining
2522/// optional items are .loc sub-directives.
2523bool AsmParser::ParseDirectiveLoc() {
2524 if (getLexer().isNot(AsmToken::Integer))
2525 return TokError("unexpected token in '.loc' directive");
2526 int64_t FileNumber = getTok().getIntVal();
2527 if (FileNumber < 1)
2528 return TokError("file number less than one in '.loc' directive");
2529 if (!getContext().isValidDwarfFileNumber(FileNumber))
2530 return TokError("unassigned file number in '.loc' directive");
2531 Lex();
2532
2533 int64_t LineNumber = 0;
2534 if (getLexer().is(AsmToken::Integer)) {
2535 LineNumber = getTok().getIntVal();
2536 if (LineNumber < 1)
2537 return TokError("line number less than one in '.loc' directive");
2538 Lex();
2539 }
2540
2541 int64_t ColumnPos = 0;
2542 if (getLexer().is(AsmToken::Integer)) {
2543 ColumnPos = getTok().getIntVal();
2544 if (ColumnPos < 0)
2545 return TokError("column position less than zero in '.loc' directive");
2546 Lex();
2547 }
2548
2549 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2550 unsigned Isa = 0;
2551 int64_t Discriminator = 0;
2552 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2553 for (;;) {
2554 if (getLexer().is(AsmToken::EndOfStatement))
2555 break;
2556
2557 StringRef Name;
2558 SMLoc Loc = getTok().getLoc();
2559 if (ParseIdentifier(Name))
2560 return TokError("unexpected token in '.loc' directive");
2561
2562 if (Name == "basic_block")
2563 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2564 else if (Name == "prologue_end")
2565 Flags |= DWARF2_FLAG_PROLOGUE_END;
2566 else if (Name == "epilogue_begin")
2567 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2568 else if (Name == "is_stmt") {
2569 Loc = getTok().getLoc();
2570 const MCExpr *Value;
2571 if (ParseExpression(Value))
2572 return true;
2573 // The expression must be the constant 0 or 1.
2574 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2575 int Value = MCE->getValue();
2576 if (Value == 0)
2577 Flags &= ~DWARF2_FLAG_IS_STMT;
2578 else if (Value == 1)
2579 Flags |= DWARF2_FLAG_IS_STMT;
2580 else
2581 return Error(Loc, "is_stmt value not 0 or 1");
2582 }
2583 else {
2584 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2585 }
2586 }
2587 else if (Name == "isa") {
2588 Loc = getTok().getLoc();
2589 const MCExpr *Value;
2590 if (ParseExpression(Value))
2591 return true;
2592 // The expression must be a constant greater or equal to 0.
2593 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2594 int Value = MCE->getValue();
2595 if (Value < 0)
2596 return Error(Loc, "isa number less than zero");
2597 Isa = Value;
2598 }
2599 else {
2600 return Error(Loc, "isa number not a constant value");
2601 }
2602 }
2603 else if (Name == "discriminator") {
2604 if (ParseAbsoluteExpression(Discriminator))
2605 return true;
2606 }
2607 else {
2608 return Error(Loc, "unknown sub-directive in '.loc' directive");
2609 }
2610
2611 if (getLexer().is(AsmToken::EndOfStatement))
2612 break;
2613 }
2614 }
2615
2616 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2617 Isa, Discriminator, StringRef());
2618
2619 return false;
2620}
2621
2622/// ParseDirectiveStabs
2623/// ::= .stabs string, number, number, number
2624bool AsmParser::ParseDirectiveStabs() {
2625 return TokError("unsupported directive '.stabs'");
2626}
2627
2628/// ParseDirectiveCFISections
2629/// ::= .cfi_sections section [, section]
2630bool AsmParser::ParseDirectiveCFISections() {
2631 StringRef Name;
2632 bool EH = false;
2633 bool Debug = false;
2634
2635 if (ParseIdentifier(Name))
2636 return TokError("Expected an identifier");
2637
2638 if (Name == ".eh_frame")
2639 EH = true;
2640 else if (Name == ".debug_frame")
2641 Debug = true;
2642
2643 if (getLexer().is(AsmToken::Comma)) {
2644 Lex();
2645
2646 if (ParseIdentifier(Name))
2647 return TokError("Expected an identifier");
2648
2649 if (Name == ".eh_frame")
2650 EH = true;
2651 else if (Name == ".debug_frame")
2652 Debug = true;
2653 }
2654
2655 getStreamer().EmitCFISections(EH, Debug);
2656 return false;
2657}
2658
2659/// ParseDirectiveCFIStartProc
2660/// ::= .cfi_startproc
2661bool AsmParser::ParseDirectiveCFIStartProc() {
2662 getStreamer().EmitCFIStartProc();
2663 return false;
2664}
2665
2666/// ParseDirectiveCFIEndProc
2667/// ::= .cfi_endproc
2668bool AsmParser::ParseDirectiveCFIEndProc() {
2669 getStreamer().EmitCFIEndProc();
2670 return false;
2671}
2672
2673/// ParseRegisterOrRegisterNumber - parse register name or number.
2674bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2675 SMLoc DirectiveLoc) {
2676 unsigned RegNo;
2677
2678 if (getLexer().isNot(AsmToken::Integer)) {
2679 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2680 return true;
2681 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2682 } else
2683 return ParseAbsoluteExpression(Register);
2684
2685 return false;
2686}
2687
2688/// ParseDirectiveCFIDefCfa
2689/// ::= .cfi_def_cfa register, offset
2690bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2691 int64_t Register = 0;
2692 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2693 return true;
2694
2695 if (getLexer().isNot(AsmToken::Comma))
2696 return TokError("unexpected token in directive");
2697 Lex();
2698
2699 int64_t Offset = 0;
2700 if (ParseAbsoluteExpression(Offset))
2701 return true;
2702
2703 getStreamer().EmitCFIDefCfa(Register, Offset);
2704 return false;
2705}
2706
2707/// ParseDirectiveCFIDefCfaOffset
2708/// ::= .cfi_def_cfa_offset offset
2709bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2710 int64_t Offset = 0;
2711 if (ParseAbsoluteExpression(Offset))
2712 return true;
2713
2714 getStreamer().EmitCFIDefCfaOffset(Offset);
2715 return false;
2716}
2717
2718/// ParseDirectiveCFIRegister
2719/// ::= .cfi_register register, register
2720bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2721 int64_t Register1 = 0;
2722 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2723 return true;
2724
2725 if (getLexer().isNot(AsmToken::Comma))
2726 return TokError("unexpected token in directive");
2727 Lex();
2728
2729 int64_t Register2 = 0;
2730 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2731 return true;
2732
2733 getStreamer().EmitCFIRegister(Register1, Register2);
2734 return false;
2735}
2736
2737/// ParseDirectiveCFIAdjustCfaOffset
2738/// ::= .cfi_adjust_cfa_offset adjustment
2739bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2740 int64_t Adjustment = 0;
2741 if (ParseAbsoluteExpression(Adjustment))
2742 return true;
2743
2744 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2745 return false;
2746}
2747
2748/// ParseDirectiveCFIDefCfaRegister
2749/// ::= .cfi_def_cfa_register register
2750bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2751 int64_t Register = 0;
2752 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2753 return true;
2754
2755 getStreamer().EmitCFIDefCfaRegister(Register);
2756 return false;
2757}
2758
2759/// ParseDirectiveCFIOffset
2760/// ::= .cfi_offset register, offset
2761bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2762 int64_t Register = 0;
2763 int64_t Offset = 0;
2764
2765 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2766 return true;
2767
2768 if (getLexer().isNot(AsmToken::Comma))
2769 return TokError("unexpected token in directive");
2770 Lex();
2771
2772 if (ParseAbsoluteExpression(Offset))
2773 return true;
2774
2775 getStreamer().EmitCFIOffset(Register, Offset);
2776 return false;
2777}
2778
2779/// ParseDirectiveCFIRelOffset
2780/// ::= .cfi_rel_offset register, offset
2781bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2782 int64_t Register = 0;
2783
2784 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2785 return true;
2786
2787 if (getLexer().isNot(AsmToken::Comma))
2788 return TokError("unexpected token in directive");
2789 Lex();
2790
2791 int64_t Offset = 0;
2792 if (ParseAbsoluteExpression(Offset))
2793 return true;
2794
2795 getStreamer().EmitCFIRelOffset(Register, Offset);
2796 return false;
2797}
2798
2799static bool isValidEncoding(int64_t Encoding) {
2800 if (Encoding & ~0xff)
2801 return false;
2802
2803 if (Encoding == dwarf::DW_EH_PE_omit)
2804 return true;
2805
2806 const unsigned Format = Encoding & 0xf;
2807 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2808 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2809 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2810 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2811 return false;
2812
2813 const unsigned Application = Encoding & 0x70;
2814 if (Application != dwarf::DW_EH_PE_absptr &&
2815 Application != dwarf::DW_EH_PE_pcrel)
2816 return false;
2817
2818 return true;
2819}
2820
2821/// ParseDirectiveCFIPersonalityOrLsda
2822/// IsPersonality true for cfi_personality, false for cfi_lsda
2823/// ::= .cfi_personality encoding, [symbol_name]
2824/// ::= .cfi_lsda encoding, [symbol_name]
2825bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2826 int64_t Encoding = 0;
2827 if (ParseAbsoluteExpression(Encoding))
2828 return true;
2829 if (Encoding == dwarf::DW_EH_PE_omit)
2830 return false;
2831
2832 if (!isValidEncoding(Encoding))
2833 return TokError("unsupported encoding.");
2834
2835 if (getLexer().isNot(AsmToken::Comma))
2836 return TokError("unexpected token in directive");
2837 Lex();
2838
2839 StringRef Name;
2840 if (ParseIdentifier(Name))
2841 return TokError("expected identifier in directive");
2842
2843 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2844
2845 if (IsPersonality)
2846 getStreamer().EmitCFIPersonality(Sym, Encoding);
2847 else
2848 getStreamer().EmitCFILsda(Sym, Encoding);
2849 return false;
2850}
2851
2852/// ParseDirectiveCFIRememberState
2853/// ::= .cfi_remember_state
2854bool AsmParser::ParseDirectiveCFIRememberState() {
2855 getStreamer().EmitCFIRememberState();
2856 return false;
2857}
2858
2859/// ParseDirectiveCFIRestoreState
2860/// ::= .cfi_remember_state
2861bool AsmParser::ParseDirectiveCFIRestoreState() {
2862 getStreamer().EmitCFIRestoreState();
2863 return false;
2864}
2865
2866/// ParseDirectiveCFISameValue
2867/// ::= .cfi_same_value register
2868bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2869 int64_t Register = 0;
2870
2871 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2872 return true;
2873
2874 getStreamer().EmitCFISameValue(Register);
2875 return false;
2876}
2877
2878/// ParseDirectiveCFIRestore
2879/// ::= .cfi_restore register
2880bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2881 int64_t Register = 0;
2882 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2883 return true;
2884
2885 getStreamer().EmitCFIRestore(Register);
2886 return false;
2887}
2888
2889/// ParseDirectiveCFIEscape
2890/// ::= .cfi_escape expression[,...]
2891bool AsmParser::ParseDirectiveCFIEscape() {
2892 std::string Values;
2893 int64_t CurrValue;
2894 if (ParseAbsoluteExpression(CurrValue))
2895 return true;
2896
2897 Values.push_back((uint8_t)CurrValue);
2898
2899 while (getLexer().is(AsmToken::Comma)) {
2900 Lex();
2901
2902 if (ParseAbsoluteExpression(CurrValue))
2903 return true;
2904
2905 Values.push_back((uint8_t)CurrValue);
2906 }
2907
2908 getStreamer().EmitCFIEscape(Values);
2909 return false;
2910}
2911
2912/// ParseDirectiveCFISignalFrame
2913/// ::= .cfi_signal_frame
2914bool AsmParser::ParseDirectiveCFISignalFrame() {
2915 if (getLexer().isNot(AsmToken::EndOfStatement))
2916 return Error(getLexer().getLoc(),
2917 "unexpected token in '.cfi_signal_frame'");
2918
2919 getStreamer().EmitCFISignalFrame();
2920 return false;
2921}
2922
2923/// ParseDirectiveCFIUndefined
2924/// ::= .cfi_undefined register
2925bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2926 int64_t Register = 0;
2927
2928 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2929 return true;
2930
2931 getStreamer().EmitCFIUndefined(Register);
2932 return false;
2933}
2934
2935/// ParseDirectiveMacrosOnOff
2936/// ::= .macros_on
2937/// ::= .macros_off
2938bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2939 if (getLexer().isNot(AsmToken::EndOfStatement))
2940 return Error(getLexer().getLoc(),
2941 "unexpected token in '" + Directive + "' directive");
2942
2943 SetMacrosEnabled(Directive == ".macros_on");
2944 return false;
2945}
2946
2947/// ParseDirectiveMacro
2948/// ::= .macro name [parameters]
2949bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2950 StringRef Name;
2951 if (ParseIdentifier(Name))
2952 return TokError("expected identifier in '.macro' directive");
2953
2954 MCAsmMacroParameters Parameters;
2955 // Argument delimiter is initially unknown. It will be set by
2956 // ParseMacroArgument()
2957 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2958 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2959 for (;;) {
2960 MCAsmMacroParameter Parameter;
2961 if (ParseIdentifier(Parameter.first))
2962 return TokError("expected identifier in '.macro' directive");
2963
2964 if (getLexer().is(AsmToken::Equal)) {
2965 Lex();
2966 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
2967 return true;
2968 }
2969
2970 Parameters.push_back(Parameter);
2971
2972 if (getLexer().is(AsmToken::Comma))
2973 Lex();
2974 else if (getLexer().is(AsmToken::EndOfStatement))
2975 break;
2976 }
2977 }
2978
2979 // Eat the end of statement.
2980 Lex();
2981
2982 AsmToken EndToken, StartToken = getTok();
2983
2984 // Lex the macro definition.
2985 for (;;) {
2986 // Check whether we have reached the end of the file.
2987 if (getLexer().is(AsmToken::Eof))
2988 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
2989
2990 // Otherwise, check whether we have reach the .endmacro.
2991 if (getLexer().is(AsmToken::Identifier) &&
2992 (getTok().getIdentifier() == ".endm" ||
2993 getTok().getIdentifier() == ".endmacro")) {
2994 EndToken = getTok();
2995 Lex();
2996 if (getLexer().isNot(AsmToken::EndOfStatement))
2997 return TokError("unexpected token in '" + EndToken.getIdentifier() +
2998 "' directive");
2999 break;
3000 }
3001
3002 // Otherwise, scan til the end of the statement.
3003 EatToEndOfStatement();
3004 }
3005
3006 if (LookupMacro(Name)) {
3007 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3008 }
3009
3010 const char *BodyStart = StartToken.getLoc().getPointer();
3011 const char *BodyEnd = EndToken.getLoc().getPointer();
3012 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3013 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3014 return false;
3015}
3016
3017/// ParseDirectiveEndMacro
3018/// ::= .endm
3019/// ::= .endmacro
3020bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3021 if (getLexer().isNot(AsmToken::EndOfStatement))
3022 return TokError("unexpected token in '" + Directive + "' directive");
3023
3024 // If we are inside a macro instantiation, terminate the current
3025 // instantiation.
3026 if (InsideMacroInstantiation()) {
3027 HandleMacroExit();
3028 return false;
3029 }
3030
3031 // Otherwise, this .endmacro is a stray entry in the file; well formed
3032 // .endmacro directives are handled during the macro definition parsing.
3033 return TokError("unexpected '" + Directive + "' in file, "
3034 "no current macro definition");
3035}
3036
3037/// ParseDirectivePurgeMacro
3038/// ::= .purgem
3039bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3040 StringRef Name;
3041 if (ParseIdentifier(Name))
3042 return TokError("expected identifier in '.purgem' directive");
3043
3044 if (getLexer().isNot(AsmToken::EndOfStatement))
3045 return TokError("unexpected token in '.purgem' directive");
3046
3047 if (!LookupMacro(Name))
3048 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3049
3050 UndefineMacro(Name);
3051 return false;
3052}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003053
3054/// ParseDirectiveBundleAlignMode
3055/// ::= {.bundle_align_mode} expression
3056bool AsmParser::ParseDirectiveBundleAlignMode() {
3057 CheckForValidSection();
3058
3059 // Expect a single argument: an expression that evaluates to a constant
3060 // in the inclusive range 0-30.
3061 SMLoc ExprLoc = getLexer().getLoc();
3062 int64_t AlignSizePow2;
3063 if (ParseAbsoluteExpression(AlignSizePow2))
3064 return true;
3065 else if (getLexer().isNot(AsmToken::EndOfStatement))
3066 return TokError("unexpected token after expression in"
3067 " '.bundle_align_mode' directive");
3068 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3069 return Error(ExprLoc,
3070 "invalid bundle alignment size (expected between 0 and 30)");
3071
3072 Lex();
3073
3074 // Because of AlignSizePow2's verified range we can safely truncate it to
3075 // unsigned.
3076 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3077 return false;
3078}
3079
3080/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003081/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003082bool AsmParser::ParseDirectiveBundleLock() {
3083 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003084 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003085
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003086 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3087 StringRef Option;
3088 SMLoc Loc = getTok().getLoc();
3089 const char *kInvalidOptionError =
3090 "invalid option for '.bundle_lock' directive";
3091
3092 if (ParseIdentifier(Option))
3093 return Error(Loc, kInvalidOptionError);
3094
3095 if (Option != "align_to_end")
3096 return Error(Loc, kInvalidOptionError);
3097 else if (getLexer().isNot(AsmToken::EndOfStatement))
3098 return Error(Loc,
3099 "unexpected token after '.bundle_lock' directive option");
3100 AlignToEnd = true;
3101 }
3102
Eli Bendersky4766ef42012-12-20 19:05:53 +00003103 Lex();
3104
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003105 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003106 return false;
3107}
3108
3109/// ParseDirectiveBundleLock
3110/// ::= {.bundle_lock}
3111bool AsmParser::ParseDirectiveBundleUnlock() {
3112 CheckForValidSection();
3113
3114 if (getLexer().isNot(AsmToken::EndOfStatement))
3115 return TokError("unexpected token in '.bundle_unlock' directive");
3116 Lex();
3117
3118 getStreamer().EmitBundleUnlock();
3119 return false;
3120}
3121
Eli Bendersky6ee13082013-01-15 22:59:42 +00003122/// ParseDirectiveSpace
3123/// ::= (.skip | .space) expression [ , expression ]
3124bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3125 CheckForValidSection();
3126
3127 int64_t NumBytes;
3128 if (ParseAbsoluteExpression(NumBytes))
3129 return true;
3130
3131 int64_t FillExpr = 0;
3132 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3133 if (getLexer().isNot(AsmToken::Comma))
3134 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3135 Lex();
3136
3137 if (ParseAbsoluteExpression(FillExpr))
3138 return true;
3139
3140 if (getLexer().isNot(AsmToken::EndOfStatement))
3141 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3142 }
3143
3144 Lex();
3145
3146 if (NumBytes <= 0)
3147 return TokError("invalid number of bytes in '" +
3148 Twine(IDVal) + "' directive");
3149
3150 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3151 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3152
3153 return false;
3154}
3155
3156/// ParseDirectiveLEB128
3157/// ::= (.sleb128 | .uleb128) expression
3158bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3159 CheckForValidSection();
3160 const MCExpr *Value;
3161
3162 if (ParseExpression(Value))
3163 return true;
3164
3165 if (getLexer().isNot(AsmToken::EndOfStatement))
3166 return TokError("unexpected token in directive");
3167
3168 if (Signed)
3169 getStreamer().EmitSLEB128Value(Value);
3170 else
3171 getStreamer().EmitULEB128Value(Value);
3172
3173 return false;
3174}
3175
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003176/// ParseDirectiveSymbolAttribute
3177/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003178bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003179 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003180 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003181 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003182 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003183
3184 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003185 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003186
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003187 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003188
Jim Grosbach10ec6502011-09-15 17:56:49 +00003189 // Assembler local symbols don't make any sense here. Complain loudly.
3190 if (Sym->isTemporary())
3191 return Error(Loc, "non-local symbol required in directive");
3192
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003193 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003194
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003195 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003196 break;
3197
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003198 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003199 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003200 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003201 }
3202 }
3203
Sean Callanan79ed1a82010-01-19 20:22:31 +00003204 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003205 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003206}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003207
3208/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003209/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3210bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003211 CheckForValidSection();
3212
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003213 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003214 StringRef Name;
3215 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003216 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003217
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003218 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003219 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003220
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003221 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003222 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003223 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003224
3225 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003226 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003227 if (ParseAbsoluteExpression(Size))
3228 return true;
3229
3230 int64_t Pow2Alignment = 0;
3231 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003232 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003233 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003234 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003235 if (ParseAbsoluteExpression(Pow2Alignment))
3236 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003237
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003238 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3239 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003240 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3241
Chris Lattner258281d2010-01-19 06:22:22 +00003242 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003243 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3244 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003245 if (!isPowerOf2_64(Pow2Alignment))
3246 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3247 Pow2Alignment = Log2_64(Pow2Alignment);
3248 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003249 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003250
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003251 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003252 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003253
Sean Callanan79ed1a82010-01-19 20:22:31 +00003254 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003255
Chris Lattner1fc3d752009-07-09 17:25:12 +00003256 // NOTE: a size of zero for a .comm should create a undefined symbol
3257 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003258 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003259 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3260 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003261
Eric Christopherc260a3e2010-05-14 01:38:54 +00003262 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003263 // may internally end up wanting an alignment in bytes.
3264 // FIXME: Diagnose overflow.
3265 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003266 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3267 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003268
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003269 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003270 return Error(IDLoc, "invalid symbol redefinition");
3271
Chris Lattner1fc3d752009-07-09 17:25:12 +00003272 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003273 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003274 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003275 return false;
3276 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003277
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003278 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003279 return false;
3280}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003281
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003282/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003283/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003284bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003285 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003286 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003287
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003288 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003289 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003290 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003291
Sean Callanan79ed1a82010-01-19 20:22:31 +00003292 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003293
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003294 if (Str.empty())
3295 Error(Loc, ".abort detected. Assembly stopping.");
3296 else
3297 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003298 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003299
3300 return false;
3301}
Kevin Enderby71148242009-07-14 21:35:03 +00003302
Kevin Enderby1f049b22009-07-14 23:21:55 +00003303/// ParseDirectiveInclude
3304/// ::= .include "filename"
3305bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003306 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003307 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003308
Sean Callanan18b83232010-01-19 21:44:56 +00003309 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003310 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003311 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003312
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003313 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003314 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003315
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003316 // Strip the quotes.
3317 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003318
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003319 // Attempt to switch the lexer to the included file before consuming the end
3320 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003321 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003322 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003323 return true;
3324 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003325
3326 return false;
3327}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003328
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003329/// ParseDirectiveIncbin
3330/// ::= .incbin "filename"
3331bool AsmParser::ParseDirectiveIncbin() {
3332 if (getLexer().isNot(AsmToken::String))
3333 return TokError("expected string in '.incbin' directive");
3334
3335 std::string Filename = getTok().getString();
3336 SMLoc IncbinLoc = getLexer().getLoc();
3337 Lex();
3338
3339 if (getLexer().isNot(AsmToken::EndOfStatement))
3340 return TokError("unexpected token in '.incbin' directive");
3341
3342 // Strip the quotes.
3343 Filename = Filename.substr(1, Filename.size()-2);
3344
3345 // Attempt to process the included file.
3346 if (ProcessIncbinFile(Filename)) {
3347 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3348 return true;
3349 }
3350
3351 return false;
3352}
3353
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003354/// ParseDirectiveIf
3355/// ::= .if expression
3356bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003357 TheCondStack.push_back(TheCondState);
3358 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003359 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003360 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003361 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003362 int64_t ExprValue;
3363 if (ParseAbsoluteExpression(ExprValue))
3364 return true;
3365
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003366 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003367 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003368
Sean Callanan79ed1a82010-01-19 20:22:31 +00003369 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003370
3371 TheCondState.CondMet = ExprValue;
3372 TheCondState.Ignore = !TheCondState.CondMet;
3373 }
3374
3375 return false;
3376}
3377
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003378/// ParseDirectiveIfb
3379/// ::= .ifb string
3380bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3381 TheCondStack.push_back(TheCondState);
3382 TheCondState.TheCond = AsmCond::IfCond;
3383
Benjamin Kramer29739e72012-05-12 16:52:21 +00003384 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003385 EatToEndOfStatement();
3386 } else {
3387 StringRef Str = ParseStringToEndOfStatement();
3388
3389 if (getLexer().isNot(AsmToken::EndOfStatement))
3390 return TokError("unexpected token in '.ifb' directive");
3391
3392 Lex();
3393
3394 TheCondState.CondMet = ExpectBlank == Str.empty();
3395 TheCondState.Ignore = !TheCondState.CondMet;
3396 }
3397
3398 return false;
3399}
3400
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003401/// ParseDirectiveIfc
3402/// ::= .ifc string1, string2
3403bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3404 TheCondStack.push_back(TheCondState);
3405 TheCondState.TheCond = AsmCond::IfCond;
3406
Benjamin Kramer29739e72012-05-12 16:52:21 +00003407 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003408 EatToEndOfStatement();
3409 } else {
3410 StringRef Str1 = ParseStringToComma();
3411
3412 if (getLexer().isNot(AsmToken::Comma))
3413 return TokError("unexpected token in '.ifc' directive");
3414
3415 Lex();
3416
3417 StringRef Str2 = ParseStringToEndOfStatement();
3418
3419 if (getLexer().isNot(AsmToken::EndOfStatement))
3420 return TokError("unexpected token in '.ifc' directive");
3421
3422 Lex();
3423
3424 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3425 TheCondState.Ignore = !TheCondState.CondMet;
3426 }
3427
3428 return false;
3429}
3430
3431/// ParseDirectiveIfdef
3432/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003433bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3434 StringRef Name;
3435 TheCondStack.push_back(TheCondState);
3436 TheCondState.TheCond = AsmCond::IfCond;
3437
3438 if (TheCondState.Ignore) {
3439 EatToEndOfStatement();
3440 } else {
3441 if (ParseIdentifier(Name))
3442 return TokError("expected identifier after '.ifdef'");
3443
3444 Lex();
3445
3446 MCSymbol *Sym = getContext().LookupSymbol(Name);
3447
3448 if (expect_defined)
3449 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3450 else
3451 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3452 TheCondState.Ignore = !TheCondState.CondMet;
3453 }
3454
3455 return false;
3456}
3457
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003458/// ParseDirectiveElseIf
3459/// ::= .elseif expression
3460bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3461 if (TheCondState.TheCond != AsmCond::IfCond &&
3462 TheCondState.TheCond != AsmCond::ElseIfCond)
3463 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3464 " an .elseif");
3465 TheCondState.TheCond = AsmCond::ElseIfCond;
3466
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003467 bool LastIgnoreState = false;
3468 if (!TheCondStack.empty())
3469 LastIgnoreState = TheCondStack.back().Ignore;
3470 if (LastIgnoreState || TheCondState.CondMet) {
3471 TheCondState.Ignore = true;
3472 EatToEndOfStatement();
3473 }
3474 else {
3475 int64_t ExprValue;
3476 if (ParseAbsoluteExpression(ExprValue))
3477 return true;
3478
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003479 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003480 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003481
Sean Callanan79ed1a82010-01-19 20:22:31 +00003482 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003483 TheCondState.CondMet = ExprValue;
3484 TheCondState.Ignore = !TheCondState.CondMet;
3485 }
3486
3487 return false;
3488}
3489
3490/// ParseDirectiveElse
3491/// ::= .else
3492bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003493 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003494 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003495
Sean Callanan79ed1a82010-01-19 20:22:31 +00003496 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003497
3498 if (TheCondState.TheCond != AsmCond::IfCond &&
3499 TheCondState.TheCond != AsmCond::ElseIfCond)
3500 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3501 ".elseif");
3502 TheCondState.TheCond = AsmCond::ElseCond;
3503 bool LastIgnoreState = false;
3504 if (!TheCondStack.empty())
3505 LastIgnoreState = TheCondStack.back().Ignore;
3506 if (LastIgnoreState || TheCondState.CondMet)
3507 TheCondState.Ignore = true;
3508 else
3509 TheCondState.Ignore = false;
3510
3511 return false;
3512}
3513
3514/// ParseDirectiveEndIf
3515/// ::= .endif
3516bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003517 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003518 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003519
Sean Callanan79ed1a82010-01-19 20:22:31 +00003520 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003521
3522 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3523 TheCondStack.empty())
3524 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3525 ".else");
3526 if (!TheCondStack.empty()) {
3527 TheCondState = TheCondStack.back();
3528 TheCondStack.pop_back();
3529 }
3530
3531 return false;
3532}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003533
Eli Bendersky6ee13082013-01-15 22:59:42 +00003534void AsmParser::initializeDirectiveKindMap() {
3535 DirectiveKindMap[".set"] = DK_SET;
3536 DirectiveKindMap[".equ"] = DK_EQU;
3537 DirectiveKindMap[".equiv"] = DK_EQUIV;
3538 DirectiveKindMap[".ascii"] = DK_ASCII;
3539 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3540 DirectiveKindMap[".string"] = DK_STRING;
3541 DirectiveKindMap[".byte"] = DK_BYTE;
3542 DirectiveKindMap[".short"] = DK_SHORT;
3543 DirectiveKindMap[".value"] = DK_VALUE;
3544 DirectiveKindMap[".2byte"] = DK_2BYTE;
3545 DirectiveKindMap[".long"] = DK_LONG;
3546 DirectiveKindMap[".int"] = DK_INT;
3547 DirectiveKindMap[".4byte"] = DK_4BYTE;
3548 DirectiveKindMap[".quad"] = DK_QUAD;
3549 DirectiveKindMap[".8byte"] = DK_8BYTE;
3550 DirectiveKindMap[".single"] = DK_SINGLE;
3551 DirectiveKindMap[".float"] = DK_FLOAT;
3552 DirectiveKindMap[".double"] = DK_DOUBLE;
3553 DirectiveKindMap[".align"] = DK_ALIGN;
3554 DirectiveKindMap[".align32"] = DK_ALIGN32;
3555 DirectiveKindMap[".balign"] = DK_BALIGN;
3556 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3557 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3558 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3559 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3560 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3561 DirectiveKindMap[".org"] = DK_ORG;
3562 DirectiveKindMap[".fill"] = DK_FILL;
3563 DirectiveKindMap[".zero"] = DK_ZERO;
3564 DirectiveKindMap[".extern"] = DK_EXTERN;
3565 DirectiveKindMap[".globl"] = DK_GLOBL;
3566 DirectiveKindMap[".global"] = DK_GLOBAL;
3567 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3568 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3569 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3570 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3571 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3572 DirectiveKindMap[".reference"] = DK_REFERENCE;
3573 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3574 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3575 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3576 DirectiveKindMap[".comm"] = DK_COMM;
3577 DirectiveKindMap[".common"] = DK_COMMON;
3578 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3579 DirectiveKindMap[".abort"] = DK_ABORT;
3580 DirectiveKindMap[".include"] = DK_INCLUDE;
3581 DirectiveKindMap[".incbin"] = DK_INCBIN;
3582 DirectiveKindMap[".code16"] = DK_CODE16;
3583 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3584 DirectiveKindMap[".rept"] = DK_REPT;
3585 DirectiveKindMap[".irp"] = DK_IRP;
3586 DirectiveKindMap[".irpc"] = DK_IRPC;
3587 DirectiveKindMap[".endr"] = DK_ENDR;
3588 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3589 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3590 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3591 DirectiveKindMap[".if"] = DK_IF;
3592 DirectiveKindMap[".ifb"] = DK_IFB;
3593 DirectiveKindMap[".ifnb"] = DK_IFNB;
3594 DirectiveKindMap[".ifc"] = DK_IFC;
3595 DirectiveKindMap[".ifnc"] = DK_IFNC;
3596 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3597 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3598 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3599 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3600 DirectiveKindMap[".else"] = DK_ELSE;
3601 DirectiveKindMap[".endif"] = DK_ENDIF;
3602 DirectiveKindMap[".skip"] = DK_SKIP;
3603 DirectiveKindMap[".space"] = DK_SPACE;
3604 DirectiveKindMap[".file"] = DK_FILE;
3605 DirectiveKindMap[".line"] = DK_LINE;
3606 DirectiveKindMap[".loc"] = DK_LOC;
3607 DirectiveKindMap[".stabs"] = DK_STABS;
3608 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3609 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3610 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3611 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3612 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3613 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3614 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3615 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3616 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3617 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3618 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3619 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3620 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3621 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3622 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3623 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3624 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3625 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3626 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3627 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3628 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3629 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3630 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3631 DirectiveKindMap[".macro"] = DK_MACRO;
3632 DirectiveKindMap[".endm"] = DK_ENDM;
3633 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3634 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003635}
3636
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003637
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003638MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003639 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003640
Rafael Espindola761cb062012-06-03 23:57:14 +00003641 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003642 for (;;) {
3643 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003644 if (getLexer().is(AsmToken::Eof)) {
3645 Error(DirectiveLoc, "no matching '.endr' in definition");
3646 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003647 }
3648
Rafael Espindola761cb062012-06-03 23:57:14 +00003649 if (Lexer.is(AsmToken::Identifier) &&
3650 (getTok().getIdentifier() == ".rept")) {
3651 ++NestLevel;
3652 }
3653
3654 // Otherwise, check whether we have reached the .endr.
3655 if (Lexer.is(AsmToken::Identifier) &&
3656 getTok().getIdentifier() == ".endr") {
3657 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003658 EndToken = getTok();
3659 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003660 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3661 TokError("unexpected token in '.endr' directive");
3662 return 0;
3663 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003664 break;
3665 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003666 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003667 }
3668
Rafael Espindola761cb062012-06-03 23:57:14 +00003669 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003670 EatToEndOfStatement();
3671 }
3672
3673 const char *BodyStart = StartToken.getLoc().getPointer();
3674 const char *BodyEnd = EndToken.getLoc().getPointer();
3675 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3676
Rafael Espindola761cb062012-06-03 23:57:14 +00003677 // We Are Anonymous.
3678 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003679 MCAsmMacroParameters Parameters;
3680 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003681}
3682
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003683void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003684 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003685 OS << ".endr\n";
3686
3687 MemoryBuffer *Instantiation =
3688 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3689
Rafael Espindola761cb062012-06-03 23:57:14 +00003690 // Create the macro instantiation object and add to the current macro
3691 // instantiation stack.
3692 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003693 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003694 getTok().getLoc(),
3695 Instantiation);
3696 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003697
Rafael Espindola761cb062012-06-03 23:57:14 +00003698 // Jump to the macro instantiation and prime the lexer.
3699 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3700 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3701 Lex();
3702}
3703
3704bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3705 int64_t Count;
3706 if (ParseAbsoluteExpression(Count))
3707 return TokError("unexpected token in '.rept' directive");
3708
3709 if (Count < 0)
3710 return TokError("Count is negative");
3711
3712 if (Lexer.isNot(AsmToken::EndOfStatement))
3713 return TokError("unexpected token in '.rept' directive");
3714
3715 // Eat the end of statement.
3716 Lex();
3717
3718 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003719 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003720 if (!M)
3721 return true;
3722
3723 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3724 // to hold the macro body with substitutions.
3725 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003726 MCAsmMacroParameters Parameters;
3727 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003728 raw_svector_ostream OS(Buf);
3729 while (Count--) {
3730 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3731 return true;
3732 }
3733 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003734
3735 return false;
3736}
3737
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003738/// ParseDirectiveIrp
3739/// ::= .irp symbol,values
3740bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003741 MCAsmMacroParameters Parameters;
3742 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003743
Preston Gurd6c9176a2012-09-19 20:29:04 +00003744 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003745 return TokError("expected identifier in '.irp' directive");
3746
3747 Parameters.push_back(Parameter);
3748
3749 if (Lexer.isNot(AsmToken::Comma))
3750 return TokError("expected comma in '.irp' directive");
3751
3752 Lex();
3753
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003754 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003755 if (ParseMacroArguments(0, A))
3756 return true;
3757
3758 // Eat the end of statement.
3759 Lex();
3760
3761 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003762 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003763 if (!M)
3764 return true;
3765
3766 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3767 // to hold the macro body with substitutions.
3768 SmallString<256> Buf;
3769 raw_svector_ostream OS(Buf);
3770
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003771 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3772 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003773 Args.push_back(*i);
3774
3775 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3776 return true;
3777 }
3778
3779 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3780
3781 return false;
3782}
3783
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003784/// ParseDirectiveIrpc
3785/// ::= .irpc symbol,values
3786bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003787 MCAsmMacroParameters Parameters;
3788 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003789
Preston Gurd6c9176a2012-09-19 20:29:04 +00003790 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003791 return TokError("expected identifier in '.irpc' directive");
3792
3793 Parameters.push_back(Parameter);
3794
3795 if (Lexer.isNot(AsmToken::Comma))
3796 return TokError("expected comma in '.irpc' directive");
3797
3798 Lex();
3799
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003800 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003801 if (ParseMacroArguments(0, A))
3802 return true;
3803
3804 if (A.size() != 1 || A.front().size() != 1)
3805 return TokError("unexpected token in '.irpc' directive");
3806
3807 // Eat the end of statement.
3808 Lex();
3809
3810 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003811 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003812 if (!M)
3813 return true;
3814
3815 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3816 // to hold the macro body with substitutions.
3817 SmallString<256> Buf;
3818 raw_svector_ostream OS(Buf);
3819
3820 StringRef Values = A.front().front().getString();
3821 std::size_t I, End = Values.size();
3822 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003823 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003824 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3825
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003826 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003827 Args.push_back(Arg);
3828
3829 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3830 return true;
3831 }
3832
3833 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3834
3835 return false;
3836}
3837
Rafael Espindola761cb062012-06-03 23:57:14 +00003838bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3839 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003840 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003841
3842 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003843 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003844 assert(getLexer().is(AsmToken::EndOfStatement));
3845
Rafael Espindola761cb062012-06-03 23:57:14 +00003846 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003847 return false;
3848}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003849
Eli Friedman2128aae2012-10-22 23:58:19 +00003850bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3851 const MCExpr *Value;
3852 SMLoc ExprLoc = getLexer().getLoc();
3853 if (ParseExpression(Value))
3854 return true;
3855 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3856 if (!MCE)
3857 return Error(ExprLoc, "unexpected expression in _emit");
3858 uint64_t IntValue = MCE->getValue();
3859 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3860 return Error(ExprLoc, "literal value out of range for directive");
3861
3862 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3863 return false;
3864}
3865
Chad Rosierb1f8c132012-10-18 15:49:34 +00003866bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3867 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003868 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003869 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003870 SmallVectorImpl<std::string> &Clobbers,
3871 const MCInstrInfo *MII,
3872 const MCInstPrinter *IP,
3873 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003874 SmallVector<void *, 4> InputDecls;
3875 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003876 SmallVector<bool, 4> InputDeclsAddressOf;
3877 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003878 SmallVector<std::string, 4> InputConstraints;
3879 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003880 std::set<std::string> ClobberRegs;
3881
Chad Rosier4e472d22012-10-20 01:02:45 +00003882 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003883
3884 // Prime the lexer.
3885 Lex();
3886
3887 // While we have input, parse each statement.
3888 unsigned InputIdx = 0;
3889 unsigned OutputIdx = 0;
3890 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003891 ParseStatementInfo Info(&AsmStrRewrites);
3892 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003893 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003894
Chad Rosier57498012012-12-12 22:45:52 +00003895 if (Info.ParseError)
3896 return true;
3897
Eli Friedman2128aae2012-10-22 23:58:19 +00003898 if (Info.Opcode != ~0U) {
3899 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003900
3901 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003902 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3903 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003904
3905 // Immediate.
3906 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003907 if (Operand->needAsmRewrite())
3908 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3909 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003910 continue;
3911 }
3912
3913 // Register operand.
Chad Rosierc1ec2072013-01-10 22:10:27 +00003914 if (Operand->isReg() && !Operand->needAddressOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003915 unsigned NumDefs = Desc.getNumDefs();
3916 // Clobber.
3917 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3918 std::string Reg;
3919 raw_string_ostream OS(Reg);
3920 IP->printRegName(OS, Operand->getReg());
3921 ClobberRegs.insert(StringRef(OS.str()));
3922 }
3923 continue;
3924 }
3925
3926 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003927 unsigned Size;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003928 bool IsVarDecl;
Chad Rosier32989592012-10-18 20:27:15 +00003929 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
Chad Rosierc1ec2072013-01-10 22:10:27 +00003930 Size, IsVarDecl);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003931 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003932 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc1ec2072013-01-10 22:10:27 +00003933 if (Operand->isMem() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003934 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003935 Operand->getStartLoc(),
3936 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003937 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003938 if (isOutput) {
3939 std::string Constraint = "=";
3940 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003941 OutputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003942 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003943 Constraint += Operand->getConstraint().str();
3944 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003945 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003946 Operand->getStartLoc(),
3947 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003948 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003949 InputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003950 InputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003951 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003952 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003953 Operand->getStartLoc(),
3954 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003955 }
3956 }
3957 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003958 }
3959 }
3960
3961 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003962 NumOutputs = OutputDecls.size();
3963 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003964
3965 // Set the unique clobbers.
3966 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3967 E = ClobberRegs.end(); I != E; ++I)
3968 Clobbers.push_back(*I);
3969
3970 // Merge the various outputs and inputs. Output are expected first.
3971 if (NumOutputs || NumInputs) {
3972 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003973 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003974 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003975 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00003976 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00003977 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003978 }
3979 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00003980 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00003981 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003982 }
3983 }
3984
3985 // Build the IR assembly string.
3986 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00003987 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003988 raw_string_ostream OS(AsmStringIR);
3989 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00003990 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00003991 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
3992 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00003993
Chad Rosier4e472d22012-10-20 01:02:45 +00003994 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00003995
3996 // Emit everything up to the immediate/expression. If the previous rewrite
3997 // was a size directive, then this has already been done.
3998 if (PrevKind != AOK_SizeDirective)
3999 OS << StringRef(Start, Loc - Start);
4000 PrevKind = Kind;
4001
Chad Rosier5a719fc2012-10-23 17:43:43 +00004002 // Skip the original expression.
4003 if (Kind == AOK_Skip) {
4004 Start = Loc + (*I).Len;
4005 continue;
4006 }
4007
Chad Rosierb1f8c132012-10-18 15:49:34 +00004008 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004009 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004010 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004011 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00004012 OS << Twine("$$");
4013 OS << (*I).Val;
4014 break;
4015 case AOK_ImmPrefix:
4016 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00004017 break;
4018 case AOK_Input:
4019 OS << '$';
4020 OS << InputIdx++;
4021 break;
4022 case AOK_Output:
4023 OS << '$';
4024 OS << OutputIdx++;
4025 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004026 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00004027 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004028 default: break;
4029 case 8: OS << "byte ptr "; break;
4030 case 16: OS << "word ptr "; break;
4031 case 32: OS << "dword ptr "; break;
4032 case 64: OS << "qword ptr "; break;
4033 case 80: OS << "xword ptr "; break;
4034 case 128: OS << "xmmword ptr "; break;
4035 case 256: OS << "ymmword ptr "; break;
4036 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004037 break;
4038 case AOK_Emit:
4039 OS << ".byte";
4040 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00004041 case AOK_DotOperator:
4042 OS << (*I).Val;
4043 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004044 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004045
Chad Rosierb1f8c132012-10-18 15:49:34 +00004046 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004047 if (Kind != AOK_SizeDirective)
4048 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004049 }
4050
4051 // Emit the remainder of the asm string.
4052 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4053 if (Start != AsmEnd)
4054 OS << StringRef(Start, AsmEnd - Start);
4055
4056 AsmString = OS.str();
4057 return false;
4058}
4059
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004060/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004061MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004062 MCContext &C, MCStreamer &Out,
4063 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004064 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004065}