blob: 7d4b4d887ddf17c718ddde0112c99290f8c3958e [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
Eli Benderskyf9f40bd2013-01-16 18:56:50 +000053/// \brief Helper types for tracking macro definitions.
54typedef std::vector<AsmToken> MCAsmMacroArgument;
55typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
56typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
57typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
58
59struct MCAsmMacro {
60 StringRef Name;
61 StringRef Body;
62 MCAsmMacroParameters Parameters;
63
64public:
65 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
66 Name(N), Body(B), Parameters(P) {}
67
68 MCAsmMacro(const MCAsmMacro& Other)
69 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
70};
71
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000072/// \brief Helper class for storing information about an active macro
73/// instantiation.
74struct MacroInstantiation {
75 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000076 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000077
78 /// The macro instantiation with substitutions.
79 MemoryBuffer *Instantiation;
80
81 /// The location of the instantiation.
82 SMLoc InstantiationLoc;
83
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000084 /// The buffer where parsing should resume upon instantiation completion.
85 int ExitBuffer;
86
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000087 /// The location where parsing should resume upon instantiation completion.
88 SMLoc ExitLoc;
89
90public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000091 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000092 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000093};
94
Eli Friedman2128aae2012-10-22 23:58:19 +000095struct ParseStatementInfo {
96 /// ParsedOperands - The parsed operands from the last parsed statement.
97 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
98
99 /// Opcode - The opcode from the last parsed instruction.
100 unsigned Opcode;
101
Chad Rosier57498012012-12-12 22:45:52 +0000102 /// Error - Was there an error parsing the inline assembly?
103 bool ParseError;
104
Eli Friedman2128aae2012-10-22 23:58:19 +0000105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
106
Chad Rosier57498012012-12-12 22:45:52 +0000107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000110
111 ~ParseStatementInfo() {
112 // Free any parsed operands.
113 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
114 delete ParsedOperands[i];
115 ParsedOperands.clear();
116 }
117};
118
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000119/// \brief The concrete assembly parser instance.
120class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000123private:
124 AsmLexer Lexer;
125 MCContext &Ctx;
126 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000127 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000128 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000131 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000132
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000133 /// This is the current buffer index we're lexing from as managed by the
134 /// SourceMgr object.
135 int CurBuffer;
136
137 AsmCond TheCondState;
138 std::vector<AsmCond> TheCondStack;
139
Eli Bendersky6ee13082013-01-15 22:59:42 +0000140 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
141 /// extensions. Extensions register themselves in this map by calling
142 /// AddDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000143 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000144
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000145 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000146 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000147
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000148 /// ActiveMacros - Stack of active macro instantiations.
149 std::vector<MacroInstantiation*> ActiveMacros;
150
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000151 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000152 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000153
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
156
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
160 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000161 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000162
Devang Patel0db58bf2012-01-31 18:14:05 +0000163 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
164 unsigned AssemblerDialect;
165
Preston Gurd7b6f2032012-09-19 20:36:12 +0000166 /// IsDarwin - is Darwin compatibility enabled?
167 bool IsDarwin;
168
Chad Rosier8f138d12012-10-15 17:19:13 +0000169 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000170 bool ParsingInlineAsm;
171
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000172public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000173 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000174 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000175 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000176
177 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
178
Eli Bendersky171192f2013-01-16 00:50:52 +0000179 virtual void AddDirectiveHandler(StringRef Directive,
180 ExtensionDirectiveHandler Handler) {
181 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000182 }
183
184public:
185 /// @name MCAsmParser Interface
186 /// {
187
188 virtual SourceMgr &getSourceManager() { return SrcMgr; }
189 virtual MCAsmLexer &getLexer() { return Lexer; }
190 virtual MCContext &getContext() { return Ctx; }
191 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000192 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000193 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000194 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000195 else
196 return AssemblerDialect;
197 }
198 virtual void setAssemblerDialect(unsigned i) {
199 AssemblerDialect = i;
200 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000201
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000202 virtual bool Warning(SMLoc L, const Twine &Msg,
203 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
204 virtual bool Error(SMLoc L, const Twine &Msg,
205 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000206
Craig Topper345d16d2012-08-29 05:48:09 +0000207 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000208
Chad Rosier84125ca2012-10-13 00:26:04 +0000209 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000210 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000211
212 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
213 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000214 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000215 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000216 SmallVectorImpl<std::string> &Clobbers,
217 const MCInstrInfo *MII,
218 const MCInstPrinter *IP,
219 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000220
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000221 bool ParseExpression(const MCExpr *&Res);
222 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
223 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
224 virtual bool ParseAbsoluteExpression(int64_t &Res);
225
Eli Benderskybf706b32013-01-12 00:05:00 +0000226 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
227 /// and set \p Res to the identifier contents.
228 virtual bool ParseIdentifier(StringRef &Res);
Eli Benderskyb2f0b592013-01-12 00:23:24 +0000229 virtual void EatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000230
Eli Bendersky318cad32013-01-14 19:15:01 +0000231 virtual void CheckForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000232 /// }
233
234private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000235
Eli Friedman2128aae2012-10-22 23:58:19 +0000236 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000237 void EatToEndOfLine();
238 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000239
Rafael Espindola761cb062012-06-03 23:57:14 +0000240 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000241 const MCAsmMacroParameters &Parameters,
242 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000243 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000244
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000245 /// \brief Are macros enabled in the parser?
246 bool MacrosEnabled() {return MacrosEnabledFlag;}
247
248 /// \brief Control a flag in the parser that enables or disables macros.
249 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
250
251 /// \brief Lookup a previously defined macro.
252 /// \param Name Macro name.
253 /// \returns Pointer to macro. NULL if no such macro was defined.
254 const MCAsmMacro* LookupMacro(StringRef Name);
255
256 /// \brief Define a new macro with the given name and information.
257 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
258
259 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
260 void UndefineMacro(StringRef Name);
261
262 /// \brief Are we inside a macro instantiation?
263 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
264
265 /// \brief Handle entry to macro instantiation.
266 ///
267 /// \param M The macro.
268 /// \param NameLoc Instantiation location.
269 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
270
271 /// \brief Handle exit from macro instantiation.
272 void HandleMacroExit();
273
274 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
275 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
276 /// correct delimiter by the method.
277 bool ParseMacroArgument(MCAsmMacroArgument &MA,
278 AsmToken::TokenKind &ArgumentDelimiter);
279
280 /// \brief Parse all macro arguments for a given macro.
281 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
282
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000283 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000284 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000285 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
286 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000287 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000288 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000289
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000290 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
291 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000292 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
293 /// This returns true on failure.
294 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000295
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000296 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000297 /// current token is not set; clients should ensure Lex() is called
298 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000299 ///
300 /// \param InBuffer If not -1, should be the known buffer id that contains the
301 /// location.
302 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000303
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000304 /// \brief Parse up to the end of statement and a return the contents from the
305 /// current token until the end of the statement; the current token on exit
306 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000307 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000308
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000309 /// \brief Parse until the end of a statement or a comma is encountered,
310 /// return the contents from the current token up to the end or comma.
311 StringRef ParseStringToComma();
312
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000313 bool ParseAssignment(StringRef Name, bool allow_redef,
314 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000315
316 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
317 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
318 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000319 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000320
Eli Bendersky6ee13082013-01-15 22:59:42 +0000321 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000322
Eli Bendersky6ee13082013-01-15 22:59:42 +0000323 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000324 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000325 DK_NO_DIRECTIVE, // Placeholder
326 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
327 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
328 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000329 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000330 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
331 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
332 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
333 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
334 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
335 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
336 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000337 DK_ELSEIF, DK_ELSE, DK_ENDIF,
338 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
339 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
340 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
341 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
342 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
343 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
344 DK_CFI_REGISTER,
345 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
346 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000347 };
348
Eli Bendersky6ee13082013-01-15 22:59:42 +0000349 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
350 /// directives parsed by this class.
351 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000352
353 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000354 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000355 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000356 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000357 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000358 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000359 // ".set", ".equ", ".equiv"
360 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000361 bool ParseDirectiveOrg(); // ".org"
362 // ".align{,32}", ".p2align{,w,l}"
363 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
364
Eli Bendersky6ee13082013-01-15 22:59:42 +0000365 // ".file", ".line", ".loc", ".stabs"
366 bool ParseDirectiveFile(SMLoc DirectiveLoc);
367 bool ParseDirectiveLine();
368 bool ParseDirectiveLoc();
369 bool ParseDirectiveStabs();
370
371 // .cfi directives
372 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
373 bool ParseDirectiveCFISections();
374 bool ParseDirectiveCFIStartProc();
375 bool ParseDirectiveCFIEndProc();
376 bool ParseDirectiveCFIDefCfaOffset();
377 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
378 bool ParseDirectiveCFIAdjustCfaOffset();
379 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
380 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
381 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
383 bool ParseDirectiveCFIRememberState();
384 bool ParseDirectiveCFIRestoreState();
385 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
386 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
387 bool ParseDirectiveCFIEscape();
388 bool ParseDirectiveCFISignalFrame();
389 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
390
391 // macro directives
392 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
393 bool ParseDirectiveEndMacro(StringRef Directive);
394 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
395 bool ParseDirectiveMacrosOnOff(StringRef Directive);
396
Eli Bendersky4766ef42012-12-20 19:05:53 +0000397 // ".bundle_align_mode"
398 bool ParseDirectiveBundleAlignMode();
399 // ".bundle_lock"
400 bool ParseDirectiveBundleLock();
401 // ".bundle_unlock"
402 bool ParseDirectiveBundleUnlock();
403
Eli Bendersky6ee13082013-01-15 22:59:42 +0000404 // ".space", ".skip"
405 bool ParseDirectiveSpace(StringRef IDVal);
406
407 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
408 bool ParseDirectiveLEB128(bool Signed);
409
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000410 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
411 /// accepts a single symbol (which should be a label or an external).
412 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000413
414 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
415
416 bool ParseDirectiveAbort(); // ".abort"
417 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000418 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000419
420 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000421 // ".ifb" or ".ifnb", depending on ExpectBlank.
422 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000423 // ".ifc" or ".ifnc", depending on ExpectEqual.
424 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000425 // ".ifdef" or ".ifndef", depending on expect_defined
426 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000427 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
428 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
429 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Daniel Dunbarbfdcc702013-01-18 01:25:33 +0000430 virtual bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000431
432 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
433 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000434
Rafael Espindola761cb062012-06-03 23:57:14 +0000435 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000436 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
437 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000438 raw_svector_ostream &OS);
439 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000440 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000441 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000442 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000443
Eli Friedman2128aae2012-10-22 23:58:19 +0000444 // "_emit"
445 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000446
Eli Bendersky6ee13082013-01-15 22:59:42 +0000447 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000448};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000449}
450
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000451namespace llvm {
452
453extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000454extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000455extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000456
457}
458
Chris Lattneraaec2052010-01-19 19:46:13 +0000459enum { DEFAULT_ADDRSPACE = 0 };
460
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000461AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000462 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000463 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000464 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000465 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000466 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000467 // Save the old handler.
468 SavedDiagHandler = SrcMgr.getDiagHandler();
469 SavedDiagContext = SrcMgr.getDiagContext();
470 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000471 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000472 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000473
Daniel Dunbare4749702010-07-12 18:12:02 +0000474 // Initialize the platform / file format parser.
475 //
476 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
477 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000478 if (_MAI.hasMicrosoftFastStdCallMangling()) {
479 PlatformParser = createCOFFAsmParser();
480 PlatformParser->Initialize(*this);
481 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000482 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000483 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000484 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000485 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000486 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000487 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000488 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000489
Eli Bendersky6ee13082013-01-15 22:59:42 +0000490 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000491}
492
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000493AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000494 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
495
496 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000497 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000498 ie = MacroMap.end(); it != ie; ++it)
499 delete it->getValue();
500
Daniel Dunbare4749702010-07-12 18:12:02 +0000501 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000502}
503
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000504void AsmParser::PrintMacroInstantiations() {
505 // Print the active macro instantiation stack.
506 for (std::vector<MacroInstantiation*>::const_reverse_iterator
507 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000508 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
509 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000510}
511
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000512bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000513 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000514 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000515 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000516 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000517 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000518}
519
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000520bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000521 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000522 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000523 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000524 return true;
525}
526
Sean Callananfd0b0282010-01-21 00:19:58 +0000527bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000528 std::string IncludedFile;
529 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000530 if (NewBuf == -1)
531 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000532
Sean Callananfd0b0282010-01-21 00:19:58 +0000533 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000534
Sean Callananfd0b0282010-01-21 00:19:58 +0000535 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000536
Sean Callananfd0b0282010-01-21 00:19:58 +0000537 return false;
538}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000539
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000540/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000541/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000542/// returns true on failure.
543bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
544 std::string IncludedFile;
545 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
546 if (NewBuf == -1)
547 return true;
548
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000549 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000550 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
551 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000552 return false;
553}
554
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000555void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
556 if (InBuffer != -1) {
557 CurBuffer = InBuffer;
558 } else {
559 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
560 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000561 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
562}
563
Sean Callananfd0b0282010-01-21 00:19:58 +0000564const AsmToken &AsmParser::Lex() {
565 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000566
Sean Callananfd0b0282010-01-21 00:19:58 +0000567 if (tok->is(AsmToken::Eof)) {
568 // If this is the end of an included file, pop the parent file off the
569 // include stack.
570 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
571 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000572 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000573 tok = &Lexer.Lex();
574 }
575 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000576
Sean Callananfd0b0282010-01-21 00:19:58 +0000577 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000578 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000579
Sean Callananfd0b0282010-01-21 00:19:58 +0000580 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000581}
582
Chris Lattner79180e22010-04-05 23:15:42 +0000583bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000584 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000585 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000586 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000587
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000588 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000589 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000590
591 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000592 AsmCond StartingCondState = TheCondState;
593
Kevin Enderby613b7572011-11-01 22:27:22 +0000594 // If we are generating dwarf for assembly source files save the initial text
595 // section and generate a .file directive.
596 if (getContext().getGenDwarfForAssembly()) {
597 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000598 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
599 getStreamer().EmitLabel(SectionStartSym);
600 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000601 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000602 StringRef(),
603 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000604 }
605
Chris Lattnerb717fb02009-07-02 21:53:43 +0000606 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000607 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000608 ParseStatementInfo Info;
609 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000610
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000611 // We had an error, validate that one was emitted and recover by skipping to
612 // the next line.
613 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000614 EatToEndOfStatement();
615 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000616
617 if (TheCondState.TheCond != StartingCondState.TheCond ||
618 TheCondState.Ignore != StartingCondState.Ignore)
619 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000620
621 // Check to see there are no empty DwarfFile slots.
622 const std::vector<MCDwarfFile *> &MCDwarfFiles =
623 getContext().getMCDwarfFiles();
624 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000625 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000626 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000627 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000628
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000629 // Check to see that all assembler local symbols were actually defined.
630 // Targets that don't do subsections via symbols may not want this, though,
631 // so conservatively exclude them. Only do this if we're finalizing, though,
632 // as otherwise we won't necessarilly have seen everything yet.
633 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
634 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
635 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
636 e = Symbols.end();
637 i != e; ++i) {
638 MCSymbol *Sym = i->getValue();
639 // Variable symbols may not be marked as defined, so check those
640 // explicitly. If we know it's a variable, we have a definition for
641 // the purposes of this check.
642 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
643 // FIXME: We would really like to refer back to where the symbol was
644 // first referenced for a source location. We need to add something
645 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000646 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
647 "assembler local symbol '" + Sym->getName() +
648 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000649 }
650 }
651
652
Chris Lattner79180e22010-04-05 23:15:42 +0000653 // Finalize the output stream if there are no errors and if the client wants
654 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000655 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000656 Out.Finish();
657
Chris Lattnerb717fb02009-07-02 21:53:43 +0000658 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000659}
660
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000661void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000662 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000663 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000664 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000665 }
666}
667
Chris Lattner2cf5f142009-06-22 01:29:09 +0000668/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
669void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000670 while (Lexer.isNot(AsmToken::EndOfStatement) &&
671 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000672 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000673
Chris Lattner2cf5f142009-06-22 01:29:09 +0000674 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000675 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000676 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000677}
678
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000679StringRef AsmParser::ParseStringToEndOfStatement() {
680 const char *Start = getTok().getLoc().getPointer();
681
682 while (Lexer.isNot(AsmToken::EndOfStatement) &&
683 Lexer.isNot(AsmToken::Eof))
684 Lex();
685
686 const char *End = getTok().getLoc().getPointer();
687 return StringRef(Start, End - Start);
688}
Chris Lattnerc4193832009-06-22 05:51:26 +0000689
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000690StringRef AsmParser::ParseStringToComma() {
691 const char *Start = getTok().getLoc().getPointer();
692
693 while (Lexer.isNot(AsmToken::EndOfStatement) &&
694 Lexer.isNot(AsmToken::Comma) &&
695 Lexer.isNot(AsmToken::Eof))
696 Lex();
697
698 const char *End = getTok().getLoc().getPointer();
699 return StringRef(Start, End - Start);
700}
701
Chris Lattner74ec1a32009-06-22 06:32:03 +0000702/// ParseParenExpr - Parse a paren expression and return it.
703/// NOTE: This assumes the leading '(' has already been consumed.
704///
705/// parenexpr ::= expr)
706///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000707bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000708 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000709 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000710 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000711 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000712 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000713 return false;
714}
Chris Lattnerc4193832009-06-22 05:51:26 +0000715
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000716/// ParseBracketExpr - Parse a bracket expression and return it.
717/// NOTE: This assumes the leading '[' has already been consumed.
718///
719/// bracketexpr ::= expr]
720///
721bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
722 if (ParseExpression(Res)) return true;
723 if (Lexer.isNot(AsmToken::RBrac))
724 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000725 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000726 Lex();
727 return false;
728}
729
Chris Lattner74ec1a32009-06-22 06:32:03 +0000730/// ParsePrimaryExpr - Parse a primary expression and return it.
731/// primaryexpr ::= (parenexpr
732/// primaryexpr ::= symbol
733/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000734/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000735/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000736bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000737 switch (Lexer.getKind()) {
738 default:
739 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000740 // If we have an error assume that we've already handled it.
741 case AsmToken::Error:
742 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000743 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000744 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000745 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000746 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000747 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000748 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000749 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000750 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000751 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000752 StringRef Identifier;
753 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000754 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000755
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000756 EndLoc = SMLoc::getFromPointer(Identifier.end());
757
Daniel Dunbarfffff912009-10-16 01:34:54 +0000758 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000759 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000760 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000761
762 // Lookup the symbol variant if used.
763 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000764 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000765 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000766 if (Variant == MCSymbolRefExpr::VK_Invalid) {
767 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000768 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000769 }
770 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000771
Daniel Dunbarfffff912009-10-16 01:34:54 +0000772 // If this is an absolute variable reference, substitute it now to preserve
773 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000774 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000775 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000776 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000777
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000778 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000779 return false;
780 }
781
782 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000783 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000784 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000785 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000786 case AsmToken::Integer: {
787 SMLoc Loc = getTok().getLoc();
788 int64_t IntVal = getTok().getIntVal();
789 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000790 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000791 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000792 // Look for 'b' or 'f' following an Integer as a directional label
793 if (Lexer.getKind() == AsmToken::Identifier) {
794 StringRef IDVal = getTok().getString();
795 if (IDVal == "f" || IDVal == "b"){
796 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
797 IDVal == "f" ? 1 : 0);
798 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
799 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000800 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000801 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000802 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000803 Lex(); // Eat identifier.
804 }
805 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000806 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000807 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000808 case AsmToken::Real: {
809 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000810 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000811 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000812 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000813 Lex(); // Eat token.
814 return false;
815 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000816 case AsmToken::Dot: {
817 // This is a '.' reference, which references the current PC. Emit a
818 // temporary label to the streamer and refer to it.
819 MCSymbol *Sym = Ctx.CreateTempSymbol();
820 Out.EmitLabel(Sym);
821 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000822 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000823 Lex(); // Eat identifier.
824 return false;
825 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000826 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000827 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000828 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000829 case AsmToken::LBrac:
830 if (!PlatformParser->HasBracketExpressions())
831 return TokError("brackets expression not supported on this target");
832 Lex(); // Eat the '['.
833 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000834 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000835 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000836 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000837 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000838 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000839 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000840 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000841 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000842 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000843 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000844 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000845 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000846 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000847 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000848 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000849 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000850 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000851 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000852 }
853}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000854
Chris Lattnerb4307b32010-01-15 19:28:38 +0000855bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000856 SMLoc EndLoc;
857 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000858}
859
Daniel Dunbarcceba832010-09-17 02:47:07 +0000860const MCExpr *
861AsmParser::ApplyModifierToExpr(const MCExpr *E,
862 MCSymbolRefExpr::VariantKind Variant) {
863 // Recurse over the given expression, rebuilding it to apply the given variant
864 // if there is exactly one symbol.
865 switch (E->getKind()) {
866 case MCExpr::Target:
867 case MCExpr::Constant:
868 return 0;
869
870 case MCExpr::SymbolRef: {
871 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
872
873 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
874 TokError("invalid variant on expression '" +
875 getTok().getIdentifier() + "' (already modified)");
876 return E;
877 }
878
879 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
880 }
881
882 case MCExpr::Unary: {
883 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
884 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
885 if (!Sub)
886 return 0;
887 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
888 }
889
890 case MCExpr::Binary: {
891 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
892 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
893 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
894
895 if (!LHS && !RHS)
896 return 0;
897
898 if (!LHS) LHS = BE->getLHS();
899 if (!RHS) RHS = BE->getRHS();
900
901 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
902 }
903 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000904
Craig Topper85814382012-02-07 05:05:23 +0000905 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000906}
907
Chris Lattner74ec1a32009-06-22 06:32:03 +0000908/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000909///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000910/// expr ::= expr &&,|| expr -> lowest.
911/// expr ::= expr |,^,&,! expr
912/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
913/// expr ::= expr <<,>> expr
914/// expr ::= expr +,- expr
915/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000916/// expr ::= primaryexpr
917///
Chris Lattner54482b42010-01-15 19:39:23 +0000918bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000919 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000920 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000921 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
922 return true;
923
Daniel Dunbarcceba832010-09-17 02:47:07 +0000924 // As a special case, we support 'a op b @ modifier' by rewriting the
925 // expression to include the modifier. This is inefficient, but in general we
926 // expect users to use 'a@modifier op b'.
927 if (Lexer.getKind() == AsmToken::At) {
928 Lex();
929
930 if (Lexer.isNot(AsmToken::Identifier))
931 return TokError("unexpected symbol modifier following '@'");
932
933 MCSymbolRefExpr::VariantKind Variant =
934 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
935 if (Variant == MCSymbolRefExpr::VK_Invalid)
936 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
937
938 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
939 if (!ModifiedRes) {
940 return TokError("invalid modifier '" + getTok().getIdentifier() +
941 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000942 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000943
Daniel Dunbarcceba832010-09-17 02:47:07 +0000944 Res = ModifiedRes;
945 Lex();
946 }
947
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000948 // Try to constant fold it up front, if possible.
949 int64_t Value;
950 if (Res->EvaluateAsAbsolute(Value))
951 Res = MCConstantExpr::Create(Value, getContext());
952
953 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000954}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000955
Chris Lattnerb4307b32010-01-15 19:28:38 +0000956bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000957 Res = 0;
958 return ParseParenExpr(Res, EndLoc) ||
959 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000960}
961
Daniel Dunbar475839e2009-06-29 20:37:27 +0000962bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000963 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000964
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000965 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000966 if (ParseExpression(Expr))
967 return true;
968
Daniel Dunbare00b0112009-10-16 01:57:52 +0000969 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000970 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000971
972 return false;
973}
974
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000975static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000976 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000977 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000978 default:
979 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000980
Jim Grosbachfbe16812011-08-20 16:24:13 +0000981 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000982 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000983 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000984 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000985 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000986 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000987 return 1;
988
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000989
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000990 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000991 //
992 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000993 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000994 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000995 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000996 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000997 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000998 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000999 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001000 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001001 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001002
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001003 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001004 case AsmToken::EqualEqual:
1005 Kind = MCBinaryExpr::EQ;
1006 return 3;
1007 case AsmToken::ExclaimEqual:
1008 case AsmToken::LessGreater:
1009 Kind = MCBinaryExpr::NE;
1010 return 3;
1011 case AsmToken::Less:
1012 Kind = MCBinaryExpr::LT;
1013 return 3;
1014 case AsmToken::LessEqual:
1015 Kind = MCBinaryExpr::LTE;
1016 return 3;
1017 case AsmToken::Greater:
1018 Kind = MCBinaryExpr::GT;
1019 return 3;
1020 case AsmToken::GreaterEqual:
1021 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001022 return 3;
1023
Jim Grosbachfbe16812011-08-20 16:24:13 +00001024 // Intermediate Precedence: <<, >>
1025 case AsmToken::LessLess:
1026 Kind = MCBinaryExpr::Shl;
1027 return 4;
1028 case AsmToken::GreaterGreater:
1029 Kind = MCBinaryExpr::Shr;
1030 return 4;
1031
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001032 // High Intermediate Precedence: +, -
1033 case AsmToken::Plus:
1034 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001035 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001036 case AsmToken::Minus:
1037 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001038 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001039
Jim Grosbachfbe16812011-08-20 16:24:13 +00001040 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001041 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001042 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001043 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001044 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001045 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001046 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001047 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001048 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001049 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001050 }
1051}
1052
1053
1054/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1055/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001056bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1057 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001058 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001059 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001060 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001061
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001062 // If the next token is lower precedence than we are allowed to eat, return
1063 // successfully with what we ate already.
1064 if (TokPrec < Precedence)
1065 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001066
Sean Callanan79ed1a82010-01-19 20:22:31 +00001067 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001068
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001069 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001070 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001071 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001072
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001073 // If BinOp binds less tightly with RHS than the operator after RHS, let
1074 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001075 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001076 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001077 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001078 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001079 }
1080
Daniel Dunbar475839e2009-06-29 20:37:27 +00001081 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001082 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001083 }
1084}
1085
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001086/// ParseStatement:
1087/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001088/// ::= Label* Directive ...Operands... EndOfStatement
1089/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001090bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001091 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001092 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001093 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001094 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001095 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001096
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001097 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001098 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001099 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001100 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001101 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001102 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001103 if (Lexer.is(AsmToken::Hash))
1104 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001105
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001106 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001107 if (Lexer.is(AsmToken::Integer)) {
1108 LocalLabelVal = getTok().getIntVal();
1109 if (LocalLabelVal < 0) {
1110 if (!TheCondState.Ignore)
1111 return TokError("unexpected token at start of statement");
1112 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001113 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001114 IDVal = getTok().getString();
1115 Lex(); // Consume the integer token to be used as an identifier token.
1116 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001117 if (!TheCondState.Ignore)
1118 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001119 }
1120 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001121 } else if (Lexer.is(AsmToken::Dot)) {
1122 // Treat '.' as a valid identifier in this context.
1123 Lex();
1124 IDVal = ".";
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001125 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001126 if (!TheCondState.Ignore)
1127 return TokError("unexpected token at start of statement");
1128 IDVal = "";
1129 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001130
Chris Lattner7834fac2010-04-17 18:14:27 +00001131 // Handle conditional assembly here before checking for skipping. We
1132 // have to do this so that .endif isn't skipped in a ".if 0" block for
1133 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001134 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001135 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001136 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001137 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1138 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001139 switch (DirKind) {
1140 default:
1141 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001142 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001143 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001144 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001145 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001146 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001147 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001148 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001149 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001150 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001151 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001152 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001153 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001154 case DK_IFNDEF:
1155 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001156 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001157 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001158 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001159 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001160 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001161 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001162 return ParseDirectiveEndIf(IDLoc);
1163 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001164
Eli Benderskyed5df012013-01-16 19:32:36 +00001165 // Ignore the statement if in the middle of inactive conditional
1166 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001167 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001168 EatToEndOfStatement();
1169 return false;
1170 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001171
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001172 // FIXME: Recurse on local labels?
1173
1174 // See what kind of statement we have.
1175 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001176 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001177 CheckForValidSection();
1178
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001179 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001180 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001181
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001182 // Diagnose attempt to use '.' as a label.
1183 if (IDVal == ".")
1184 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1185
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001186 // Diagnose attempt to use a variable as a label.
1187 //
1188 // FIXME: Diagnostics. Note the location of the definition as a label.
1189 // FIXME: This doesn't diagnose assignment to a symbol which has been
1190 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001191 MCSymbol *Sym;
1192 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001193 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001194 else
1195 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001196 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001197 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001198
Daniel Dunbar959fd882009-08-26 22:13:22 +00001199 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001200 if (!ParsingInlineAsm)
1201 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001202
Kevin Enderby94c2e852011-12-09 18:09:40 +00001203 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001204 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001205 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001206 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1207 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001208
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001209 // Consume any end of statement token, if present, to avoid spurious
1210 // AddBlankLine calls().
1211 if (Lexer.is(AsmToken::EndOfStatement)) {
1212 Lex();
1213 if (Lexer.is(AsmToken::Eof))
1214 return false;
1215 }
1216
Eli Friedman2128aae2012-10-22 23:58:19 +00001217 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001218 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001219
Daniel Dunbar3f872332009-07-28 16:08:33 +00001220 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001221 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001222 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001223
Nico Weber4c4c7322011-01-28 03:04:41 +00001224 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001225
1226 default: // Normal instruction or directive.
1227 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001228 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001229
1230 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001231 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001232 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1233 return HandleMacroEntry(M, IDLoc);
1234 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001235
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001236 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001237
1238 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001239 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001240 // There are several entities interested in parsing directives:
1241 //
1242 // 1. The target-specific assembly parser. Some directives are target
1243 // specific or may potentially behave differently on certain targets.
1244 // 2. Asm parser extensions. For example, platform-specific parsers
1245 // (like the ELF parser) register themselves as extensions.
1246 // 3. The generic directive parser implemented by this class. These are
1247 // all the directives that behave in a target and platform independent
1248 // manner, or at least have a default behavior that's shared between
1249 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001250
Eli Bendersky6ee13082013-01-15 22:59:42 +00001251 // First query the target-specific parser. It will return 'true' if it
1252 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001253 if (!getTargetParser().ParseDirective(ID))
1254 return false;
1255
Eli Bendersky6ee13082013-01-15 22:59:42 +00001256 // Next, check the extention directive map to see if any extension has
1257 // registered itself to parse this directive.
1258 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1259 ExtensionDirectiveMap.lookup(IDVal);
1260 if (Handler.first)
1261 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1262
1263 // Finally, if no one else is interested in this directive, it must be
1264 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001265 switch (DirKind) {
1266 default:
1267 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001268 case DK_SET:
1269 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001270 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001271 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001272 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001273 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001274 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001275 case DK_ASCIZ:
1276 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001277 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001278 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001279 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001280 case DK_SHORT:
1281 case DK_VALUE:
1282 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001283 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001284 case DK_LONG:
1285 case DK_INT:
1286 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001287 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001288 case DK_QUAD:
1289 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001290 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001291 case DK_SINGLE:
1292 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001293 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001294 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001295 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001296 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001297 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1298 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1299 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001300 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001301 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1302 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1303 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001304 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001305 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001306 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001307 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001308 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001309 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001310 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001311 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001312 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001313 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001314 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001315 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001316 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001317 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001318 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001319 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001320 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001321 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001322 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001323 EatToEndOfStatement(); // .extern is the default, ignore it.
1324 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_GLOBL:
1326 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001327 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001328 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001329 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001330 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001331 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001332 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001333 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001334 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001335 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001336 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001337 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001338 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001339 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001340 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001341 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001342 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001343 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001344 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001345 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001346 case DK_COMM:
1347 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001350 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001351 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001352 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001353 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001354 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001355 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001356 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001357 case DK_CODE16:
1358 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001359 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001360 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001361 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001362 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001363 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001364 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001365 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001366 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001367 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001368 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001369 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001370 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001371 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001372 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001373 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001374 case DK_SLEB128:
1375 return ParseDirectiveLEB128(true);
1376 case DK_ULEB128:
1377 return ParseDirectiveLEB128(false);
1378 case DK_SPACE:
1379 case DK_SKIP:
1380 return ParseDirectiveSpace(IDVal);
1381 case DK_FILE:
1382 return ParseDirectiveFile(IDLoc);
1383 case DK_LINE:
1384 return ParseDirectiveLine();
1385 case DK_LOC:
1386 return ParseDirectiveLoc();
1387 case DK_STABS:
1388 return ParseDirectiveStabs();
1389 case DK_CFI_SECTIONS:
1390 return ParseDirectiveCFISections();
1391 case DK_CFI_STARTPROC:
1392 return ParseDirectiveCFIStartProc();
1393 case DK_CFI_ENDPROC:
1394 return ParseDirectiveCFIEndProc();
1395 case DK_CFI_DEF_CFA:
1396 return ParseDirectiveCFIDefCfa(IDLoc);
1397 case DK_CFI_DEF_CFA_OFFSET:
1398 return ParseDirectiveCFIDefCfaOffset();
1399 case DK_CFI_ADJUST_CFA_OFFSET:
1400 return ParseDirectiveCFIAdjustCfaOffset();
1401 case DK_CFI_DEF_CFA_REGISTER:
1402 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1403 case DK_CFI_OFFSET:
1404 return ParseDirectiveCFIOffset(IDLoc);
1405 case DK_CFI_REL_OFFSET:
1406 return ParseDirectiveCFIRelOffset(IDLoc);
1407 case DK_CFI_PERSONALITY:
1408 return ParseDirectiveCFIPersonalityOrLsda(true);
1409 case DK_CFI_LSDA:
1410 return ParseDirectiveCFIPersonalityOrLsda(false);
1411 case DK_CFI_REMEMBER_STATE:
1412 return ParseDirectiveCFIRememberState();
1413 case DK_CFI_RESTORE_STATE:
1414 return ParseDirectiveCFIRestoreState();
1415 case DK_CFI_SAME_VALUE:
1416 return ParseDirectiveCFISameValue(IDLoc);
1417 case DK_CFI_RESTORE:
1418 return ParseDirectiveCFIRestore(IDLoc);
1419 case DK_CFI_ESCAPE:
1420 return ParseDirectiveCFIEscape();
1421 case DK_CFI_SIGNAL_FRAME:
1422 return ParseDirectiveCFISignalFrame();
1423 case DK_CFI_UNDEFINED:
1424 return ParseDirectiveCFIUndefined(IDLoc);
1425 case DK_CFI_REGISTER:
1426 return ParseDirectiveCFIRegister(IDLoc);
1427 case DK_MACROS_ON:
1428 case DK_MACROS_OFF:
1429 return ParseDirectiveMacrosOnOff(IDVal);
1430 case DK_MACRO:
1431 return ParseDirectiveMacro(IDLoc);
1432 case DK_ENDM:
1433 case DK_ENDMACRO:
1434 return ParseDirectiveEndMacro(IDVal);
1435 case DK_PURGEM:
1436 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001437 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001438
Jim Grosbach686c0182012-05-01 18:38:27 +00001439 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001440 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001441
Eli Friedman2128aae2012-10-22 23:58:19 +00001442 // _emit
1443 if (ParsingInlineAsm && IDVal == "_emit")
1444 return ParseDirectiveEmit(IDLoc, Info);
1445
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001446 CheckForValidSection();
1447
Chris Lattnera7f13542010-05-19 23:34:33 +00001448 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001449 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001450 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001451 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1452 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001453 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001454
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001455 // Dump the parsed representation, if requested.
1456 if (getShowParsedOperands()) {
1457 SmallString<256> Str;
1458 raw_svector_ostream OS(Str);
1459 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001460 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001461 if (i != 0)
1462 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001463 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001464 }
1465 OS << "]";
1466
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001467 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001468 }
1469
Kevin Enderby613b7572011-11-01 22:27:22 +00001470 // If we are generating dwarf for assembly source files and the current
1471 // section is the initial text section then generate a .loc directive for
1472 // the instruction.
1473 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001474 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001475
Eli Benderskyed5df012013-01-16 19:32:36 +00001476 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001477
Eli Benderskyed5df012013-01-16 19:32:36 +00001478 // If we previously parsed a cpp hash file line comment then make sure the
1479 // current Dwarf File is for the CppHashFilename if not then emit the
1480 // Dwarf File table for it and adjust the line number for the .loc.
1481 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1482 getContext().getMCDwarfFiles();
1483 if (CppHashFilename.size() != 0) {
1484 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001485 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001486 getStreamer().EmitDwarfFileDirective(
1487 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001488
Kevin Enderby32c1a822012-11-05 21:55:41 +00001489 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001490 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001491 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001492
Kevin Enderby613b7572011-11-01 22:27:22 +00001493 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001494 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001495 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001496 StringRef());
1497 }
1498
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001499 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001500 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001501 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001502 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1503 Info.ParsedOperands,
1504 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001505 ParsingInlineAsm);
1506 }
Chris Lattner98986712010-01-14 22:21:20 +00001507
Chris Lattnercbf8a982010-09-11 16:18:25 +00001508 // Don't skip the rest of the line, the instruction parser is responsible for
1509 // that.
1510 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001511}
Chris Lattner9a023f72009-06-24 04:43:34 +00001512
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001513/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1514/// since they may not be able to be tokenized to get to the end of line token.
1515void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001516 if (!Lexer.is(AsmToken::EndOfStatement))
1517 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001518 // Eat EOL.
1519 Lex();
1520}
1521
1522/// ParseCppHashLineFilenameComment as this:
1523/// ::= # number "filename"
1524/// or just as a full line comment if it doesn't have a number and a string.
1525bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1526 Lex(); // Eat the hash token.
1527
1528 if (getLexer().isNot(AsmToken::Integer)) {
1529 // Consume the line since in cases it is not a well-formed line directive,
1530 // as if were simply a full line comment.
1531 EatToEndOfLine();
1532 return false;
1533 }
1534
1535 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001536 Lex();
1537
1538 if (getLexer().isNot(AsmToken::String)) {
1539 EatToEndOfLine();
1540 return false;
1541 }
1542
1543 StringRef Filename = getTok().getString();
1544 // Get rid of the enclosing quotes.
1545 Filename = Filename.substr(1, Filename.size()-2);
1546
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001547 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1548 CppHashLoc = L;
1549 CppHashFilename = Filename;
1550 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001551 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001552
1553 // Ignore any trailing characters, they're just comment.
1554 EatToEndOfLine();
1555 return false;
1556}
1557
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001558/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001559/// for the Filename and LineNo if any in the diagnostic.
1560void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1561 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1562 raw_ostream &OS = errs();
1563
1564 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1565 const SMLoc &DiagLoc = Diag.getLoc();
1566 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1567 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1568
1569 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1570 // before printing the message.
1571 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001572 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001573 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1574 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1575 }
1576
Eric Christopher2318ba12012-12-18 00:30:54 +00001577 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001578 // manager changed or buffer changed (like in a nested include) then just
1579 // print the normal diagnostic using its Filename and LineNo.
1580 if (!Parser->CppHashLineNumber ||
1581 &DiagSrcMgr != &Parser->SrcMgr ||
1582 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001583 if (Parser->SavedDiagHandler)
1584 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1585 else
1586 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001587 return;
1588 }
1589
Eric Christopher2318ba12012-12-18 00:30:54 +00001590 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001591 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1592 // the diagnostic.
1593 const std::string Filename = Parser->CppHashFilename;
1594
1595 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1596 int CppHashLocLineNo =
1597 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1598 int LineNo = Parser->CppHashLineNumber - 1 +
1599 (DiagLocLineNo - CppHashLocLineNo);
1600
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001601 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1602 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001603 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001604 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001605
Benjamin Kramer04a04262011-10-16 10:48:29 +00001606 if (Parser->SavedDiagHandler)
1607 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1608 else
1609 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001610}
1611
Rafael Espindola799aacf2012-08-21 18:29:30 +00001612// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1613// difference being that that function accepts '@' as part of identifiers and
1614// we can't do that. AsmLexer.cpp should probably be changed to handle
1615// '@' as a special case when needed.
1616static bool isIdentifierChar(char c) {
1617 return isalnum(c) || c == '_' || c == '$' || c == '.';
1618}
1619
Rafael Espindola761cb062012-06-03 23:57:14 +00001620bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001621 const MCAsmMacroParameters &Parameters,
1622 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001623 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001624 unsigned NParameters = Parameters.size();
1625 if (NParameters != 0 && NParameters != A.size())
1626 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001627
Preston Gurd7b6f2032012-09-19 20:36:12 +00001628 // A macro without parameters is handled differently on Darwin:
1629 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001630 while (!Body.empty()) {
1631 // Scan for the next substitution.
1632 std::size_t End = Body.size(), Pos = 0;
1633 for (; Pos != End; ++Pos) {
1634 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001635 if (!NParameters) {
1636 // This macro has no parameters, look for $0, $1, etc.
1637 if (Body[Pos] != '$' || Pos + 1 == End)
1638 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001639
Rafael Espindola65366442011-06-05 02:43:45 +00001640 char Next = Body[Pos + 1];
1641 if (Next == '$' || Next == 'n' || isdigit(Next))
1642 break;
1643 } else {
1644 // This macro has parameters, look for \foo, \bar, etc.
1645 if (Body[Pos] == '\\' && Pos + 1 != End)
1646 break;
1647 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001648 }
1649
1650 // Add the prefix.
1651 OS << Body.slice(0, Pos);
1652
1653 // Check if we reached the end.
1654 if (Pos == End)
1655 break;
1656
Rafael Espindola65366442011-06-05 02:43:45 +00001657 if (!NParameters) {
1658 switch (Body[Pos+1]) {
1659 // $$ => $
1660 case '$':
1661 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001662 break;
1663
Rafael Espindola65366442011-06-05 02:43:45 +00001664 // $n => number of arguments
1665 case 'n':
1666 OS << A.size();
1667 break;
1668
1669 // $[0-9] => argument
1670 default: {
1671 // Missing arguments are ignored.
1672 unsigned Index = Body[Pos+1] - '0';
1673 if (Index >= A.size())
1674 break;
1675
1676 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001677 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001678 ie = A[Index].end(); it != ie; ++it)
1679 OS << it->getString();
1680 break;
1681 }
1682 }
1683 Pos += 2;
1684 } else {
1685 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001686 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001687 ++I;
1688
1689 const char *Begin = Body.data() + Pos +1;
1690 StringRef Argument(Begin, I - (Pos +1));
1691 unsigned Index = 0;
1692 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001693 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001694 break;
1695
Preston Gurd7b6f2032012-09-19 20:36:12 +00001696 if (Index == NParameters) {
1697 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1698 Pos += 3;
1699 else {
1700 OS << '\\' << Argument;
1701 Pos = I;
1702 }
1703 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001704 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001705 ie = A[Index].end(); it != ie; ++it)
1706 if (it->getKind() == AsmToken::String)
1707 OS << it->getStringContents();
1708 else
1709 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001710
Preston Gurd7b6f2032012-09-19 20:36:12 +00001711 Pos += 1 + Argument.size();
1712 }
Rafael Espindola65366442011-06-05 02:43:45 +00001713 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001714 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001715 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001716 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001717
Rafael Espindola65366442011-06-05 02:43:45 +00001718 return false;
1719}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001720
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001721MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001722 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001723 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001724 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1725 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001726{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001727}
1728
Preston Gurd7b6f2032012-09-19 20:36:12 +00001729static bool IsOperator(AsmToken::TokenKind kind)
1730{
1731 switch (kind)
1732 {
1733 default:
1734 return false;
1735 case AsmToken::Plus:
1736 case AsmToken::Minus:
1737 case AsmToken::Tilde:
1738 case AsmToken::Slash:
1739 case AsmToken::Star:
1740 case AsmToken::Dot:
1741 case AsmToken::Equal:
1742 case AsmToken::EqualEqual:
1743 case AsmToken::Pipe:
1744 case AsmToken::PipePipe:
1745 case AsmToken::Caret:
1746 case AsmToken::Amp:
1747 case AsmToken::AmpAmp:
1748 case AsmToken::Exclaim:
1749 case AsmToken::ExclaimEqual:
1750 case AsmToken::Percent:
1751 case AsmToken::Less:
1752 case AsmToken::LessEqual:
1753 case AsmToken::LessLess:
1754 case AsmToken::LessGreater:
1755 case AsmToken::Greater:
1756 case AsmToken::GreaterEqual:
1757 case AsmToken::GreaterGreater:
1758 return true;
1759 }
1760}
1761
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001762bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001763 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001764 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001765 unsigned AddTokens = 0;
1766
1767 // gas accepts arguments separated by whitespace, except on Darwin
1768 if (!IsDarwin)
1769 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001770
1771 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001772 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1773 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001774 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001775 }
1776
1777 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1778 // Spaces and commas cannot be mixed to delimit parameters
1779 if (ArgumentDelimiter == AsmToken::Eof)
1780 ArgumentDelimiter = AsmToken::Comma;
1781 else if (ArgumentDelimiter != AsmToken::Comma) {
1782 Lexer.setSkipSpace(true);
1783 return TokError("expected ' ' for macro argument separator");
1784 }
1785 break;
1786 }
1787
1788 if (Lexer.is(AsmToken::Space)) {
1789 Lex(); // Eat spaces
1790
1791 // Spaces can delimit parameters, but could also be part an expression.
1792 // If the token after a space is an operator, add the token and the next
1793 // one into this argument
1794 if (ArgumentDelimiter == AsmToken::Space ||
1795 ArgumentDelimiter == AsmToken::Eof) {
1796 if (IsOperator(Lexer.getKind())) {
1797 // Check to see whether the token is used as an operator,
1798 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001799 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001800 if (*NextChar == ' ')
1801 AddTokens = 2;
1802 }
1803
1804 if (!AddTokens && ParenLevel == 0) {
1805 if (ArgumentDelimiter == AsmToken::Eof &&
1806 !IsOperator(Lexer.getKind()))
1807 ArgumentDelimiter = AsmToken::Space;
1808 break;
1809 }
1810 }
1811 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001812
1813 // HandleMacroEntry relies on not advancing the lexer here
1814 // to be able to fill in the remaining default parameter values
1815 if (Lexer.is(AsmToken::EndOfStatement))
1816 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001817
1818 // Adjust the current parentheses level.
1819 if (Lexer.is(AsmToken::LParen))
1820 ++ParenLevel;
1821 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1822 --ParenLevel;
1823
1824 // Append the token to the current argument list.
1825 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001826 if (AddTokens)
1827 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001828 Lex();
1829 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001830
1831 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001832 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001833 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001834 return false;
1835}
1836
1837// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001838bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001839 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001840 // Argument delimiter is initially unknown. It will be set by
1841 // ParseMacroArgument()
1842 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001843
1844 // Parse two kinds of macro invocations:
1845 // - macros defined without any parameters accept an arbitrary number of them
1846 // - macros defined with parameters accept at most that many of them
1847 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1848 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001849 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001850
Preston Gurd7b6f2032012-09-19 20:36:12 +00001851 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001852 return true;
1853
Preston Gurd6c9176a2012-09-19 20:29:04 +00001854 if (!MA.empty() || !NParameters)
1855 A.push_back(MA);
1856 else if (NParameters) {
1857 if (!M->Parameters[Parameter].second.empty())
1858 A.push_back(M->Parameters[Parameter].second);
1859 }
Jim Grosbach97146442012-07-30 22:44:17 +00001860
Preston Gurd6c9176a2012-09-19 20:29:04 +00001861 // At the end of the statement, fill in remaining arguments that have
1862 // default values. If there aren't any, then the next argument is
1863 // required but missing
1864 if (Lexer.is(AsmToken::EndOfStatement)) {
1865 if (NParameters && Parameter < NParameters - 1) {
1866 if (M->Parameters[Parameter + 1].second.empty())
1867 return TokError("macro argument '" +
1868 Twine(M->Parameters[Parameter + 1].first) +
1869 "' is missing");
1870 else
1871 continue;
1872 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001873 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001874 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001875
1876 if (Lexer.is(AsmToken::Comma))
1877 Lex();
1878 }
1879 return TokError("Too many arguments");
1880}
1881
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001882const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1883 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1884 return (I == MacroMap.end()) ? NULL : I->getValue();
1885}
1886
1887void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1888 MacroMap[Name] = new MCAsmMacro(Macro);
1889}
1890
1891void AsmParser::UndefineMacro(StringRef Name) {
1892 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1893 if (I != MacroMap.end()) {
1894 delete I->getValue();
1895 MacroMap.erase(I);
1896 }
1897}
1898
1899bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001900 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1901 // this, although we should protect against infinite loops.
1902 if (ActiveMacros.size() == 20)
1903 return TokError("macros cannot be nested more than 20 levels deep");
1904
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001905 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001906 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001907 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001908
Jim Grosbach97146442012-07-30 22:44:17 +00001909 // Remove any trailing empty arguments. Do this after-the-fact as we have
1910 // to keep empty arguments in the middle of the list or positionality
1911 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001912 while (!A.empty() && A.back().empty())
1913 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001914
Rafael Espindola65366442011-06-05 02:43:45 +00001915 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1916 // to hold the macro body with substitutions.
1917 SmallString<256> Buf;
1918 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001919 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001920
Rafael Espindola8a403d32012-08-08 14:51:03 +00001921 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001922 return true;
1923
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001924 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001925 // instantiation.
1926 OS << ".endmacro\n";
1927
Rafael Espindola65366442011-06-05 02:43:45 +00001928 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001929 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001930
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001931 // Create the macro instantiation object and add to the current macro
1932 // instantiation stack.
1933 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001934 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001935 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001936 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001937 ActiveMacros.push_back(MI);
1938
1939 // Jump to the macro instantiation and prime the lexer.
1940 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1941 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1942 Lex();
1943
1944 return false;
1945}
1946
1947void AsmParser::HandleMacroExit() {
1948 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001949 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001950 Lex();
1951
1952 // Pop the instantiation entry.
1953 delete ActiveMacros.back();
1954 ActiveMacros.pop_back();
1955}
1956
Rafael Espindolae71cc862012-01-28 05:57:00 +00001957static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001958 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001959 case MCExpr::Binary: {
1960 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1961 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001962 break;
1963 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001964 case MCExpr::Target:
1965 case MCExpr::Constant:
1966 return false;
1967 case MCExpr::SymbolRef: {
1968 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001969 if (S.isVariable())
1970 return IsUsedIn(Sym, S.getVariableValue());
1971 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001972 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001973 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001974 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001975 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001976
1977 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001978}
1979
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001980bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1981 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001982 // FIXME: Use better location, we should use proper tokens.
1983 SMLoc EqualLoc = Lexer.getLoc();
1984
Daniel Dunbar821e3332009-08-31 08:09:28 +00001985 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001986 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001987 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001988
Rafael Espindolae71cc862012-01-28 05:57:00 +00001989 // Note: we don't count b as used in "a = b". This is to allow
1990 // a = b
1991 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001992
Daniel Dunbar3f872332009-07-28 16:08:33 +00001993 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001994 return TokError("unexpected token in assignment");
1995
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001996 // Error on assignment to '.'.
1997 if (Name == ".") {
1998 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
1999 "(use '.space' or '.org').)"));
2000 }
2001
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002002 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002003 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002004
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002005 // Validate that the LHS is allowed to be a variable (either it has not been
2006 // used as a symbol, or it is an absolute symbol).
2007 MCSymbol *Sym = getContext().LookupSymbol(Name);
2008 if (Sym) {
2009 // Diagnose assignment to a label.
2010 //
2011 // FIXME: Diagnostics. Note the location of the definition as a label.
2012 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002013 if (IsUsedIn(Sym, Value))
2014 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2015 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002016 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002017 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2018 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002019 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002020 return Error(EqualLoc, "redefinition of '" + Name + "'");
2021 else if (!Sym->isVariable())
2022 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002023 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002024 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2025 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002026
2027 // Don't count these checks as uses.
2028 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002029 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002030 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002031
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002032 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002033
2034 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002035 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002036 if (NoDeadStrip)
2037 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2038
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002039
2040 return false;
2041}
2042
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002043/// ParseIdentifier:
2044/// ::= identifier
2045/// ::= string
2046bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002047 // The assembler has relaxed rules for accepting identifiers, in particular we
2048 // allow things like '.globl $foo', which would normally be separate
2049 // tokens. At this level, we have already lexed so we cannot (currently)
2050 // handle this as a context dependent token, instead we detect adjacent tokens
2051 // and return the combined identifier.
2052 if (Lexer.is(AsmToken::Dollar)) {
2053 SMLoc DollarLoc = getLexer().getLoc();
2054
2055 // Consume the dollar sign, and check for a following identifier.
2056 Lex();
2057 if (Lexer.isNot(AsmToken::Identifier))
2058 return true;
2059
2060 // We have a '$' followed by an identifier, make sure they are adjacent.
2061 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2062 return true;
2063
2064 // Construct the joined identifier and consume the token.
2065 Res = StringRef(DollarLoc.getPointer(),
2066 getTok().getIdentifier().size() + 1);
2067 Lex();
2068 return false;
2069 }
2070
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002071 if (Lexer.isNot(AsmToken::Identifier) &&
2072 Lexer.isNot(AsmToken::String))
2073 return true;
2074
Sean Callanan18b83232010-01-19 21:44:56 +00002075 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002076
Sean Callanan79ed1a82010-01-19 20:22:31 +00002077 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002078
2079 return false;
2080}
2081
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002082/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002083/// ::= .equ identifier ',' expression
2084/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002085/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002086bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002087 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002088
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002089 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002090 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002091
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002092 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002093 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002094 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002095
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002096 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002097}
2098
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002099bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002100 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002101
2102 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002103 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002104 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2105 if (Str[i] != '\\') {
2106 Data += Str[i];
2107 continue;
2108 }
2109
2110 // Recognize escaped characters. Note that this escape semantics currently
2111 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2112 ++i;
2113 if (i == e)
2114 return TokError("unexpected backslash at end of string");
2115
2116 // Recognize octal sequences.
2117 if ((unsigned) (Str[i] - '0') <= 7) {
2118 // Consume up to three octal characters.
2119 unsigned Value = Str[i] - '0';
2120
2121 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2122 ++i;
2123 Value = Value * 8 + (Str[i] - '0');
2124
2125 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2126 ++i;
2127 Value = Value * 8 + (Str[i] - '0');
2128 }
2129 }
2130
2131 if (Value > 255)
2132 return TokError("invalid octal escape sequence (out of range)");
2133
2134 Data += (unsigned char) Value;
2135 continue;
2136 }
2137
2138 // Otherwise recognize individual escapes.
2139 switch (Str[i]) {
2140 default:
2141 // Just reject invalid escape sequences for now.
2142 return TokError("invalid escape sequence (unrecognized character)");
2143
2144 case 'b': Data += '\b'; break;
2145 case 'f': Data += '\f'; break;
2146 case 'n': Data += '\n'; break;
2147 case 'r': Data += '\r'; break;
2148 case 't': Data += '\t'; break;
2149 case '"': Data += '"'; break;
2150 case '\\': Data += '\\'; break;
2151 }
2152 }
2153
2154 return false;
2155}
2156
Daniel Dunbara0d14262009-06-24 23:30:00 +00002157/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002158/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2159bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002160 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002161 CheckForValidSection();
2162
Daniel Dunbara0d14262009-06-24 23:30:00 +00002163 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002164 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002165 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002166
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002167 std::string Data;
2168 if (ParseEscapedString(Data))
2169 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002170
2171 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002172 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002173 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2174
Sean Callanan79ed1a82010-01-19 20:22:31 +00002175 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002176
2177 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002178 break;
2179
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002180 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002181 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002182 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002183 }
2184 }
2185
Sean Callanan79ed1a82010-01-19 20:22:31 +00002186 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002187 return false;
2188}
2189
2190/// ParseDirectiveValue
2191/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2192bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002193 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002194 CheckForValidSection();
2195
Daniel Dunbara0d14262009-06-24 23:30:00 +00002196 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002197 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002198 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002199 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002200 return true;
2201
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002202 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002203 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2204 assert(Size <= 8 && "Invalid size");
2205 uint64_t IntValue = MCE->getValue();
2206 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2207 return Error(ExprLoc, "literal value out of range for directive");
2208 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2209 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002210 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002211
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002212 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002213 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002214
Daniel Dunbara0d14262009-06-24 23:30:00 +00002215 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002216 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002217 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002218 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002219 }
2220 }
2221
Sean Callanan79ed1a82010-01-19 20:22:31 +00002222 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002223 return false;
2224}
2225
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002226/// ParseDirectiveRealValue
2227/// ::= (.single | .double) [ expression (, expression)* ]
2228bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2229 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2230 CheckForValidSection();
2231
2232 for (;;) {
2233 // We don't truly support arithmetic on floating point expressions, so we
2234 // have to manually parse unary prefixes.
2235 bool IsNeg = false;
2236 if (getLexer().is(AsmToken::Minus)) {
2237 Lex();
2238 IsNeg = true;
2239 } else if (getLexer().is(AsmToken::Plus))
2240 Lex();
2241
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002242 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002243 getLexer().isNot(AsmToken::Real) &&
2244 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002245 return TokError("unexpected token in directive");
2246
2247 // Convert to an APFloat.
2248 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002249 StringRef IDVal = getTok().getString();
2250 if (getLexer().is(AsmToken::Identifier)) {
2251 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2252 Value = APFloat::getInf(Semantics);
2253 else if (!IDVal.compare_lower("nan"))
2254 Value = APFloat::getNaN(Semantics, false, ~0);
2255 else
2256 return TokError("invalid floating point literal");
2257 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002258 APFloat::opInvalidOp)
2259 return TokError("invalid floating point literal");
2260 if (IsNeg)
2261 Value.changeSign();
2262
2263 // Consume the numeric token.
2264 Lex();
2265
2266 // Emit the value as an integer.
2267 APInt AsInt = Value.bitcastToAPInt();
2268 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2269 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2270
2271 if (getLexer().is(AsmToken::EndOfStatement))
2272 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002273
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002274 if (getLexer().isNot(AsmToken::Comma))
2275 return TokError("unexpected token in directive");
2276 Lex();
2277 }
2278 }
2279
2280 Lex();
2281 return false;
2282}
2283
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002284/// ParseDirectiveZero
2285/// ::= .zero expression
2286bool AsmParser::ParseDirectiveZero() {
2287 CheckForValidSection();
2288
2289 int64_t NumBytes;
2290 if (ParseAbsoluteExpression(NumBytes))
2291 return true;
2292
Rafael Espindolae452b172010-10-05 19:42:57 +00002293 int64_t Val = 0;
2294 if (getLexer().is(AsmToken::Comma)) {
2295 Lex();
2296 if (ParseAbsoluteExpression(Val))
2297 return true;
2298 }
2299
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002300 if (getLexer().isNot(AsmToken::EndOfStatement))
2301 return TokError("unexpected token in '.zero' directive");
2302
2303 Lex();
2304
Rafael Espindolae452b172010-10-05 19:42:57 +00002305 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002306
2307 return false;
2308}
2309
Daniel Dunbara0d14262009-06-24 23:30:00 +00002310/// ParseDirectiveFill
2311/// ::= .fill expression , expression , expression
2312bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002313 CheckForValidSection();
2314
Daniel Dunbara0d14262009-06-24 23:30:00 +00002315 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002316 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002317 return true;
2318
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002319 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002320 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002321 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002322
Daniel Dunbara0d14262009-06-24 23:30:00 +00002323 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002324 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002325 return true;
2326
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002327 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002328 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002329 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002330
Daniel Dunbara0d14262009-06-24 23:30:00 +00002331 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002332 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002333 return true;
2334
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002335 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002336 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002337
Sean Callanan79ed1a82010-01-19 20:22:31 +00002338 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002339
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002340 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2341 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002342
2343 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002344 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002345
2346 return false;
2347}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002348
2349/// ParseDirectiveOrg
2350/// ::= .org expression [ , expression ]
2351bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002352 CheckForValidSection();
2353
Daniel Dunbar821e3332009-08-31 08:09:28 +00002354 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002355 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002356 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002357 return true;
2358
2359 // Parse optional fill expression.
2360 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002361 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2362 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002363 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002364 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002365
Daniel Dunbar475839e2009-06-29 20:37:27 +00002366 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002367 return true;
2368
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002369 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002370 return TokError("unexpected token in '.org' directive");
2371 }
2372
Sean Callanan79ed1a82010-01-19 20:22:31 +00002373 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002374
Jim Grosbachebd4c052012-01-27 00:37:08 +00002375 // Only limited forms of relocatable expressions are accepted here, it
2376 // has to be relative to the current section. The streamer will return
2377 // 'true' if the expression wasn't evaluatable.
2378 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2379 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002380
2381 return false;
2382}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002383
2384/// ParseDirectiveAlign
2385/// ::= {.align, ...} expression [ , expression [ , expression ]]
2386bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002387 CheckForValidSection();
2388
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002389 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002390 int64_t Alignment;
2391 if (ParseAbsoluteExpression(Alignment))
2392 return true;
2393
2394 SMLoc MaxBytesLoc;
2395 bool HasFillExpr = false;
2396 int64_t FillExpr = 0;
2397 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002398 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2399 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002400 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002401 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002402
2403 // The fill expression can be omitted while specifying a maximum number of
2404 // alignment bytes, e.g:
2405 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002406 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002407 HasFillExpr = true;
2408 if (ParseAbsoluteExpression(FillExpr))
2409 return true;
2410 }
2411
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002412 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2413 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002414 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002415 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002416
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002417 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002418 if (ParseAbsoluteExpression(MaxBytesToFill))
2419 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002420
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002421 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002422 return TokError("unexpected token in directive");
2423 }
2424 }
2425
Sean Callanan79ed1a82010-01-19 20:22:31 +00002426 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002427
Daniel Dunbar648ac512010-05-17 21:54:30 +00002428 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002429 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002430
2431 // Compute alignment in bytes.
2432 if (IsPow2) {
2433 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002434 if (Alignment >= 32) {
2435 Error(AlignmentLoc, "invalid alignment value");
2436 Alignment = 31;
2437 }
2438
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002439 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002440 }
2441
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002442 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002443 if (MaxBytesLoc.isValid()) {
2444 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002445 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2446 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002447 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002448 }
2449
2450 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002451 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2452 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002453 MaxBytesToFill = 0;
2454 }
2455 }
2456
Daniel Dunbar648ac512010-05-17 21:54:30 +00002457 // Check whether we should use optimal code alignment for this .align
2458 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002459 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002460 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2461 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002462 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002463 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002464 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002465 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2466 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002467 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002468
2469 return false;
2470}
2471
Eli Bendersky6ee13082013-01-15 22:59:42 +00002472/// ParseDirectiveFile
2473/// ::= .file [number] filename
2474/// ::= .file number directory filename
2475bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2476 // FIXME: I'm not sure what this is.
2477 int64_t FileNumber = -1;
2478 SMLoc FileNumberLoc = getLexer().getLoc();
2479 if (getLexer().is(AsmToken::Integer)) {
2480 FileNumber = getTok().getIntVal();
2481 Lex();
2482
2483 if (FileNumber < 1)
2484 return TokError("file number less than one");
2485 }
2486
2487 if (getLexer().isNot(AsmToken::String))
2488 return TokError("unexpected token in '.file' directive");
2489
2490 // Usually the directory and filename together, otherwise just the directory.
2491 StringRef Path = getTok().getString();
2492 Path = Path.substr(1, Path.size()-2);
2493 Lex();
2494
2495 StringRef Directory;
2496 StringRef Filename;
2497 if (getLexer().is(AsmToken::String)) {
2498 if (FileNumber == -1)
2499 return TokError("explicit path specified, but no file number");
2500 Filename = getTok().getString();
2501 Filename = Filename.substr(1, Filename.size()-2);
2502 Directory = Path;
2503 Lex();
2504 } else {
2505 Filename = Path;
2506 }
2507
2508 if (getLexer().isNot(AsmToken::EndOfStatement))
2509 return TokError("unexpected token in '.file' directive");
2510
2511 if (FileNumber == -1)
2512 getStreamer().EmitFileDirective(Filename);
2513 else {
2514 if (getContext().getGenDwarfForAssembly() == true)
2515 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2516 "used to generate dwarf debug info for assembly code");
2517
2518 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2519 Error(FileNumberLoc, "file number already allocated");
2520 }
2521
2522 return false;
2523}
2524
2525/// ParseDirectiveLine
2526/// ::= .line [number]
2527bool AsmParser::ParseDirectiveLine() {
2528 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2529 if (getLexer().isNot(AsmToken::Integer))
2530 return TokError("unexpected token in '.line' directive");
2531
2532 int64_t LineNumber = getTok().getIntVal();
2533 (void) LineNumber;
2534 Lex();
2535
2536 // FIXME: Do something with the .line.
2537 }
2538
2539 if (getLexer().isNot(AsmToken::EndOfStatement))
2540 return TokError("unexpected token in '.line' directive");
2541
2542 return false;
2543}
2544
2545/// ParseDirectiveLoc
2546/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2547/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2548/// The first number is a file number, must have been previously assigned with
2549/// a .file directive, the second number is the line number and optionally the
2550/// third number is a column position (zero if not specified). The remaining
2551/// optional items are .loc sub-directives.
2552bool AsmParser::ParseDirectiveLoc() {
2553 if (getLexer().isNot(AsmToken::Integer))
2554 return TokError("unexpected token in '.loc' directive");
2555 int64_t FileNumber = getTok().getIntVal();
2556 if (FileNumber < 1)
2557 return TokError("file number less than one in '.loc' directive");
2558 if (!getContext().isValidDwarfFileNumber(FileNumber))
2559 return TokError("unassigned file number in '.loc' directive");
2560 Lex();
2561
2562 int64_t LineNumber = 0;
2563 if (getLexer().is(AsmToken::Integer)) {
2564 LineNumber = getTok().getIntVal();
2565 if (LineNumber < 1)
2566 return TokError("line number less than one in '.loc' directive");
2567 Lex();
2568 }
2569
2570 int64_t ColumnPos = 0;
2571 if (getLexer().is(AsmToken::Integer)) {
2572 ColumnPos = getTok().getIntVal();
2573 if (ColumnPos < 0)
2574 return TokError("column position less than zero in '.loc' directive");
2575 Lex();
2576 }
2577
2578 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2579 unsigned Isa = 0;
2580 int64_t Discriminator = 0;
2581 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2582 for (;;) {
2583 if (getLexer().is(AsmToken::EndOfStatement))
2584 break;
2585
2586 StringRef Name;
2587 SMLoc Loc = getTok().getLoc();
2588 if (ParseIdentifier(Name))
2589 return TokError("unexpected token in '.loc' directive");
2590
2591 if (Name == "basic_block")
2592 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2593 else if (Name == "prologue_end")
2594 Flags |= DWARF2_FLAG_PROLOGUE_END;
2595 else if (Name == "epilogue_begin")
2596 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2597 else if (Name == "is_stmt") {
2598 Loc = getTok().getLoc();
2599 const MCExpr *Value;
2600 if (ParseExpression(Value))
2601 return true;
2602 // The expression must be the constant 0 or 1.
2603 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2604 int Value = MCE->getValue();
2605 if (Value == 0)
2606 Flags &= ~DWARF2_FLAG_IS_STMT;
2607 else if (Value == 1)
2608 Flags |= DWARF2_FLAG_IS_STMT;
2609 else
2610 return Error(Loc, "is_stmt value not 0 or 1");
2611 }
2612 else {
2613 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2614 }
2615 }
2616 else if (Name == "isa") {
2617 Loc = getTok().getLoc();
2618 const MCExpr *Value;
2619 if (ParseExpression(Value))
2620 return true;
2621 // The expression must be a constant greater or equal to 0.
2622 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2623 int Value = MCE->getValue();
2624 if (Value < 0)
2625 return Error(Loc, "isa number less than zero");
2626 Isa = Value;
2627 }
2628 else {
2629 return Error(Loc, "isa number not a constant value");
2630 }
2631 }
2632 else if (Name == "discriminator") {
2633 if (ParseAbsoluteExpression(Discriminator))
2634 return true;
2635 }
2636 else {
2637 return Error(Loc, "unknown sub-directive in '.loc' directive");
2638 }
2639
2640 if (getLexer().is(AsmToken::EndOfStatement))
2641 break;
2642 }
2643 }
2644
2645 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2646 Isa, Discriminator, StringRef());
2647
2648 return false;
2649}
2650
2651/// ParseDirectiveStabs
2652/// ::= .stabs string, number, number, number
2653bool AsmParser::ParseDirectiveStabs() {
2654 return TokError("unsupported directive '.stabs'");
2655}
2656
2657/// ParseDirectiveCFISections
2658/// ::= .cfi_sections section [, section]
2659bool AsmParser::ParseDirectiveCFISections() {
2660 StringRef Name;
2661 bool EH = false;
2662 bool Debug = false;
2663
2664 if (ParseIdentifier(Name))
2665 return TokError("Expected an identifier");
2666
2667 if (Name == ".eh_frame")
2668 EH = true;
2669 else if (Name == ".debug_frame")
2670 Debug = true;
2671
2672 if (getLexer().is(AsmToken::Comma)) {
2673 Lex();
2674
2675 if (ParseIdentifier(Name))
2676 return TokError("Expected an identifier");
2677
2678 if (Name == ".eh_frame")
2679 EH = true;
2680 else if (Name == ".debug_frame")
2681 Debug = true;
2682 }
2683
2684 getStreamer().EmitCFISections(EH, Debug);
2685 return false;
2686}
2687
2688/// ParseDirectiveCFIStartProc
2689/// ::= .cfi_startproc
2690bool AsmParser::ParseDirectiveCFIStartProc() {
2691 getStreamer().EmitCFIStartProc();
2692 return false;
2693}
2694
2695/// ParseDirectiveCFIEndProc
2696/// ::= .cfi_endproc
2697bool AsmParser::ParseDirectiveCFIEndProc() {
2698 getStreamer().EmitCFIEndProc();
2699 return false;
2700}
2701
2702/// ParseRegisterOrRegisterNumber - parse register name or number.
2703bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2704 SMLoc DirectiveLoc) {
2705 unsigned RegNo;
2706
2707 if (getLexer().isNot(AsmToken::Integer)) {
2708 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2709 return true;
2710 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2711 } else
2712 return ParseAbsoluteExpression(Register);
2713
2714 return false;
2715}
2716
2717/// ParseDirectiveCFIDefCfa
2718/// ::= .cfi_def_cfa register, offset
2719bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2720 int64_t Register = 0;
2721 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2722 return true;
2723
2724 if (getLexer().isNot(AsmToken::Comma))
2725 return TokError("unexpected token in directive");
2726 Lex();
2727
2728 int64_t Offset = 0;
2729 if (ParseAbsoluteExpression(Offset))
2730 return true;
2731
2732 getStreamer().EmitCFIDefCfa(Register, Offset);
2733 return false;
2734}
2735
2736/// ParseDirectiveCFIDefCfaOffset
2737/// ::= .cfi_def_cfa_offset offset
2738bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2739 int64_t Offset = 0;
2740 if (ParseAbsoluteExpression(Offset))
2741 return true;
2742
2743 getStreamer().EmitCFIDefCfaOffset(Offset);
2744 return false;
2745}
2746
2747/// ParseDirectiveCFIRegister
2748/// ::= .cfi_register register, register
2749bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2750 int64_t Register1 = 0;
2751 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2752 return true;
2753
2754 if (getLexer().isNot(AsmToken::Comma))
2755 return TokError("unexpected token in directive");
2756 Lex();
2757
2758 int64_t Register2 = 0;
2759 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2760 return true;
2761
2762 getStreamer().EmitCFIRegister(Register1, Register2);
2763 return false;
2764}
2765
2766/// ParseDirectiveCFIAdjustCfaOffset
2767/// ::= .cfi_adjust_cfa_offset adjustment
2768bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2769 int64_t Adjustment = 0;
2770 if (ParseAbsoluteExpression(Adjustment))
2771 return true;
2772
2773 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2774 return false;
2775}
2776
2777/// ParseDirectiveCFIDefCfaRegister
2778/// ::= .cfi_def_cfa_register register
2779bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2780 int64_t Register = 0;
2781 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2782 return true;
2783
2784 getStreamer().EmitCFIDefCfaRegister(Register);
2785 return false;
2786}
2787
2788/// ParseDirectiveCFIOffset
2789/// ::= .cfi_offset register, offset
2790bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2791 int64_t Register = 0;
2792 int64_t Offset = 0;
2793
2794 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2795 return true;
2796
2797 if (getLexer().isNot(AsmToken::Comma))
2798 return TokError("unexpected token in directive");
2799 Lex();
2800
2801 if (ParseAbsoluteExpression(Offset))
2802 return true;
2803
2804 getStreamer().EmitCFIOffset(Register, Offset);
2805 return false;
2806}
2807
2808/// ParseDirectiveCFIRelOffset
2809/// ::= .cfi_rel_offset register, offset
2810bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2811 int64_t Register = 0;
2812
2813 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2814 return true;
2815
2816 if (getLexer().isNot(AsmToken::Comma))
2817 return TokError("unexpected token in directive");
2818 Lex();
2819
2820 int64_t Offset = 0;
2821 if (ParseAbsoluteExpression(Offset))
2822 return true;
2823
2824 getStreamer().EmitCFIRelOffset(Register, Offset);
2825 return false;
2826}
2827
2828static bool isValidEncoding(int64_t Encoding) {
2829 if (Encoding & ~0xff)
2830 return false;
2831
2832 if (Encoding == dwarf::DW_EH_PE_omit)
2833 return true;
2834
2835 const unsigned Format = Encoding & 0xf;
2836 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2837 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2838 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2839 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2840 return false;
2841
2842 const unsigned Application = Encoding & 0x70;
2843 if (Application != dwarf::DW_EH_PE_absptr &&
2844 Application != dwarf::DW_EH_PE_pcrel)
2845 return false;
2846
2847 return true;
2848}
2849
2850/// ParseDirectiveCFIPersonalityOrLsda
2851/// IsPersonality true for cfi_personality, false for cfi_lsda
2852/// ::= .cfi_personality encoding, [symbol_name]
2853/// ::= .cfi_lsda encoding, [symbol_name]
2854bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2855 int64_t Encoding = 0;
2856 if (ParseAbsoluteExpression(Encoding))
2857 return true;
2858 if (Encoding == dwarf::DW_EH_PE_omit)
2859 return false;
2860
2861 if (!isValidEncoding(Encoding))
2862 return TokError("unsupported encoding.");
2863
2864 if (getLexer().isNot(AsmToken::Comma))
2865 return TokError("unexpected token in directive");
2866 Lex();
2867
2868 StringRef Name;
2869 if (ParseIdentifier(Name))
2870 return TokError("expected identifier in directive");
2871
2872 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2873
2874 if (IsPersonality)
2875 getStreamer().EmitCFIPersonality(Sym, Encoding);
2876 else
2877 getStreamer().EmitCFILsda(Sym, Encoding);
2878 return false;
2879}
2880
2881/// ParseDirectiveCFIRememberState
2882/// ::= .cfi_remember_state
2883bool AsmParser::ParseDirectiveCFIRememberState() {
2884 getStreamer().EmitCFIRememberState();
2885 return false;
2886}
2887
2888/// ParseDirectiveCFIRestoreState
2889/// ::= .cfi_remember_state
2890bool AsmParser::ParseDirectiveCFIRestoreState() {
2891 getStreamer().EmitCFIRestoreState();
2892 return false;
2893}
2894
2895/// ParseDirectiveCFISameValue
2896/// ::= .cfi_same_value register
2897bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2898 int64_t Register = 0;
2899
2900 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2901 return true;
2902
2903 getStreamer().EmitCFISameValue(Register);
2904 return false;
2905}
2906
2907/// ParseDirectiveCFIRestore
2908/// ::= .cfi_restore register
2909bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2910 int64_t Register = 0;
2911 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2912 return true;
2913
2914 getStreamer().EmitCFIRestore(Register);
2915 return false;
2916}
2917
2918/// ParseDirectiveCFIEscape
2919/// ::= .cfi_escape expression[,...]
2920bool AsmParser::ParseDirectiveCFIEscape() {
2921 std::string Values;
2922 int64_t CurrValue;
2923 if (ParseAbsoluteExpression(CurrValue))
2924 return true;
2925
2926 Values.push_back((uint8_t)CurrValue);
2927
2928 while (getLexer().is(AsmToken::Comma)) {
2929 Lex();
2930
2931 if (ParseAbsoluteExpression(CurrValue))
2932 return true;
2933
2934 Values.push_back((uint8_t)CurrValue);
2935 }
2936
2937 getStreamer().EmitCFIEscape(Values);
2938 return false;
2939}
2940
2941/// ParseDirectiveCFISignalFrame
2942/// ::= .cfi_signal_frame
2943bool AsmParser::ParseDirectiveCFISignalFrame() {
2944 if (getLexer().isNot(AsmToken::EndOfStatement))
2945 return Error(getLexer().getLoc(),
2946 "unexpected token in '.cfi_signal_frame'");
2947
2948 getStreamer().EmitCFISignalFrame();
2949 return false;
2950}
2951
2952/// ParseDirectiveCFIUndefined
2953/// ::= .cfi_undefined register
2954bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2955 int64_t Register = 0;
2956
2957 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2958 return true;
2959
2960 getStreamer().EmitCFIUndefined(Register);
2961 return false;
2962}
2963
2964/// ParseDirectiveMacrosOnOff
2965/// ::= .macros_on
2966/// ::= .macros_off
2967bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2968 if (getLexer().isNot(AsmToken::EndOfStatement))
2969 return Error(getLexer().getLoc(),
2970 "unexpected token in '" + Directive + "' directive");
2971
2972 SetMacrosEnabled(Directive == ".macros_on");
2973 return false;
2974}
2975
2976/// ParseDirectiveMacro
2977/// ::= .macro name [parameters]
2978bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2979 StringRef Name;
2980 if (ParseIdentifier(Name))
2981 return TokError("expected identifier in '.macro' directive");
2982
2983 MCAsmMacroParameters Parameters;
2984 // Argument delimiter is initially unknown. It will be set by
2985 // ParseMacroArgument()
2986 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2987 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2988 for (;;) {
2989 MCAsmMacroParameter Parameter;
2990 if (ParseIdentifier(Parameter.first))
2991 return TokError("expected identifier in '.macro' directive");
2992
2993 if (getLexer().is(AsmToken::Equal)) {
2994 Lex();
2995 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
2996 return true;
2997 }
2998
2999 Parameters.push_back(Parameter);
3000
3001 if (getLexer().is(AsmToken::Comma))
3002 Lex();
3003 else if (getLexer().is(AsmToken::EndOfStatement))
3004 break;
3005 }
3006 }
3007
3008 // Eat the end of statement.
3009 Lex();
3010
3011 AsmToken EndToken, StartToken = getTok();
3012
3013 // Lex the macro definition.
3014 for (;;) {
3015 // Check whether we have reached the end of the file.
3016 if (getLexer().is(AsmToken::Eof))
3017 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3018
3019 // Otherwise, check whether we have reach the .endmacro.
3020 if (getLexer().is(AsmToken::Identifier) &&
3021 (getTok().getIdentifier() == ".endm" ||
3022 getTok().getIdentifier() == ".endmacro")) {
3023 EndToken = getTok();
3024 Lex();
3025 if (getLexer().isNot(AsmToken::EndOfStatement))
3026 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3027 "' directive");
3028 break;
3029 }
3030
3031 // Otherwise, scan til the end of the statement.
3032 EatToEndOfStatement();
3033 }
3034
3035 if (LookupMacro(Name)) {
3036 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3037 }
3038
3039 const char *BodyStart = StartToken.getLoc().getPointer();
3040 const char *BodyEnd = EndToken.getLoc().getPointer();
3041 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3042 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3043 return false;
3044}
3045
3046/// ParseDirectiveEndMacro
3047/// ::= .endm
3048/// ::= .endmacro
3049bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3050 if (getLexer().isNot(AsmToken::EndOfStatement))
3051 return TokError("unexpected token in '" + Directive + "' directive");
3052
3053 // If we are inside a macro instantiation, terminate the current
3054 // instantiation.
3055 if (InsideMacroInstantiation()) {
3056 HandleMacroExit();
3057 return false;
3058 }
3059
3060 // Otherwise, this .endmacro is a stray entry in the file; well formed
3061 // .endmacro directives are handled during the macro definition parsing.
3062 return TokError("unexpected '" + Directive + "' in file, "
3063 "no current macro definition");
3064}
3065
3066/// ParseDirectivePurgeMacro
3067/// ::= .purgem
3068bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3069 StringRef Name;
3070 if (ParseIdentifier(Name))
3071 return TokError("expected identifier in '.purgem' directive");
3072
3073 if (getLexer().isNot(AsmToken::EndOfStatement))
3074 return TokError("unexpected token in '.purgem' directive");
3075
3076 if (!LookupMacro(Name))
3077 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3078
3079 UndefineMacro(Name);
3080 return false;
3081}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003082
3083/// ParseDirectiveBundleAlignMode
3084/// ::= {.bundle_align_mode} expression
3085bool AsmParser::ParseDirectiveBundleAlignMode() {
3086 CheckForValidSection();
3087
3088 // Expect a single argument: an expression that evaluates to a constant
3089 // in the inclusive range 0-30.
3090 SMLoc ExprLoc = getLexer().getLoc();
3091 int64_t AlignSizePow2;
3092 if (ParseAbsoluteExpression(AlignSizePow2))
3093 return true;
3094 else if (getLexer().isNot(AsmToken::EndOfStatement))
3095 return TokError("unexpected token after expression in"
3096 " '.bundle_align_mode' directive");
3097 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3098 return Error(ExprLoc,
3099 "invalid bundle alignment size (expected between 0 and 30)");
3100
3101 Lex();
3102
3103 // Because of AlignSizePow2's verified range we can safely truncate it to
3104 // unsigned.
3105 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3106 return false;
3107}
3108
3109/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003110/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003111bool AsmParser::ParseDirectiveBundleLock() {
3112 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003113 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003114
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003115 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3116 StringRef Option;
3117 SMLoc Loc = getTok().getLoc();
3118 const char *kInvalidOptionError =
3119 "invalid option for '.bundle_lock' directive";
3120
3121 if (ParseIdentifier(Option))
3122 return Error(Loc, kInvalidOptionError);
3123
3124 if (Option != "align_to_end")
3125 return Error(Loc, kInvalidOptionError);
3126 else if (getLexer().isNot(AsmToken::EndOfStatement))
3127 return Error(Loc,
3128 "unexpected token after '.bundle_lock' directive option");
3129 AlignToEnd = true;
3130 }
3131
Eli Bendersky4766ef42012-12-20 19:05:53 +00003132 Lex();
3133
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003134 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003135 return false;
3136}
3137
3138/// ParseDirectiveBundleLock
3139/// ::= {.bundle_lock}
3140bool AsmParser::ParseDirectiveBundleUnlock() {
3141 CheckForValidSection();
3142
3143 if (getLexer().isNot(AsmToken::EndOfStatement))
3144 return TokError("unexpected token in '.bundle_unlock' directive");
3145 Lex();
3146
3147 getStreamer().EmitBundleUnlock();
3148 return false;
3149}
3150
Eli Bendersky6ee13082013-01-15 22:59:42 +00003151/// ParseDirectiveSpace
3152/// ::= (.skip | .space) expression [ , expression ]
3153bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3154 CheckForValidSection();
3155
3156 int64_t NumBytes;
3157 if (ParseAbsoluteExpression(NumBytes))
3158 return true;
3159
3160 int64_t FillExpr = 0;
3161 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3162 if (getLexer().isNot(AsmToken::Comma))
3163 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3164 Lex();
3165
3166 if (ParseAbsoluteExpression(FillExpr))
3167 return true;
3168
3169 if (getLexer().isNot(AsmToken::EndOfStatement))
3170 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3171 }
3172
3173 Lex();
3174
3175 if (NumBytes <= 0)
3176 return TokError("invalid number of bytes in '" +
3177 Twine(IDVal) + "' directive");
3178
3179 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3180 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3181
3182 return false;
3183}
3184
3185/// ParseDirectiveLEB128
3186/// ::= (.sleb128 | .uleb128) expression
3187bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3188 CheckForValidSection();
3189 const MCExpr *Value;
3190
3191 if (ParseExpression(Value))
3192 return true;
3193
3194 if (getLexer().isNot(AsmToken::EndOfStatement))
3195 return TokError("unexpected token in directive");
3196
3197 if (Signed)
3198 getStreamer().EmitSLEB128Value(Value);
3199 else
3200 getStreamer().EmitULEB128Value(Value);
3201
3202 return false;
3203}
3204
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003205/// ParseDirectiveSymbolAttribute
3206/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003207bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003208 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003209 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003210 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003211 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003212
3213 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003214 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003215
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003216 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003217
Jim Grosbach10ec6502011-09-15 17:56:49 +00003218 // Assembler local symbols don't make any sense here. Complain loudly.
3219 if (Sym->isTemporary())
3220 return Error(Loc, "non-local symbol required in directive");
3221
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003222 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003223
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003224 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003225 break;
3226
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003227 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003228 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003229 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003230 }
3231 }
3232
Sean Callanan79ed1a82010-01-19 20:22:31 +00003233 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003234 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003235}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003236
3237/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003238/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3239bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003240 CheckForValidSection();
3241
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003242 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003243 StringRef Name;
3244 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003245 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003246
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003247 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003248 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003249
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003250 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003251 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003252 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003253
3254 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003255 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003256 if (ParseAbsoluteExpression(Size))
3257 return true;
3258
3259 int64_t Pow2Alignment = 0;
3260 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003261 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003262 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003263 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003264 if (ParseAbsoluteExpression(Pow2Alignment))
3265 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003266
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003267 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3268 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003269 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3270
Chris Lattner258281d2010-01-19 06:22:22 +00003271 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003272 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3273 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003274 if (!isPowerOf2_64(Pow2Alignment))
3275 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3276 Pow2Alignment = Log2_64(Pow2Alignment);
3277 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003278 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003279
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003280 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003281 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003282
Sean Callanan79ed1a82010-01-19 20:22:31 +00003283 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003284
Chris Lattner1fc3d752009-07-09 17:25:12 +00003285 // NOTE: a size of zero for a .comm should create a undefined symbol
3286 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003287 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003288 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3289 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003290
Eric Christopherc260a3e2010-05-14 01:38:54 +00003291 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003292 // may internally end up wanting an alignment in bytes.
3293 // FIXME: Diagnose overflow.
3294 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003295 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3296 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003297
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003298 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003299 return Error(IDLoc, "invalid symbol redefinition");
3300
Chris Lattner1fc3d752009-07-09 17:25:12 +00003301 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003302 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003303 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003304 return false;
3305 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003306
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003307 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003308 return false;
3309}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003310
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003311/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003312/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003313bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003314 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003315 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003316
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003317 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003318 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003319 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003320
Sean Callanan79ed1a82010-01-19 20:22:31 +00003321 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003322
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003323 if (Str.empty())
3324 Error(Loc, ".abort detected. Assembly stopping.");
3325 else
3326 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003327 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003328
3329 return false;
3330}
Kevin Enderby71148242009-07-14 21:35:03 +00003331
Kevin Enderby1f049b22009-07-14 23:21:55 +00003332/// ParseDirectiveInclude
3333/// ::= .include "filename"
3334bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003335 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003336 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003337
Sean Callanan18b83232010-01-19 21:44:56 +00003338 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003339 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003340 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003341
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003342 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003343 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003344
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003345 // Strip the quotes.
3346 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003347
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003348 // Attempt to switch the lexer to the included file before consuming the end
3349 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003350 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003351 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003352 return true;
3353 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003354
3355 return false;
3356}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003357
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003358/// ParseDirectiveIncbin
3359/// ::= .incbin "filename"
3360bool AsmParser::ParseDirectiveIncbin() {
3361 if (getLexer().isNot(AsmToken::String))
3362 return TokError("expected string in '.incbin' directive");
3363
3364 std::string Filename = getTok().getString();
3365 SMLoc IncbinLoc = getLexer().getLoc();
3366 Lex();
3367
3368 if (getLexer().isNot(AsmToken::EndOfStatement))
3369 return TokError("unexpected token in '.incbin' directive");
3370
3371 // Strip the quotes.
3372 Filename = Filename.substr(1, Filename.size()-2);
3373
3374 // Attempt to process the included file.
3375 if (ProcessIncbinFile(Filename)) {
3376 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3377 return true;
3378 }
3379
3380 return false;
3381}
3382
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003383/// ParseDirectiveIf
3384/// ::= .if expression
3385bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003386 TheCondStack.push_back(TheCondState);
3387 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003388 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003389 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003390 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003391 int64_t ExprValue;
3392 if (ParseAbsoluteExpression(ExprValue))
3393 return true;
3394
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003395 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003396 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003397
Sean Callanan79ed1a82010-01-19 20:22:31 +00003398 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003399
3400 TheCondState.CondMet = ExprValue;
3401 TheCondState.Ignore = !TheCondState.CondMet;
3402 }
3403
3404 return false;
3405}
3406
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003407/// ParseDirectiveIfb
3408/// ::= .ifb string
3409bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3410 TheCondStack.push_back(TheCondState);
3411 TheCondState.TheCond = AsmCond::IfCond;
3412
Benjamin Kramer29739e72012-05-12 16:52:21 +00003413 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003414 EatToEndOfStatement();
3415 } else {
3416 StringRef Str = ParseStringToEndOfStatement();
3417
3418 if (getLexer().isNot(AsmToken::EndOfStatement))
3419 return TokError("unexpected token in '.ifb' directive");
3420
3421 Lex();
3422
3423 TheCondState.CondMet = ExpectBlank == Str.empty();
3424 TheCondState.Ignore = !TheCondState.CondMet;
3425 }
3426
3427 return false;
3428}
3429
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003430/// ParseDirectiveIfc
3431/// ::= .ifc string1, string2
3432bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3433 TheCondStack.push_back(TheCondState);
3434 TheCondState.TheCond = AsmCond::IfCond;
3435
Benjamin Kramer29739e72012-05-12 16:52:21 +00003436 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003437 EatToEndOfStatement();
3438 } else {
3439 StringRef Str1 = ParseStringToComma();
3440
3441 if (getLexer().isNot(AsmToken::Comma))
3442 return TokError("unexpected token in '.ifc' directive");
3443
3444 Lex();
3445
3446 StringRef Str2 = ParseStringToEndOfStatement();
3447
3448 if (getLexer().isNot(AsmToken::EndOfStatement))
3449 return TokError("unexpected token in '.ifc' directive");
3450
3451 Lex();
3452
3453 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3454 TheCondState.Ignore = !TheCondState.CondMet;
3455 }
3456
3457 return false;
3458}
3459
3460/// ParseDirectiveIfdef
3461/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003462bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3463 StringRef Name;
3464 TheCondStack.push_back(TheCondState);
3465 TheCondState.TheCond = AsmCond::IfCond;
3466
3467 if (TheCondState.Ignore) {
3468 EatToEndOfStatement();
3469 } else {
3470 if (ParseIdentifier(Name))
3471 return TokError("expected identifier after '.ifdef'");
3472
3473 Lex();
3474
3475 MCSymbol *Sym = getContext().LookupSymbol(Name);
3476
3477 if (expect_defined)
3478 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3479 else
3480 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3481 TheCondState.Ignore = !TheCondState.CondMet;
3482 }
3483
3484 return false;
3485}
3486
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003487/// ParseDirectiveElseIf
3488/// ::= .elseif expression
3489bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3490 if (TheCondState.TheCond != AsmCond::IfCond &&
3491 TheCondState.TheCond != AsmCond::ElseIfCond)
3492 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3493 " an .elseif");
3494 TheCondState.TheCond = AsmCond::ElseIfCond;
3495
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003496 bool LastIgnoreState = false;
3497 if (!TheCondStack.empty())
3498 LastIgnoreState = TheCondStack.back().Ignore;
3499 if (LastIgnoreState || TheCondState.CondMet) {
3500 TheCondState.Ignore = true;
3501 EatToEndOfStatement();
3502 }
3503 else {
3504 int64_t ExprValue;
3505 if (ParseAbsoluteExpression(ExprValue))
3506 return true;
3507
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003508 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003509 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003510
Sean Callanan79ed1a82010-01-19 20:22:31 +00003511 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003512 TheCondState.CondMet = ExprValue;
3513 TheCondState.Ignore = !TheCondState.CondMet;
3514 }
3515
3516 return false;
3517}
3518
3519/// ParseDirectiveElse
3520/// ::= .else
3521bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003522 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003523 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003524
Sean Callanan79ed1a82010-01-19 20:22:31 +00003525 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003526
3527 if (TheCondState.TheCond != AsmCond::IfCond &&
3528 TheCondState.TheCond != AsmCond::ElseIfCond)
3529 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3530 ".elseif");
3531 TheCondState.TheCond = AsmCond::ElseCond;
3532 bool LastIgnoreState = false;
3533 if (!TheCondStack.empty())
3534 LastIgnoreState = TheCondStack.back().Ignore;
3535 if (LastIgnoreState || TheCondState.CondMet)
3536 TheCondState.Ignore = true;
3537 else
3538 TheCondState.Ignore = false;
3539
3540 return false;
3541}
3542
3543/// ParseDirectiveEndIf
3544/// ::= .endif
3545bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003546 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003547 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003548
Sean Callanan79ed1a82010-01-19 20:22:31 +00003549 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003550
3551 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3552 TheCondStack.empty())
3553 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3554 ".else");
3555 if (!TheCondStack.empty()) {
3556 TheCondState = TheCondStack.back();
3557 TheCondStack.pop_back();
3558 }
3559
3560 return false;
3561}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003562
Eli Bendersky6ee13082013-01-15 22:59:42 +00003563void AsmParser::initializeDirectiveKindMap() {
3564 DirectiveKindMap[".set"] = DK_SET;
3565 DirectiveKindMap[".equ"] = DK_EQU;
3566 DirectiveKindMap[".equiv"] = DK_EQUIV;
3567 DirectiveKindMap[".ascii"] = DK_ASCII;
3568 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3569 DirectiveKindMap[".string"] = DK_STRING;
3570 DirectiveKindMap[".byte"] = DK_BYTE;
3571 DirectiveKindMap[".short"] = DK_SHORT;
3572 DirectiveKindMap[".value"] = DK_VALUE;
3573 DirectiveKindMap[".2byte"] = DK_2BYTE;
3574 DirectiveKindMap[".long"] = DK_LONG;
3575 DirectiveKindMap[".int"] = DK_INT;
3576 DirectiveKindMap[".4byte"] = DK_4BYTE;
3577 DirectiveKindMap[".quad"] = DK_QUAD;
3578 DirectiveKindMap[".8byte"] = DK_8BYTE;
3579 DirectiveKindMap[".single"] = DK_SINGLE;
3580 DirectiveKindMap[".float"] = DK_FLOAT;
3581 DirectiveKindMap[".double"] = DK_DOUBLE;
3582 DirectiveKindMap[".align"] = DK_ALIGN;
3583 DirectiveKindMap[".align32"] = DK_ALIGN32;
3584 DirectiveKindMap[".balign"] = DK_BALIGN;
3585 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3586 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3587 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3588 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3589 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3590 DirectiveKindMap[".org"] = DK_ORG;
3591 DirectiveKindMap[".fill"] = DK_FILL;
3592 DirectiveKindMap[".zero"] = DK_ZERO;
3593 DirectiveKindMap[".extern"] = DK_EXTERN;
3594 DirectiveKindMap[".globl"] = DK_GLOBL;
3595 DirectiveKindMap[".global"] = DK_GLOBAL;
3596 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3597 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3598 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3599 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3600 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3601 DirectiveKindMap[".reference"] = DK_REFERENCE;
3602 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3603 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3604 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3605 DirectiveKindMap[".comm"] = DK_COMM;
3606 DirectiveKindMap[".common"] = DK_COMMON;
3607 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3608 DirectiveKindMap[".abort"] = DK_ABORT;
3609 DirectiveKindMap[".include"] = DK_INCLUDE;
3610 DirectiveKindMap[".incbin"] = DK_INCBIN;
3611 DirectiveKindMap[".code16"] = DK_CODE16;
3612 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3613 DirectiveKindMap[".rept"] = DK_REPT;
3614 DirectiveKindMap[".irp"] = DK_IRP;
3615 DirectiveKindMap[".irpc"] = DK_IRPC;
3616 DirectiveKindMap[".endr"] = DK_ENDR;
3617 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3618 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3619 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3620 DirectiveKindMap[".if"] = DK_IF;
3621 DirectiveKindMap[".ifb"] = DK_IFB;
3622 DirectiveKindMap[".ifnb"] = DK_IFNB;
3623 DirectiveKindMap[".ifc"] = DK_IFC;
3624 DirectiveKindMap[".ifnc"] = DK_IFNC;
3625 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3626 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3627 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3628 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3629 DirectiveKindMap[".else"] = DK_ELSE;
3630 DirectiveKindMap[".endif"] = DK_ENDIF;
3631 DirectiveKindMap[".skip"] = DK_SKIP;
3632 DirectiveKindMap[".space"] = DK_SPACE;
3633 DirectiveKindMap[".file"] = DK_FILE;
3634 DirectiveKindMap[".line"] = DK_LINE;
3635 DirectiveKindMap[".loc"] = DK_LOC;
3636 DirectiveKindMap[".stabs"] = DK_STABS;
3637 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3638 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3639 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3640 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3641 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3642 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3643 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3644 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3645 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3646 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3647 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3648 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3649 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3650 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3651 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3652 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3653 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3654 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3655 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3656 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3657 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3658 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3659 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3660 DirectiveKindMap[".macro"] = DK_MACRO;
3661 DirectiveKindMap[".endm"] = DK_ENDM;
3662 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3663 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003664}
3665
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003666
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003667MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003668 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003669
Rafael Espindola761cb062012-06-03 23:57:14 +00003670 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003671 for (;;) {
3672 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003673 if (getLexer().is(AsmToken::Eof)) {
3674 Error(DirectiveLoc, "no matching '.endr' in definition");
3675 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003676 }
3677
Rafael Espindola761cb062012-06-03 23:57:14 +00003678 if (Lexer.is(AsmToken::Identifier) &&
3679 (getTok().getIdentifier() == ".rept")) {
3680 ++NestLevel;
3681 }
3682
3683 // Otherwise, check whether we have reached the .endr.
3684 if (Lexer.is(AsmToken::Identifier) &&
3685 getTok().getIdentifier() == ".endr") {
3686 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003687 EndToken = getTok();
3688 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003689 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3690 TokError("unexpected token in '.endr' directive");
3691 return 0;
3692 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003693 break;
3694 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003695 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003696 }
3697
Rafael Espindola761cb062012-06-03 23:57:14 +00003698 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003699 EatToEndOfStatement();
3700 }
3701
3702 const char *BodyStart = StartToken.getLoc().getPointer();
3703 const char *BodyEnd = EndToken.getLoc().getPointer();
3704 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3705
Rafael Espindola761cb062012-06-03 23:57:14 +00003706 // We Are Anonymous.
3707 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003708 MCAsmMacroParameters Parameters;
3709 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003710}
3711
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003712void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003713 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003714 OS << ".endr\n";
3715
3716 MemoryBuffer *Instantiation =
3717 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3718
Rafael Espindola761cb062012-06-03 23:57:14 +00003719 // Create the macro instantiation object and add to the current macro
3720 // instantiation stack.
3721 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003722 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003723 getTok().getLoc(),
3724 Instantiation);
3725 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003726
Rafael Espindola761cb062012-06-03 23:57:14 +00003727 // Jump to the macro instantiation and prime the lexer.
3728 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3729 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3730 Lex();
3731}
3732
3733bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3734 int64_t Count;
3735 if (ParseAbsoluteExpression(Count))
3736 return TokError("unexpected token in '.rept' directive");
3737
3738 if (Count < 0)
3739 return TokError("Count is negative");
3740
3741 if (Lexer.isNot(AsmToken::EndOfStatement))
3742 return TokError("unexpected token in '.rept' directive");
3743
3744 // Eat the end of statement.
3745 Lex();
3746
3747 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003748 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003749 if (!M)
3750 return true;
3751
3752 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3753 // to hold the macro body with substitutions.
3754 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003755 MCAsmMacroParameters Parameters;
3756 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003757 raw_svector_ostream OS(Buf);
3758 while (Count--) {
3759 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3760 return true;
3761 }
3762 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003763
3764 return false;
3765}
3766
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003767/// ParseDirectiveIrp
3768/// ::= .irp symbol,values
3769bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003770 MCAsmMacroParameters Parameters;
3771 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003772
Preston Gurd6c9176a2012-09-19 20:29:04 +00003773 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003774 return TokError("expected identifier in '.irp' directive");
3775
3776 Parameters.push_back(Parameter);
3777
3778 if (Lexer.isNot(AsmToken::Comma))
3779 return TokError("expected comma in '.irp' directive");
3780
3781 Lex();
3782
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003783 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003784 if (ParseMacroArguments(0, A))
3785 return true;
3786
3787 // Eat the end of statement.
3788 Lex();
3789
3790 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003791 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003792 if (!M)
3793 return true;
3794
3795 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3796 // to hold the macro body with substitutions.
3797 SmallString<256> Buf;
3798 raw_svector_ostream OS(Buf);
3799
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003800 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3801 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003802 Args.push_back(*i);
3803
3804 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3805 return true;
3806 }
3807
3808 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3809
3810 return false;
3811}
3812
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003813/// ParseDirectiveIrpc
3814/// ::= .irpc symbol,values
3815bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003816 MCAsmMacroParameters Parameters;
3817 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003818
Preston Gurd6c9176a2012-09-19 20:29:04 +00003819 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003820 return TokError("expected identifier in '.irpc' directive");
3821
3822 Parameters.push_back(Parameter);
3823
3824 if (Lexer.isNot(AsmToken::Comma))
3825 return TokError("expected comma in '.irpc' directive");
3826
3827 Lex();
3828
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003829 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003830 if (ParseMacroArguments(0, A))
3831 return true;
3832
3833 if (A.size() != 1 || A.front().size() != 1)
3834 return TokError("unexpected token in '.irpc' directive");
3835
3836 // Eat the end of statement.
3837 Lex();
3838
3839 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003840 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003841 if (!M)
3842 return true;
3843
3844 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3845 // to hold the macro body with substitutions.
3846 SmallString<256> Buf;
3847 raw_svector_ostream OS(Buf);
3848
3849 StringRef Values = A.front().front().getString();
3850 std::size_t I, End = Values.size();
3851 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003852 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003853 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3854
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003855 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003856 Args.push_back(Arg);
3857
3858 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3859 return true;
3860 }
3861
3862 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3863
3864 return false;
3865}
3866
Rafael Espindola761cb062012-06-03 23:57:14 +00003867bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3868 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003869 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003870
3871 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003872 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003873 assert(getLexer().is(AsmToken::EndOfStatement));
3874
Rafael Espindola761cb062012-06-03 23:57:14 +00003875 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003876 return false;
3877}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003878
Eli Friedman2128aae2012-10-22 23:58:19 +00003879bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3880 const MCExpr *Value;
3881 SMLoc ExprLoc = getLexer().getLoc();
3882 if (ParseExpression(Value))
3883 return true;
3884 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3885 if (!MCE)
3886 return Error(ExprLoc, "unexpected expression in _emit");
3887 uint64_t IntValue = MCE->getValue();
3888 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3889 return Error(ExprLoc, "literal value out of range for directive");
3890
3891 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3892 return false;
3893}
3894
Chad Rosierb1f8c132012-10-18 15:49:34 +00003895bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3896 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003897 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003898 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003899 SmallVectorImpl<std::string> &Clobbers,
3900 const MCInstrInfo *MII,
3901 const MCInstPrinter *IP,
3902 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003903 SmallVector<void *, 4> InputDecls;
3904 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003905 SmallVector<bool, 4> InputDeclsAddressOf;
3906 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003907 SmallVector<std::string, 4> InputConstraints;
3908 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003909 std::set<std::string> ClobberRegs;
3910
Chad Rosier4e472d22012-10-20 01:02:45 +00003911 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003912
3913 // Prime the lexer.
3914 Lex();
3915
3916 // While we have input, parse each statement.
3917 unsigned InputIdx = 0;
3918 unsigned OutputIdx = 0;
3919 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003920 ParseStatementInfo Info(&AsmStrRewrites);
3921 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003922 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003923
Chad Rosier57498012012-12-12 22:45:52 +00003924 if (Info.ParseError)
3925 return true;
3926
Eli Friedman2128aae2012-10-22 23:58:19 +00003927 if (Info.Opcode != ~0U) {
3928 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003929
3930 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003931 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3932 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003933
3934 // Immediate.
3935 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003936 if (Operand->needAsmRewrite())
3937 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3938 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003939 continue;
3940 }
3941
3942 // Register operand.
Chad Rosierc1ec2072013-01-10 22:10:27 +00003943 if (Operand->isReg() && !Operand->needAddressOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003944 unsigned NumDefs = Desc.getNumDefs();
3945 // Clobber.
3946 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3947 std::string Reg;
3948 raw_string_ostream OS(Reg);
3949 IP->printRegName(OS, Operand->getReg());
3950 ClobberRegs.insert(StringRef(OS.str()));
3951 }
3952 continue;
3953 }
3954
3955 // Expr/Input or Output.
Chad Rosierc1ec2072013-01-10 22:10:27 +00003956 bool IsVarDecl;
Chad Rosier505bca32013-01-17 19:21:48 +00003957 unsigned Length, Size, Type;
Chad Rosier32989592012-10-18 20:27:15 +00003958 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
Chad Rosier505bca32013-01-17 19:21:48 +00003959 Length, Size, Type, IsVarDecl);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003960 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003961 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc1ec2072013-01-10 22:10:27 +00003962 if (Operand->isMem() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003963 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003964 Operand->getStartLoc(),
3965 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003966 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003967 if (isOutput) {
3968 std::string Constraint = "=";
3969 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003970 OutputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003971 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003972 Constraint += Operand->getConstraint().str();
3973 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003974 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003975 Operand->getStartLoc(),
3976 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003977 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003978 InputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003979 InputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003980 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003981 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003982 Operand->getStartLoc(),
3983 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003984 }
3985 }
3986 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003987 }
3988 }
3989
3990 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003991 NumOutputs = OutputDecls.size();
3992 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003993
3994 // Set the unique clobbers.
3995 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3996 E = ClobberRegs.end(); I != E; ++I)
3997 Clobbers.push_back(*I);
3998
3999 // Merge the various outputs and inputs. Output are expected first.
4000 if (NumOutputs || NumInputs) {
4001 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004002 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004003 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004004 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004005 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004006 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004007 }
4008 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004009 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004010 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004011 }
4012 }
4013
4014 // Build the IR assembly string.
4015 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00004016 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004017 raw_string_ostream OS(AsmStringIR);
4018 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00004019 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00004020 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4021 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00004022
Chad Rosier4e472d22012-10-20 01:02:45 +00004023 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004024
4025 // Emit everything up to the immediate/expression. If the previous rewrite
4026 // was a size directive, then this has already been done.
4027 if (PrevKind != AOK_SizeDirective)
4028 OS << StringRef(Start, Loc - Start);
4029 PrevKind = Kind;
4030
Chad Rosier5a719fc2012-10-23 17:43:43 +00004031 // Skip the original expression.
4032 if (Kind == AOK_Skip) {
4033 Start = Loc + (*I).Len;
4034 continue;
4035 }
4036
Chad Rosierb1f8c132012-10-18 15:49:34 +00004037 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004038 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004039 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004040 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00004041 OS << Twine("$$");
4042 OS << (*I).Val;
4043 break;
4044 case AOK_ImmPrefix:
4045 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00004046 break;
4047 case AOK_Input:
4048 OS << '$';
4049 OS << InputIdx++;
4050 break;
4051 case AOK_Output:
4052 OS << '$';
4053 OS << OutputIdx++;
4054 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004055 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00004056 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004057 default: break;
4058 case 8: OS << "byte ptr "; break;
4059 case 16: OS << "word ptr "; break;
4060 case 32: OS << "dword ptr "; break;
4061 case 64: OS << "qword ptr "; break;
4062 case 80: OS << "xword ptr "; break;
4063 case 128: OS << "xmmword ptr "; break;
4064 case 256: OS << "ymmword ptr "; break;
4065 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004066 break;
4067 case AOK_Emit:
4068 OS << ".byte";
4069 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00004070 case AOK_DotOperator:
4071 OS << (*I).Val;
4072 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004073 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004074
Chad Rosierb1f8c132012-10-18 15:49:34 +00004075 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004076 if (Kind != AOK_SizeDirective)
4077 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004078 }
4079
4080 // Emit the remainder of the asm string.
4081 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4082 if (Start != AsmEnd)
4083 OS << StringRef(Start, AsmEnd - Start);
4084
4085 AsmString = OS.str();
4086 return false;
4087}
4088
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004089/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004090MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004091 MCContext &C, MCStreamer &Out,
4092 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004093 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004094}