blob: bfe361273343e447d4577cd58209983fe1d5fac2 [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"
Chad Rosierabde6752013-02-13 18:38:58 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000019#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000020#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000021#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000022#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000023#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000025#include "llvm/MC/MCParser/AsmCond.h"
26#include "llvm/MC/MCParser/AsmLexer.h"
27#include "llvm/MC/MCParser/MCAsmParser.h"
28#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000029#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000030#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000031#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000032#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000033#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000034#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000035#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000036#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000038#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000039#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000040#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000041#include <set>
42#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000043#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000044using namespace llvm;
45
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000046static cl::opt<bool>
47FatalAssemblerWarnings("fatal-assembler-warnings",
48 cl::desc("Consider warnings as error"));
49
Eric Christopher2318ba12012-12-18 00:30:54 +000050MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000051
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000052namespace {
53
Eli Benderskyf9f40bd2013-01-16 18:56:50 +000054/// \brief Helper types for tracking macro definitions.
55typedef std::vector<AsmToken> MCAsmMacroArgument;
56typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
57typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
58typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
59
60struct MCAsmMacro {
61 StringRef Name;
62 StringRef Body;
63 MCAsmMacroParameters Parameters;
64
65public:
66 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
67 Name(N), Body(B), Parameters(P) {}
68
69 MCAsmMacro(const MCAsmMacro& Other)
70 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
71};
72
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000073/// \brief Helper class for storing information about an active macro
74/// instantiation.
75struct MacroInstantiation {
76 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000077 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000078
79 /// The macro instantiation with substitutions.
80 MemoryBuffer *Instantiation;
81
82 /// The location of the instantiation.
83 SMLoc InstantiationLoc;
84
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000085 /// The buffer where parsing should resume upon instantiation completion.
86 int ExitBuffer;
87
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000088 /// The location where parsing should resume upon instantiation completion.
89 SMLoc ExitLoc;
90
91public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000092 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000093 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000094};
95
Eli Friedman2128aae2012-10-22 23:58:19 +000096struct ParseStatementInfo {
97 /// ParsedOperands - The parsed operands from the last parsed statement.
98 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
99
100 /// Opcode - The opcode from the last parsed instruction.
101 unsigned Opcode;
102
Chad Rosier57498012012-12-12 22:45:52 +0000103 /// Error - Was there an error parsing the inline assembly?
104 bool ParseError;
105
Eli Friedman2128aae2012-10-22 23:58:19 +0000106 SmallVectorImpl<AsmRewrite> *AsmRewrites;
107
Chad Rosier57498012012-12-12 22:45:52 +0000108 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000109 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000110 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000111
112 ~ParseStatementInfo() {
113 // Free any parsed operands.
114 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
115 delete ParsedOperands[i];
116 ParsedOperands.clear();
117 }
118};
119
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000120/// \brief The concrete assembly parser instance.
121class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000122 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
123 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000124private:
125 AsmLexer Lexer;
126 MCContext &Ctx;
127 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000128 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000129 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000132 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000133
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
136 int CurBuffer;
137
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
140
Eli Bendersky6ee13082013-01-15 22:59:42 +0000141 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
142 /// extensions. Extensions register themselves in this map by calling
143 /// AddDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000145
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000146 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000147 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000148
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000149 /// ActiveMacros - Stack of active macro instantiations.
150 std::vector<MacroInstantiation*> ActiveMacros;
151
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000152 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000153 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000154
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000155 /// Flag tracking whether any errors have been encountered.
156 unsigned HadError : 1;
157
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000158 /// The values from the last parsed cpp hash file line comment if any.
159 StringRef CppHashFilename;
160 int64_t CppHashLineNumber;
161 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000162 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000163
Devang Patel0db58bf2012-01-31 18:14:05 +0000164 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
165 unsigned AssemblerDialect;
166
Preston Gurd7b6f2032012-09-19 20:36:12 +0000167 /// IsDarwin - is Darwin compatibility enabled?
168 bool IsDarwin;
169
Chad Rosier8f138d12012-10-15 17:19:13 +0000170 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000171 bool ParsingInlineAsm;
172
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000173public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000174 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000175 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000176 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000177
178 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
179
Eli Bendersky171192f2013-01-16 00:50:52 +0000180 virtual void AddDirectiveHandler(StringRef Directive,
181 ExtensionDirectiveHandler Handler) {
182 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000183 }
184
185public:
186 /// @name MCAsmParser Interface
187 /// {
188
189 virtual SourceMgr &getSourceManager() { return SrcMgr; }
190 virtual MCAsmLexer &getLexer() { return Lexer; }
191 virtual MCContext &getContext() { return Ctx; }
192 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000193 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000194 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000195 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000196 else
197 return AssemblerDialect;
198 }
199 virtual void setAssemblerDialect(unsigned i) {
200 AssemblerDialect = i;
201 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000202
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000203 virtual bool Warning(SMLoc L, const Twine &Msg,
204 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
205 virtual bool Error(SMLoc L, const Twine &Msg,
206 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000207
Craig Topper345d16d2012-08-29 05:48:09 +0000208 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000209
Chad Rosier84125ca2012-10-13 00:26:04 +0000210 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000211 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000212
213 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
214 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000215 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000216 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000217 SmallVectorImpl<std::string> &Clobbers,
218 const MCInstrInfo *MII,
219 const MCInstPrinter *IP,
220 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000221
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000222 bool ParseExpression(const MCExpr *&Res);
223 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
224 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
225 virtual bool ParseAbsoluteExpression(int64_t &Res);
226
Eli Benderskybf706b32013-01-12 00:05:00 +0000227 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
228 /// and set \p Res to the identifier contents.
229 virtual bool ParseIdentifier(StringRef &Res);
Eli Benderskyb2f0b592013-01-12 00:23:24 +0000230 virtual void EatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000231
Eli Bendersky318cad32013-01-14 19:15:01 +0000232 virtual void CheckForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000233 /// }
234
235private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000236
Eli Friedman2128aae2012-10-22 23:58:19 +0000237 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000238 void EatToEndOfLine();
239 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000240
Kevin Enderby221514e2013-01-22 21:44:53 +0000241 void CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
242 MCAsmMacroParameters Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +0000243 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000244 const MCAsmMacroParameters &Parameters,
245 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000246 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000247
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000248 /// \brief Are macros enabled in the parser?
249 bool MacrosEnabled() {return MacrosEnabledFlag;}
250
251 /// \brief Control a flag in the parser that enables or disables macros.
252 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
253
254 /// \brief Lookup a previously defined macro.
255 /// \param Name Macro name.
256 /// \returns Pointer to macro. NULL if no such macro was defined.
257 const MCAsmMacro* LookupMacro(StringRef Name);
258
259 /// \brief Define a new macro with the given name and information.
260 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
261
262 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
263 void UndefineMacro(StringRef Name);
264
265 /// \brief Are we inside a macro instantiation?
266 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
267
268 /// \brief Handle entry to macro instantiation.
269 ///
270 /// \param M The macro.
271 /// \param NameLoc Instantiation location.
272 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
273
274 /// \brief Handle exit from macro instantiation.
275 void HandleMacroExit();
276
277 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
278 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
279 /// correct delimiter by the method.
280 bool ParseMacroArgument(MCAsmMacroArgument &MA,
281 AsmToken::TokenKind &ArgumentDelimiter);
282
283 /// \brief Parse all macro arguments for a given macro.
284 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
285
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000286 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000287 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000288 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
289 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000290 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000291 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000292
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000293 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
294 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000295 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
296 /// This returns true on failure.
297 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000298
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000299 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000300 /// current token is not set; clients should ensure Lex() is called
301 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000302 ///
303 /// \param InBuffer If not -1, should be the known buffer id that contains the
304 /// location.
305 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000306
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000307 /// \brief Parse up to the end of statement and a return the contents from the
308 /// current token until the end of the statement; the current token on exit
309 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000310 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000311
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000312 /// \brief Parse until the end of a statement or a comma is encountered,
313 /// return the contents from the current token up to the end or comma.
314 StringRef ParseStringToComma();
315
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000316 bool ParseAssignment(StringRef Name, bool allow_redef,
317 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000318
319 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
320 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
321 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000322 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000323
Eli Bendersky6ee13082013-01-15 22:59:42 +0000324 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000325
Eli Bendersky6ee13082013-01-15 22:59:42 +0000326 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000327 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000328 DK_NO_DIRECTIVE, // Placeholder
329 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
330 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
331 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000332 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000333 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
334 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
335 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
336 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
337 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
338 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
339 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000340 DK_ELSEIF, DK_ELSE, DK_ENDIF,
341 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
342 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
343 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
344 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
345 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
346 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
347 DK_CFI_REGISTER,
348 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
349 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000350 };
351
Eli Bendersky6ee13082013-01-15 22:59:42 +0000352 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
353 /// directives parsed by this class.
354 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000355
356 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000357 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000358 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000359 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000360 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000361 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000362 // ".set", ".equ", ".equiv"
363 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000364 bool ParseDirectiveOrg(); // ".org"
365 // ".align{,32}", ".p2align{,w,l}"
366 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
367
Eli Bendersky6ee13082013-01-15 22:59:42 +0000368 // ".file", ".line", ".loc", ".stabs"
369 bool ParseDirectiveFile(SMLoc DirectiveLoc);
370 bool ParseDirectiveLine();
371 bool ParseDirectiveLoc();
372 bool ParseDirectiveStabs();
373
374 // .cfi directives
375 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
376 bool ParseDirectiveCFISections();
377 bool ParseDirectiveCFIStartProc();
378 bool ParseDirectiveCFIEndProc();
379 bool ParseDirectiveCFIDefCfaOffset();
380 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
381 bool ParseDirectiveCFIAdjustCfaOffset();
382 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
383 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
384 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
385 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
386 bool ParseDirectiveCFIRememberState();
387 bool ParseDirectiveCFIRestoreState();
388 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
389 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
390 bool ParseDirectiveCFIEscape();
391 bool ParseDirectiveCFISignalFrame();
392 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
393
394 // macro directives
395 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
396 bool ParseDirectiveEndMacro(StringRef Directive);
397 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
398 bool ParseDirectiveMacrosOnOff(StringRef Directive);
399
Eli Bendersky4766ef42012-12-20 19:05:53 +0000400 // ".bundle_align_mode"
401 bool ParseDirectiveBundleAlignMode();
402 // ".bundle_lock"
403 bool ParseDirectiveBundleLock();
404 // ".bundle_unlock"
405 bool ParseDirectiveBundleUnlock();
406
Eli Bendersky6ee13082013-01-15 22:59:42 +0000407 // ".space", ".skip"
408 bool ParseDirectiveSpace(StringRef IDVal);
409
410 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
411 bool ParseDirectiveLEB128(bool Signed);
412
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000413 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
414 /// accepts a single symbol (which should be a label or an external).
415 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000416
417 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
418
419 bool ParseDirectiveAbort(); // ".abort"
420 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000421 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000422
423 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000424 // ".ifb" or ".ifnb", depending on ExpectBlank.
425 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000426 // ".ifc" or ".ifnc", depending on ExpectEqual.
427 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000428 // ".ifdef" or ".ifndef", depending on expect_defined
429 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000430 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
431 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
432 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Daniel Dunbarbfdcc702013-01-18 01:25:33 +0000433 virtual 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
Chad Rosier469b1442013-02-12 21:33:51 +0000447 // "_emit" or "__emit"
448 bool ParseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
449 size_t Len);
450
451 // "align"
452 bool ParseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000453
Eli Bendersky6ee13082013-01-15 22:59:42 +0000454 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000455};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000456}
457
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000458namespace llvm {
459
460extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000461extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000462extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000463
464}
465
Chris Lattneraaec2052010-01-19 19:46:13 +0000466enum { DEFAULT_ADDRSPACE = 0 };
467
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000468AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000469 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000470 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000471 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000472 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000473 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000474 // Save the old handler.
475 SavedDiagHandler = SrcMgr.getDiagHandler();
476 SavedDiagContext = SrcMgr.getDiagContext();
477 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000478 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000479 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000480
Daniel Dunbare4749702010-07-12 18:12:02 +0000481 // Initialize the platform / file format parser.
482 //
483 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
484 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000485 if (_MAI.hasMicrosoftFastStdCallMangling()) {
486 PlatformParser = createCOFFAsmParser();
487 PlatformParser->Initialize(*this);
488 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000489 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000490 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000491 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000492 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000493 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000494 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000495 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000496
Eli Bendersky6ee13082013-01-15 22:59:42 +0000497 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000498}
499
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000500AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000501 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
502
503 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000504 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000505 ie = MacroMap.end(); it != ie; ++it)
506 delete it->getValue();
507
Daniel Dunbare4749702010-07-12 18:12:02 +0000508 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000509}
510
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000511void AsmParser::PrintMacroInstantiations() {
512 // Print the active macro instantiation stack.
513 for (std::vector<MacroInstantiation*>::const_reverse_iterator
514 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000515 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
516 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000517}
518
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000519bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000520 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000521 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000522 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000523 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000524 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000525}
526
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000527bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000528 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000529 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000530 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000531 return true;
532}
533
Sean Callananfd0b0282010-01-21 00:19:58 +0000534bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000535 std::string IncludedFile;
536 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000537 if (NewBuf == -1)
538 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000539
Sean Callananfd0b0282010-01-21 00:19:58 +0000540 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000541
Sean Callananfd0b0282010-01-21 00:19:58 +0000542 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000543
Sean Callananfd0b0282010-01-21 00:19:58 +0000544 return false;
545}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000546
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000547/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000548/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000549/// returns true on failure.
550bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
551 std::string IncludedFile;
552 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
553 if (NewBuf == -1)
554 return true;
555
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000556 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000557 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
558 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000559 return false;
560}
561
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000562void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
563 if (InBuffer != -1) {
564 CurBuffer = InBuffer;
565 } else {
566 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
567 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000568 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
569}
570
Sean Callananfd0b0282010-01-21 00:19:58 +0000571const AsmToken &AsmParser::Lex() {
572 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000573
Sean Callananfd0b0282010-01-21 00:19:58 +0000574 if (tok->is(AsmToken::Eof)) {
575 // If this is the end of an included file, pop the parent file off the
576 // include stack.
577 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
578 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000579 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000580 tok = &Lexer.Lex();
581 }
582 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000583
Sean Callananfd0b0282010-01-21 00:19:58 +0000584 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000585 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000586
Sean Callananfd0b0282010-01-21 00:19:58 +0000587 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000588}
589
Chris Lattner79180e22010-04-05 23:15:42 +0000590bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000591 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000592 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000593 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000594
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000595 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000596 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000597
598 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000599 AsmCond StartingCondState = TheCondState;
600
Kevin Enderby613b7572011-11-01 22:27:22 +0000601 // If we are generating dwarf for assembly source files save the initial text
602 // section and generate a .file directive.
603 if (getContext().getGenDwarfForAssembly()) {
604 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000605 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
606 getStreamer().EmitLabel(SectionStartSym);
607 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000608 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000609 StringRef(),
610 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000611 }
612
Chris Lattnerb717fb02009-07-02 21:53:43 +0000613 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000614 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000615 ParseStatementInfo Info;
616 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000617
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000618 // We had an error, validate that one was emitted and recover by skipping to
619 // the next line.
620 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000621 EatToEndOfStatement();
622 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000623
624 if (TheCondState.TheCond != StartingCondState.TheCond ||
625 TheCondState.Ignore != StartingCondState.Ignore)
626 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000627
628 // Check to see there are no empty DwarfFile slots.
629 const std::vector<MCDwarfFile *> &MCDwarfFiles =
630 getContext().getMCDwarfFiles();
631 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000632 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000633 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000634 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000635
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000636 // Check to see that all assembler local symbols were actually defined.
637 // Targets that don't do subsections via symbols may not want this, though,
638 // so conservatively exclude them. Only do this if we're finalizing, though,
639 // as otherwise we won't necessarilly have seen everything yet.
640 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
641 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
642 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
643 e = Symbols.end();
644 i != e; ++i) {
645 MCSymbol *Sym = i->getValue();
646 // Variable symbols may not be marked as defined, so check those
647 // explicitly. If we know it's a variable, we have a definition for
648 // the purposes of this check.
649 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
650 // FIXME: We would really like to refer back to where the symbol was
651 // first referenced for a source location. We need to add something
652 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000653 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
654 "assembler local symbol '" + Sym->getName() +
655 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000656 }
657 }
658
659
Chris Lattner79180e22010-04-05 23:15:42 +0000660 // Finalize the output stream if there are no errors and if the client wants
661 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000662 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000663 Out.Finish();
664
Chris Lattnerb717fb02009-07-02 21:53:43 +0000665 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000666}
667
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000668void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000669 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000670 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000671 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000672 }
673}
674
Chris Lattner2cf5f142009-06-22 01:29:09 +0000675/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
676void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000677 while (Lexer.isNot(AsmToken::EndOfStatement) &&
678 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000679 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000680
Chris Lattner2cf5f142009-06-22 01:29:09 +0000681 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000682 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000683 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000684}
685
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000686StringRef AsmParser::ParseStringToEndOfStatement() {
687 const char *Start = getTok().getLoc().getPointer();
688
689 while (Lexer.isNot(AsmToken::EndOfStatement) &&
690 Lexer.isNot(AsmToken::Eof))
691 Lex();
692
693 const char *End = getTok().getLoc().getPointer();
694 return StringRef(Start, End - Start);
695}
Chris Lattnerc4193832009-06-22 05:51:26 +0000696
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000697StringRef AsmParser::ParseStringToComma() {
698 const char *Start = getTok().getLoc().getPointer();
699
700 while (Lexer.isNot(AsmToken::EndOfStatement) &&
701 Lexer.isNot(AsmToken::Comma) &&
702 Lexer.isNot(AsmToken::Eof))
703 Lex();
704
705 const char *End = getTok().getLoc().getPointer();
706 return StringRef(Start, End - Start);
707}
708
Chris Lattner74ec1a32009-06-22 06:32:03 +0000709/// ParseParenExpr - Parse a paren expression and return it.
710/// NOTE: This assumes the leading '(' has already been consumed.
711///
712/// parenexpr ::= expr)
713///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000714bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000715 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000716 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000717 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000718 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000719 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000720 return false;
721}
Chris Lattnerc4193832009-06-22 05:51:26 +0000722
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000723/// ParseBracketExpr - Parse a bracket expression and return it.
724/// NOTE: This assumes the leading '[' has already been consumed.
725///
726/// bracketexpr ::= expr]
727///
728bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
729 if (ParseExpression(Res)) return true;
730 if (Lexer.isNot(AsmToken::RBrac))
731 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000732 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000733 Lex();
734 return false;
735}
736
Chris Lattner74ec1a32009-06-22 06:32:03 +0000737/// ParsePrimaryExpr - Parse a primary expression and return it.
738/// primaryexpr ::= (parenexpr
739/// primaryexpr ::= symbol
740/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000741/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000742/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000743bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby5de048e2013-01-22 21:09:20 +0000744 SMLoc FirstTokenLoc = getLexer().getLoc();
745 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
746 switch (FirstTokenKind) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000747 default:
748 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000749 // If we have an error assume that we've already handled it.
750 case AsmToken::Error:
751 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000752 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000753 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000754 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000755 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000756 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000757 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000758 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000759 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000760 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000761 StringRef Identifier;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000762 if (ParseIdentifier(Identifier)) {
763 if (FirstTokenKind == AsmToken::Dollar)
764 return Error(FirstTokenLoc, "invalid token in expression");
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000765 return true;
Kevin Enderby5de048e2013-01-22 21:09:20 +0000766 }
Daniel Dunbare17edff2010-08-24 19:13:42 +0000767
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000768 EndLoc = SMLoc::getFromPointer(Identifier.end());
769
Daniel Dunbarfffff912009-10-16 01:34:54 +0000770 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000771 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000772 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000773
774 // Lookup the symbol variant if used.
775 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000776 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000777 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000778 if (Variant == MCSymbolRefExpr::VK_Invalid) {
779 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000780 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000781 }
782 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000783
Daniel Dunbarfffff912009-10-16 01:34:54 +0000784 // If this is an absolute variable reference, substitute it now to preserve
785 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000786 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000787 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000788 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000789
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000790 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000791 return false;
792 }
793
794 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000795 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000796 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000797 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000798 case AsmToken::Integer: {
799 SMLoc Loc = getTok().getLoc();
800 int64_t IntVal = getTok().getIntVal();
801 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000802 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000803 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000804 // Look for 'b' or 'f' following an Integer as a directional label
805 if (Lexer.getKind() == AsmToken::Identifier) {
806 StringRef IDVal = getTok().getString();
807 if (IDVal == "f" || IDVal == "b"){
808 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
809 IDVal == "f" ? 1 : 0);
810 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
811 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000812 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000813 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000814 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000815 Lex(); // Eat identifier.
816 }
817 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000818 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000819 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000820 case AsmToken::Real: {
821 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000822 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000823 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000824 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000825 Lex(); // Eat token.
826 return false;
827 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000828 case AsmToken::Dot: {
829 // This is a '.' reference, which references the current PC. Emit a
830 // temporary label to the streamer and refer to it.
831 MCSymbol *Sym = Ctx.CreateTempSymbol();
832 Out.EmitLabel(Sym);
833 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000834 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000835 Lex(); // Eat identifier.
836 return false;
837 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000838 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000839 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000840 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000841 case AsmToken::LBrac:
842 if (!PlatformParser->HasBracketExpressions())
843 return TokError("brackets expression not supported on this target");
844 Lex(); // Eat the '['.
845 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000846 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000847 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000848 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000849 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000850 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000851 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000852 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000853 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000854 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000855 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000856 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000857 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000858 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000859 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000860 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000861 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000862 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000863 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000864 }
865}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000866
Chris Lattnerb4307b32010-01-15 19:28:38 +0000867bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000868 SMLoc EndLoc;
869 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000870}
871
Daniel Dunbarcceba832010-09-17 02:47:07 +0000872const MCExpr *
873AsmParser::ApplyModifierToExpr(const MCExpr *E,
874 MCSymbolRefExpr::VariantKind Variant) {
875 // Recurse over the given expression, rebuilding it to apply the given variant
876 // if there is exactly one symbol.
877 switch (E->getKind()) {
878 case MCExpr::Target:
879 case MCExpr::Constant:
880 return 0;
881
882 case MCExpr::SymbolRef: {
883 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
884
885 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
886 TokError("invalid variant on expression '" +
887 getTok().getIdentifier() + "' (already modified)");
888 return E;
889 }
890
891 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
892 }
893
894 case MCExpr::Unary: {
895 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
896 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
897 if (!Sub)
898 return 0;
899 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
900 }
901
902 case MCExpr::Binary: {
903 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
904 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
905 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
906
907 if (!LHS && !RHS)
908 return 0;
909
910 if (!LHS) LHS = BE->getLHS();
911 if (!RHS) RHS = BE->getRHS();
912
913 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
914 }
915 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000916
Craig Topper85814382012-02-07 05:05:23 +0000917 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000918}
919
Chris Lattner74ec1a32009-06-22 06:32:03 +0000920/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000921///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000922/// expr ::= expr &&,|| expr -> lowest.
923/// expr ::= expr |,^,&,! expr
924/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
925/// expr ::= expr <<,>> expr
926/// expr ::= expr +,- expr
927/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000928/// expr ::= primaryexpr
929///
Chris Lattner54482b42010-01-15 19:39:23 +0000930bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000931 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000932 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000933 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
934 return true;
935
Daniel Dunbarcceba832010-09-17 02:47:07 +0000936 // As a special case, we support 'a op b @ modifier' by rewriting the
937 // expression to include the modifier. This is inefficient, but in general we
938 // expect users to use 'a@modifier op b'.
939 if (Lexer.getKind() == AsmToken::At) {
940 Lex();
941
942 if (Lexer.isNot(AsmToken::Identifier))
943 return TokError("unexpected symbol modifier following '@'");
944
945 MCSymbolRefExpr::VariantKind Variant =
946 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
947 if (Variant == MCSymbolRefExpr::VK_Invalid)
948 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
949
950 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
951 if (!ModifiedRes) {
952 return TokError("invalid modifier '" + getTok().getIdentifier() +
953 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000954 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000955
Daniel Dunbarcceba832010-09-17 02:47:07 +0000956 Res = ModifiedRes;
957 Lex();
958 }
959
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000960 // Try to constant fold it up front, if possible.
961 int64_t Value;
962 if (Res->EvaluateAsAbsolute(Value))
963 Res = MCConstantExpr::Create(Value, getContext());
964
965 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000966}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000967
Chris Lattnerb4307b32010-01-15 19:28:38 +0000968bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000969 Res = 0;
970 return ParseParenExpr(Res, EndLoc) ||
971 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000972}
973
Daniel Dunbar475839e2009-06-29 20:37:27 +0000974bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000975 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000976
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000977 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000978 if (ParseExpression(Expr))
979 return true;
980
Daniel Dunbare00b0112009-10-16 01:57:52 +0000981 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000982 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000983
984 return false;
985}
986
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000987static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000988 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000989 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000990 default:
991 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000992
Jim Grosbachfbe16812011-08-20 16:24:13 +0000993 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000994 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000995 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000996 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000997 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000998 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000999 return 1;
1000
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001001
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001002 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +00001003 //
1004 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +00001005 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001006 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001007 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001008 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001009 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001010 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001011 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001012 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001013 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001014
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001015 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001016 case AsmToken::EqualEqual:
1017 Kind = MCBinaryExpr::EQ;
1018 return 3;
1019 case AsmToken::ExclaimEqual:
1020 case AsmToken::LessGreater:
1021 Kind = MCBinaryExpr::NE;
1022 return 3;
1023 case AsmToken::Less:
1024 Kind = MCBinaryExpr::LT;
1025 return 3;
1026 case AsmToken::LessEqual:
1027 Kind = MCBinaryExpr::LTE;
1028 return 3;
1029 case AsmToken::Greater:
1030 Kind = MCBinaryExpr::GT;
1031 return 3;
1032 case AsmToken::GreaterEqual:
1033 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001034 return 3;
1035
Jim Grosbachfbe16812011-08-20 16:24:13 +00001036 // Intermediate Precedence: <<, >>
1037 case AsmToken::LessLess:
1038 Kind = MCBinaryExpr::Shl;
1039 return 4;
1040 case AsmToken::GreaterGreater:
1041 Kind = MCBinaryExpr::Shr;
1042 return 4;
1043
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001044 // High Intermediate Precedence: +, -
1045 case AsmToken::Plus:
1046 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001047 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001048 case AsmToken::Minus:
1049 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001050 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001051
Jim Grosbachfbe16812011-08-20 16:24:13 +00001052 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001053 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001054 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001055 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001056 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001057 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001058 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001059 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001060 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001061 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001062 }
1063}
1064
1065
1066/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1067/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001068bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1069 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001070 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001071 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001072 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001073
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001074 // If the next token is lower precedence than we are allowed to eat, return
1075 // successfully with what we ate already.
1076 if (TokPrec < Precedence)
1077 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001078
Sean Callanan79ed1a82010-01-19 20:22:31 +00001079 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001080
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001081 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001082 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001083 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001084
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001085 // If BinOp binds less tightly with RHS than the operator after RHS, let
1086 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001087 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001088 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001089 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001090 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001091 }
1092
Daniel Dunbar475839e2009-06-29 20:37:27 +00001093 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001094 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001095 }
1096}
1097
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001098/// ParseStatement:
1099/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001100/// ::= Label* Directive ...Operands... EndOfStatement
1101/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001102bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001103 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001104 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001105 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001106 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001107 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001108
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001109 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001110 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001111 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001112 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001113 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001114 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001115 if (Lexer.is(AsmToken::Hash))
1116 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001117
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001118 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001119 if (Lexer.is(AsmToken::Integer)) {
1120 LocalLabelVal = getTok().getIntVal();
1121 if (LocalLabelVal < 0) {
1122 if (!TheCondState.Ignore)
1123 return TokError("unexpected token at start of statement");
1124 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001125 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001126 IDVal = getTok().getString();
1127 Lex(); // Consume the integer token to be used as an identifier token.
1128 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001129 if (!TheCondState.Ignore)
1130 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001131 }
1132 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001133 } else if (Lexer.is(AsmToken::Dot)) {
1134 // Treat '.' as a valid identifier in this context.
1135 Lex();
1136 IDVal = ".";
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001137 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001138 if (!TheCondState.Ignore)
1139 return TokError("unexpected token at start of statement");
1140 IDVal = "";
1141 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001142
Chris Lattner7834fac2010-04-17 18:14:27 +00001143 // Handle conditional assembly here before checking for skipping. We
1144 // have to do this so that .endif isn't skipped in a ".if 0" block for
1145 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001146 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001147 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001148 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001149 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1150 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001151 switch (DirKind) {
1152 default:
1153 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001154 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001155 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001156 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001157 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001158 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001159 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001160 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001161 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001162 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001163 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001164 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001165 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001166 case DK_IFNDEF:
1167 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001168 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001169 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001170 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001171 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001172 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001173 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001174 return ParseDirectiveEndIf(IDLoc);
1175 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001176
Eli Benderskyed5df012013-01-16 19:32:36 +00001177 // Ignore the statement if in the middle of inactive conditional
1178 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001179 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001180 EatToEndOfStatement();
1181 return false;
1182 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001183
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001184 // FIXME: Recurse on local labels?
1185
1186 // See what kind of statement we have.
1187 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001188 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001189 CheckForValidSection();
1190
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001191 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001192 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001193
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001194 // Diagnose attempt to use '.' as a label.
1195 if (IDVal == ".")
1196 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1197
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001198 // Diagnose attempt to use a variable as a label.
1199 //
1200 // FIXME: Diagnostics. Note the location of the definition as a label.
1201 // FIXME: This doesn't diagnose assignment to a symbol which has been
1202 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001203 MCSymbol *Sym;
1204 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001205 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001206 else
1207 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001208 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001209 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001210
Daniel Dunbar959fd882009-08-26 22:13:22 +00001211 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001212 if (!ParsingInlineAsm)
1213 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001214
Kevin Enderby94c2e852011-12-09 18:09:40 +00001215 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001216 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001217 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001218 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1219 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001220
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001221 // Consume any end of statement token, if present, to avoid spurious
1222 // AddBlankLine calls().
1223 if (Lexer.is(AsmToken::EndOfStatement)) {
1224 Lex();
1225 if (Lexer.is(AsmToken::Eof))
1226 return false;
1227 }
1228
Eli Friedman2128aae2012-10-22 23:58:19 +00001229 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001230 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001231
Daniel Dunbar3f872332009-07-28 16:08:33 +00001232 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001233 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001234 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001235
Nico Weber4c4c7322011-01-28 03:04:41 +00001236 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001237
1238 default: // Normal instruction or directive.
1239 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001240 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001241
1242 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001243 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001244 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1245 return HandleMacroEntry(M, IDLoc);
1246 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001247
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001248 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001249
1250 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001251 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001252 // There are several entities interested in parsing directives:
1253 //
1254 // 1. The target-specific assembly parser. Some directives are target
1255 // specific or may potentially behave differently on certain targets.
1256 // 2. Asm parser extensions. For example, platform-specific parsers
1257 // (like the ELF parser) register themselves as extensions.
1258 // 3. The generic directive parser implemented by this class. These are
1259 // all the directives that behave in a target and platform independent
1260 // manner, or at least have a default behavior that's shared between
1261 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001262
Eli Bendersky6ee13082013-01-15 22:59:42 +00001263 // First query the target-specific parser. It will return 'true' if it
1264 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001265 if (!getTargetParser().ParseDirective(ID))
1266 return false;
1267
Eli Bendersky6ee13082013-01-15 22:59:42 +00001268 // Next, check the extention directive map to see if any extension has
1269 // registered itself to parse this directive.
1270 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1271 ExtensionDirectiveMap.lookup(IDVal);
1272 if (Handler.first)
1273 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1274
1275 // Finally, if no one else is interested in this directive, it must be
1276 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001277 switch (DirKind) {
1278 default:
1279 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001280 case DK_SET:
1281 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001282 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001283 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001284 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001285 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001286 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001287 case DK_ASCIZ:
1288 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001289 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001290 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001291 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001292 case DK_SHORT:
1293 case DK_VALUE:
1294 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001295 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001296 case DK_LONG:
1297 case DK_INT:
1298 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001299 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001300 case DK_QUAD:
1301 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001302 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001303 case DK_SINGLE:
1304 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001305 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001306 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001307 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001308 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001309 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1310 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1311 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001312 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001313 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1314 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1315 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001316 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001317 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001318 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001319 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001320 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001321 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001322 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001323 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001324 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001325 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001326 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001327 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001328 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001329 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001330 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001331 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001332 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001333 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001334 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001335 EatToEndOfStatement(); // .extern is the default, ignore it.
1336 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_GLOBL:
1338 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001339 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001340 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001341 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001342 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001343 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001344 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001345 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001346 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001347 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001348 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001349 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001350 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001351 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001352 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001353 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001354 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001355 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001356 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001357 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001358 case DK_COMM:
1359 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001360 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001361 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001362 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001363 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001364 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001365 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001366 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001367 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001368 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001369 case DK_CODE16:
1370 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001371 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001372 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001373 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001374 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001375 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001376 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001377 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001378 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001379 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001380 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001381 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001382 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001383 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001384 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001385 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001386 case DK_SLEB128:
1387 return ParseDirectiveLEB128(true);
1388 case DK_ULEB128:
1389 return ParseDirectiveLEB128(false);
1390 case DK_SPACE:
1391 case DK_SKIP:
1392 return ParseDirectiveSpace(IDVal);
1393 case DK_FILE:
1394 return ParseDirectiveFile(IDLoc);
1395 case DK_LINE:
1396 return ParseDirectiveLine();
1397 case DK_LOC:
1398 return ParseDirectiveLoc();
1399 case DK_STABS:
1400 return ParseDirectiveStabs();
1401 case DK_CFI_SECTIONS:
1402 return ParseDirectiveCFISections();
1403 case DK_CFI_STARTPROC:
1404 return ParseDirectiveCFIStartProc();
1405 case DK_CFI_ENDPROC:
1406 return ParseDirectiveCFIEndProc();
1407 case DK_CFI_DEF_CFA:
1408 return ParseDirectiveCFIDefCfa(IDLoc);
1409 case DK_CFI_DEF_CFA_OFFSET:
1410 return ParseDirectiveCFIDefCfaOffset();
1411 case DK_CFI_ADJUST_CFA_OFFSET:
1412 return ParseDirectiveCFIAdjustCfaOffset();
1413 case DK_CFI_DEF_CFA_REGISTER:
1414 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1415 case DK_CFI_OFFSET:
1416 return ParseDirectiveCFIOffset(IDLoc);
1417 case DK_CFI_REL_OFFSET:
1418 return ParseDirectiveCFIRelOffset(IDLoc);
1419 case DK_CFI_PERSONALITY:
1420 return ParseDirectiveCFIPersonalityOrLsda(true);
1421 case DK_CFI_LSDA:
1422 return ParseDirectiveCFIPersonalityOrLsda(false);
1423 case DK_CFI_REMEMBER_STATE:
1424 return ParseDirectiveCFIRememberState();
1425 case DK_CFI_RESTORE_STATE:
1426 return ParseDirectiveCFIRestoreState();
1427 case DK_CFI_SAME_VALUE:
1428 return ParseDirectiveCFISameValue(IDLoc);
1429 case DK_CFI_RESTORE:
1430 return ParseDirectiveCFIRestore(IDLoc);
1431 case DK_CFI_ESCAPE:
1432 return ParseDirectiveCFIEscape();
1433 case DK_CFI_SIGNAL_FRAME:
1434 return ParseDirectiveCFISignalFrame();
1435 case DK_CFI_UNDEFINED:
1436 return ParseDirectiveCFIUndefined(IDLoc);
1437 case DK_CFI_REGISTER:
1438 return ParseDirectiveCFIRegister(IDLoc);
1439 case DK_MACROS_ON:
1440 case DK_MACROS_OFF:
1441 return ParseDirectiveMacrosOnOff(IDVal);
1442 case DK_MACRO:
1443 return ParseDirectiveMacro(IDLoc);
1444 case DK_ENDM:
1445 case DK_ENDMACRO:
1446 return ParseDirectiveEndMacro(IDVal);
1447 case DK_PURGEM:
1448 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001449 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001450
Jim Grosbach686c0182012-05-01 18:38:27 +00001451 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001452 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001453
Chad Rosier469b1442013-02-12 21:33:51 +00001454 // __asm _emit or __asm __emit
1455 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1456 IDVal == "_EMIT" || IDVal == "__EMIT"))
1457 return ParseDirectiveMSEmit(IDLoc, Info, IDVal.size());
1458
1459 // __asm align
1460 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
1461 return ParseDirectiveMSAlign(IDLoc, Info);
Eli Friedman2128aae2012-10-22 23:58:19 +00001462
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001463 CheckForValidSection();
1464
Chris Lattnera7f13542010-05-19 23:34:33 +00001465 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001466 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001467 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001468 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1469 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001470 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001471
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001472 // Dump the parsed representation, if requested.
1473 if (getShowParsedOperands()) {
1474 SmallString<256> Str;
1475 raw_svector_ostream OS(Str);
1476 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001477 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001478 if (i != 0)
1479 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001480 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001481 }
1482 OS << "]";
1483
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001484 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001485 }
1486
Kevin Enderby613b7572011-11-01 22:27:22 +00001487 // If we are generating dwarf for assembly source files and the current
1488 // section is the initial text section then generate a .loc directive for
1489 // the instruction.
1490 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001491 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001492
Eli Benderskyed5df012013-01-16 19:32:36 +00001493 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001494
Eli Benderskyed5df012013-01-16 19:32:36 +00001495 // If we previously parsed a cpp hash file line comment then make sure the
1496 // current Dwarf File is for the CppHashFilename if not then emit the
1497 // Dwarf File table for it and adjust the line number for the .loc.
1498 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1499 getContext().getMCDwarfFiles();
1500 if (CppHashFilename.size() != 0) {
1501 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001502 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001503 getStreamer().EmitDwarfFileDirective(
1504 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001505
Kevin Enderby32c1a822012-11-05 21:55:41 +00001506 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001507 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001508 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001509
Kevin Enderby613b7572011-11-01 22:27:22 +00001510 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001511 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001512 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001513 StringRef());
1514 }
1515
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001516 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001517 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001518 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001519 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1520 Info.ParsedOperands,
1521 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001522 ParsingInlineAsm);
1523 }
Chris Lattner98986712010-01-14 22:21:20 +00001524
Chris Lattnercbf8a982010-09-11 16:18:25 +00001525 // Don't skip the rest of the line, the instruction parser is responsible for
1526 // that.
1527 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001528}
Chris Lattner9a023f72009-06-24 04:43:34 +00001529
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001530/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1531/// since they may not be able to be tokenized to get to the end of line token.
1532void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001533 if (!Lexer.is(AsmToken::EndOfStatement))
1534 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001535 // Eat EOL.
1536 Lex();
1537}
1538
1539/// ParseCppHashLineFilenameComment as this:
1540/// ::= # number "filename"
1541/// or just as a full line comment if it doesn't have a number and a string.
1542bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1543 Lex(); // Eat the hash token.
1544
1545 if (getLexer().isNot(AsmToken::Integer)) {
1546 // Consume the line since in cases it is not a well-formed line directive,
1547 // as if were simply a full line comment.
1548 EatToEndOfLine();
1549 return false;
1550 }
1551
1552 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001553 Lex();
1554
1555 if (getLexer().isNot(AsmToken::String)) {
1556 EatToEndOfLine();
1557 return false;
1558 }
1559
1560 StringRef Filename = getTok().getString();
1561 // Get rid of the enclosing quotes.
1562 Filename = Filename.substr(1, Filename.size()-2);
1563
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001564 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1565 CppHashLoc = L;
1566 CppHashFilename = Filename;
1567 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001568 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001569
1570 // Ignore any trailing characters, they're just comment.
1571 EatToEndOfLine();
1572 return false;
1573}
1574
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001575/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001576/// for the Filename and LineNo if any in the diagnostic.
1577void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1578 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1579 raw_ostream &OS = errs();
1580
1581 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1582 const SMLoc &DiagLoc = Diag.getLoc();
1583 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1584 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1585
1586 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1587 // before printing the message.
1588 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001589 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001590 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1591 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1592 }
1593
Eric Christopher2318ba12012-12-18 00:30:54 +00001594 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001595 // manager changed or buffer changed (like in a nested include) then just
1596 // print the normal diagnostic using its Filename and LineNo.
1597 if (!Parser->CppHashLineNumber ||
1598 &DiagSrcMgr != &Parser->SrcMgr ||
1599 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001600 if (Parser->SavedDiagHandler)
1601 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1602 else
1603 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001604 return;
1605 }
1606
Eric Christopher2318ba12012-12-18 00:30:54 +00001607 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001608 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1609 // the diagnostic.
1610 const std::string Filename = Parser->CppHashFilename;
1611
1612 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1613 int CppHashLocLineNo =
1614 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1615 int LineNo = Parser->CppHashLineNumber - 1 +
1616 (DiagLocLineNo - CppHashLocLineNo);
1617
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001618 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1619 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001620 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001621 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001622
Benjamin Kramer04a04262011-10-16 10:48:29 +00001623 if (Parser->SavedDiagHandler)
1624 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1625 else
1626 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001627}
1628
Rafael Espindola799aacf2012-08-21 18:29:30 +00001629// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1630// difference being that that function accepts '@' as part of identifiers and
1631// we can't do that. AsmLexer.cpp should probably be changed to handle
1632// '@' as a special case when needed.
1633static bool isIdentifierChar(char c) {
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001634 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
1635 c == '.';
Rafael Espindola799aacf2012-08-21 18:29:30 +00001636}
1637
Rafael Espindola761cb062012-06-03 23:57:14 +00001638bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001639 const MCAsmMacroParameters &Parameters,
1640 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001641 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001642 unsigned NParameters = Parameters.size();
1643 if (NParameters != 0 && NParameters != A.size())
1644 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001645
Preston Gurd7b6f2032012-09-19 20:36:12 +00001646 // A macro without parameters is handled differently on Darwin:
1647 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001648 while (!Body.empty()) {
1649 // Scan for the next substitution.
1650 std::size_t End = Body.size(), Pos = 0;
1651 for (; Pos != End; ++Pos) {
1652 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001653 if (!NParameters) {
1654 // This macro has no parameters, look for $0, $1, etc.
1655 if (Body[Pos] != '$' || Pos + 1 == End)
1656 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001657
Rafael Espindola65366442011-06-05 02:43:45 +00001658 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00001659 if (Next == '$' || Next == 'n' ||
1660 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola65366442011-06-05 02:43:45 +00001661 break;
1662 } else {
1663 // This macro has parameters, look for \foo, \bar, etc.
1664 if (Body[Pos] == '\\' && Pos + 1 != End)
1665 break;
1666 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001667 }
1668
1669 // Add the prefix.
1670 OS << Body.slice(0, Pos);
1671
1672 // Check if we reached the end.
1673 if (Pos == End)
1674 break;
1675
Rafael Espindola65366442011-06-05 02:43:45 +00001676 if (!NParameters) {
1677 switch (Body[Pos+1]) {
1678 // $$ => $
1679 case '$':
1680 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001681 break;
1682
Rafael Espindola65366442011-06-05 02:43:45 +00001683 // $n => number of arguments
1684 case 'n':
1685 OS << A.size();
1686 break;
1687
1688 // $[0-9] => argument
1689 default: {
1690 // Missing arguments are ignored.
1691 unsigned Index = Body[Pos+1] - '0';
1692 if (Index >= A.size())
1693 break;
1694
1695 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001696 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001697 ie = A[Index].end(); it != ie; ++it)
1698 OS << it->getString();
1699 break;
1700 }
1701 }
1702 Pos += 2;
1703 } else {
1704 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001705 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001706 ++I;
1707
1708 const char *Begin = Body.data() + Pos +1;
1709 StringRef Argument(Begin, I - (Pos +1));
1710 unsigned Index = 0;
1711 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001712 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001713 break;
1714
Preston Gurd7b6f2032012-09-19 20:36:12 +00001715 if (Index == NParameters) {
1716 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1717 Pos += 3;
1718 else {
1719 OS << '\\' << Argument;
1720 Pos = I;
1721 }
1722 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001723 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001724 ie = A[Index].end(); it != ie; ++it)
1725 if (it->getKind() == AsmToken::String)
1726 OS << it->getStringContents();
1727 else
1728 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001729
Preston Gurd7b6f2032012-09-19 20:36:12 +00001730 Pos += 1 + Argument.size();
1731 }
Rafael Espindola65366442011-06-05 02:43:45 +00001732 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001733 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001734 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001735 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001736
Rafael Espindola65366442011-06-05 02:43:45 +00001737 return false;
1738}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001739
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001740MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001741 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001742 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001743 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1744 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001745{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001746}
1747
Preston Gurd7b6f2032012-09-19 20:36:12 +00001748static bool IsOperator(AsmToken::TokenKind kind)
1749{
1750 switch (kind)
1751 {
1752 default:
1753 return false;
1754 case AsmToken::Plus:
1755 case AsmToken::Minus:
1756 case AsmToken::Tilde:
1757 case AsmToken::Slash:
1758 case AsmToken::Star:
1759 case AsmToken::Dot:
1760 case AsmToken::Equal:
1761 case AsmToken::EqualEqual:
1762 case AsmToken::Pipe:
1763 case AsmToken::PipePipe:
1764 case AsmToken::Caret:
1765 case AsmToken::Amp:
1766 case AsmToken::AmpAmp:
1767 case AsmToken::Exclaim:
1768 case AsmToken::ExclaimEqual:
1769 case AsmToken::Percent:
1770 case AsmToken::Less:
1771 case AsmToken::LessEqual:
1772 case AsmToken::LessLess:
1773 case AsmToken::LessGreater:
1774 case AsmToken::Greater:
1775 case AsmToken::GreaterEqual:
1776 case AsmToken::GreaterGreater:
1777 return true;
1778 }
1779}
1780
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001781bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001782 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001783 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001784 unsigned AddTokens = 0;
1785
1786 // gas accepts arguments separated by whitespace, except on Darwin
1787 if (!IsDarwin)
1788 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001789
1790 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001791 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1792 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001793 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001794 }
1795
1796 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1797 // Spaces and commas cannot be mixed to delimit parameters
1798 if (ArgumentDelimiter == AsmToken::Eof)
1799 ArgumentDelimiter = AsmToken::Comma;
1800 else if (ArgumentDelimiter != AsmToken::Comma) {
1801 Lexer.setSkipSpace(true);
1802 return TokError("expected ' ' for macro argument separator");
1803 }
1804 break;
1805 }
1806
1807 if (Lexer.is(AsmToken::Space)) {
1808 Lex(); // Eat spaces
1809
1810 // Spaces can delimit parameters, but could also be part an expression.
1811 // If the token after a space is an operator, add the token and the next
1812 // one into this argument
1813 if (ArgumentDelimiter == AsmToken::Space ||
1814 ArgumentDelimiter == AsmToken::Eof) {
1815 if (IsOperator(Lexer.getKind())) {
1816 // Check to see whether the token is used as an operator,
1817 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001818 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001819 if (*NextChar == ' ')
1820 AddTokens = 2;
1821 }
1822
1823 if (!AddTokens && ParenLevel == 0) {
1824 if (ArgumentDelimiter == AsmToken::Eof &&
1825 !IsOperator(Lexer.getKind()))
1826 ArgumentDelimiter = AsmToken::Space;
1827 break;
1828 }
1829 }
1830 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001831
1832 // HandleMacroEntry relies on not advancing the lexer here
1833 // to be able to fill in the remaining default parameter values
1834 if (Lexer.is(AsmToken::EndOfStatement))
1835 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001836
1837 // Adjust the current parentheses level.
1838 if (Lexer.is(AsmToken::LParen))
1839 ++ParenLevel;
1840 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1841 --ParenLevel;
1842
1843 // Append the token to the current argument list.
1844 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001845 if (AddTokens)
1846 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001847 Lex();
1848 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001849
1850 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001851 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001852 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001853 return false;
1854}
1855
1856// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001857bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001858 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001859 // Argument delimiter is initially unknown. It will be set by
1860 // ParseMacroArgument()
1861 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001862
1863 // Parse two kinds of macro invocations:
1864 // - macros defined without any parameters accept an arbitrary number of them
1865 // - macros defined with parameters accept at most that many of them
1866 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1867 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001868 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001869
Preston Gurd7b6f2032012-09-19 20:36:12 +00001870 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001871 return true;
1872
Preston Gurd6c9176a2012-09-19 20:29:04 +00001873 if (!MA.empty() || !NParameters)
1874 A.push_back(MA);
1875 else if (NParameters) {
1876 if (!M->Parameters[Parameter].second.empty())
1877 A.push_back(M->Parameters[Parameter].second);
1878 }
Jim Grosbach97146442012-07-30 22:44:17 +00001879
Preston Gurd6c9176a2012-09-19 20:29:04 +00001880 // At the end of the statement, fill in remaining arguments that have
1881 // default values. If there aren't any, then the next argument is
1882 // required but missing
1883 if (Lexer.is(AsmToken::EndOfStatement)) {
1884 if (NParameters && Parameter < NParameters - 1) {
1885 if (M->Parameters[Parameter + 1].second.empty())
1886 return TokError("macro argument '" +
1887 Twine(M->Parameters[Parameter + 1].first) +
1888 "' is missing");
1889 else
1890 continue;
1891 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001892 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001893 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001894
1895 if (Lexer.is(AsmToken::Comma))
1896 Lex();
1897 }
1898 return TokError("Too many arguments");
1899}
1900
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001901const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1902 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1903 return (I == MacroMap.end()) ? NULL : I->getValue();
1904}
1905
1906void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1907 MacroMap[Name] = new MCAsmMacro(Macro);
1908}
1909
1910void AsmParser::UndefineMacro(StringRef Name) {
1911 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1912 if (I != MacroMap.end()) {
1913 delete I->getValue();
1914 MacroMap.erase(I);
1915 }
1916}
1917
1918bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001919 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1920 // this, although we should protect against infinite loops.
1921 if (ActiveMacros.size() == 20)
1922 return TokError("macros cannot be nested more than 20 levels deep");
1923
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001924 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001925 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001926 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001927
Jim Grosbach97146442012-07-30 22:44:17 +00001928 // Remove any trailing empty arguments. Do this after-the-fact as we have
1929 // to keep empty arguments in the middle of the list or positionality
1930 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001931 while (!A.empty() && A.back().empty())
1932 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001933
Rafael Espindola65366442011-06-05 02:43:45 +00001934 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1935 // to hold the macro body with substitutions.
1936 SmallString<256> Buf;
1937 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001938 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001939
Rafael Espindola8a403d32012-08-08 14:51:03 +00001940 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001941 return true;
1942
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001943 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001944 // instantiation.
1945 OS << ".endmacro\n";
1946
Rafael Espindola65366442011-06-05 02:43:45 +00001947 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001948 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001949
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001950 // Create the macro instantiation object and add to the current macro
1951 // instantiation stack.
1952 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001953 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001954 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001955 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001956 ActiveMacros.push_back(MI);
1957
1958 // Jump to the macro instantiation and prime the lexer.
1959 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1960 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1961 Lex();
1962
1963 return false;
1964}
1965
1966void AsmParser::HandleMacroExit() {
1967 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001968 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001969 Lex();
1970
1971 // Pop the instantiation entry.
1972 delete ActiveMacros.back();
1973 ActiveMacros.pop_back();
1974}
1975
Rafael Espindolae71cc862012-01-28 05:57:00 +00001976static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001977 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001978 case MCExpr::Binary: {
1979 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1980 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001981 break;
1982 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001983 case MCExpr::Target:
1984 case MCExpr::Constant:
1985 return false;
1986 case MCExpr::SymbolRef: {
1987 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001988 if (S.isVariable())
1989 return IsUsedIn(Sym, S.getVariableValue());
1990 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001991 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001992 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001993 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001994 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001995
1996 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001997}
1998
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001999bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
2000 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002001 // FIXME: Use better location, we should use proper tokens.
2002 SMLoc EqualLoc = Lexer.getLoc();
2003
Daniel Dunbar821e3332009-08-31 08:09:28 +00002004 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00002005 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002006 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002007
Rafael Espindolae71cc862012-01-28 05:57:00 +00002008 // Note: we don't count b as used in "a = b". This is to allow
2009 // a = b
2010 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002011
Daniel Dunbar3f872332009-07-28 16:08:33 +00002012 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002013 return TokError("unexpected token in assignment");
2014
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00002015 // Error on assignment to '.'.
2016 if (Name == ".") {
2017 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2018 "(use '.space' or '.org').)"));
2019 }
2020
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002021 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002022 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002023
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002024 // Validate that the LHS is allowed to be a variable (either it has not been
2025 // used as a symbol, or it is an absolute symbol).
2026 MCSymbol *Sym = getContext().LookupSymbol(Name);
2027 if (Sym) {
2028 // Diagnose assignment to a label.
2029 //
2030 // FIXME: Diagnostics. Note the location of the definition as a label.
2031 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002032 if (IsUsedIn(Sym, Value))
2033 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2034 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002035 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002036 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2037 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002038 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002039 return Error(EqualLoc, "redefinition of '" + Name + "'");
2040 else if (!Sym->isVariable())
2041 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002042 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002043 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2044 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002045
2046 // Don't count these checks as uses.
2047 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002048 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002049 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002050
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002051 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002052
2053 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002054 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002055 if (NoDeadStrip)
2056 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2057
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002058
2059 return false;
2060}
2061
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002062/// ParseIdentifier:
2063/// ::= identifier
2064/// ::= string
2065bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002066 // The assembler has relaxed rules for accepting identifiers, in particular we
2067 // allow things like '.globl $foo', which would normally be separate
2068 // tokens. At this level, we have already lexed so we cannot (currently)
2069 // handle this as a context dependent token, instead we detect adjacent tokens
2070 // and return the combined identifier.
2071 if (Lexer.is(AsmToken::Dollar)) {
2072 SMLoc DollarLoc = getLexer().getLoc();
2073
2074 // Consume the dollar sign, and check for a following identifier.
2075 Lex();
2076 if (Lexer.isNot(AsmToken::Identifier))
2077 return true;
2078
2079 // We have a '$' followed by an identifier, make sure they are adjacent.
2080 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2081 return true;
2082
2083 // Construct the joined identifier and consume the token.
2084 Res = StringRef(DollarLoc.getPointer(),
2085 getTok().getIdentifier().size() + 1);
2086 Lex();
2087 return false;
2088 }
2089
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002090 if (Lexer.isNot(AsmToken::Identifier) &&
2091 Lexer.isNot(AsmToken::String))
2092 return true;
2093
Sean Callanan18b83232010-01-19 21:44:56 +00002094 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002095
Sean Callanan79ed1a82010-01-19 20:22:31 +00002096 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002097
2098 return false;
2099}
2100
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002101/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002102/// ::= .equ identifier ',' expression
2103/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002104/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002105bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002106 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002107
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002108 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002109 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002110
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002111 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002112 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002113 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002114
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002115 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002116}
2117
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002118bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002119 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002120
2121 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002122 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002123 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2124 if (Str[i] != '\\') {
2125 Data += Str[i];
2126 continue;
2127 }
2128
2129 // Recognize escaped characters. Note that this escape semantics currently
2130 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2131 ++i;
2132 if (i == e)
2133 return TokError("unexpected backslash at end of string");
2134
2135 // Recognize octal sequences.
2136 if ((unsigned) (Str[i] - '0') <= 7) {
2137 // Consume up to three octal characters.
2138 unsigned Value = Str[i] - '0';
2139
2140 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2141 ++i;
2142 Value = Value * 8 + (Str[i] - '0');
2143
2144 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2145 ++i;
2146 Value = Value * 8 + (Str[i] - '0');
2147 }
2148 }
2149
2150 if (Value > 255)
2151 return TokError("invalid octal escape sequence (out of range)");
2152
2153 Data += (unsigned char) Value;
2154 continue;
2155 }
2156
2157 // Otherwise recognize individual escapes.
2158 switch (Str[i]) {
2159 default:
2160 // Just reject invalid escape sequences for now.
2161 return TokError("invalid escape sequence (unrecognized character)");
2162
2163 case 'b': Data += '\b'; break;
2164 case 'f': Data += '\f'; break;
2165 case 'n': Data += '\n'; break;
2166 case 'r': Data += '\r'; break;
2167 case 't': Data += '\t'; break;
2168 case '"': Data += '"'; break;
2169 case '\\': Data += '\\'; break;
2170 }
2171 }
2172
2173 return false;
2174}
2175
Daniel Dunbara0d14262009-06-24 23:30:00 +00002176/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002177/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2178bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002179 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002180 CheckForValidSection();
2181
Daniel Dunbara0d14262009-06-24 23:30:00 +00002182 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002183 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002184 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002185
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002186 std::string Data;
2187 if (ParseEscapedString(Data))
2188 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002189
2190 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002191 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002192 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2193
Sean Callanan79ed1a82010-01-19 20:22:31 +00002194 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002195
2196 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002197 break;
2198
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002199 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002200 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002201 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002202 }
2203 }
2204
Sean Callanan79ed1a82010-01-19 20:22:31 +00002205 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002206 return false;
2207}
2208
2209/// ParseDirectiveValue
2210/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2211bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002212 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002213 CheckForValidSection();
2214
Daniel Dunbara0d14262009-06-24 23:30:00 +00002215 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002216 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002217 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002218 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002219 return true;
2220
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002221 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002222 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2223 assert(Size <= 8 && "Invalid size");
2224 uint64_t IntValue = MCE->getValue();
2225 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2226 return Error(ExprLoc, "literal value out of range for directive");
2227 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2228 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002229 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002230
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002231 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002232 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002233
Daniel Dunbara0d14262009-06-24 23:30:00 +00002234 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002235 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002236 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002237 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002238 }
2239 }
2240
Sean Callanan79ed1a82010-01-19 20:22:31 +00002241 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002242 return false;
2243}
2244
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002245/// ParseDirectiveRealValue
2246/// ::= (.single | .double) [ expression (, expression)* ]
2247bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2248 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2249 CheckForValidSection();
2250
2251 for (;;) {
2252 // We don't truly support arithmetic on floating point expressions, so we
2253 // have to manually parse unary prefixes.
2254 bool IsNeg = false;
2255 if (getLexer().is(AsmToken::Minus)) {
2256 Lex();
2257 IsNeg = true;
2258 } else if (getLexer().is(AsmToken::Plus))
2259 Lex();
2260
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002261 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002262 getLexer().isNot(AsmToken::Real) &&
2263 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002264 return TokError("unexpected token in directive");
2265
2266 // Convert to an APFloat.
2267 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002268 StringRef IDVal = getTok().getString();
2269 if (getLexer().is(AsmToken::Identifier)) {
2270 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2271 Value = APFloat::getInf(Semantics);
2272 else if (!IDVal.compare_lower("nan"))
2273 Value = APFloat::getNaN(Semantics, false, ~0);
2274 else
2275 return TokError("invalid floating point literal");
2276 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002277 APFloat::opInvalidOp)
2278 return TokError("invalid floating point literal");
2279 if (IsNeg)
2280 Value.changeSign();
2281
2282 // Consume the numeric token.
2283 Lex();
2284
2285 // Emit the value as an integer.
2286 APInt AsInt = Value.bitcastToAPInt();
2287 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2288 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2289
2290 if (getLexer().is(AsmToken::EndOfStatement))
2291 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002292
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002293 if (getLexer().isNot(AsmToken::Comma))
2294 return TokError("unexpected token in directive");
2295 Lex();
2296 }
2297 }
2298
2299 Lex();
2300 return false;
2301}
2302
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002303/// ParseDirectiveZero
2304/// ::= .zero expression
2305bool AsmParser::ParseDirectiveZero() {
2306 CheckForValidSection();
2307
2308 int64_t NumBytes;
2309 if (ParseAbsoluteExpression(NumBytes))
2310 return true;
2311
Rafael Espindolae452b172010-10-05 19:42:57 +00002312 int64_t Val = 0;
2313 if (getLexer().is(AsmToken::Comma)) {
2314 Lex();
2315 if (ParseAbsoluteExpression(Val))
2316 return true;
2317 }
2318
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002319 if (getLexer().isNot(AsmToken::EndOfStatement))
2320 return TokError("unexpected token in '.zero' directive");
2321
2322 Lex();
2323
Rafael Espindolae452b172010-10-05 19:42:57 +00002324 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002325
2326 return false;
2327}
2328
Daniel Dunbara0d14262009-06-24 23:30:00 +00002329/// ParseDirectiveFill
2330/// ::= .fill expression , expression , expression
2331bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002332 CheckForValidSection();
2333
Daniel Dunbara0d14262009-06-24 23:30:00 +00002334 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002335 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002336 return true;
2337
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002338 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002339 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002340 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002341
Daniel Dunbara0d14262009-06-24 23:30:00 +00002342 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002343 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002344 return true;
2345
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002346 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002347 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002348 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002349
Daniel Dunbara0d14262009-06-24 23:30:00 +00002350 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002351 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002352 return true;
2353
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002354 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002355 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002356
Sean Callanan79ed1a82010-01-19 20:22:31 +00002357 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002358
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002359 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2360 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002361
2362 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002363 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002364
2365 return false;
2366}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002367
2368/// ParseDirectiveOrg
2369/// ::= .org expression [ , expression ]
2370bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002371 CheckForValidSection();
2372
Daniel Dunbar821e3332009-08-31 08:09:28 +00002373 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002374 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002375 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002376 return true;
2377
2378 // Parse optional fill expression.
2379 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002380 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2381 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002382 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002383 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002384
Daniel Dunbar475839e2009-06-29 20:37:27 +00002385 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002386 return true;
2387
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002388 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002389 return TokError("unexpected token in '.org' directive");
2390 }
2391
Sean Callanan79ed1a82010-01-19 20:22:31 +00002392 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002393
Jim Grosbachebd4c052012-01-27 00:37:08 +00002394 // Only limited forms of relocatable expressions are accepted here, it
2395 // has to be relative to the current section. The streamer will return
2396 // 'true' if the expression wasn't evaluatable.
2397 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2398 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002399
2400 return false;
2401}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002402
2403/// ParseDirectiveAlign
2404/// ::= {.align, ...} expression [ , expression [ , expression ]]
2405bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002406 CheckForValidSection();
2407
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002408 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002409 int64_t Alignment;
2410 if (ParseAbsoluteExpression(Alignment))
2411 return true;
2412
2413 SMLoc MaxBytesLoc;
2414 bool HasFillExpr = false;
2415 int64_t FillExpr = 0;
2416 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002417 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2418 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002419 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002420 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002421
2422 // The fill expression can be omitted while specifying a maximum number of
2423 // alignment bytes, e.g:
2424 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002425 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002426 HasFillExpr = true;
2427 if (ParseAbsoluteExpression(FillExpr))
2428 return true;
2429 }
2430
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002431 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2432 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002433 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002434 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002435
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002436 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002437 if (ParseAbsoluteExpression(MaxBytesToFill))
2438 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002439
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002440 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002441 return TokError("unexpected token in directive");
2442 }
2443 }
2444
Sean Callanan79ed1a82010-01-19 20:22:31 +00002445 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002446
Daniel Dunbar648ac512010-05-17 21:54:30 +00002447 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002448 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002449
2450 // Compute alignment in bytes.
2451 if (IsPow2) {
2452 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002453 if (Alignment >= 32) {
2454 Error(AlignmentLoc, "invalid alignment value");
2455 Alignment = 31;
2456 }
2457
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002458 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002459 }
2460
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002461 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002462 if (MaxBytesLoc.isValid()) {
2463 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002464 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2465 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002466 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002467 }
2468
2469 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002470 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2471 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002472 MaxBytesToFill = 0;
2473 }
2474 }
2475
Daniel Dunbar648ac512010-05-17 21:54:30 +00002476 // Check whether we should use optimal code alignment for this .align
2477 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002478 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002479 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2480 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002481 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002482 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002483 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002484 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2485 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002486 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002487
2488 return false;
2489}
2490
Eli Bendersky6ee13082013-01-15 22:59:42 +00002491/// ParseDirectiveFile
2492/// ::= .file [number] filename
2493/// ::= .file number directory filename
2494bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2495 // FIXME: I'm not sure what this is.
2496 int64_t FileNumber = -1;
2497 SMLoc FileNumberLoc = getLexer().getLoc();
2498 if (getLexer().is(AsmToken::Integer)) {
2499 FileNumber = getTok().getIntVal();
2500 Lex();
2501
2502 if (FileNumber < 1)
2503 return TokError("file number less than one");
2504 }
2505
2506 if (getLexer().isNot(AsmToken::String))
2507 return TokError("unexpected token in '.file' directive");
2508
2509 // Usually the directory and filename together, otherwise just the directory.
2510 StringRef Path = getTok().getString();
2511 Path = Path.substr(1, Path.size()-2);
2512 Lex();
2513
2514 StringRef Directory;
2515 StringRef Filename;
2516 if (getLexer().is(AsmToken::String)) {
2517 if (FileNumber == -1)
2518 return TokError("explicit path specified, but no file number");
2519 Filename = getTok().getString();
2520 Filename = Filename.substr(1, Filename.size()-2);
2521 Directory = Path;
2522 Lex();
2523 } else {
2524 Filename = Path;
2525 }
2526
2527 if (getLexer().isNot(AsmToken::EndOfStatement))
2528 return TokError("unexpected token in '.file' directive");
2529
2530 if (FileNumber == -1)
2531 getStreamer().EmitFileDirective(Filename);
2532 else {
2533 if (getContext().getGenDwarfForAssembly() == true)
2534 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2535 "used to generate dwarf debug info for assembly code");
2536
2537 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2538 Error(FileNumberLoc, "file number already allocated");
2539 }
2540
2541 return false;
2542}
2543
2544/// ParseDirectiveLine
2545/// ::= .line [number]
2546bool AsmParser::ParseDirectiveLine() {
2547 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2548 if (getLexer().isNot(AsmToken::Integer))
2549 return TokError("unexpected token in '.line' directive");
2550
2551 int64_t LineNumber = getTok().getIntVal();
2552 (void) LineNumber;
2553 Lex();
2554
2555 // FIXME: Do something with the .line.
2556 }
2557
2558 if (getLexer().isNot(AsmToken::EndOfStatement))
2559 return TokError("unexpected token in '.line' directive");
2560
2561 return false;
2562}
2563
2564/// ParseDirectiveLoc
2565/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2566/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2567/// The first number is a file number, must have been previously assigned with
2568/// a .file directive, the second number is the line number and optionally the
2569/// third number is a column position (zero if not specified). The remaining
2570/// optional items are .loc sub-directives.
2571bool AsmParser::ParseDirectiveLoc() {
2572 if (getLexer().isNot(AsmToken::Integer))
2573 return TokError("unexpected token in '.loc' directive");
2574 int64_t FileNumber = getTok().getIntVal();
2575 if (FileNumber < 1)
2576 return TokError("file number less than one in '.loc' directive");
2577 if (!getContext().isValidDwarfFileNumber(FileNumber))
2578 return TokError("unassigned file number in '.loc' directive");
2579 Lex();
2580
2581 int64_t LineNumber = 0;
2582 if (getLexer().is(AsmToken::Integer)) {
2583 LineNumber = getTok().getIntVal();
2584 if (LineNumber < 1)
2585 return TokError("line number less than one in '.loc' directive");
2586 Lex();
2587 }
2588
2589 int64_t ColumnPos = 0;
2590 if (getLexer().is(AsmToken::Integer)) {
2591 ColumnPos = getTok().getIntVal();
2592 if (ColumnPos < 0)
2593 return TokError("column position less than zero in '.loc' directive");
2594 Lex();
2595 }
2596
2597 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2598 unsigned Isa = 0;
2599 int64_t Discriminator = 0;
2600 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2601 for (;;) {
2602 if (getLexer().is(AsmToken::EndOfStatement))
2603 break;
2604
2605 StringRef Name;
2606 SMLoc Loc = getTok().getLoc();
2607 if (ParseIdentifier(Name))
2608 return TokError("unexpected token in '.loc' directive");
2609
2610 if (Name == "basic_block")
2611 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2612 else if (Name == "prologue_end")
2613 Flags |= DWARF2_FLAG_PROLOGUE_END;
2614 else if (Name == "epilogue_begin")
2615 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2616 else if (Name == "is_stmt") {
2617 Loc = getTok().getLoc();
2618 const MCExpr *Value;
2619 if (ParseExpression(Value))
2620 return true;
2621 // The expression must be the constant 0 or 1.
2622 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2623 int Value = MCE->getValue();
2624 if (Value == 0)
2625 Flags &= ~DWARF2_FLAG_IS_STMT;
2626 else if (Value == 1)
2627 Flags |= DWARF2_FLAG_IS_STMT;
2628 else
2629 return Error(Loc, "is_stmt value not 0 or 1");
2630 }
2631 else {
2632 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2633 }
2634 }
2635 else if (Name == "isa") {
2636 Loc = getTok().getLoc();
2637 const MCExpr *Value;
2638 if (ParseExpression(Value))
2639 return true;
2640 // The expression must be a constant greater or equal to 0.
2641 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2642 int Value = MCE->getValue();
2643 if (Value < 0)
2644 return Error(Loc, "isa number less than zero");
2645 Isa = Value;
2646 }
2647 else {
2648 return Error(Loc, "isa number not a constant value");
2649 }
2650 }
2651 else if (Name == "discriminator") {
2652 if (ParseAbsoluteExpression(Discriminator))
2653 return true;
2654 }
2655 else {
2656 return Error(Loc, "unknown sub-directive in '.loc' directive");
2657 }
2658
2659 if (getLexer().is(AsmToken::EndOfStatement))
2660 break;
2661 }
2662 }
2663
2664 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2665 Isa, Discriminator, StringRef());
2666
2667 return false;
2668}
2669
2670/// ParseDirectiveStabs
2671/// ::= .stabs string, number, number, number
2672bool AsmParser::ParseDirectiveStabs() {
2673 return TokError("unsupported directive '.stabs'");
2674}
2675
2676/// ParseDirectiveCFISections
2677/// ::= .cfi_sections section [, section]
2678bool AsmParser::ParseDirectiveCFISections() {
2679 StringRef Name;
2680 bool EH = false;
2681 bool Debug = false;
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 if (getLexer().is(AsmToken::Comma)) {
2692 Lex();
2693
2694 if (ParseIdentifier(Name))
2695 return TokError("Expected an identifier");
2696
2697 if (Name == ".eh_frame")
2698 EH = true;
2699 else if (Name == ".debug_frame")
2700 Debug = true;
2701 }
2702
2703 getStreamer().EmitCFISections(EH, Debug);
2704 return false;
2705}
2706
2707/// ParseDirectiveCFIStartProc
2708/// ::= .cfi_startproc
2709bool AsmParser::ParseDirectiveCFIStartProc() {
2710 getStreamer().EmitCFIStartProc();
2711 return false;
2712}
2713
2714/// ParseDirectiveCFIEndProc
2715/// ::= .cfi_endproc
2716bool AsmParser::ParseDirectiveCFIEndProc() {
2717 getStreamer().EmitCFIEndProc();
2718 return false;
2719}
2720
2721/// ParseRegisterOrRegisterNumber - parse register name or number.
2722bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2723 SMLoc DirectiveLoc) {
2724 unsigned RegNo;
2725
2726 if (getLexer().isNot(AsmToken::Integer)) {
2727 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2728 return true;
2729 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2730 } else
2731 return ParseAbsoluteExpression(Register);
2732
2733 return false;
2734}
2735
2736/// ParseDirectiveCFIDefCfa
2737/// ::= .cfi_def_cfa register, offset
2738bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2739 int64_t Register = 0;
2740 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2741 return true;
2742
2743 if (getLexer().isNot(AsmToken::Comma))
2744 return TokError("unexpected token in directive");
2745 Lex();
2746
2747 int64_t Offset = 0;
2748 if (ParseAbsoluteExpression(Offset))
2749 return true;
2750
2751 getStreamer().EmitCFIDefCfa(Register, Offset);
2752 return false;
2753}
2754
2755/// ParseDirectiveCFIDefCfaOffset
2756/// ::= .cfi_def_cfa_offset offset
2757bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2758 int64_t Offset = 0;
2759 if (ParseAbsoluteExpression(Offset))
2760 return true;
2761
2762 getStreamer().EmitCFIDefCfaOffset(Offset);
2763 return false;
2764}
2765
2766/// ParseDirectiveCFIRegister
2767/// ::= .cfi_register register, register
2768bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2769 int64_t Register1 = 0;
2770 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2771 return true;
2772
2773 if (getLexer().isNot(AsmToken::Comma))
2774 return TokError("unexpected token in directive");
2775 Lex();
2776
2777 int64_t Register2 = 0;
2778 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2779 return true;
2780
2781 getStreamer().EmitCFIRegister(Register1, Register2);
2782 return false;
2783}
2784
2785/// ParseDirectiveCFIAdjustCfaOffset
2786/// ::= .cfi_adjust_cfa_offset adjustment
2787bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2788 int64_t Adjustment = 0;
2789 if (ParseAbsoluteExpression(Adjustment))
2790 return true;
2791
2792 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2793 return false;
2794}
2795
2796/// ParseDirectiveCFIDefCfaRegister
2797/// ::= .cfi_def_cfa_register register
2798bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2799 int64_t Register = 0;
2800 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2801 return true;
2802
2803 getStreamer().EmitCFIDefCfaRegister(Register);
2804 return false;
2805}
2806
2807/// ParseDirectiveCFIOffset
2808/// ::= .cfi_offset register, offset
2809bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2810 int64_t Register = 0;
2811 int64_t Offset = 0;
2812
2813 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2814 return true;
2815
2816 if (getLexer().isNot(AsmToken::Comma))
2817 return TokError("unexpected token in directive");
2818 Lex();
2819
2820 if (ParseAbsoluteExpression(Offset))
2821 return true;
2822
2823 getStreamer().EmitCFIOffset(Register, Offset);
2824 return false;
2825}
2826
2827/// ParseDirectiveCFIRelOffset
2828/// ::= .cfi_rel_offset register, offset
2829bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2830 int64_t Register = 0;
2831
2832 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2833 return true;
2834
2835 if (getLexer().isNot(AsmToken::Comma))
2836 return TokError("unexpected token in directive");
2837 Lex();
2838
2839 int64_t Offset = 0;
2840 if (ParseAbsoluteExpression(Offset))
2841 return true;
2842
2843 getStreamer().EmitCFIRelOffset(Register, Offset);
2844 return false;
2845}
2846
2847static bool isValidEncoding(int64_t Encoding) {
2848 if (Encoding & ~0xff)
2849 return false;
2850
2851 if (Encoding == dwarf::DW_EH_PE_omit)
2852 return true;
2853
2854 const unsigned Format = Encoding & 0xf;
2855 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2856 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2857 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2858 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2859 return false;
2860
2861 const unsigned Application = Encoding & 0x70;
2862 if (Application != dwarf::DW_EH_PE_absptr &&
2863 Application != dwarf::DW_EH_PE_pcrel)
2864 return false;
2865
2866 return true;
2867}
2868
2869/// ParseDirectiveCFIPersonalityOrLsda
2870/// IsPersonality true for cfi_personality, false for cfi_lsda
2871/// ::= .cfi_personality encoding, [symbol_name]
2872/// ::= .cfi_lsda encoding, [symbol_name]
2873bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2874 int64_t Encoding = 0;
2875 if (ParseAbsoluteExpression(Encoding))
2876 return true;
2877 if (Encoding == dwarf::DW_EH_PE_omit)
2878 return false;
2879
2880 if (!isValidEncoding(Encoding))
2881 return TokError("unsupported encoding.");
2882
2883 if (getLexer().isNot(AsmToken::Comma))
2884 return TokError("unexpected token in directive");
2885 Lex();
2886
2887 StringRef Name;
2888 if (ParseIdentifier(Name))
2889 return TokError("expected identifier in directive");
2890
2891 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2892
2893 if (IsPersonality)
2894 getStreamer().EmitCFIPersonality(Sym, Encoding);
2895 else
2896 getStreamer().EmitCFILsda(Sym, Encoding);
2897 return false;
2898}
2899
2900/// ParseDirectiveCFIRememberState
2901/// ::= .cfi_remember_state
2902bool AsmParser::ParseDirectiveCFIRememberState() {
2903 getStreamer().EmitCFIRememberState();
2904 return false;
2905}
2906
2907/// ParseDirectiveCFIRestoreState
2908/// ::= .cfi_remember_state
2909bool AsmParser::ParseDirectiveCFIRestoreState() {
2910 getStreamer().EmitCFIRestoreState();
2911 return false;
2912}
2913
2914/// ParseDirectiveCFISameValue
2915/// ::= .cfi_same_value register
2916bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2917 int64_t Register = 0;
2918
2919 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2920 return true;
2921
2922 getStreamer().EmitCFISameValue(Register);
2923 return false;
2924}
2925
2926/// ParseDirectiveCFIRestore
2927/// ::= .cfi_restore register
2928bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2929 int64_t Register = 0;
2930 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2931 return true;
2932
2933 getStreamer().EmitCFIRestore(Register);
2934 return false;
2935}
2936
2937/// ParseDirectiveCFIEscape
2938/// ::= .cfi_escape expression[,...]
2939bool AsmParser::ParseDirectiveCFIEscape() {
2940 std::string Values;
2941 int64_t CurrValue;
2942 if (ParseAbsoluteExpression(CurrValue))
2943 return true;
2944
2945 Values.push_back((uint8_t)CurrValue);
2946
2947 while (getLexer().is(AsmToken::Comma)) {
2948 Lex();
2949
2950 if (ParseAbsoluteExpression(CurrValue))
2951 return true;
2952
2953 Values.push_back((uint8_t)CurrValue);
2954 }
2955
2956 getStreamer().EmitCFIEscape(Values);
2957 return false;
2958}
2959
2960/// ParseDirectiveCFISignalFrame
2961/// ::= .cfi_signal_frame
2962bool AsmParser::ParseDirectiveCFISignalFrame() {
2963 if (getLexer().isNot(AsmToken::EndOfStatement))
2964 return Error(getLexer().getLoc(),
2965 "unexpected token in '.cfi_signal_frame'");
2966
2967 getStreamer().EmitCFISignalFrame();
2968 return false;
2969}
2970
2971/// ParseDirectiveCFIUndefined
2972/// ::= .cfi_undefined register
2973bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2974 int64_t Register = 0;
2975
2976 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2977 return true;
2978
2979 getStreamer().EmitCFIUndefined(Register);
2980 return false;
2981}
2982
2983/// ParseDirectiveMacrosOnOff
2984/// ::= .macros_on
2985/// ::= .macros_off
2986bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2987 if (getLexer().isNot(AsmToken::EndOfStatement))
2988 return Error(getLexer().getLoc(),
2989 "unexpected token in '" + Directive + "' directive");
2990
2991 SetMacrosEnabled(Directive == ".macros_on");
2992 return false;
2993}
2994
2995/// ParseDirectiveMacro
2996/// ::= .macro name [parameters]
2997bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2998 StringRef Name;
2999 if (ParseIdentifier(Name))
3000 return TokError("expected identifier in '.macro' directive");
3001
3002 MCAsmMacroParameters Parameters;
3003 // Argument delimiter is initially unknown. It will be set by
3004 // ParseMacroArgument()
3005 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
3006 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3007 for (;;) {
3008 MCAsmMacroParameter Parameter;
3009 if (ParseIdentifier(Parameter.first))
3010 return TokError("expected identifier in '.macro' directive");
3011
3012 if (getLexer().is(AsmToken::Equal)) {
3013 Lex();
3014 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
3015 return true;
3016 }
3017
3018 Parameters.push_back(Parameter);
3019
3020 if (getLexer().is(AsmToken::Comma))
3021 Lex();
3022 else if (getLexer().is(AsmToken::EndOfStatement))
3023 break;
3024 }
3025 }
3026
3027 // Eat the end of statement.
3028 Lex();
3029
3030 AsmToken EndToken, StartToken = getTok();
3031
3032 // Lex the macro definition.
3033 for (;;) {
3034 // Check whether we have reached the end of the file.
3035 if (getLexer().is(AsmToken::Eof))
3036 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3037
3038 // Otherwise, check whether we have reach the .endmacro.
3039 if (getLexer().is(AsmToken::Identifier) &&
3040 (getTok().getIdentifier() == ".endm" ||
3041 getTok().getIdentifier() == ".endmacro")) {
3042 EndToken = getTok();
3043 Lex();
3044 if (getLexer().isNot(AsmToken::EndOfStatement))
3045 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3046 "' directive");
3047 break;
3048 }
3049
3050 // Otherwise, scan til the end of the statement.
3051 EatToEndOfStatement();
3052 }
3053
3054 if (LookupMacro(Name)) {
3055 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3056 }
3057
3058 const char *BodyStart = StartToken.getLoc().getPointer();
3059 const char *BodyEnd = EndToken.getLoc().getPointer();
3060 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Kevin Enderby221514e2013-01-22 21:44:53 +00003061 CheckForBadMacro(DirectiveLoc, Name, Body, Parameters);
Eli Bendersky6ee13082013-01-15 22:59:42 +00003062 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3063 return false;
3064}
3065
Kevin Enderby221514e2013-01-22 21:44:53 +00003066/// CheckForBadMacro
3067///
3068/// With the support added for named parameters there may be code out there that
3069/// is transitioning from positional parameters. In versions of gas that did
3070/// not support named parameters they would be ignored on the macro defintion.
3071/// But to support both styles of parameters this is not possible so if a macro
3072/// defintion has named parameters but does not use them and has what appears
3073/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3074/// warning that the positional parameter found in body which have no effect.
3075/// Hoping the developer will either remove the named parameters from the macro
3076/// definiton so the positional parameters get used if that was what was
3077/// intended or change the macro to use the named parameters. It is possible
3078/// this warning will trigger when the none of the named parameters are used
3079/// and the strings like $1 are infact to simply to be passed trough unchanged.
3080void AsmParser::CheckForBadMacro(SMLoc DirectiveLoc, StringRef Name,
3081 StringRef Body,
3082 MCAsmMacroParameters Parameters) {
3083 // If this macro is not defined with named parameters the warning we are
3084 // checking for here doesn't apply.
3085 unsigned NParameters = Parameters.size();
3086 if (NParameters == 0)
3087 return;
3088
3089 bool NamedParametersFound = false;
3090 bool PositionalParametersFound = false;
3091
3092 // Look at the body of the macro for use of both the named parameters and what
3093 // are likely to be positional parameters. This is what expandMacro() is
3094 // doing when it finds the parameters in the body.
3095 while (!Body.empty()) {
3096 // Scan for the next possible parameter.
3097 std::size_t End = Body.size(), Pos = 0;
3098 for (; Pos != End; ++Pos) {
3099 // Check for a substitution or escape.
3100 // This macro is defined with parameters, look for \foo, \bar, etc.
3101 if (Body[Pos] == '\\' && Pos + 1 != End)
3102 break;
3103
3104 // This macro should have parameters, but look for $0, $1, ..., $n too.
3105 if (Body[Pos] != '$' || Pos + 1 == End)
3106 continue;
3107 char Next = Body[Pos + 1];
Guy Benyei87d0b9e2013-02-12 21:21:59 +00003108 if (Next == '$' || Next == 'n' ||
3109 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby221514e2013-01-22 21:44:53 +00003110 break;
3111 }
3112
3113 // Check if we reached the end.
3114 if (Pos == End)
3115 break;
3116
3117 if (Body[Pos] == '$') {
3118 switch (Body[Pos+1]) {
3119 // $$ => $
3120 case '$':
3121 break;
3122
3123 // $n => number of arguments
3124 case 'n':
3125 PositionalParametersFound = true;
3126 break;
3127
3128 // $[0-9] => argument
3129 default: {
3130 PositionalParametersFound = true;
3131 break;
3132 }
3133 }
3134 Pos += 2;
3135 } else {
3136 unsigned I = Pos + 1;
3137 while (isIdentifierChar(Body[I]) && I + 1 != End)
3138 ++I;
3139
3140 const char *Begin = Body.data() + Pos +1;
3141 StringRef Argument(Begin, I - (Pos +1));
3142 unsigned Index = 0;
3143 for (; Index < NParameters; ++Index)
3144 if (Parameters[Index].first == Argument)
3145 break;
3146
3147 if (Index == NParameters) {
3148 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
3149 Pos += 3;
3150 else {
3151 Pos = I;
3152 }
3153 } else {
3154 NamedParametersFound = true;
3155 Pos += 1 + Argument.size();
3156 }
3157 }
3158 // Update the scan point.
3159 Body = Body.substr(Pos);
3160 }
3161
3162 if (!NamedParametersFound && PositionalParametersFound)
3163 Warning(DirectiveLoc, "macro defined with named parameters which are not "
3164 "used in macro body, possible positional parameter "
3165 "found in body which will have no effect");
3166}
3167
Eli Bendersky6ee13082013-01-15 22:59:42 +00003168/// ParseDirectiveEndMacro
3169/// ::= .endm
3170/// ::= .endmacro
3171bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3172 if (getLexer().isNot(AsmToken::EndOfStatement))
3173 return TokError("unexpected token in '" + Directive + "' directive");
3174
3175 // If we are inside a macro instantiation, terminate the current
3176 // instantiation.
3177 if (InsideMacroInstantiation()) {
3178 HandleMacroExit();
3179 return false;
3180 }
3181
3182 // Otherwise, this .endmacro is a stray entry in the file; well formed
3183 // .endmacro directives are handled during the macro definition parsing.
3184 return TokError("unexpected '" + Directive + "' in file, "
3185 "no current macro definition");
3186}
3187
3188/// ParseDirectivePurgeMacro
3189/// ::= .purgem
3190bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3191 StringRef Name;
3192 if (ParseIdentifier(Name))
3193 return TokError("expected identifier in '.purgem' directive");
3194
3195 if (getLexer().isNot(AsmToken::EndOfStatement))
3196 return TokError("unexpected token in '.purgem' directive");
3197
3198 if (!LookupMacro(Name))
3199 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3200
3201 UndefineMacro(Name);
3202 return false;
3203}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003204
3205/// ParseDirectiveBundleAlignMode
3206/// ::= {.bundle_align_mode} expression
3207bool AsmParser::ParseDirectiveBundleAlignMode() {
3208 CheckForValidSection();
3209
3210 // Expect a single argument: an expression that evaluates to a constant
3211 // in the inclusive range 0-30.
3212 SMLoc ExprLoc = getLexer().getLoc();
3213 int64_t AlignSizePow2;
3214 if (ParseAbsoluteExpression(AlignSizePow2))
3215 return true;
3216 else if (getLexer().isNot(AsmToken::EndOfStatement))
3217 return TokError("unexpected token after expression in"
3218 " '.bundle_align_mode' directive");
3219 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3220 return Error(ExprLoc,
3221 "invalid bundle alignment size (expected between 0 and 30)");
3222
3223 Lex();
3224
3225 // Because of AlignSizePow2's verified range we can safely truncate it to
3226 // unsigned.
3227 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3228 return false;
3229}
3230
3231/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003232/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003233bool AsmParser::ParseDirectiveBundleLock() {
3234 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003235 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003236
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003237 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3238 StringRef Option;
3239 SMLoc Loc = getTok().getLoc();
3240 const char *kInvalidOptionError =
3241 "invalid option for '.bundle_lock' directive";
3242
3243 if (ParseIdentifier(Option))
3244 return Error(Loc, kInvalidOptionError);
3245
3246 if (Option != "align_to_end")
3247 return Error(Loc, kInvalidOptionError);
3248 else if (getLexer().isNot(AsmToken::EndOfStatement))
3249 return Error(Loc,
3250 "unexpected token after '.bundle_lock' directive option");
3251 AlignToEnd = true;
3252 }
3253
Eli Bendersky4766ef42012-12-20 19:05:53 +00003254 Lex();
3255
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003256 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003257 return false;
3258}
3259
3260/// ParseDirectiveBundleLock
3261/// ::= {.bundle_lock}
3262bool AsmParser::ParseDirectiveBundleUnlock() {
3263 CheckForValidSection();
3264
3265 if (getLexer().isNot(AsmToken::EndOfStatement))
3266 return TokError("unexpected token in '.bundle_unlock' directive");
3267 Lex();
3268
3269 getStreamer().EmitBundleUnlock();
3270 return false;
3271}
3272
Eli Bendersky6ee13082013-01-15 22:59:42 +00003273/// ParseDirectiveSpace
3274/// ::= (.skip | .space) expression [ , expression ]
3275bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3276 CheckForValidSection();
3277
3278 int64_t NumBytes;
3279 if (ParseAbsoluteExpression(NumBytes))
3280 return true;
3281
3282 int64_t FillExpr = 0;
3283 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3284 if (getLexer().isNot(AsmToken::Comma))
3285 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3286 Lex();
3287
3288 if (ParseAbsoluteExpression(FillExpr))
3289 return true;
3290
3291 if (getLexer().isNot(AsmToken::EndOfStatement))
3292 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3293 }
3294
3295 Lex();
3296
3297 if (NumBytes <= 0)
3298 return TokError("invalid number of bytes in '" +
3299 Twine(IDVal) + "' directive");
3300
3301 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3302 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3303
3304 return false;
3305}
3306
3307/// ParseDirectiveLEB128
3308/// ::= (.sleb128 | .uleb128) expression
3309bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3310 CheckForValidSection();
3311 const MCExpr *Value;
3312
3313 if (ParseExpression(Value))
3314 return true;
3315
3316 if (getLexer().isNot(AsmToken::EndOfStatement))
3317 return TokError("unexpected token in directive");
3318
3319 if (Signed)
3320 getStreamer().EmitSLEB128Value(Value);
3321 else
3322 getStreamer().EmitULEB128Value(Value);
3323
3324 return false;
3325}
3326
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003327/// ParseDirectiveSymbolAttribute
3328/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003329bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003330 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003331 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003332 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003333 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003334
3335 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003336 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003337
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003338 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003339
Jim Grosbach10ec6502011-09-15 17:56:49 +00003340 // Assembler local symbols don't make any sense here. Complain loudly.
3341 if (Sym->isTemporary())
3342 return Error(Loc, "non-local symbol required in directive");
3343
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003344 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003345
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003346 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003347 break;
3348
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003349 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003350 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003351 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003352 }
3353 }
3354
Sean Callanan79ed1a82010-01-19 20:22:31 +00003355 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003356 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003357}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003358
3359/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003360/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3361bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003362 CheckForValidSection();
3363
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003364 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003365 StringRef Name;
3366 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003367 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003368
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003369 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003370 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003371
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003372 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003373 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003374 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003375
3376 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003377 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003378 if (ParseAbsoluteExpression(Size))
3379 return true;
3380
3381 int64_t Pow2Alignment = 0;
3382 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003383 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003384 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003385 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003386 if (ParseAbsoluteExpression(Pow2Alignment))
3387 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003388
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003389 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3390 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003391 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3392
Chris Lattner258281d2010-01-19 06:22:22 +00003393 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003394 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3395 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003396 if (!isPowerOf2_64(Pow2Alignment))
3397 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3398 Pow2Alignment = Log2_64(Pow2Alignment);
3399 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003400 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003401
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003402 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003403 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003404
Sean Callanan79ed1a82010-01-19 20:22:31 +00003405 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003406
Chris Lattner1fc3d752009-07-09 17:25:12 +00003407 // NOTE: a size of zero for a .comm should create a undefined symbol
3408 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003409 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003410 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3411 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003412
Eric Christopherc260a3e2010-05-14 01:38:54 +00003413 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003414 // may internally end up wanting an alignment in bytes.
3415 // FIXME: Diagnose overflow.
3416 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003417 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3418 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003419
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003420 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003421 return Error(IDLoc, "invalid symbol redefinition");
3422
Chris Lattner1fc3d752009-07-09 17:25:12 +00003423 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003424 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003425 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003426 return false;
3427 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003428
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003429 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003430 return false;
3431}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003432
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003433/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003434/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003435bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003436 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003437 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003438
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003439 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003440 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003441 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003442
Sean Callanan79ed1a82010-01-19 20:22:31 +00003443 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003444
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003445 if (Str.empty())
3446 Error(Loc, ".abort detected. Assembly stopping.");
3447 else
3448 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003449 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003450
3451 return false;
3452}
Kevin Enderby71148242009-07-14 21:35:03 +00003453
Kevin Enderby1f049b22009-07-14 23:21:55 +00003454/// ParseDirectiveInclude
3455/// ::= .include "filename"
3456bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003457 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003458 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003459
Sean Callanan18b83232010-01-19 21:44:56 +00003460 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003461 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003462 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003463
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003464 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003465 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003466
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003467 // Strip the quotes.
3468 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003469
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003470 // Attempt to switch the lexer to the included file before consuming the end
3471 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003472 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003473 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003474 return true;
3475 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003476
3477 return false;
3478}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003479
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003480/// ParseDirectiveIncbin
3481/// ::= .incbin "filename"
3482bool AsmParser::ParseDirectiveIncbin() {
3483 if (getLexer().isNot(AsmToken::String))
3484 return TokError("expected string in '.incbin' directive");
3485
3486 std::string Filename = getTok().getString();
3487 SMLoc IncbinLoc = getLexer().getLoc();
3488 Lex();
3489
3490 if (getLexer().isNot(AsmToken::EndOfStatement))
3491 return TokError("unexpected token in '.incbin' directive");
3492
3493 // Strip the quotes.
3494 Filename = Filename.substr(1, Filename.size()-2);
3495
3496 // Attempt to process the included file.
3497 if (ProcessIncbinFile(Filename)) {
3498 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3499 return true;
3500 }
3501
3502 return false;
3503}
3504
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003505/// ParseDirectiveIf
3506/// ::= .if expression
3507bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003508 TheCondStack.push_back(TheCondState);
3509 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003510 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003511 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003512 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003513 int64_t ExprValue;
3514 if (ParseAbsoluteExpression(ExprValue))
3515 return true;
3516
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003517 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003518 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003519
Sean Callanan79ed1a82010-01-19 20:22:31 +00003520 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003521
3522 TheCondState.CondMet = ExprValue;
3523 TheCondState.Ignore = !TheCondState.CondMet;
3524 }
3525
3526 return false;
3527}
3528
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003529/// ParseDirectiveIfb
3530/// ::= .ifb string
3531bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3532 TheCondStack.push_back(TheCondState);
3533 TheCondState.TheCond = AsmCond::IfCond;
3534
Benjamin Kramer29739e72012-05-12 16:52:21 +00003535 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003536 EatToEndOfStatement();
3537 } else {
3538 StringRef Str = ParseStringToEndOfStatement();
3539
3540 if (getLexer().isNot(AsmToken::EndOfStatement))
3541 return TokError("unexpected token in '.ifb' directive");
3542
3543 Lex();
3544
3545 TheCondState.CondMet = ExpectBlank == Str.empty();
3546 TheCondState.Ignore = !TheCondState.CondMet;
3547 }
3548
3549 return false;
3550}
3551
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003552/// ParseDirectiveIfc
3553/// ::= .ifc string1, string2
3554bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3555 TheCondStack.push_back(TheCondState);
3556 TheCondState.TheCond = AsmCond::IfCond;
3557
Benjamin Kramer29739e72012-05-12 16:52:21 +00003558 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003559 EatToEndOfStatement();
3560 } else {
3561 StringRef Str1 = ParseStringToComma();
3562
3563 if (getLexer().isNot(AsmToken::Comma))
3564 return TokError("unexpected token in '.ifc' directive");
3565
3566 Lex();
3567
3568 StringRef Str2 = ParseStringToEndOfStatement();
3569
3570 if (getLexer().isNot(AsmToken::EndOfStatement))
3571 return TokError("unexpected token in '.ifc' directive");
3572
3573 Lex();
3574
3575 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3576 TheCondState.Ignore = !TheCondState.CondMet;
3577 }
3578
3579 return false;
3580}
3581
3582/// ParseDirectiveIfdef
3583/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003584bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3585 StringRef Name;
3586 TheCondStack.push_back(TheCondState);
3587 TheCondState.TheCond = AsmCond::IfCond;
3588
3589 if (TheCondState.Ignore) {
3590 EatToEndOfStatement();
3591 } else {
3592 if (ParseIdentifier(Name))
3593 return TokError("expected identifier after '.ifdef'");
3594
3595 Lex();
3596
3597 MCSymbol *Sym = getContext().LookupSymbol(Name);
3598
3599 if (expect_defined)
3600 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3601 else
3602 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3603 TheCondState.Ignore = !TheCondState.CondMet;
3604 }
3605
3606 return false;
3607}
3608
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003609/// ParseDirectiveElseIf
3610/// ::= .elseif expression
3611bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3612 if (TheCondState.TheCond != AsmCond::IfCond &&
3613 TheCondState.TheCond != AsmCond::ElseIfCond)
3614 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3615 " an .elseif");
3616 TheCondState.TheCond = AsmCond::ElseIfCond;
3617
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003618 bool LastIgnoreState = false;
3619 if (!TheCondStack.empty())
3620 LastIgnoreState = TheCondStack.back().Ignore;
3621 if (LastIgnoreState || TheCondState.CondMet) {
3622 TheCondState.Ignore = true;
3623 EatToEndOfStatement();
3624 }
3625 else {
3626 int64_t ExprValue;
3627 if (ParseAbsoluteExpression(ExprValue))
3628 return true;
3629
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003630 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003631 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003632
Sean Callanan79ed1a82010-01-19 20:22:31 +00003633 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003634 TheCondState.CondMet = ExprValue;
3635 TheCondState.Ignore = !TheCondState.CondMet;
3636 }
3637
3638 return false;
3639}
3640
3641/// ParseDirectiveElse
3642/// ::= .else
3643bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003644 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003645 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003646
Sean Callanan79ed1a82010-01-19 20:22:31 +00003647 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003648
3649 if (TheCondState.TheCond != AsmCond::IfCond &&
3650 TheCondState.TheCond != AsmCond::ElseIfCond)
3651 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3652 ".elseif");
3653 TheCondState.TheCond = AsmCond::ElseCond;
3654 bool LastIgnoreState = false;
3655 if (!TheCondStack.empty())
3656 LastIgnoreState = TheCondStack.back().Ignore;
3657 if (LastIgnoreState || TheCondState.CondMet)
3658 TheCondState.Ignore = true;
3659 else
3660 TheCondState.Ignore = false;
3661
3662 return false;
3663}
3664
3665/// ParseDirectiveEndIf
3666/// ::= .endif
3667bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003668 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003669 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003670
Sean Callanan79ed1a82010-01-19 20:22:31 +00003671 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003672
3673 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3674 TheCondStack.empty())
3675 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3676 ".else");
3677 if (!TheCondStack.empty()) {
3678 TheCondState = TheCondStack.back();
3679 TheCondStack.pop_back();
3680 }
3681
3682 return false;
3683}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003684
Eli Bendersky6ee13082013-01-15 22:59:42 +00003685void AsmParser::initializeDirectiveKindMap() {
3686 DirectiveKindMap[".set"] = DK_SET;
3687 DirectiveKindMap[".equ"] = DK_EQU;
3688 DirectiveKindMap[".equiv"] = DK_EQUIV;
3689 DirectiveKindMap[".ascii"] = DK_ASCII;
3690 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3691 DirectiveKindMap[".string"] = DK_STRING;
3692 DirectiveKindMap[".byte"] = DK_BYTE;
3693 DirectiveKindMap[".short"] = DK_SHORT;
3694 DirectiveKindMap[".value"] = DK_VALUE;
3695 DirectiveKindMap[".2byte"] = DK_2BYTE;
3696 DirectiveKindMap[".long"] = DK_LONG;
3697 DirectiveKindMap[".int"] = DK_INT;
3698 DirectiveKindMap[".4byte"] = DK_4BYTE;
3699 DirectiveKindMap[".quad"] = DK_QUAD;
3700 DirectiveKindMap[".8byte"] = DK_8BYTE;
3701 DirectiveKindMap[".single"] = DK_SINGLE;
3702 DirectiveKindMap[".float"] = DK_FLOAT;
3703 DirectiveKindMap[".double"] = DK_DOUBLE;
3704 DirectiveKindMap[".align"] = DK_ALIGN;
3705 DirectiveKindMap[".align32"] = DK_ALIGN32;
3706 DirectiveKindMap[".balign"] = DK_BALIGN;
3707 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3708 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3709 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3710 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3711 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3712 DirectiveKindMap[".org"] = DK_ORG;
3713 DirectiveKindMap[".fill"] = DK_FILL;
3714 DirectiveKindMap[".zero"] = DK_ZERO;
3715 DirectiveKindMap[".extern"] = DK_EXTERN;
3716 DirectiveKindMap[".globl"] = DK_GLOBL;
3717 DirectiveKindMap[".global"] = DK_GLOBAL;
3718 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3719 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3720 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3721 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3722 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3723 DirectiveKindMap[".reference"] = DK_REFERENCE;
3724 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3725 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3726 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3727 DirectiveKindMap[".comm"] = DK_COMM;
3728 DirectiveKindMap[".common"] = DK_COMMON;
3729 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3730 DirectiveKindMap[".abort"] = DK_ABORT;
3731 DirectiveKindMap[".include"] = DK_INCLUDE;
3732 DirectiveKindMap[".incbin"] = DK_INCBIN;
3733 DirectiveKindMap[".code16"] = DK_CODE16;
3734 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3735 DirectiveKindMap[".rept"] = DK_REPT;
3736 DirectiveKindMap[".irp"] = DK_IRP;
3737 DirectiveKindMap[".irpc"] = DK_IRPC;
3738 DirectiveKindMap[".endr"] = DK_ENDR;
3739 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3740 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3741 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3742 DirectiveKindMap[".if"] = DK_IF;
3743 DirectiveKindMap[".ifb"] = DK_IFB;
3744 DirectiveKindMap[".ifnb"] = DK_IFNB;
3745 DirectiveKindMap[".ifc"] = DK_IFC;
3746 DirectiveKindMap[".ifnc"] = DK_IFNC;
3747 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3748 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3749 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3750 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3751 DirectiveKindMap[".else"] = DK_ELSE;
3752 DirectiveKindMap[".endif"] = DK_ENDIF;
3753 DirectiveKindMap[".skip"] = DK_SKIP;
3754 DirectiveKindMap[".space"] = DK_SPACE;
3755 DirectiveKindMap[".file"] = DK_FILE;
3756 DirectiveKindMap[".line"] = DK_LINE;
3757 DirectiveKindMap[".loc"] = DK_LOC;
3758 DirectiveKindMap[".stabs"] = DK_STABS;
3759 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3760 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3761 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3762 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3763 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3764 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3765 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3766 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3767 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3768 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3769 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3770 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3771 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3772 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3773 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3774 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3775 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3776 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3777 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3778 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3779 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3780 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3781 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3782 DirectiveKindMap[".macro"] = DK_MACRO;
3783 DirectiveKindMap[".endm"] = DK_ENDM;
3784 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3785 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003786}
3787
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003788
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003789MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003790 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003791
Rafael Espindola761cb062012-06-03 23:57:14 +00003792 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003793 for (;;) {
3794 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003795 if (getLexer().is(AsmToken::Eof)) {
3796 Error(DirectiveLoc, "no matching '.endr' in definition");
3797 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003798 }
3799
Rafael Espindola761cb062012-06-03 23:57:14 +00003800 if (Lexer.is(AsmToken::Identifier) &&
3801 (getTok().getIdentifier() == ".rept")) {
3802 ++NestLevel;
3803 }
3804
3805 // Otherwise, check whether we have reached the .endr.
3806 if (Lexer.is(AsmToken::Identifier) &&
3807 getTok().getIdentifier() == ".endr") {
3808 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003809 EndToken = getTok();
3810 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003811 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3812 TokError("unexpected token in '.endr' directive");
3813 return 0;
3814 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003815 break;
3816 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003817 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003818 }
3819
Rafael Espindola761cb062012-06-03 23:57:14 +00003820 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003821 EatToEndOfStatement();
3822 }
3823
3824 const char *BodyStart = StartToken.getLoc().getPointer();
3825 const char *BodyEnd = EndToken.getLoc().getPointer();
3826 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3827
Rafael Espindola761cb062012-06-03 23:57:14 +00003828 // We Are Anonymous.
3829 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003830 MCAsmMacroParameters Parameters;
3831 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003832}
3833
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003834void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003835 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003836 OS << ".endr\n";
3837
3838 MemoryBuffer *Instantiation =
3839 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3840
Rafael Espindola761cb062012-06-03 23:57:14 +00003841 // Create the macro instantiation object and add to the current macro
3842 // instantiation stack.
3843 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003844 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003845 getTok().getLoc(),
3846 Instantiation);
3847 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003848
Rafael Espindola761cb062012-06-03 23:57:14 +00003849 // Jump to the macro instantiation and prime the lexer.
3850 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3851 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3852 Lex();
3853}
3854
3855bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3856 int64_t Count;
3857 if (ParseAbsoluteExpression(Count))
3858 return TokError("unexpected token in '.rept' directive");
3859
3860 if (Count < 0)
3861 return TokError("Count is negative");
3862
3863 if (Lexer.isNot(AsmToken::EndOfStatement))
3864 return TokError("unexpected token in '.rept' directive");
3865
3866 // Eat the end of statement.
3867 Lex();
3868
3869 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003870 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003871 if (!M)
3872 return true;
3873
3874 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3875 // to hold the macro body with substitutions.
3876 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003877 MCAsmMacroParameters Parameters;
3878 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003879 raw_svector_ostream OS(Buf);
3880 while (Count--) {
3881 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3882 return true;
3883 }
3884 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003885
3886 return false;
3887}
3888
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003889/// ParseDirectiveIrp
3890/// ::= .irp symbol,values
3891bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003892 MCAsmMacroParameters Parameters;
3893 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003894
Preston Gurd6c9176a2012-09-19 20:29:04 +00003895 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003896 return TokError("expected identifier in '.irp' directive");
3897
3898 Parameters.push_back(Parameter);
3899
3900 if (Lexer.isNot(AsmToken::Comma))
3901 return TokError("expected comma in '.irp' directive");
3902
3903 Lex();
3904
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003905 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003906 if (ParseMacroArguments(0, A))
3907 return true;
3908
3909 // Eat the end of statement.
3910 Lex();
3911
3912 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003913 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003914 if (!M)
3915 return true;
3916
3917 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3918 // to hold the macro body with substitutions.
3919 SmallString<256> Buf;
3920 raw_svector_ostream OS(Buf);
3921
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003922 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3923 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003924 Args.push_back(*i);
3925
3926 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3927 return true;
3928 }
3929
3930 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3931
3932 return false;
3933}
3934
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003935/// ParseDirectiveIrpc
3936/// ::= .irpc symbol,values
3937bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003938 MCAsmMacroParameters Parameters;
3939 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003940
Preston Gurd6c9176a2012-09-19 20:29:04 +00003941 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003942 return TokError("expected identifier in '.irpc' directive");
3943
3944 Parameters.push_back(Parameter);
3945
3946 if (Lexer.isNot(AsmToken::Comma))
3947 return TokError("expected comma in '.irpc' directive");
3948
3949 Lex();
3950
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003951 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003952 if (ParseMacroArguments(0, A))
3953 return true;
3954
3955 if (A.size() != 1 || A.front().size() != 1)
3956 return TokError("unexpected token in '.irpc' directive");
3957
3958 // Eat the end of statement.
3959 Lex();
3960
3961 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003962 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003963 if (!M)
3964 return true;
3965
3966 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3967 // to hold the macro body with substitutions.
3968 SmallString<256> Buf;
3969 raw_svector_ostream OS(Buf);
3970
3971 StringRef Values = A.front().front().getString();
3972 std::size_t I, End = Values.size();
3973 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003974 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003975 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3976
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003977 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003978 Args.push_back(Arg);
3979
3980 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3981 return true;
3982 }
3983
3984 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3985
3986 return false;
3987}
3988
Rafael Espindola761cb062012-06-03 23:57:14 +00003989bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3990 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003991 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003992
3993 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003994 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003995 assert(getLexer().is(AsmToken::EndOfStatement));
3996
Rafael Espindola761cb062012-06-03 23:57:14 +00003997 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003998 return false;
3999}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00004000
Benjamin Kramer75234372013-02-15 20:37:21 +00004001bool AsmParser::ParseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
4002 size_t Len) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004003 const MCExpr *Value;
4004 SMLoc ExprLoc = getLexer().getLoc();
4005 if (ParseExpression(Value))
4006 return true;
4007 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4008 if (!MCE)
4009 return Error(ExprLoc, "unexpected expression in _emit");
4010 uint64_t IntValue = MCE->getValue();
4011 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
4012 return Error(ExprLoc, "literal value out of range for directive");
4013
Chad Rosier469b1442013-02-12 21:33:51 +00004014 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, Len));
4015 return false;
4016}
4017
4018bool AsmParser::ParseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
4019 const MCExpr *Value;
4020 SMLoc ExprLoc = getLexer().getLoc();
4021 if (ParseExpression(Value))
4022 return true;
4023 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4024 if (!MCE)
4025 return Error(ExprLoc, "unexpected expression in align");
4026 uint64_t IntValue = MCE->getValue();
4027 if (!isPowerOf2_64(IntValue))
4028 return Error(ExprLoc, "literal value not a power of two greater then zero");
4029
Benjamin Kramer75234372013-02-15 20:37:21 +00004030 Info.AsmRewrites->push_back(AsmRewrite(AOK_Align, IDLoc, 5,
4031 Log2_64(IntValue)));
Eli Friedman2128aae2012-10-22 23:58:19 +00004032 return false;
4033}
4034
Chad Rosier19aa3e32013-02-13 21:27:17 +00004035// We are comparing pointers, but the pointers are relative to a single string.
4036// Thus, this should always be deterministic.
Benjamin Kramer75234372013-02-15 20:37:21 +00004037static int RewritesSort(const void *A, const void *B) {
4038 const AsmRewrite *AsmRewriteA = static_cast<const AsmRewrite *>(A);
4039 const AsmRewrite *AsmRewriteB = static_cast<const AsmRewrite *>(B);
Chad Rosierabde6752013-02-13 18:38:58 +00004040 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
4041 return -1;
4042 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
4043 return 1;
4044 return 0;
Chad Rosierb1953982013-02-13 01:03:13 +00004045}
4046
Benjamin Kramer75234372013-02-15 20:37:21 +00004047bool
4048AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
4049 unsigned &NumOutputs, unsigned &NumInputs,
4050 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
4051 SmallVectorImpl<std::string> &Constraints,
4052 SmallVectorImpl<std::string> &Clobbers,
4053 const MCInstrInfo *MII,
4054 const MCInstPrinter *IP,
4055 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004056 SmallVector<void *, 4> InputDecls;
4057 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00004058 SmallVector<bool, 4> InputDeclsAddressOf;
4059 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004060 SmallVector<std::string, 4> InputConstraints;
4061 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer75234372013-02-15 20:37:21 +00004062 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004063
Benjamin Kramer75234372013-02-15 20:37:21 +00004064 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004065
4066 // Prime the lexer.
4067 Lex();
4068
4069 // While we have input, parse each statement.
4070 unsigned InputIdx = 0;
4071 unsigned OutputIdx = 0;
4072 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00004073 ParseStatementInfo Info(&AsmStrRewrites);
4074 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00004075 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004076
Chad Rosier57498012012-12-12 22:45:52 +00004077 if (Info.ParseError)
4078 return true;
4079
Benjamin Kramer75234372013-02-15 20:37:21 +00004080 if (Info.Opcode == ~0U)
4081 continue;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004082
Benjamin Kramer75234372013-02-15 20:37:21 +00004083 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004084
Benjamin Kramer75234372013-02-15 20:37:21 +00004085 // Build the list of clobbers, outputs and inputs.
4086 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
4087 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004088
Benjamin Kramer75234372013-02-15 20:37:21 +00004089 // Immediate.
4090 if (Operand->isImm()) {
4091 if (Operand->needAsmRewrite())
4092 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
4093 Operand->getStartLoc()));
4094 continue;
4095 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004096
Benjamin Kramer75234372013-02-15 20:37:21 +00004097 // Register operand.
4098 if (Operand->isReg() && !Operand->needAddressOf()) {
4099 unsigned NumDefs = Desc.getNumDefs();
4100 // Clobber.
4101 if (NumDefs && Operand->getMCOperandNum() < NumDefs)
4102 ClobberRegs.push_back(Operand->getReg());
4103 continue;
4104 }
4105
4106 // Expr/Input or Output.
4107 bool IsVarDecl;
4108 unsigned Length, Size, Type;
4109 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
4110 Length, Size, Type,
4111 IsVarDecl);
4112 if (!OpDecl)
4113 continue;
4114
4115 bool isOutput = (i == 1) && Desc.mayStore();
4116 if (Operand->isMem() && Operand->needSizeDirective())
4117 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
4118 Operand->getStartLoc(), /*Len*/0,
4119 Operand->getMemSize()));
4120
4121 if (isOutput) {
4122 ++InputIdx;
4123 OutputDecls.push_back(OpDecl);
4124 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
4125 OutputConstraints.push_back('=' + Operand->getConstraint().str());
4126 AsmStrRewrites.push_back(AsmRewrite(AOK_Output, Operand->getStartLoc(),
4127 Operand->getNameLen()));
4128 } else {
4129 InputDecls.push_back(OpDecl);
4130 InputDeclsAddressOf.push_back(Operand->needAddressOf());
4131 InputConstraints.push_back(Operand->getConstraint().str());
4132 AsmStrRewrites.push_back(AsmRewrite(AOK_Input, Operand->getStartLoc(),
4133 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00004134 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004135 }
4136 }
4137
4138 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004139 NumOutputs = OutputDecls.size();
4140 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00004141
4142 // Set the unique clobbers.
Benjamin Kramer75234372013-02-15 20:37:21 +00004143 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
4144 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
4145 ClobberRegs.end());
4146 Clobbers.assign(ClobberRegs.size(), std::string());
4147 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
4148 raw_string_ostream OS(Clobbers[I]);
4149 IP->printRegName(OS, ClobberRegs[I]);
4150 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00004151
4152 // Merge the various outputs and inputs. Output are expected first.
4153 if (NumOutputs || NumInputs) {
4154 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004155 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004156 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004157 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004158 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004159 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004160 }
4161 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004162 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004163 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004164 }
4165 }
4166
4167 // Build the IR assembly string.
4168 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00004169 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004170 raw_string_ostream OS(AsmStringIR);
4171 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Benjamin Kramer75234372013-02-15 20:37:21 +00004172 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), RewritesSort);
4173 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmStrRewrites.begin(),
4174 E = AsmStrRewrites.end();
4175 I != E; ++I) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00004176 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00004177
Chad Rosier469b1442013-02-12 21:33:51 +00004178 unsigned AdditionalSkip = 0;
Chad Rosier4e472d22012-10-20 01:02:45 +00004179 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004180
4181 // Emit everything up to the immediate/expression. If the previous rewrite
4182 // was a size directive, then this has already been done.
4183 if (PrevKind != AOK_SizeDirective)
4184 OS << StringRef(Start, Loc - Start);
4185 PrevKind = Kind;
4186
Chad Rosier5a719fc2012-10-23 17:43:43 +00004187 // Skip the original expression.
4188 if (Kind == AOK_Skip) {
4189 Start = Loc + (*I).Len;
4190 continue;
4191 }
4192
Chad Rosierb1f8c132012-10-18 15:49:34 +00004193 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004194 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004195 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004196 case AOK_Imm:
Benjamin Kramer75234372013-02-15 20:37:21 +00004197 OS << "$$" << (*I).Val;
Chad Rosierefcb3d92012-10-26 18:04:20 +00004198 break;
4199 case AOK_ImmPrefix:
Benjamin Kramer75234372013-02-15 20:37:21 +00004200 OS << "$$";
Chad Rosierb1f8c132012-10-18 15:49:34 +00004201 break;
4202 case AOK_Input:
Benjamin Kramer75234372013-02-15 20:37:21 +00004203 OS << '$' << InputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004204 break;
4205 case AOK_Output:
Benjamin Kramer75234372013-02-15 20:37:21 +00004206 OS << '$' << OutputIdx++;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004207 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004208 case AOK_SizeDirective:
Benjamin Kramer75234372013-02-15 20:37:21 +00004209 switch ((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004210 default: break;
4211 case 8: OS << "byte ptr "; break;
4212 case 16: OS << "word ptr "; break;
4213 case 32: OS << "dword ptr "; break;
4214 case 64: OS << "qword ptr "; break;
4215 case 80: OS << "xword ptr "; break;
4216 case 128: OS << "xmmword ptr "; break;
4217 case 256: OS << "ymmword ptr "; break;
4218 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004219 break;
4220 case AOK_Emit:
4221 OS << ".byte";
4222 break;
Chad Rosier469b1442013-02-12 21:33:51 +00004223 case AOK_Align: {
4224 unsigned Val = (*I).Val;
4225 OS << ".align " << Val;
4226
4227 // Skip the original immediate.
Benjamin Kramer75234372013-02-15 20:37:21 +00004228 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosier469b1442013-02-12 21:33:51 +00004229 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
4230 break;
4231 }
Chad Rosier6a020a72012-10-25 20:41:34 +00004232 case AOK_DotOperator:
4233 OS << (*I).Val;
4234 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004235 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004236
Chad Rosierb1f8c132012-10-18 15:49:34 +00004237 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004238 if (Kind != AOK_SizeDirective)
Chad Rosier469b1442013-02-12 21:33:51 +00004239 Start = Loc + (*I).Len + AdditionalSkip;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004240 }
4241
4242 // Emit the remainder of the asm string.
4243 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4244 if (Start != AsmEnd)
4245 OS << StringRef(Start, AsmEnd - Start);
4246
4247 AsmString = OS.str();
4248 return false;
4249}
4250
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004251/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004252MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004253 MCContext &C, MCStreamer &Out,
4254 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004255 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004256}