blob: 838a5542d31a832dc9caae23f43fc5552bd36b92 [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
430
431 /// ParseEscapedString - Parse the current token as a string which may include
432 /// escaped characters and return the string contents.
433 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000434
435 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
436 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000437
Rafael Espindola761cb062012-06-03 23:57:14 +0000438 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000439 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
440 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000441 raw_svector_ostream &OS);
442 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000443 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000444 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000445 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000446
Eli Friedman2128aae2012-10-22 23:58:19 +0000447 // "_emit"
448 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000449
Eli Bendersky6ee13082013-01-15 22:59:42 +0000450 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000451};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000452}
453
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000454namespace llvm {
455
456extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000457extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000458extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000459
460}
461
Chris Lattneraaec2052010-01-19 19:46:13 +0000462enum { DEFAULT_ADDRSPACE = 0 };
463
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000464AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000465 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000466 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000467 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000468 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000469 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000470 // Save the old handler.
471 SavedDiagHandler = SrcMgr.getDiagHandler();
472 SavedDiagContext = SrcMgr.getDiagContext();
473 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000474 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000475 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000476
Daniel Dunbare4749702010-07-12 18:12:02 +0000477 // Initialize the platform / file format parser.
478 //
479 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
480 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000481 if (_MAI.hasMicrosoftFastStdCallMangling()) {
482 PlatformParser = createCOFFAsmParser();
483 PlatformParser->Initialize(*this);
484 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000485 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000486 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000487 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000488 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000489 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000490 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000491 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000492
Eli Bendersky6ee13082013-01-15 22:59:42 +0000493 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000494}
495
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000496AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000497 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
498
499 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000500 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000501 ie = MacroMap.end(); it != ie; ++it)
502 delete it->getValue();
503
Daniel Dunbare4749702010-07-12 18:12:02 +0000504 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000505}
506
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000507void AsmParser::PrintMacroInstantiations() {
508 // Print the active macro instantiation stack.
509 for (std::vector<MacroInstantiation*>::const_reverse_iterator
510 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000511 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
512 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000513}
514
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000515bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000516 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000517 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000518 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000519 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000520 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000521}
522
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000523bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000524 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000525 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000526 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000527 return true;
528}
529
Sean Callananfd0b0282010-01-21 00:19:58 +0000530bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000531 std::string IncludedFile;
532 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000533 if (NewBuf == -1)
534 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000535
Sean Callananfd0b0282010-01-21 00:19:58 +0000536 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000537
Sean Callananfd0b0282010-01-21 00:19:58 +0000538 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000539
Sean Callananfd0b0282010-01-21 00:19:58 +0000540 return false;
541}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000542
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000543/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000544/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000545/// returns true on failure.
546bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
547 std::string IncludedFile;
548 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
549 if (NewBuf == -1)
550 return true;
551
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000552 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000553 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
554 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000555 return false;
556}
557
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000558void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
559 if (InBuffer != -1) {
560 CurBuffer = InBuffer;
561 } else {
562 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
563 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000564 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
565}
566
Sean Callananfd0b0282010-01-21 00:19:58 +0000567const AsmToken &AsmParser::Lex() {
568 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000569
Sean Callananfd0b0282010-01-21 00:19:58 +0000570 if (tok->is(AsmToken::Eof)) {
571 // If this is the end of an included file, pop the parent file off the
572 // include stack.
573 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
574 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000575 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000576 tok = &Lexer.Lex();
577 }
578 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000579
Sean Callananfd0b0282010-01-21 00:19:58 +0000580 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000581 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000582
Sean Callananfd0b0282010-01-21 00:19:58 +0000583 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000584}
585
Chris Lattner79180e22010-04-05 23:15:42 +0000586bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000587 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000588 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000589 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000590
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000591 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000592 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000593
594 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000595 AsmCond StartingCondState = TheCondState;
596
Kevin Enderby613b7572011-11-01 22:27:22 +0000597 // If we are generating dwarf for assembly source files save the initial text
598 // section and generate a .file directive.
599 if (getContext().getGenDwarfForAssembly()) {
600 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000601 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
602 getStreamer().EmitLabel(SectionStartSym);
603 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000604 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000605 StringRef(),
606 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000607 }
608
Chris Lattnerb717fb02009-07-02 21:53:43 +0000609 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000610 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000611 ParseStatementInfo Info;
612 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000613
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000614 // We had an error, validate that one was emitted and recover by skipping to
615 // the next line.
616 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000617 EatToEndOfStatement();
618 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000619
620 if (TheCondState.TheCond != StartingCondState.TheCond ||
621 TheCondState.Ignore != StartingCondState.Ignore)
622 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000623
624 // Check to see there are no empty DwarfFile slots.
625 const std::vector<MCDwarfFile *> &MCDwarfFiles =
626 getContext().getMCDwarfFiles();
627 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000628 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000629 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000630 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000631
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000632 // Check to see that all assembler local symbols were actually defined.
633 // Targets that don't do subsections via symbols may not want this, though,
634 // so conservatively exclude them. Only do this if we're finalizing, though,
635 // as otherwise we won't necessarilly have seen everything yet.
636 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
637 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
638 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
639 e = Symbols.end();
640 i != e; ++i) {
641 MCSymbol *Sym = i->getValue();
642 // Variable symbols may not be marked as defined, so check those
643 // explicitly. If we know it's a variable, we have a definition for
644 // the purposes of this check.
645 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
646 // FIXME: We would really like to refer back to where the symbol was
647 // first referenced for a source location. We need to add something
648 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000649 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
650 "assembler local symbol '" + Sym->getName() +
651 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000652 }
653 }
654
655
Chris Lattner79180e22010-04-05 23:15:42 +0000656 // Finalize the output stream if there are no errors and if the client wants
657 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000658 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000659 Out.Finish();
660
Chris Lattnerb717fb02009-07-02 21:53:43 +0000661 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000662}
663
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000664void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000665 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000666 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000667 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000668 }
669}
670
Chris Lattner2cf5f142009-06-22 01:29:09 +0000671/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
672void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000673 while (Lexer.isNot(AsmToken::EndOfStatement) &&
674 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000675 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000676
Chris Lattner2cf5f142009-06-22 01:29:09 +0000677 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000678 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000679 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000680}
681
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000682StringRef AsmParser::ParseStringToEndOfStatement() {
683 const char *Start = getTok().getLoc().getPointer();
684
685 while (Lexer.isNot(AsmToken::EndOfStatement) &&
686 Lexer.isNot(AsmToken::Eof))
687 Lex();
688
689 const char *End = getTok().getLoc().getPointer();
690 return StringRef(Start, End - Start);
691}
Chris Lattnerc4193832009-06-22 05:51:26 +0000692
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000693StringRef AsmParser::ParseStringToComma() {
694 const char *Start = getTok().getLoc().getPointer();
695
696 while (Lexer.isNot(AsmToken::EndOfStatement) &&
697 Lexer.isNot(AsmToken::Comma) &&
698 Lexer.isNot(AsmToken::Eof))
699 Lex();
700
701 const char *End = getTok().getLoc().getPointer();
702 return StringRef(Start, End - Start);
703}
704
Chris Lattner74ec1a32009-06-22 06:32:03 +0000705/// ParseParenExpr - Parse a paren expression and return it.
706/// NOTE: This assumes the leading '(' has already been consumed.
707///
708/// parenexpr ::= expr)
709///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000710bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000711 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000712 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000713 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000714 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000715 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000716 return false;
717}
Chris Lattnerc4193832009-06-22 05:51:26 +0000718
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000719/// ParseBracketExpr - Parse a bracket expression and return it.
720/// NOTE: This assumes the leading '[' has already been consumed.
721///
722/// bracketexpr ::= expr]
723///
724bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
725 if (ParseExpression(Res)) return true;
726 if (Lexer.isNot(AsmToken::RBrac))
727 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000728 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000729 Lex();
730 return false;
731}
732
Chris Lattner74ec1a32009-06-22 06:32:03 +0000733/// ParsePrimaryExpr - Parse a primary expression and return it.
734/// primaryexpr ::= (parenexpr
735/// primaryexpr ::= symbol
736/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000737/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000738/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000739bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000740 switch (Lexer.getKind()) {
741 default:
742 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000743 // If we have an error assume that we've already handled it.
744 case AsmToken::Error:
745 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000746 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000747 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000748 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000749 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000750 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000751 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000752 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000753 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000754 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000755 StringRef Identifier;
756 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000757 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000758
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000759 EndLoc = SMLoc::getFromPointer(Identifier.end());
760
Daniel Dunbarfffff912009-10-16 01:34:54 +0000761 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000762 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000763 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000764
765 // Lookup the symbol variant if used.
766 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000767 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000768 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000769 if (Variant == MCSymbolRefExpr::VK_Invalid) {
770 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000771 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000772 }
773 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000774
Daniel Dunbarfffff912009-10-16 01:34:54 +0000775 // If this is an absolute variable reference, substitute it now to preserve
776 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000777 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000778 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000779 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000780
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000781 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000782 return false;
783 }
784
785 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000786 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000787 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000788 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000789 case AsmToken::Integer: {
790 SMLoc Loc = getTok().getLoc();
791 int64_t IntVal = getTok().getIntVal();
792 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000793 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000794 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000795 // Look for 'b' or 'f' following an Integer as a directional label
796 if (Lexer.getKind() == AsmToken::Identifier) {
797 StringRef IDVal = getTok().getString();
798 if (IDVal == "f" || IDVal == "b"){
799 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
800 IDVal == "f" ? 1 : 0);
801 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
802 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000803 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000804 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000805 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000806 Lex(); // Eat identifier.
807 }
808 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000809 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000810 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000811 case AsmToken::Real: {
812 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000813 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000814 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000815 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000816 Lex(); // Eat token.
817 return false;
818 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000819 case AsmToken::Dot: {
820 // This is a '.' reference, which references the current PC. Emit a
821 // temporary label to the streamer and refer to it.
822 MCSymbol *Sym = Ctx.CreateTempSymbol();
823 Out.EmitLabel(Sym);
824 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000825 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000826 Lex(); // Eat identifier.
827 return false;
828 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000829 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000830 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000831 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000832 case AsmToken::LBrac:
833 if (!PlatformParser->HasBracketExpressions())
834 return TokError("brackets expression not supported on this target");
835 Lex(); // Eat the '['.
836 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000837 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000838 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000839 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000840 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000841 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000842 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000843 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000844 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000845 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000846 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000847 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000848 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000849 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000850 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000851 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000852 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000853 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000854 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000855 }
856}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000857
Chris Lattnerb4307b32010-01-15 19:28:38 +0000858bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000859 SMLoc EndLoc;
860 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000861}
862
Daniel Dunbarcceba832010-09-17 02:47:07 +0000863const MCExpr *
864AsmParser::ApplyModifierToExpr(const MCExpr *E,
865 MCSymbolRefExpr::VariantKind Variant) {
866 // Recurse over the given expression, rebuilding it to apply the given variant
867 // if there is exactly one symbol.
868 switch (E->getKind()) {
869 case MCExpr::Target:
870 case MCExpr::Constant:
871 return 0;
872
873 case MCExpr::SymbolRef: {
874 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
875
876 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
877 TokError("invalid variant on expression '" +
878 getTok().getIdentifier() + "' (already modified)");
879 return E;
880 }
881
882 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
883 }
884
885 case MCExpr::Unary: {
886 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
887 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
888 if (!Sub)
889 return 0;
890 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
891 }
892
893 case MCExpr::Binary: {
894 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
895 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
896 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
897
898 if (!LHS && !RHS)
899 return 0;
900
901 if (!LHS) LHS = BE->getLHS();
902 if (!RHS) RHS = BE->getRHS();
903
904 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
905 }
906 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000907
Craig Topper85814382012-02-07 05:05:23 +0000908 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000909}
910
Chris Lattner74ec1a32009-06-22 06:32:03 +0000911/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000912///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000913/// expr ::= expr &&,|| expr -> lowest.
914/// expr ::= expr |,^,&,! expr
915/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
916/// expr ::= expr <<,>> expr
917/// expr ::= expr +,- expr
918/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000919/// expr ::= primaryexpr
920///
Chris Lattner54482b42010-01-15 19:39:23 +0000921bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000922 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000923 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000924 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
925 return true;
926
Daniel Dunbarcceba832010-09-17 02:47:07 +0000927 // As a special case, we support 'a op b @ modifier' by rewriting the
928 // expression to include the modifier. This is inefficient, but in general we
929 // expect users to use 'a@modifier op b'.
930 if (Lexer.getKind() == AsmToken::At) {
931 Lex();
932
933 if (Lexer.isNot(AsmToken::Identifier))
934 return TokError("unexpected symbol modifier following '@'");
935
936 MCSymbolRefExpr::VariantKind Variant =
937 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
938 if (Variant == MCSymbolRefExpr::VK_Invalid)
939 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
940
941 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
942 if (!ModifiedRes) {
943 return TokError("invalid modifier '" + getTok().getIdentifier() +
944 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000945 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000946
Daniel Dunbarcceba832010-09-17 02:47:07 +0000947 Res = ModifiedRes;
948 Lex();
949 }
950
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000951 // Try to constant fold it up front, if possible.
952 int64_t Value;
953 if (Res->EvaluateAsAbsolute(Value))
954 Res = MCConstantExpr::Create(Value, getContext());
955
956 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000957}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000958
Chris Lattnerb4307b32010-01-15 19:28:38 +0000959bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000960 Res = 0;
961 return ParseParenExpr(Res, EndLoc) ||
962 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000963}
964
Daniel Dunbar475839e2009-06-29 20:37:27 +0000965bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000966 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000967
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000968 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000969 if (ParseExpression(Expr))
970 return true;
971
Daniel Dunbare00b0112009-10-16 01:57:52 +0000972 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000973 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000974
975 return false;
976}
977
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000978static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000979 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000980 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000981 default:
982 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000983
Jim Grosbachfbe16812011-08-20 16:24:13 +0000984 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000985 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000986 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000987 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000988 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000989 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000990 return 1;
991
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000992
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000993 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000994 //
995 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000996 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000997 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000998 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000999 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001000 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001001 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001002 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001003 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001004 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001005
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001006 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001007 case AsmToken::EqualEqual:
1008 Kind = MCBinaryExpr::EQ;
1009 return 3;
1010 case AsmToken::ExclaimEqual:
1011 case AsmToken::LessGreater:
1012 Kind = MCBinaryExpr::NE;
1013 return 3;
1014 case AsmToken::Less:
1015 Kind = MCBinaryExpr::LT;
1016 return 3;
1017 case AsmToken::LessEqual:
1018 Kind = MCBinaryExpr::LTE;
1019 return 3;
1020 case AsmToken::Greater:
1021 Kind = MCBinaryExpr::GT;
1022 return 3;
1023 case AsmToken::GreaterEqual:
1024 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001025 return 3;
1026
Jim Grosbachfbe16812011-08-20 16:24:13 +00001027 // Intermediate Precedence: <<, >>
1028 case AsmToken::LessLess:
1029 Kind = MCBinaryExpr::Shl;
1030 return 4;
1031 case AsmToken::GreaterGreater:
1032 Kind = MCBinaryExpr::Shr;
1033 return 4;
1034
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001035 // High Intermediate Precedence: +, -
1036 case AsmToken::Plus:
1037 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001038 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001039 case AsmToken::Minus:
1040 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001041 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001042
Jim Grosbachfbe16812011-08-20 16:24:13 +00001043 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001044 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001045 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001046 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001047 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001048 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001049 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001050 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001051 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001052 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001053 }
1054}
1055
1056
1057/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1058/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001059bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1060 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001061 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001062 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001063 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001064
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001065 // If the next token is lower precedence than we are allowed to eat, return
1066 // successfully with what we ate already.
1067 if (TokPrec < Precedence)
1068 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001069
Sean Callanan79ed1a82010-01-19 20:22:31 +00001070 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001071
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001072 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001073 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001074 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001075
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001076 // If BinOp binds less tightly with RHS than the operator after RHS, let
1077 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001078 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001079 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001080 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001081 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001082 }
1083
Daniel Dunbar475839e2009-06-29 20:37:27 +00001084 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001085 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001086 }
1087}
1088
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001089/// ParseStatement:
1090/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001091/// ::= Label* Directive ...Operands... EndOfStatement
1092/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001093bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001094 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001095 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001096 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001097 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001098 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001099
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001100 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001101 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001102 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001103 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001104 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001105 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001106 if (Lexer.is(AsmToken::Hash))
1107 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001108
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001109 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001110 if (Lexer.is(AsmToken::Integer)) {
1111 LocalLabelVal = getTok().getIntVal();
1112 if (LocalLabelVal < 0) {
1113 if (!TheCondState.Ignore)
1114 return TokError("unexpected token at start of statement");
1115 IDVal = "";
1116 }
1117 else {
1118 IDVal = getTok().getString();
1119 Lex(); // Consume the integer token to be used as an identifier token.
1120 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001121 if (!TheCondState.Ignore)
1122 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001123 }
1124 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001125
1126 } else if (Lexer.is(AsmToken::Dot)) {
1127 // Treat '.' as a valid identifier in this context.
1128 Lex();
1129 IDVal = ".";
1130
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001131 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001132 if (!TheCondState.Ignore)
1133 return TokError("unexpected token at start of statement");
1134 IDVal = "";
1135 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001136
Chris Lattner7834fac2010-04-17 18:14:27 +00001137 // Handle conditional assembly here before checking for skipping. We
1138 // have to do this so that .endif isn't skipped in a ".if 0" block for
1139 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001140 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001141 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001142 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001143 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1144 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001145 switch (DirKind) {
1146 default:
1147 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001148 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001149 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001150 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001151 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001152 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001153 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001154 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001155 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001156 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001157 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001158 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001159 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001160 case DK_IFNDEF:
1161 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001162 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001163 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001164 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001165 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001166 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001167 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001168 return ParseDirectiveEndIf(IDLoc);
1169 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001170
Chris Lattner7834fac2010-04-17 18:14:27 +00001171 // If we are in a ".if 0" block, ignore this statement.
Chad Rosier17feeec2012-10-20 00:47:08 +00001172 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001173 EatToEndOfStatement();
1174 return false;
1175 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001176
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001177 // FIXME: Recurse on local labels?
1178
1179 // See what kind of statement we have.
1180 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001181 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001182 CheckForValidSection();
1183
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001184 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001185 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001186
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001187 // Diagnose attempt to use '.' as a label.
1188 if (IDVal == ".")
1189 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1190
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001191 // Diagnose attempt to use a variable as a label.
1192 //
1193 // FIXME: Diagnostics. Note the location of the definition as a label.
1194 // FIXME: This doesn't diagnose assignment to a symbol which has been
1195 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001196 MCSymbol *Sym;
1197 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001198 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001199 else
1200 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001201 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001202 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001203
Daniel Dunbar959fd882009-08-26 22:13:22 +00001204 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001205 if (!ParsingInlineAsm)
1206 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001207
Kevin Enderby94c2e852011-12-09 18:09:40 +00001208 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001209 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001210 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001211 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1212 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001213
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001214 // Consume any end of statement token, if present, to avoid spurious
1215 // AddBlankLine calls().
1216 if (Lexer.is(AsmToken::EndOfStatement)) {
1217 Lex();
1218 if (Lexer.is(AsmToken::Eof))
1219 return false;
1220 }
1221
Eli Friedman2128aae2012-10-22 23:58:19 +00001222 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001223 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001224
Daniel Dunbar3f872332009-07-28 16:08:33 +00001225 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001226 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001227 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001228
Nico Weber4c4c7322011-01-28 03:04:41 +00001229 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001230
1231 default: // Normal instruction or directive.
1232 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001233 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001234
1235 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001236 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001237 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1238 return HandleMacroEntry(M, IDLoc);
1239 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001240
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001241 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001242
1243 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001244 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001245 // There are several entities interested in parsing directives:
1246 //
1247 // 1. The target-specific assembly parser. Some directives are target
1248 // specific or may potentially behave differently on certain targets.
1249 // 2. Asm parser extensions. For example, platform-specific parsers
1250 // (like the ELF parser) register themselves as extensions.
1251 // 3. The generic directive parser implemented by this class. These are
1252 // all the directives that behave in a target and platform independent
1253 // manner, or at least have a default behavior that's shared between
1254 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001255
Eli Bendersky6ee13082013-01-15 22:59:42 +00001256 // First query the target-specific parser. It will return 'true' if it
1257 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001258 if (!getTargetParser().ParseDirective(ID))
1259 return false;
1260
Eli Bendersky6ee13082013-01-15 22:59:42 +00001261 // Next, check the extention directive map to see if any extension has
1262 // registered itself to parse this directive.
1263 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1264 ExtensionDirectiveMap.lookup(IDVal);
1265 if (Handler.first)
1266 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1267
1268 // Finally, if no one else is interested in this directive, it must be
1269 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001270 switch (DirKind) {
1271 default:
1272 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001273 case DK_SET:
1274 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001275 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001276 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001277 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001278 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001279 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001280 case DK_ASCIZ:
1281 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001282 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001283 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001284 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001285 case DK_SHORT:
1286 case DK_VALUE:
1287 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001288 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001289 case DK_LONG:
1290 case DK_INT:
1291 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001292 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001293 case DK_QUAD:
1294 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001295 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001296 case DK_SINGLE:
1297 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001298 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001299 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001300 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001301 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001302 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1303 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1304 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001305 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001306 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1307 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1308 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001309 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001313 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001314 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001315 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001316 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001317 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001318 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001319 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001320 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001322 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001323 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001327 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001328 EatToEndOfStatement(); // .extern is the default, ignore it.
1329 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001330 case DK_GLOBL:
1331 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001332 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001335 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001339 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001340 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001341 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001342 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001343 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001344 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001345 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001346 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001347 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001350 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001351 case DK_COMM:
1352 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001353 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001354 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001355 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001356 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001357 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001358 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001359 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001360 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001361 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001362 case DK_CODE16:
1363 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001364 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001365 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001366 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001367 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001368 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001369 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001370 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001371 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001372 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001373 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001374 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001375 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001376 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001377 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001378 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001379 case DK_SLEB128:
1380 return ParseDirectiveLEB128(true);
1381 case DK_ULEB128:
1382 return ParseDirectiveLEB128(false);
1383 case DK_SPACE:
1384 case DK_SKIP:
1385 return ParseDirectiveSpace(IDVal);
1386 case DK_FILE:
1387 return ParseDirectiveFile(IDLoc);
1388 case DK_LINE:
1389 return ParseDirectiveLine();
1390 case DK_LOC:
1391 return ParseDirectiveLoc();
1392 case DK_STABS:
1393 return ParseDirectiveStabs();
1394 case DK_CFI_SECTIONS:
1395 return ParseDirectiveCFISections();
1396 case DK_CFI_STARTPROC:
1397 return ParseDirectiveCFIStartProc();
1398 case DK_CFI_ENDPROC:
1399 return ParseDirectiveCFIEndProc();
1400 case DK_CFI_DEF_CFA:
1401 return ParseDirectiveCFIDefCfa(IDLoc);
1402 case DK_CFI_DEF_CFA_OFFSET:
1403 return ParseDirectiveCFIDefCfaOffset();
1404 case DK_CFI_ADJUST_CFA_OFFSET:
1405 return ParseDirectiveCFIAdjustCfaOffset();
1406 case DK_CFI_DEF_CFA_REGISTER:
1407 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1408 case DK_CFI_OFFSET:
1409 return ParseDirectiveCFIOffset(IDLoc);
1410 case DK_CFI_REL_OFFSET:
1411 return ParseDirectiveCFIRelOffset(IDLoc);
1412 case DK_CFI_PERSONALITY:
1413 return ParseDirectiveCFIPersonalityOrLsda(true);
1414 case DK_CFI_LSDA:
1415 return ParseDirectiveCFIPersonalityOrLsda(false);
1416 case DK_CFI_REMEMBER_STATE:
1417 return ParseDirectiveCFIRememberState();
1418 case DK_CFI_RESTORE_STATE:
1419 return ParseDirectiveCFIRestoreState();
1420 case DK_CFI_SAME_VALUE:
1421 return ParseDirectiveCFISameValue(IDLoc);
1422 case DK_CFI_RESTORE:
1423 return ParseDirectiveCFIRestore(IDLoc);
1424 case DK_CFI_ESCAPE:
1425 return ParseDirectiveCFIEscape();
1426 case DK_CFI_SIGNAL_FRAME:
1427 return ParseDirectiveCFISignalFrame();
1428 case DK_CFI_UNDEFINED:
1429 return ParseDirectiveCFIUndefined(IDLoc);
1430 case DK_CFI_REGISTER:
1431 return ParseDirectiveCFIRegister(IDLoc);
1432 case DK_MACROS_ON:
1433 case DK_MACROS_OFF:
1434 return ParseDirectiveMacrosOnOff(IDVal);
1435 case DK_MACRO:
1436 return ParseDirectiveMacro(IDLoc);
1437 case DK_ENDM:
1438 case DK_ENDMACRO:
1439 return ParseDirectiveEndMacro(IDVal);
1440 case DK_PURGEM:
1441 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001442 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001443
Jim Grosbach686c0182012-05-01 18:38:27 +00001444 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001445 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001446
Eli Friedman2128aae2012-10-22 23:58:19 +00001447 // _emit
1448 if (ParsingInlineAsm && IDVal == "_emit")
1449 return ParseDirectiveEmit(IDLoc, Info);
1450
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001451 CheckForValidSection();
1452
Chris Lattnera7f13542010-05-19 23:34:33 +00001453 // Canonicalize the opcode to lower case.
Chad Rosier8f138d12012-10-15 17:19:13 +00001454 SmallString<128> OpcodeStr;
Chris Lattnera7f13542010-05-19 23:34:33 +00001455 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
Chad Rosier8f138d12012-10-15 17:19:13 +00001456 OpcodeStr.push_back(tolower(IDVal[i]));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001457
Chad Rosier6a020a72012-10-25 20:41:34 +00001458 ParseInstructionInfo IInfo(Info.AsmRewrites);
1459 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr.str(),
1460 IDLoc,Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001461 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001462
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001463 // Dump the parsed representation, if requested.
1464 if (getShowParsedOperands()) {
1465 SmallString<256> Str;
1466 raw_svector_ostream OS(Str);
1467 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001468 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001469 if (i != 0)
1470 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001471 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001472 }
1473 OS << "]";
1474
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001475 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001476 }
1477
Kevin Enderby613b7572011-11-01 22:27:22 +00001478 // If we are generating dwarf for assembly source files and the current
1479 // section is the initial text section then generate a .loc directive for
1480 // the instruction.
1481 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001482 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001483
1484 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1485
1486 // If we previously parsed a cpp hash file line comment then make sure the
1487 // current Dwarf File is for the CppHashFilename if not then emit the
1488 // Dwarf File table for it and adjust the line number for the .loc.
1489 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1490 getContext().getMCDwarfFiles();
1491 if (CppHashFilename.size() != 0) {
1492 if(MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
1493 CppHashFilename)
Eric Christopher2318ba12012-12-18 00:30:54 +00001494 getStreamer().EmitDwarfFileDirective(
1495 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001496
Kevin Enderby32c1a822012-11-05 21:55:41 +00001497 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001498 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
1499 }
1500
Kevin Enderby613b7572011-11-01 22:27:22 +00001501 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001502 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001503 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001504 StringRef());
1505 }
1506
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001507 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001508 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001509 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001510 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1511 Info.ParsedOperands,
1512 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001513 ParsingInlineAsm);
1514 }
Chris Lattner98986712010-01-14 22:21:20 +00001515
Chris Lattnercbf8a982010-09-11 16:18:25 +00001516 // Don't skip the rest of the line, the instruction parser is responsible for
1517 // that.
1518 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001519}
Chris Lattner9a023f72009-06-24 04:43:34 +00001520
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001521/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1522/// since they may not be able to be tokenized to get to the end of line token.
1523void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001524 if (!Lexer.is(AsmToken::EndOfStatement))
1525 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001526 // Eat EOL.
1527 Lex();
1528}
1529
1530/// ParseCppHashLineFilenameComment as this:
1531/// ::= # number "filename"
1532/// or just as a full line comment if it doesn't have a number and a string.
1533bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1534 Lex(); // Eat the hash token.
1535
1536 if (getLexer().isNot(AsmToken::Integer)) {
1537 // Consume the line since in cases it is not a well-formed line directive,
1538 // as if were simply a full line comment.
1539 EatToEndOfLine();
1540 return false;
1541 }
1542
1543 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001544 Lex();
1545
1546 if (getLexer().isNot(AsmToken::String)) {
1547 EatToEndOfLine();
1548 return false;
1549 }
1550
1551 StringRef Filename = getTok().getString();
1552 // Get rid of the enclosing quotes.
1553 Filename = Filename.substr(1, Filename.size()-2);
1554
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001555 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1556 CppHashLoc = L;
1557 CppHashFilename = Filename;
1558 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001559 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001560
1561 // Ignore any trailing characters, they're just comment.
1562 EatToEndOfLine();
1563 return false;
1564}
1565
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001566/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001567/// for the Filename and LineNo if any in the diagnostic.
1568void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1569 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1570 raw_ostream &OS = errs();
1571
1572 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1573 const SMLoc &DiagLoc = Diag.getLoc();
1574 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1575 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1576
1577 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1578 // before printing the message.
1579 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001580 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001581 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1582 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1583 }
1584
Eric Christopher2318ba12012-12-18 00:30:54 +00001585 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001586 // manager changed or buffer changed (like in a nested include) then just
1587 // print the normal diagnostic using its Filename and LineNo.
1588 if (!Parser->CppHashLineNumber ||
1589 &DiagSrcMgr != &Parser->SrcMgr ||
1590 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001591 if (Parser->SavedDiagHandler)
1592 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1593 else
1594 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001595 return;
1596 }
1597
Eric Christopher2318ba12012-12-18 00:30:54 +00001598 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001599 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1600 // the diagnostic.
1601 const std::string Filename = Parser->CppHashFilename;
1602
1603 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1604 int CppHashLocLineNo =
1605 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1606 int LineNo = Parser->CppHashLineNumber - 1 +
1607 (DiagLocLineNo - CppHashLocLineNo);
1608
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001609 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1610 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001611 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001612 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001613
Benjamin Kramer04a04262011-10-16 10:48:29 +00001614 if (Parser->SavedDiagHandler)
1615 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1616 else
1617 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001618}
1619
Rafael Espindola799aacf2012-08-21 18:29:30 +00001620// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1621// difference being that that function accepts '@' as part of identifiers and
1622// we can't do that. AsmLexer.cpp should probably be changed to handle
1623// '@' as a special case when needed.
1624static bool isIdentifierChar(char c) {
1625 return isalnum(c) || c == '_' || c == '$' || c == '.';
1626}
1627
Rafael Espindola761cb062012-06-03 23:57:14 +00001628bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001629 const MCAsmMacroParameters &Parameters,
1630 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001631 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001632 unsigned NParameters = Parameters.size();
1633 if (NParameters != 0 && NParameters != A.size())
1634 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001635
Preston Gurd7b6f2032012-09-19 20:36:12 +00001636 // A macro without parameters is handled differently on Darwin:
1637 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001638 while (!Body.empty()) {
1639 // Scan for the next substitution.
1640 std::size_t End = Body.size(), Pos = 0;
1641 for (; Pos != End; ++Pos) {
1642 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001643 if (!NParameters) {
1644 // This macro has no parameters, look for $0, $1, etc.
1645 if (Body[Pos] != '$' || Pos + 1 == End)
1646 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001647
Rafael Espindola65366442011-06-05 02:43:45 +00001648 char Next = Body[Pos + 1];
1649 if (Next == '$' || Next == 'n' || isdigit(Next))
1650 break;
1651 } else {
1652 // This macro has parameters, look for \foo, \bar, etc.
1653 if (Body[Pos] == '\\' && Pos + 1 != End)
1654 break;
1655 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001656 }
1657
1658 // Add the prefix.
1659 OS << Body.slice(0, Pos);
1660
1661 // Check if we reached the end.
1662 if (Pos == End)
1663 break;
1664
Rafael Espindola65366442011-06-05 02:43:45 +00001665 if (!NParameters) {
1666 switch (Body[Pos+1]) {
1667 // $$ => $
1668 case '$':
1669 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001670 break;
1671
Rafael Espindola65366442011-06-05 02:43:45 +00001672 // $n => number of arguments
1673 case 'n':
1674 OS << A.size();
1675 break;
1676
1677 // $[0-9] => argument
1678 default: {
1679 // Missing arguments are ignored.
1680 unsigned Index = Body[Pos+1] - '0';
1681 if (Index >= A.size())
1682 break;
1683
1684 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001685 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001686 ie = A[Index].end(); it != ie; ++it)
1687 OS << it->getString();
1688 break;
1689 }
1690 }
1691 Pos += 2;
1692 } else {
1693 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001694 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001695 ++I;
1696
1697 const char *Begin = Body.data() + Pos +1;
1698 StringRef Argument(Begin, I - (Pos +1));
1699 unsigned Index = 0;
1700 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001701 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001702 break;
1703
Preston Gurd7b6f2032012-09-19 20:36:12 +00001704 if (Index == NParameters) {
1705 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1706 Pos += 3;
1707 else {
1708 OS << '\\' << Argument;
1709 Pos = I;
1710 }
1711 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001712 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001713 ie = A[Index].end(); it != ie; ++it)
1714 if (it->getKind() == AsmToken::String)
1715 OS << it->getStringContents();
1716 else
1717 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001718
Preston Gurd7b6f2032012-09-19 20:36:12 +00001719 Pos += 1 + Argument.size();
1720 }
Rafael Espindola65366442011-06-05 02:43:45 +00001721 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001722 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001723 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001724 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001725
Rafael Espindola65366442011-06-05 02:43:45 +00001726 return false;
1727}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001728
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001729MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001730 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001731 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001732 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1733 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001734{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001735}
1736
Preston Gurd7b6f2032012-09-19 20:36:12 +00001737static bool IsOperator(AsmToken::TokenKind kind)
1738{
1739 switch (kind)
1740 {
1741 default:
1742 return false;
1743 case AsmToken::Plus:
1744 case AsmToken::Minus:
1745 case AsmToken::Tilde:
1746 case AsmToken::Slash:
1747 case AsmToken::Star:
1748 case AsmToken::Dot:
1749 case AsmToken::Equal:
1750 case AsmToken::EqualEqual:
1751 case AsmToken::Pipe:
1752 case AsmToken::PipePipe:
1753 case AsmToken::Caret:
1754 case AsmToken::Amp:
1755 case AsmToken::AmpAmp:
1756 case AsmToken::Exclaim:
1757 case AsmToken::ExclaimEqual:
1758 case AsmToken::Percent:
1759 case AsmToken::Less:
1760 case AsmToken::LessEqual:
1761 case AsmToken::LessLess:
1762 case AsmToken::LessGreater:
1763 case AsmToken::Greater:
1764 case AsmToken::GreaterEqual:
1765 case AsmToken::GreaterGreater:
1766 return true;
1767 }
1768}
1769
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001770bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001771 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001772 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001773 unsigned AddTokens = 0;
1774
1775 // gas accepts arguments separated by whitespace, except on Darwin
1776 if (!IsDarwin)
1777 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001778
1779 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001780 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1781 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001782 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001783 }
1784
1785 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1786 // Spaces and commas cannot be mixed to delimit parameters
1787 if (ArgumentDelimiter == AsmToken::Eof)
1788 ArgumentDelimiter = AsmToken::Comma;
1789 else if (ArgumentDelimiter != AsmToken::Comma) {
1790 Lexer.setSkipSpace(true);
1791 return TokError("expected ' ' for macro argument separator");
1792 }
1793 break;
1794 }
1795
1796 if (Lexer.is(AsmToken::Space)) {
1797 Lex(); // Eat spaces
1798
1799 // Spaces can delimit parameters, but could also be part an expression.
1800 // If the token after a space is an operator, add the token and the next
1801 // one into this argument
1802 if (ArgumentDelimiter == AsmToken::Space ||
1803 ArgumentDelimiter == AsmToken::Eof) {
1804 if (IsOperator(Lexer.getKind())) {
1805 // Check to see whether the token is used as an operator,
1806 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001807 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001808 if (*NextChar == ' ')
1809 AddTokens = 2;
1810 }
1811
1812 if (!AddTokens && ParenLevel == 0) {
1813 if (ArgumentDelimiter == AsmToken::Eof &&
1814 !IsOperator(Lexer.getKind()))
1815 ArgumentDelimiter = AsmToken::Space;
1816 break;
1817 }
1818 }
1819 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001820
1821 // HandleMacroEntry relies on not advancing the lexer here
1822 // to be able to fill in the remaining default parameter values
1823 if (Lexer.is(AsmToken::EndOfStatement))
1824 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001825
1826 // Adjust the current parentheses level.
1827 if (Lexer.is(AsmToken::LParen))
1828 ++ParenLevel;
1829 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1830 --ParenLevel;
1831
1832 // Append the token to the current argument list.
1833 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001834 if (AddTokens)
1835 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001836 Lex();
1837 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001838
1839 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001840 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001841 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001842 return false;
1843}
1844
1845// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001846bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001847 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001848 // Argument delimiter is initially unknown. It will be set by
1849 // ParseMacroArgument()
1850 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001851
1852 // Parse two kinds of macro invocations:
1853 // - macros defined without any parameters accept an arbitrary number of them
1854 // - macros defined with parameters accept at most that many of them
1855 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1856 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001857 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001858
Preston Gurd7b6f2032012-09-19 20:36:12 +00001859 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001860 return true;
1861
Preston Gurd6c9176a2012-09-19 20:29:04 +00001862 if (!MA.empty() || !NParameters)
1863 A.push_back(MA);
1864 else if (NParameters) {
1865 if (!M->Parameters[Parameter].second.empty())
1866 A.push_back(M->Parameters[Parameter].second);
1867 }
Jim Grosbach97146442012-07-30 22:44:17 +00001868
Preston Gurd6c9176a2012-09-19 20:29:04 +00001869 // At the end of the statement, fill in remaining arguments that have
1870 // default values. If there aren't any, then the next argument is
1871 // required but missing
1872 if (Lexer.is(AsmToken::EndOfStatement)) {
1873 if (NParameters && Parameter < NParameters - 1) {
1874 if (M->Parameters[Parameter + 1].second.empty())
1875 return TokError("macro argument '" +
1876 Twine(M->Parameters[Parameter + 1].first) +
1877 "' is missing");
1878 else
1879 continue;
1880 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001881 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001882 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001883
1884 if (Lexer.is(AsmToken::Comma))
1885 Lex();
1886 }
1887 return TokError("Too many arguments");
1888}
1889
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001890const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1891 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1892 return (I == MacroMap.end()) ? NULL : I->getValue();
1893}
1894
1895void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1896 MacroMap[Name] = new MCAsmMacro(Macro);
1897}
1898
1899void AsmParser::UndefineMacro(StringRef Name) {
1900 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1901 if (I != MacroMap.end()) {
1902 delete I->getValue();
1903 MacroMap.erase(I);
1904 }
1905}
1906
1907bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001908 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1909 // this, although we should protect against infinite loops.
1910 if (ActiveMacros.size() == 20)
1911 return TokError("macros cannot be nested more than 20 levels deep");
1912
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001913 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001914 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001915 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001916
Jim Grosbach97146442012-07-30 22:44:17 +00001917 // Remove any trailing empty arguments. Do this after-the-fact as we have
1918 // to keep empty arguments in the middle of the list or positionality
1919 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001920 while (!A.empty() && A.back().empty())
1921 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001922
Rafael Espindola65366442011-06-05 02:43:45 +00001923 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1924 // to hold the macro body with substitutions.
1925 SmallString<256> Buf;
1926 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001927 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001928
Rafael Espindola8a403d32012-08-08 14:51:03 +00001929 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001930 return true;
1931
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001932 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001933 // instantiation.
1934 OS << ".endmacro\n";
1935
Rafael Espindola65366442011-06-05 02:43:45 +00001936 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001937 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001938
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001939 // Create the macro instantiation object and add to the current macro
1940 // instantiation stack.
1941 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001942 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001943 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001944 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001945 ActiveMacros.push_back(MI);
1946
1947 // Jump to the macro instantiation and prime the lexer.
1948 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1949 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1950 Lex();
1951
1952 return false;
1953}
1954
1955void AsmParser::HandleMacroExit() {
1956 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001957 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001958 Lex();
1959
1960 // Pop the instantiation entry.
1961 delete ActiveMacros.back();
1962 ActiveMacros.pop_back();
1963}
1964
Rafael Espindolae71cc862012-01-28 05:57:00 +00001965static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001966 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001967 case MCExpr::Binary: {
1968 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1969 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001970 break;
1971 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001972 case MCExpr::Target:
1973 case MCExpr::Constant:
1974 return false;
1975 case MCExpr::SymbolRef: {
1976 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001977 if (S.isVariable())
1978 return IsUsedIn(Sym, S.getVariableValue());
1979 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001980 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001981 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001982 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001983 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001984
1985 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001986}
1987
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001988bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1989 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001990 // FIXME: Use better location, we should use proper tokens.
1991 SMLoc EqualLoc = Lexer.getLoc();
1992
Daniel Dunbar821e3332009-08-31 08:09:28 +00001993 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001994 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001995 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001996
Rafael Espindolae71cc862012-01-28 05:57:00 +00001997 // Note: we don't count b as used in "a = b". This is to allow
1998 // a = b
1999 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002000
Daniel Dunbar3f872332009-07-28 16:08:33 +00002001 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002002 return TokError("unexpected token in assignment");
2003
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002004 // Error on assignment to '.'.
2005 if (Name == ".") {
2006 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2007 "(use '.space' or '.org').)"));
2008 }
2009
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002010 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002011 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002012
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002013 // Validate that the LHS is allowed to be a variable (either it has not been
2014 // used as a symbol, or it is an absolute symbol).
2015 MCSymbol *Sym = getContext().LookupSymbol(Name);
2016 if (Sym) {
2017 // Diagnose assignment to a label.
2018 //
2019 // FIXME: Diagnostics. Note the location of the definition as a label.
2020 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002021 if (IsUsedIn(Sym, Value))
2022 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2023 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002024 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002025 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2026 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002027 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002028 return Error(EqualLoc, "redefinition of '" + Name + "'");
2029 else if (!Sym->isVariable())
2030 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002031 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002032 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2033 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002034
2035 // Don't count these checks as uses.
2036 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002037 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002038 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002039
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002040 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002041
2042 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002043 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002044 if (NoDeadStrip)
2045 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2046
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002047
2048 return false;
2049}
2050
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002051/// ParseIdentifier:
2052/// ::= identifier
2053/// ::= string
2054bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002055 // The assembler has relaxed rules for accepting identifiers, in particular we
2056 // allow things like '.globl $foo', which would normally be separate
2057 // tokens. At this level, we have already lexed so we cannot (currently)
2058 // handle this as a context dependent token, instead we detect adjacent tokens
2059 // and return the combined identifier.
2060 if (Lexer.is(AsmToken::Dollar)) {
2061 SMLoc DollarLoc = getLexer().getLoc();
2062
2063 // Consume the dollar sign, and check for a following identifier.
2064 Lex();
2065 if (Lexer.isNot(AsmToken::Identifier))
2066 return true;
2067
2068 // We have a '$' followed by an identifier, make sure they are adjacent.
2069 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2070 return true;
2071
2072 // Construct the joined identifier and consume the token.
2073 Res = StringRef(DollarLoc.getPointer(),
2074 getTok().getIdentifier().size() + 1);
2075 Lex();
2076 return false;
2077 }
2078
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002079 if (Lexer.isNot(AsmToken::Identifier) &&
2080 Lexer.isNot(AsmToken::String))
2081 return true;
2082
Sean Callanan18b83232010-01-19 21:44:56 +00002083 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002084
Sean Callanan79ed1a82010-01-19 20:22:31 +00002085 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002086
2087 return false;
2088}
2089
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002090/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002091/// ::= .equ identifier ',' expression
2092/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002093/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002094bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002095 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002096
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002097 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002098 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002099
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002100 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002101 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002102 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002103
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002104 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002105}
2106
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002107bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002108 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002109
2110 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002111 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002112 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2113 if (Str[i] != '\\') {
2114 Data += Str[i];
2115 continue;
2116 }
2117
2118 // Recognize escaped characters. Note that this escape semantics currently
2119 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2120 ++i;
2121 if (i == e)
2122 return TokError("unexpected backslash at end of string");
2123
2124 // Recognize octal sequences.
2125 if ((unsigned) (Str[i] - '0') <= 7) {
2126 // Consume up to three octal characters.
2127 unsigned Value = Str[i] - '0';
2128
2129 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2130 ++i;
2131 Value = Value * 8 + (Str[i] - '0');
2132
2133 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2134 ++i;
2135 Value = Value * 8 + (Str[i] - '0');
2136 }
2137 }
2138
2139 if (Value > 255)
2140 return TokError("invalid octal escape sequence (out of range)");
2141
2142 Data += (unsigned char) Value;
2143 continue;
2144 }
2145
2146 // Otherwise recognize individual escapes.
2147 switch (Str[i]) {
2148 default:
2149 // Just reject invalid escape sequences for now.
2150 return TokError("invalid escape sequence (unrecognized character)");
2151
2152 case 'b': Data += '\b'; break;
2153 case 'f': Data += '\f'; break;
2154 case 'n': Data += '\n'; break;
2155 case 'r': Data += '\r'; break;
2156 case 't': Data += '\t'; break;
2157 case '"': Data += '"'; break;
2158 case '\\': Data += '\\'; break;
2159 }
2160 }
2161
2162 return false;
2163}
2164
Daniel Dunbara0d14262009-06-24 23:30:00 +00002165/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002166/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2167bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002168 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002169 CheckForValidSection();
2170
Daniel Dunbara0d14262009-06-24 23:30:00 +00002171 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002172 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002173 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002174
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002175 std::string Data;
2176 if (ParseEscapedString(Data))
2177 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002178
2179 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002180 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002181 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2182
Sean Callanan79ed1a82010-01-19 20:22:31 +00002183 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002184
2185 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002186 break;
2187
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002188 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002189 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002190 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002191 }
2192 }
2193
Sean Callanan79ed1a82010-01-19 20:22:31 +00002194 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002195 return false;
2196}
2197
2198/// ParseDirectiveValue
2199/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2200bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002201 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002202 CheckForValidSection();
2203
Daniel Dunbara0d14262009-06-24 23:30:00 +00002204 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002205 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002206 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002207 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002208 return true;
2209
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002210 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002211 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2212 assert(Size <= 8 && "Invalid size");
2213 uint64_t IntValue = MCE->getValue();
2214 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2215 return Error(ExprLoc, "literal value out of range for directive");
2216 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2217 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002218 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002219
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002220 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002221 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002222
Daniel Dunbara0d14262009-06-24 23:30:00 +00002223 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002224 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002225 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002226 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002227 }
2228 }
2229
Sean Callanan79ed1a82010-01-19 20:22:31 +00002230 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002231 return false;
2232}
2233
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002234/// ParseDirectiveRealValue
2235/// ::= (.single | .double) [ expression (, expression)* ]
2236bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2237 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2238 CheckForValidSection();
2239
2240 for (;;) {
2241 // We don't truly support arithmetic on floating point expressions, so we
2242 // have to manually parse unary prefixes.
2243 bool IsNeg = false;
2244 if (getLexer().is(AsmToken::Minus)) {
2245 Lex();
2246 IsNeg = true;
2247 } else if (getLexer().is(AsmToken::Plus))
2248 Lex();
2249
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002250 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002251 getLexer().isNot(AsmToken::Real) &&
2252 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002253 return TokError("unexpected token in directive");
2254
2255 // Convert to an APFloat.
2256 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002257 StringRef IDVal = getTok().getString();
2258 if (getLexer().is(AsmToken::Identifier)) {
2259 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2260 Value = APFloat::getInf(Semantics);
2261 else if (!IDVal.compare_lower("nan"))
2262 Value = APFloat::getNaN(Semantics, false, ~0);
2263 else
2264 return TokError("invalid floating point literal");
2265 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002266 APFloat::opInvalidOp)
2267 return TokError("invalid floating point literal");
2268 if (IsNeg)
2269 Value.changeSign();
2270
2271 // Consume the numeric token.
2272 Lex();
2273
2274 // Emit the value as an integer.
2275 APInt AsInt = Value.bitcastToAPInt();
2276 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2277 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2278
2279 if (getLexer().is(AsmToken::EndOfStatement))
2280 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002281
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002282 if (getLexer().isNot(AsmToken::Comma))
2283 return TokError("unexpected token in directive");
2284 Lex();
2285 }
2286 }
2287
2288 Lex();
2289 return false;
2290}
2291
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002292/// ParseDirectiveZero
2293/// ::= .zero expression
2294bool AsmParser::ParseDirectiveZero() {
2295 CheckForValidSection();
2296
2297 int64_t NumBytes;
2298 if (ParseAbsoluteExpression(NumBytes))
2299 return true;
2300
Rafael Espindolae452b172010-10-05 19:42:57 +00002301 int64_t Val = 0;
2302 if (getLexer().is(AsmToken::Comma)) {
2303 Lex();
2304 if (ParseAbsoluteExpression(Val))
2305 return true;
2306 }
2307
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002308 if (getLexer().isNot(AsmToken::EndOfStatement))
2309 return TokError("unexpected token in '.zero' directive");
2310
2311 Lex();
2312
Rafael Espindolae452b172010-10-05 19:42:57 +00002313 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002314
2315 return false;
2316}
2317
Daniel Dunbara0d14262009-06-24 23:30:00 +00002318/// ParseDirectiveFill
2319/// ::= .fill expression , expression , expression
2320bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002321 CheckForValidSection();
2322
Daniel Dunbara0d14262009-06-24 23:30:00 +00002323 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002324 if (ParseAbsoluteExpression(NumValues))
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 FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002332 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002333 return true;
2334
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002335 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002336 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002337 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002338
Daniel Dunbara0d14262009-06-24 23:30:00 +00002339 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002340 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002341 return true;
2342
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002343 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002344 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002345
Sean Callanan79ed1a82010-01-19 20:22:31 +00002346 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002347
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002348 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2349 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002350
2351 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002352 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002353
2354 return false;
2355}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002356
2357/// ParseDirectiveOrg
2358/// ::= .org expression [ , expression ]
2359bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002360 CheckForValidSection();
2361
Daniel Dunbar821e3332009-08-31 08:09:28 +00002362 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002363 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002364 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002365 return true;
2366
2367 // Parse optional fill expression.
2368 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002369 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2370 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002371 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002372 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002373
Daniel Dunbar475839e2009-06-29 20:37:27 +00002374 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002375 return true;
2376
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002377 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002378 return TokError("unexpected token in '.org' directive");
2379 }
2380
Sean Callanan79ed1a82010-01-19 20:22:31 +00002381 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002382
Jim Grosbachebd4c052012-01-27 00:37:08 +00002383 // Only limited forms of relocatable expressions are accepted here, it
2384 // has to be relative to the current section. The streamer will return
2385 // 'true' if the expression wasn't evaluatable.
2386 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2387 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002388
2389 return false;
2390}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002391
2392/// ParseDirectiveAlign
2393/// ::= {.align, ...} expression [ , expression [ , expression ]]
2394bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002395 CheckForValidSection();
2396
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002397 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002398 int64_t Alignment;
2399 if (ParseAbsoluteExpression(Alignment))
2400 return true;
2401
2402 SMLoc MaxBytesLoc;
2403 bool HasFillExpr = false;
2404 int64_t FillExpr = 0;
2405 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002406 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2407 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002408 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002409 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002410
2411 // The fill expression can be omitted while specifying a maximum number of
2412 // alignment bytes, e.g:
2413 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002414 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002415 HasFillExpr = true;
2416 if (ParseAbsoluteExpression(FillExpr))
2417 return true;
2418 }
2419
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002420 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2421 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002422 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002423 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002424
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002425 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002426 if (ParseAbsoluteExpression(MaxBytesToFill))
2427 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002428
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002429 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002430 return TokError("unexpected token in directive");
2431 }
2432 }
2433
Sean Callanan79ed1a82010-01-19 20:22:31 +00002434 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002435
Daniel Dunbar648ac512010-05-17 21:54:30 +00002436 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002437 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002438
2439 // Compute alignment in bytes.
2440 if (IsPow2) {
2441 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002442 if (Alignment >= 32) {
2443 Error(AlignmentLoc, "invalid alignment value");
2444 Alignment = 31;
2445 }
2446
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002447 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002448 }
2449
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002450 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002451 if (MaxBytesLoc.isValid()) {
2452 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002453 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2454 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002455 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002456 }
2457
2458 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002459 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2460 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002461 MaxBytesToFill = 0;
2462 }
2463 }
2464
Daniel Dunbar648ac512010-05-17 21:54:30 +00002465 // Check whether we should use optimal code alignment for this .align
2466 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002467 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002468 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2469 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002470 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002471 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002472 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002473 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2474 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002475 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002476
2477 return false;
2478}
2479
Eli Bendersky6ee13082013-01-15 22:59:42 +00002480/// ParseDirectiveFile
2481/// ::= .file [number] filename
2482/// ::= .file number directory filename
2483bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2484 // FIXME: I'm not sure what this is.
2485 int64_t FileNumber = -1;
2486 SMLoc FileNumberLoc = getLexer().getLoc();
2487 if (getLexer().is(AsmToken::Integer)) {
2488 FileNumber = getTok().getIntVal();
2489 Lex();
2490
2491 if (FileNumber < 1)
2492 return TokError("file number less than one");
2493 }
2494
2495 if (getLexer().isNot(AsmToken::String))
2496 return TokError("unexpected token in '.file' directive");
2497
2498 // Usually the directory and filename together, otherwise just the directory.
2499 StringRef Path = getTok().getString();
2500 Path = Path.substr(1, Path.size()-2);
2501 Lex();
2502
2503 StringRef Directory;
2504 StringRef Filename;
2505 if (getLexer().is(AsmToken::String)) {
2506 if (FileNumber == -1)
2507 return TokError("explicit path specified, but no file number");
2508 Filename = getTok().getString();
2509 Filename = Filename.substr(1, Filename.size()-2);
2510 Directory = Path;
2511 Lex();
2512 } else {
2513 Filename = Path;
2514 }
2515
2516 if (getLexer().isNot(AsmToken::EndOfStatement))
2517 return TokError("unexpected token in '.file' directive");
2518
2519 if (FileNumber == -1)
2520 getStreamer().EmitFileDirective(Filename);
2521 else {
2522 if (getContext().getGenDwarfForAssembly() == true)
2523 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2524 "used to generate dwarf debug info for assembly code");
2525
2526 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2527 Error(FileNumberLoc, "file number already allocated");
2528 }
2529
2530 return false;
2531}
2532
2533/// ParseDirectiveLine
2534/// ::= .line [number]
2535bool AsmParser::ParseDirectiveLine() {
2536 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2537 if (getLexer().isNot(AsmToken::Integer))
2538 return TokError("unexpected token in '.line' directive");
2539
2540 int64_t LineNumber = getTok().getIntVal();
2541 (void) LineNumber;
2542 Lex();
2543
2544 // FIXME: Do something with the .line.
2545 }
2546
2547 if (getLexer().isNot(AsmToken::EndOfStatement))
2548 return TokError("unexpected token in '.line' directive");
2549
2550 return false;
2551}
2552
2553/// ParseDirectiveLoc
2554/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2555/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2556/// The first number is a file number, must have been previously assigned with
2557/// a .file directive, the second number is the line number and optionally the
2558/// third number is a column position (zero if not specified). The remaining
2559/// optional items are .loc sub-directives.
2560bool AsmParser::ParseDirectiveLoc() {
2561 if (getLexer().isNot(AsmToken::Integer))
2562 return TokError("unexpected token in '.loc' directive");
2563 int64_t FileNumber = getTok().getIntVal();
2564 if (FileNumber < 1)
2565 return TokError("file number less than one in '.loc' directive");
2566 if (!getContext().isValidDwarfFileNumber(FileNumber))
2567 return TokError("unassigned file number in '.loc' directive");
2568 Lex();
2569
2570 int64_t LineNumber = 0;
2571 if (getLexer().is(AsmToken::Integer)) {
2572 LineNumber = getTok().getIntVal();
2573 if (LineNumber < 1)
2574 return TokError("line number less than one in '.loc' directive");
2575 Lex();
2576 }
2577
2578 int64_t ColumnPos = 0;
2579 if (getLexer().is(AsmToken::Integer)) {
2580 ColumnPos = getTok().getIntVal();
2581 if (ColumnPos < 0)
2582 return TokError("column position less than zero in '.loc' directive");
2583 Lex();
2584 }
2585
2586 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2587 unsigned Isa = 0;
2588 int64_t Discriminator = 0;
2589 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2590 for (;;) {
2591 if (getLexer().is(AsmToken::EndOfStatement))
2592 break;
2593
2594 StringRef Name;
2595 SMLoc Loc = getTok().getLoc();
2596 if (ParseIdentifier(Name))
2597 return TokError("unexpected token in '.loc' directive");
2598
2599 if (Name == "basic_block")
2600 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2601 else if (Name == "prologue_end")
2602 Flags |= DWARF2_FLAG_PROLOGUE_END;
2603 else if (Name == "epilogue_begin")
2604 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2605 else if (Name == "is_stmt") {
2606 Loc = getTok().getLoc();
2607 const MCExpr *Value;
2608 if (ParseExpression(Value))
2609 return true;
2610 // The expression must be the constant 0 or 1.
2611 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2612 int Value = MCE->getValue();
2613 if (Value == 0)
2614 Flags &= ~DWARF2_FLAG_IS_STMT;
2615 else if (Value == 1)
2616 Flags |= DWARF2_FLAG_IS_STMT;
2617 else
2618 return Error(Loc, "is_stmt value not 0 or 1");
2619 }
2620 else {
2621 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2622 }
2623 }
2624 else if (Name == "isa") {
2625 Loc = getTok().getLoc();
2626 const MCExpr *Value;
2627 if (ParseExpression(Value))
2628 return true;
2629 // The expression must be a constant greater or equal to 0.
2630 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2631 int Value = MCE->getValue();
2632 if (Value < 0)
2633 return Error(Loc, "isa number less than zero");
2634 Isa = Value;
2635 }
2636 else {
2637 return Error(Loc, "isa number not a constant value");
2638 }
2639 }
2640 else if (Name == "discriminator") {
2641 if (ParseAbsoluteExpression(Discriminator))
2642 return true;
2643 }
2644 else {
2645 return Error(Loc, "unknown sub-directive in '.loc' directive");
2646 }
2647
2648 if (getLexer().is(AsmToken::EndOfStatement))
2649 break;
2650 }
2651 }
2652
2653 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2654 Isa, Discriminator, StringRef());
2655
2656 return false;
2657}
2658
2659/// ParseDirectiveStabs
2660/// ::= .stabs string, number, number, number
2661bool AsmParser::ParseDirectiveStabs() {
2662 return TokError("unsupported directive '.stabs'");
2663}
2664
2665/// ParseDirectiveCFISections
2666/// ::= .cfi_sections section [, section]
2667bool AsmParser::ParseDirectiveCFISections() {
2668 StringRef Name;
2669 bool EH = false;
2670 bool Debug = false;
2671
2672 if (ParseIdentifier(Name))
2673 return TokError("Expected an identifier");
2674
2675 if (Name == ".eh_frame")
2676 EH = true;
2677 else if (Name == ".debug_frame")
2678 Debug = true;
2679
2680 if (getLexer().is(AsmToken::Comma)) {
2681 Lex();
2682
2683 if (ParseIdentifier(Name))
2684 return TokError("Expected an identifier");
2685
2686 if (Name == ".eh_frame")
2687 EH = true;
2688 else if (Name == ".debug_frame")
2689 Debug = true;
2690 }
2691
2692 getStreamer().EmitCFISections(EH, Debug);
2693 return false;
2694}
2695
2696/// ParseDirectiveCFIStartProc
2697/// ::= .cfi_startproc
2698bool AsmParser::ParseDirectiveCFIStartProc() {
2699 getStreamer().EmitCFIStartProc();
2700 return false;
2701}
2702
2703/// ParseDirectiveCFIEndProc
2704/// ::= .cfi_endproc
2705bool AsmParser::ParseDirectiveCFIEndProc() {
2706 getStreamer().EmitCFIEndProc();
2707 return false;
2708}
2709
2710/// ParseRegisterOrRegisterNumber - parse register name or number.
2711bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2712 SMLoc DirectiveLoc) {
2713 unsigned RegNo;
2714
2715 if (getLexer().isNot(AsmToken::Integer)) {
2716 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2717 return true;
2718 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2719 } else
2720 return ParseAbsoluteExpression(Register);
2721
2722 return false;
2723}
2724
2725/// ParseDirectiveCFIDefCfa
2726/// ::= .cfi_def_cfa register, offset
2727bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2728 int64_t Register = 0;
2729 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2730 return true;
2731
2732 if (getLexer().isNot(AsmToken::Comma))
2733 return TokError("unexpected token in directive");
2734 Lex();
2735
2736 int64_t Offset = 0;
2737 if (ParseAbsoluteExpression(Offset))
2738 return true;
2739
2740 getStreamer().EmitCFIDefCfa(Register, Offset);
2741 return false;
2742}
2743
2744/// ParseDirectiveCFIDefCfaOffset
2745/// ::= .cfi_def_cfa_offset offset
2746bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2747 int64_t Offset = 0;
2748 if (ParseAbsoluteExpression(Offset))
2749 return true;
2750
2751 getStreamer().EmitCFIDefCfaOffset(Offset);
2752 return false;
2753}
2754
2755/// ParseDirectiveCFIRegister
2756/// ::= .cfi_register register, register
2757bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2758 int64_t Register1 = 0;
2759 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2760 return true;
2761
2762 if (getLexer().isNot(AsmToken::Comma))
2763 return TokError("unexpected token in directive");
2764 Lex();
2765
2766 int64_t Register2 = 0;
2767 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2768 return true;
2769
2770 getStreamer().EmitCFIRegister(Register1, Register2);
2771 return false;
2772}
2773
2774/// ParseDirectiveCFIAdjustCfaOffset
2775/// ::= .cfi_adjust_cfa_offset adjustment
2776bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2777 int64_t Adjustment = 0;
2778 if (ParseAbsoluteExpression(Adjustment))
2779 return true;
2780
2781 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2782 return false;
2783}
2784
2785/// ParseDirectiveCFIDefCfaRegister
2786/// ::= .cfi_def_cfa_register register
2787bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2788 int64_t Register = 0;
2789 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2790 return true;
2791
2792 getStreamer().EmitCFIDefCfaRegister(Register);
2793 return false;
2794}
2795
2796/// ParseDirectiveCFIOffset
2797/// ::= .cfi_offset register, offset
2798bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2799 int64_t Register = 0;
2800 int64_t Offset = 0;
2801
2802 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2803 return true;
2804
2805 if (getLexer().isNot(AsmToken::Comma))
2806 return TokError("unexpected token in directive");
2807 Lex();
2808
2809 if (ParseAbsoluteExpression(Offset))
2810 return true;
2811
2812 getStreamer().EmitCFIOffset(Register, Offset);
2813 return false;
2814}
2815
2816/// ParseDirectiveCFIRelOffset
2817/// ::= .cfi_rel_offset register, offset
2818bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2819 int64_t Register = 0;
2820
2821 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2822 return true;
2823
2824 if (getLexer().isNot(AsmToken::Comma))
2825 return TokError("unexpected token in directive");
2826 Lex();
2827
2828 int64_t Offset = 0;
2829 if (ParseAbsoluteExpression(Offset))
2830 return true;
2831
2832 getStreamer().EmitCFIRelOffset(Register, Offset);
2833 return false;
2834}
2835
2836static bool isValidEncoding(int64_t Encoding) {
2837 if (Encoding & ~0xff)
2838 return false;
2839
2840 if (Encoding == dwarf::DW_EH_PE_omit)
2841 return true;
2842
2843 const unsigned Format = Encoding & 0xf;
2844 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2845 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2846 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2847 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2848 return false;
2849
2850 const unsigned Application = Encoding & 0x70;
2851 if (Application != dwarf::DW_EH_PE_absptr &&
2852 Application != dwarf::DW_EH_PE_pcrel)
2853 return false;
2854
2855 return true;
2856}
2857
2858/// ParseDirectiveCFIPersonalityOrLsda
2859/// IsPersonality true for cfi_personality, false for cfi_lsda
2860/// ::= .cfi_personality encoding, [symbol_name]
2861/// ::= .cfi_lsda encoding, [symbol_name]
2862bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2863 int64_t Encoding = 0;
2864 if (ParseAbsoluteExpression(Encoding))
2865 return true;
2866 if (Encoding == dwarf::DW_EH_PE_omit)
2867 return false;
2868
2869 if (!isValidEncoding(Encoding))
2870 return TokError("unsupported encoding.");
2871
2872 if (getLexer().isNot(AsmToken::Comma))
2873 return TokError("unexpected token in directive");
2874 Lex();
2875
2876 StringRef Name;
2877 if (ParseIdentifier(Name))
2878 return TokError("expected identifier in directive");
2879
2880 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2881
2882 if (IsPersonality)
2883 getStreamer().EmitCFIPersonality(Sym, Encoding);
2884 else
2885 getStreamer().EmitCFILsda(Sym, Encoding);
2886 return false;
2887}
2888
2889/// ParseDirectiveCFIRememberState
2890/// ::= .cfi_remember_state
2891bool AsmParser::ParseDirectiveCFIRememberState() {
2892 getStreamer().EmitCFIRememberState();
2893 return false;
2894}
2895
2896/// ParseDirectiveCFIRestoreState
2897/// ::= .cfi_remember_state
2898bool AsmParser::ParseDirectiveCFIRestoreState() {
2899 getStreamer().EmitCFIRestoreState();
2900 return false;
2901}
2902
2903/// ParseDirectiveCFISameValue
2904/// ::= .cfi_same_value register
2905bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2906 int64_t Register = 0;
2907
2908 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2909 return true;
2910
2911 getStreamer().EmitCFISameValue(Register);
2912 return false;
2913}
2914
2915/// ParseDirectiveCFIRestore
2916/// ::= .cfi_restore register
2917bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2918 int64_t Register = 0;
2919 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2920 return true;
2921
2922 getStreamer().EmitCFIRestore(Register);
2923 return false;
2924}
2925
2926/// ParseDirectiveCFIEscape
2927/// ::= .cfi_escape expression[,...]
2928bool AsmParser::ParseDirectiveCFIEscape() {
2929 std::string Values;
2930 int64_t CurrValue;
2931 if (ParseAbsoluteExpression(CurrValue))
2932 return true;
2933
2934 Values.push_back((uint8_t)CurrValue);
2935
2936 while (getLexer().is(AsmToken::Comma)) {
2937 Lex();
2938
2939 if (ParseAbsoluteExpression(CurrValue))
2940 return true;
2941
2942 Values.push_back((uint8_t)CurrValue);
2943 }
2944
2945 getStreamer().EmitCFIEscape(Values);
2946 return false;
2947}
2948
2949/// ParseDirectiveCFISignalFrame
2950/// ::= .cfi_signal_frame
2951bool AsmParser::ParseDirectiveCFISignalFrame() {
2952 if (getLexer().isNot(AsmToken::EndOfStatement))
2953 return Error(getLexer().getLoc(),
2954 "unexpected token in '.cfi_signal_frame'");
2955
2956 getStreamer().EmitCFISignalFrame();
2957 return false;
2958}
2959
2960/// ParseDirectiveCFIUndefined
2961/// ::= .cfi_undefined register
2962bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2963 int64_t Register = 0;
2964
2965 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2966 return true;
2967
2968 getStreamer().EmitCFIUndefined(Register);
2969 return false;
2970}
2971
2972/// ParseDirectiveMacrosOnOff
2973/// ::= .macros_on
2974/// ::= .macros_off
2975bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2976 if (getLexer().isNot(AsmToken::EndOfStatement))
2977 return Error(getLexer().getLoc(),
2978 "unexpected token in '" + Directive + "' directive");
2979
2980 SetMacrosEnabled(Directive == ".macros_on");
2981 return false;
2982}
2983
2984/// ParseDirectiveMacro
2985/// ::= .macro name [parameters]
2986bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2987 StringRef Name;
2988 if (ParseIdentifier(Name))
2989 return TokError("expected identifier in '.macro' directive");
2990
2991 MCAsmMacroParameters Parameters;
2992 // Argument delimiter is initially unknown. It will be set by
2993 // ParseMacroArgument()
2994 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2995 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2996 for (;;) {
2997 MCAsmMacroParameter Parameter;
2998 if (ParseIdentifier(Parameter.first))
2999 return TokError("expected identifier in '.macro' directive");
3000
3001 if (getLexer().is(AsmToken::Equal)) {
3002 Lex();
3003 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3004 return true;
3005 }
3006
3007 Parameters.push_back(Parameter);
3008
3009 if (getLexer().is(AsmToken::Comma))
3010 Lex();
3011 else if (getLexer().is(AsmToken::EndOfStatement))
3012 break;
3013 }
3014 }
3015
3016 // Eat the end of statement.
3017 Lex();
3018
3019 AsmToken EndToken, StartToken = getTok();
3020
3021 // Lex the macro definition.
3022 for (;;) {
3023 // Check whether we have reached the end of the file.
3024 if (getLexer().is(AsmToken::Eof))
3025 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3026
3027 // Otherwise, check whether we have reach the .endmacro.
3028 if (getLexer().is(AsmToken::Identifier) &&
3029 (getTok().getIdentifier() == ".endm" ||
3030 getTok().getIdentifier() == ".endmacro")) {
3031 EndToken = getTok();
3032 Lex();
3033 if (getLexer().isNot(AsmToken::EndOfStatement))
3034 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3035 "' directive");
3036 break;
3037 }
3038
3039 // Otherwise, scan til the end of the statement.
3040 EatToEndOfStatement();
3041 }
3042
3043 if (LookupMacro(Name)) {
3044 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3045 }
3046
3047 const char *BodyStart = StartToken.getLoc().getPointer();
3048 const char *BodyEnd = EndToken.getLoc().getPointer();
3049 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3050 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3051 return false;
3052}
3053
3054/// ParseDirectiveEndMacro
3055/// ::= .endm
3056/// ::= .endmacro
3057bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3058 if (getLexer().isNot(AsmToken::EndOfStatement))
3059 return TokError("unexpected token in '" + Directive + "' directive");
3060
3061 // If we are inside a macro instantiation, terminate the current
3062 // instantiation.
3063 if (InsideMacroInstantiation()) {
3064 HandleMacroExit();
3065 return false;
3066 }
3067
3068 // Otherwise, this .endmacro is a stray entry in the file; well formed
3069 // .endmacro directives are handled during the macro definition parsing.
3070 return TokError("unexpected '" + Directive + "' in file, "
3071 "no current macro definition");
3072}
3073
3074/// ParseDirectivePurgeMacro
3075/// ::= .purgem
3076bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3077 StringRef Name;
3078 if (ParseIdentifier(Name))
3079 return TokError("expected identifier in '.purgem' directive");
3080
3081 if (getLexer().isNot(AsmToken::EndOfStatement))
3082 return TokError("unexpected token in '.purgem' directive");
3083
3084 if (!LookupMacro(Name))
3085 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3086
3087 UndefineMacro(Name);
3088 return false;
3089}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003090
3091/// ParseDirectiveBundleAlignMode
3092/// ::= {.bundle_align_mode} expression
3093bool AsmParser::ParseDirectiveBundleAlignMode() {
3094 CheckForValidSection();
3095
3096 // Expect a single argument: an expression that evaluates to a constant
3097 // in the inclusive range 0-30.
3098 SMLoc ExprLoc = getLexer().getLoc();
3099 int64_t AlignSizePow2;
3100 if (ParseAbsoluteExpression(AlignSizePow2))
3101 return true;
3102 else if (getLexer().isNot(AsmToken::EndOfStatement))
3103 return TokError("unexpected token after expression in"
3104 " '.bundle_align_mode' directive");
3105 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3106 return Error(ExprLoc,
3107 "invalid bundle alignment size (expected between 0 and 30)");
3108
3109 Lex();
3110
3111 // Because of AlignSizePow2's verified range we can safely truncate it to
3112 // unsigned.
3113 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3114 return false;
3115}
3116
3117/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003118/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003119bool AsmParser::ParseDirectiveBundleLock() {
3120 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003121 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003122
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003123 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3124 StringRef Option;
3125 SMLoc Loc = getTok().getLoc();
3126 const char *kInvalidOptionError =
3127 "invalid option for '.bundle_lock' directive";
3128
3129 if (ParseIdentifier(Option))
3130 return Error(Loc, kInvalidOptionError);
3131
3132 if (Option != "align_to_end")
3133 return Error(Loc, kInvalidOptionError);
3134 else if (getLexer().isNot(AsmToken::EndOfStatement))
3135 return Error(Loc,
3136 "unexpected token after '.bundle_lock' directive option");
3137 AlignToEnd = true;
3138 }
3139
Eli Bendersky4766ef42012-12-20 19:05:53 +00003140 Lex();
3141
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003142 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003143 return false;
3144}
3145
3146/// ParseDirectiveBundleLock
3147/// ::= {.bundle_lock}
3148bool AsmParser::ParseDirectiveBundleUnlock() {
3149 CheckForValidSection();
3150
3151 if (getLexer().isNot(AsmToken::EndOfStatement))
3152 return TokError("unexpected token in '.bundle_unlock' directive");
3153 Lex();
3154
3155 getStreamer().EmitBundleUnlock();
3156 return false;
3157}
3158
Eli Bendersky6ee13082013-01-15 22:59:42 +00003159/// ParseDirectiveSpace
3160/// ::= (.skip | .space) expression [ , expression ]
3161bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3162 CheckForValidSection();
3163
3164 int64_t NumBytes;
3165 if (ParseAbsoluteExpression(NumBytes))
3166 return true;
3167
3168 int64_t FillExpr = 0;
3169 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3170 if (getLexer().isNot(AsmToken::Comma))
3171 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3172 Lex();
3173
3174 if (ParseAbsoluteExpression(FillExpr))
3175 return true;
3176
3177 if (getLexer().isNot(AsmToken::EndOfStatement))
3178 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3179 }
3180
3181 Lex();
3182
3183 if (NumBytes <= 0)
3184 return TokError("invalid number of bytes in '" +
3185 Twine(IDVal) + "' directive");
3186
3187 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3188 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3189
3190 return false;
3191}
3192
3193/// ParseDirectiveLEB128
3194/// ::= (.sleb128 | .uleb128) expression
3195bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3196 CheckForValidSection();
3197 const MCExpr *Value;
3198
3199 if (ParseExpression(Value))
3200 return true;
3201
3202 if (getLexer().isNot(AsmToken::EndOfStatement))
3203 return TokError("unexpected token in directive");
3204
3205 if (Signed)
3206 getStreamer().EmitSLEB128Value(Value);
3207 else
3208 getStreamer().EmitULEB128Value(Value);
3209
3210 return false;
3211}
3212
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003213/// ParseDirectiveSymbolAttribute
3214/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003215bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003216 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003217 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003218 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003219 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003220
3221 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003222 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003223
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003224 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003225
Jim Grosbach10ec6502011-09-15 17:56:49 +00003226 // Assembler local symbols don't make any sense here. Complain loudly.
3227 if (Sym->isTemporary())
3228 return Error(Loc, "non-local symbol required in directive");
3229
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003230 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003231
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003232 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003233 break;
3234
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003235 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003236 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003237 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003238 }
3239 }
3240
Sean Callanan79ed1a82010-01-19 20:22:31 +00003241 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003242 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003243}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003244
3245/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003246/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3247bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003248 CheckForValidSection();
3249
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003250 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003251 StringRef Name;
3252 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003253 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003254
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003255 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003256 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003257
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003258 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003259 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003260 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003261
3262 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003263 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003264 if (ParseAbsoluteExpression(Size))
3265 return true;
3266
3267 int64_t Pow2Alignment = 0;
3268 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003269 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003270 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003271 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003272 if (ParseAbsoluteExpression(Pow2Alignment))
3273 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003274
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003275 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3276 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003277 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3278
Chris Lattner258281d2010-01-19 06:22:22 +00003279 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003280 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3281 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003282 if (!isPowerOf2_64(Pow2Alignment))
3283 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3284 Pow2Alignment = Log2_64(Pow2Alignment);
3285 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003286 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003287
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003288 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003289 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003290
Sean Callanan79ed1a82010-01-19 20:22:31 +00003291 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003292
Chris Lattner1fc3d752009-07-09 17:25:12 +00003293 // NOTE: a size of zero for a .comm should create a undefined symbol
3294 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003295 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003296 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3297 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003298
Eric Christopherc260a3e2010-05-14 01:38:54 +00003299 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003300 // may internally end up wanting an alignment in bytes.
3301 // FIXME: Diagnose overflow.
3302 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003303 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3304 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003305
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003306 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003307 return Error(IDLoc, "invalid symbol redefinition");
3308
Chris Lattner1fc3d752009-07-09 17:25:12 +00003309 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003310 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003311 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003312 return false;
3313 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003314
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003315 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003316 return false;
3317}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003318
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003319/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003320/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003321bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003322 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003323 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003324
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003325 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003326 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003327 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003328
Sean Callanan79ed1a82010-01-19 20:22:31 +00003329 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003330
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003331 if (Str.empty())
3332 Error(Loc, ".abort detected. Assembly stopping.");
3333 else
3334 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003335 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003336
3337 return false;
3338}
Kevin Enderby71148242009-07-14 21:35:03 +00003339
Kevin Enderby1f049b22009-07-14 23:21:55 +00003340/// ParseDirectiveInclude
3341/// ::= .include "filename"
3342bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003343 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003344 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003345
Sean Callanan18b83232010-01-19 21:44:56 +00003346 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003347 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003348 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003349
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003350 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003351 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003352
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003353 // Strip the quotes.
3354 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003355
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003356 // Attempt to switch the lexer to the included file before consuming the end
3357 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003358 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003359 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003360 return true;
3361 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003362
3363 return false;
3364}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003365
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003366/// ParseDirectiveIncbin
3367/// ::= .incbin "filename"
3368bool AsmParser::ParseDirectiveIncbin() {
3369 if (getLexer().isNot(AsmToken::String))
3370 return TokError("expected string in '.incbin' directive");
3371
3372 std::string Filename = getTok().getString();
3373 SMLoc IncbinLoc = getLexer().getLoc();
3374 Lex();
3375
3376 if (getLexer().isNot(AsmToken::EndOfStatement))
3377 return TokError("unexpected token in '.incbin' directive");
3378
3379 // Strip the quotes.
3380 Filename = Filename.substr(1, Filename.size()-2);
3381
3382 // Attempt to process the included file.
3383 if (ProcessIncbinFile(Filename)) {
3384 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3385 return true;
3386 }
3387
3388 return false;
3389}
3390
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003391/// ParseDirectiveIf
3392/// ::= .if expression
3393bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003394 TheCondStack.push_back(TheCondState);
3395 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003396 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003397 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003398 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003399 int64_t ExprValue;
3400 if (ParseAbsoluteExpression(ExprValue))
3401 return true;
3402
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003403 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003404 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003405
Sean Callanan79ed1a82010-01-19 20:22:31 +00003406 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003407
3408 TheCondState.CondMet = ExprValue;
3409 TheCondState.Ignore = !TheCondState.CondMet;
3410 }
3411
3412 return false;
3413}
3414
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003415/// ParseDirectiveIfb
3416/// ::= .ifb string
3417bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3418 TheCondStack.push_back(TheCondState);
3419 TheCondState.TheCond = AsmCond::IfCond;
3420
Benjamin Kramer29739e72012-05-12 16:52:21 +00003421 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003422 EatToEndOfStatement();
3423 } else {
3424 StringRef Str = ParseStringToEndOfStatement();
3425
3426 if (getLexer().isNot(AsmToken::EndOfStatement))
3427 return TokError("unexpected token in '.ifb' directive");
3428
3429 Lex();
3430
3431 TheCondState.CondMet = ExpectBlank == Str.empty();
3432 TheCondState.Ignore = !TheCondState.CondMet;
3433 }
3434
3435 return false;
3436}
3437
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003438/// ParseDirectiveIfc
3439/// ::= .ifc string1, string2
3440bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3441 TheCondStack.push_back(TheCondState);
3442 TheCondState.TheCond = AsmCond::IfCond;
3443
Benjamin Kramer29739e72012-05-12 16:52:21 +00003444 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003445 EatToEndOfStatement();
3446 } else {
3447 StringRef Str1 = ParseStringToComma();
3448
3449 if (getLexer().isNot(AsmToken::Comma))
3450 return TokError("unexpected token in '.ifc' directive");
3451
3452 Lex();
3453
3454 StringRef Str2 = ParseStringToEndOfStatement();
3455
3456 if (getLexer().isNot(AsmToken::EndOfStatement))
3457 return TokError("unexpected token in '.ifc' directive");
3458
3459 Lex();
3460
3461 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3462 TheCondState.Ignore = !TheCondState.CondMet;
3463 }
3464
3465 return false;
3466}
3467
3468/// ParseDirectiveIfdef
3469/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003470bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3471 StringRef Name;
3472 TheCondStack.push_back(TheCondState);
3473 TheCondState.TheCond = AsmCond::IfCond;
3474
3475 if (TheCondState.Ignore) {
3476 EatToEndOfStatement();
3477 } else {
3478 if (ParseIdentifier(Name))
3479 return TokError("expected identifier after '.ifdef'");
3480
3481 Lex();
3482
3483 MCSymbol *Sym = getContext().LookupSymbol(Name);
3484
3485 if (expect_defined)
3486 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3487 else
3488 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3489 TheCondState.Ignore = !TheCondState.CondMet;
3490 }
3491
3492 return false;
3493}
3494
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003495/// ParseDirectiveElseIf
3496/// ::= .elseif expression
3497bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3498 if (TheCondState.TheCond != AsmCond::IfCond &&
3499 TheCondState.TheCond != AsmCond::ElseIfCond)
3500 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3501 " an .elseif");
3502 TheCondState.TheCond = AsmCond::ElseIfCond;
3503
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003504 bool LastIgnoreState = false;
3505 if (!TheCondStack.empty())
3506 LastIgnoreState = TheCondStack.back().Ignore;
3507 if (LastIgnoreState || TheCondState.CondMet) {
3508 TheCondState.Ignore = true;
3509 EatToEndOfStatement();
3510 }
3511 else {
3512 int64_t ExprValue;
3513 if (ParseAbsoluteExpression(ExprValue))
3514 return true;
3515
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003516 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003517 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003518
Sean Callanan79ed1a82010-01-19 20:22:31 +00003519 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003520 TheCondState.CondMet = ExprValue;
3521 TheCondState.Ignore = !TheCondState.CondMet;
3522 }
3523
3524 return false;
3525}
3526
3527/// ParseDirectiveElse
3528/// ::= .else
3529bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003530 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003531 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003532
Sean Callanan79ed1a82010-01-19 20:22:31 +00003533 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003534
3535 if (TheCondState.TheCond != AsmCond::IfCond &&
3536 TheCondState.TheCond != AsmCond::ElseIfCond)
3537 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3538 ".elseif");
3539 TheCondState.TheCond = AsmCond::ElseCond;
3540 bool LastIgnoreState = false;
3541 if (!TheCondStack.empty())
3542 LastIgnoreState = TheCondStack.back().Ignore;
3543 if (LastIgnoreState || TheCondState.CondMet)
3544 TheCondState.Ignore = true;
3545 else
3546 TheCondState.Ignore = false;
3547
3548 return false;
3549}
3550
3551/// ParseDirectiveEndIf
3552/// ::= .endif
3553bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003554 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003555 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003556
Sean Callanan79ed1a82010-01-19 20:22:31 +00003557 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003558
3559 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3560 TheCondStack.empty())
3561 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3562 ".else");
3563 if (!TheCondStack.empty()) {
3564 TheCondState = TheCondStack.back();
3565 TheCondStack.pop_back();
3566 }
3567
3568 return false;
3569}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003570
Eli Bendersky6ee13082013-01-15 22:59:42 +00003571void AsmParser::initializeDirectiveKindMap() {
3572 DirectiveKindMap[".set"] = DK_SET;
3573 DirectiveKindMap[".equ"] = DK_EQU;
3574 DirectiveKindMap[".equiv"] = DK_EQUIV;
3575 DirectiveKindMap[".ascii"] = DK_ASCII;
3576 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3577 DirectiveKindMap[".string"] = DK_STRING;
3578 DirectiveKindMap[".byte"] = DK_BYTE;
3579 DirectiveKindMap[".short"] = DK_SHORT;
3580 DirectiveKindMap[".value"] = DK_VALUE;
3581 DirectiveKindMap[".2byte"] = DK_2BYTE;
3582 DirectiveKindMap[".long"] = DK_LONG;
3583 DirectiveKindMap[".int"] = DK_INT;
3584 DirectiveKindMap[".4byte"] = DK_4BYTE;
3585 DirectiveKindMap[".quad"] = DK_QUAD;
3586 DirectiveKindMap[".8byte"] = DK_8BYTE;
3587 DirectiveKindMap[".single"] = DK_SINGLE;
3588 DirectiveKindMap[".float"] = DK_FLOAT;
3589 DirectiveKindMap[".double"] = DK_DOUBLE;
3590 DirectiveKindMap[".align"] = DK_ALIGN;
3591 DirectiveKindMap[".align32"] = DK_ALIGN32;
3592 DirectiveKindMap[".balign"] = DK_BALIGN;
3593 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3594 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3595 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3596 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3597 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3598 DirectiveKindMap[".org"] = DK_ORG;
3599 DirectiveKindMap[".fill"] = DK_FILL;
3600 DirectiveKindMap[".zero"] = DK_ZERO;
3601 DirectiveKindMap[".extern"] = DK_EXTERN;
3602 DirectiveKindMap[".globl"] = DK_GLOBL;
3603 DirectiveKindMap[".global"] = DK_GLOBAL;
3604 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3605 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3606 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3607 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3608 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3609 DirectiveKindMap[".reference"] = DK_REFERENCE;
3610 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3611 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3612 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3613 DirectiveKindMap[".comm"] = DK_COMM;
3614 DirectiveKindMap[".common"] = DK_COMMON;
3615 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3616 DirectiveKindMap[".abort"] = DK_ABORT;
3617 DirectiveKindMap[".include"] = DK_INCLUDE;
3618 DirectiveKindMap[".incbin"] = DK_INCBIN;
3619 DirectiveKindMap[".code16"] = DK_CODE16;
3620 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3621 DirectiveKindMap[".rept"] = DK_REPT;
3622 DirectiveKindMap[".irp"] = DK_IRP;
3623 DirectiveKindMap[".irpc"] = DK_IRPC;
3624 DirectiveKindMap[".endr"] = DK_ENDR;
3625 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3626 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3627 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3628 DirectiveKindMap[".if"] = DK_IF;
3629 DirectiveKindMap[".ifb"] = DK_IFB;
3630 DirectiveKindMap[".ifnb"] = DK_IFNB;
3631 DirectiveKindMap[".ifc"] = DK_IFC;
3632 DirectiveKindMap[".ifnc"] = DK_IFNC;
3633 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3634 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3635 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3636 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3637 DirectiveKindMap[".else"] = DK_ELSE;
3638 DirectiveKindMap[".endif"] = DK_ENDIF;
3639 DirectiveKindMap[".skip"] = DK_SKIP;
3640 DirectiveKindMap[".space"] = DK_SPACE;
3641 DirectiveKindMap[".file"] = DK_FILE;
3642 DirectiveKindMap[".line"] = DK_LINE;
3643 DirectiveKindMap[".loc"] = DK_LOC;
3644 DirectiveKindMap[".stabs"] = DK_STABS;
3645 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3646 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3647 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3648 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3649 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3650 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3651 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3652 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3653 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3654 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3655 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3656 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3657 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3658 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3659 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3660 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3661 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3662 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3663 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3664 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3665 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3666 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3667 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3668 DirectiveKindMap[".macro"] = DK_MACRO;
3669 DirectiveKindMap[".endm"] = DK_ENDM;
3670 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3671 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003672}
3673
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003674
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003675MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003676 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003677
Rafael Espindola761cb062012-06-03 23:57:14 +00003678 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003679 for (;;) {
3680 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003681 if (getLexer().is(AsmToken::Eof)) {
3682 Error(DirectiveLoc, "no matching '.endr' in definition");
3683 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003684 }
3685
Rafael Espindola761cb062012-06-03 23:57:14 +00003686 if (Lexer.is(AsmToken::Identifier) &&
3687 (getTok().getIdentifier() == ".rept")) {
3688 ++NestLevel;
3689 }
3690
3691 // Otherwise, check whether we have reached the .endr.
3692 if (Lexer.is(AsmToken::Identifier) &&
3693 getTok().getIdentifier() == ".endr") {
3694 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003695 EndToken = getTok();
3696 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003697 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3698 TokError("unexpected token in '.endr' directive");
3699 return 0;
3700 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003701 break;
3702 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003703 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003704 }
3705
Rafael Espindola761cb062012-06-03 23:57:14 +00003706 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003707 EatToEndOfStatement();
3708 }
3709
3710 const char *BodyStart = StartToken.getLoc().getPointer();
3711 const char *BodyEnd = EndToken.getLoc().getPointer();
3712 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3713
Rafael Espindola761cb062012-06-03 23:57:14 +00003714 // We Are Anonymous.
3715 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003716 MCAsmMacroParameters Parameters;
3717 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003718}
3719
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003720void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003721 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003722 OS << ".endr\n";
3723
3724 MemoryBuffer *Instantiation =
3725 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3726
Rafael Espindola761cb062012-06-03 23:57:14 +00003727 // Create the macro instantiation object and add to the current macro
3728 // instantiation stack.
3729 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003730 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003731 getTok().getLoc(),
3732 Instantiation);
3733 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003734
Rafael Espindola761cb062012-06-03 23:57:14 +00003735 // Jump to the macro instantiation and prime the lexer.
3736 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3737 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3738 Lex();
3739}
3740
3741bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3742 int64_t Count;
3743 if (ParseAbsoluteExpression(Count))
3744 return TokError("unexpected token in '.rept' directive");
3745
3746 if (Count < 0)
3747 return TokError("Count is negative");
3748
3749 if (Lexer.isNot(AsmToken::EndOfStatement))
3750 return TokError("unexpected token in '.rept' directive");
3751
3752 // Eat the end of statement.
3753 Lex();
3754
3755 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003756 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003757 if (!M)
3758 return true;
3759
3760 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3761 // to hold the macro body with substitutions.
3762 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003763 MCAsmMacroParameters Parameters;
3764 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003765 raw_svector_ostream OS(Buf);
3766 while (Count--) {
3767 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3768 return true;
3769 }
3770 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003771
3772 return false;
3773}
3774
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003775/// ParseDirectiveIrp
3776/// ::= .irp symbol,values
3777bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003778 MCAsmMacroParameters Parameters;
3779 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003780
Preston Gurd6c9176a2012-09-19 20:29:04 +00003781 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003782 return TokError("expected identifier in '.irp' directive");
3783
3784 Parameters.push_back(Parameter);
3785
3786 if (Lexer.isNot(AsmToken::Comma))
3787 return TokError("expected comma in '.irp' directive");
3788
3789 Lex();
3790
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003791 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003792 if (ParseMacroArguments(0, A))
3793 return true;
3794
3795 // Eat the end of statement.
3796 Lex();
3797
3798 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003799 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003800 if (!M)
3801 return true;
3802
3803 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3804 // to hold the macro body with substitutions.
3805 SmallString<256> Buf;
3806 raw_svector_ostream OS(Buf);
3807
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003808 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3809 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003810 Args.push_back(*i);
3811
3812 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3813 return true;
3814 }
3815
3816 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3817
3818 return false;
3819}
3820
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003821/// ParseDirectiveIrpc
3822/// ::= .irpc symbol,values
3823bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003824 MCAsmMacroParameters Parameters;
3825 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003826
Preston Gurd6c9176a2012-09-19 20:29:04 +00003827 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003828 return TokError("expected identifier in '.irpc' directive");
3829
3830 Parameters.push_back(Parameter);
3831
3832 if (Lexer.isNot(AsmToken::Comma))
3833 return TokError("expected comma in '.irpc' directive");
3834
3835 Lex();
3836
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003837 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003838 if (ParseMacroArguments(0, A))
3839 return true;
3840
3841 if (A.size() != 1 || A.front().size() != 1)
3842 return TokError("unexpected token in '.irpc' directive");
3843
3844 // Eat the end of statement.
3845 Lex();
3846
3847 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003848 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003849 if (!M)
3850 return true;
3851
3852 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3853 // to hold the macro body with substitutions.
3854 SmallString<256> Buf;
3855 raw_svector_ostream OS(Buf);
3856
3857 StringRef Values = A.front().front().getString();
3858 std::size_t I, End = Values.size();
3859 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003860 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003861 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3862
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003863 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003864 Args.push_back(Arg);
3865
3866 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3867 return true;
3868 }
3869
3870 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3871
3872 return false;
3873}
3874
Rafael Espindola761cb062012-06-03 23:57:14 +00003875bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3876 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003877 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003878
3879 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003880 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003881 assert(getLexer().is(AsmToken::EndOfStatement));
3882
Rafael Espindola761cb062012-06-03 23:57:14 +00003883 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003884 return false;
3885}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003886
Eli Friedman2128aae2012-10-22 23:58:19 +00003887bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3888 const MCExpr *Value;
3889 SMLoc ExprLoc = getLexer().getLoc();
3890 if (ParseExpression(Value))
3891 return true;
3892 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3893 if (!MCE)
3894 return Error(ExprLoc, "unexpected expression in _emit");
3895 uint64_t IntValue = MCE->getValue();
3896 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3897 return Error(ExprLoc, "literal value out of range for directive");
3898
3899 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3900 return false;
3901}
3902
Chad Rosierb1f8c132012-10-18 15:49:34 +00003903bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3904 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003905 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003906 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003907 SmallVectorImpl<std::string> &Clobbers,
3908 const MCInstrInfo *MII,
3909 const MCInstPrinter *IP,
3910 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003911 SmallVector<void *, 4> InputDecls;
3912 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003913 SmallVector<bool, 4> InputDeclsAddressOf;
3914 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003915 SmallVector<std::string, 4> InputConstraints;
3916 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003917 std::set<std::string> ClobberRegs;
3918
Chad Rosier4e472d22012-10-20 01:02:45 +00003919 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003920
3921 // Prime the lexer.
3922 Lex();
3923
3924 // While we have input, parse each statement.
3925 unsigned InputIdx = 0;
3926 unsigned OutputIdx = 0;
3927 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003928 ParseStatementInfo Info(&AsmStrRewrites);
3929 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003930 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003931
Chad Rosier57498012012-12-12 22:45:52 +00003932 if (Info.ParseError)
3933 return true;
3934
Eli Friedman2128aae2012-10-22 23:58:19 +00003935 if (Info.Opcode != ~0U) {
3936 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003937
3938 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003939 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3940 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003941
3942 // Immediate.
3943 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003944 if (Operand->needAsmRewrite())
3945 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3946 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003947 continue;
3948 }
3949
3950 // Register operand.
Chad Rosierc1ec2072013-01-10 22:10:27 +00003951 if (Operand->isReg() && !Operand->needAddressOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003952 unsigned NumDefs = Desc.getNumDefs();
3953 // Clobber.
3954 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3955 std::string Reg;
3956 raw_string_ostream OS(Reg);
3957 IP->printRegName(OS, Operand->getReg());
3958 ClobberRegs.insert(StringRef(OS.str()));
3959 }
3960 continue;
3961 }
3962
3963 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003964 unsigned Size;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003965 bool IsVarDecl;
Chad Rosier32989592012-10-18 20:27:15 +00003966 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
Chad Rosierc1ec2072013-01-10 22:10:27 +00003967 Size, IsVarDecl);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003968 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003969 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc1ec2072013-01-10 22:10:27 +00003970 if (Operand->isMem() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003971 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003972 Operand->getStartLoc(),
3973 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003974 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003975 if (isOutput) {
3976 std::string Constraint = "=";
3977 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003978 OutputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003979 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003980 Constraint += Operand->getConstraint().str();
3981 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003982 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003983 Operand->getStartLoc(),
3984 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003985 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003986 InputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003987 InputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003988 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003989 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003990 Operand->getStartLoc(),
3991 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003992 }
3993 }
3994 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003995 }
3996 }
3997
3998 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003999 NumOutputs = OutputDecls.size();
4000 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004001
4002 // Set the unique clobbers.
4003 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
4004 E = ClobberRegs.end(); I != E; ++I)
4005 Clobbers.push_back(*I);
4006
4007 // Merge the various outputs and inputs. Output are expected first.
4008 if (NumOutputs || NumInputs) {
4009 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004010 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004011 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004012 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004013 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004014 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004015 }
4016 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004017 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004018 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004019 }
4020 }
4021
4022 // Build the IR assembly string.
4023 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00004024 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004025 raw_string_ostream OS(AsmStringIR);
4026 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00004027 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00004028 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4029 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00004030
Chad Rosier4e472d22012-10-20 01:02:45 +00004031 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004032
4033 // Emit everything up to the immediate/expression. If the previous rewrite
4034 // was a size directive, then this has already been done.
4035 if (PrevKind != AOK_SizeDirective)
4036 OS << StringRef(Start, Loc - Start);
4037 PrevKind = Kind;
4038
Chad Rosier5a719fc2012-10-23 17:43:43 +00004039 // Skip the original expression.
4040 if (Kind == AOK_Skip) {
4041 Start = Loc + (*I).Len;
4042 continue;
4043 }
4044
Chad Rosierb1f8c132012-10-18 15:49:34 +00004045 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004046 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004047 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004048 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00004049 OS << Twine("$$");
4050 OS << (*I).Val;
4051 break;
4052 case AOK_ImmPrefix:
4053 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00004054 break;
4055 case AOK_Input:
4056 OS << '$';
4057 OS << InputIdx++;
4058 break;
4059 case AOK_Output:
4060 OS << '$';
4061 OS << OutputIdx++;
4062 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004063 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00004064 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004065 default: break;
4066 case 8: OS << "byte ptr "; break;
4067 case 16: OS << "word ptr "; break;
4068 case 32: OS << "dword ptr "; break;
4069 case 64: OS << "qword ptr "; break;
4070 case 80: OS << "xword ptr "; break;
4071 case 128: OS << "xmmword ptr "; break;
4072 case 256: OS << "ymmword ptr "; break;
4073 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004074 break;
4075 case AOK_Emit:
4076 OS << ".byte";
4077 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00004078 case AOK_DotOperator:
4079 OS << (*I).Val;
4080 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004081 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004082
Chad Rosierb1f8c132012-10-18 15:49:34 +00004083 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004084 if (Kind != AOK_SizeDirective)
4085 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004086 }
4087
4088 // Emit the remainder of the asm string.
4089 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4090 if (Start != AsmEnd)
4091 OS << StringRef(Start, AsmEnd - Start);
4092
4093 AsmString = OS.str();
4094 return false;
4095}
4096
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004097/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004098MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004099 MCContext &C, MCStreamer &Out,
4100 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004101 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004102}