blob: f9ed63a668c54d0ae7d2c1a423fe053b1c47fb2f [file] [log] [blame]
Chris Lattner27aa7d22009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbarb95a0792010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Daniel Dunbar7c0a3342009-08-26 22:49:51 +000015#include "llvm/ADT/SmallString.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000016#include "llvm/ADT/StringMap.h"
Daniel Dunbarf9507ff2009-07-27 23:20:52 +000017#include "llvm/ADT/Twine.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000018#include "llvm/MC/MCAsmInfo.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000019#include "llvm/MC/MCContext.h"
Evan Cheng94b95502011-07-26 00:24:13 +000020#include "llvm/MC/MCDwarf.h"
Daniel Dunbar28c251b2009-08-31 08:06:59 +000021#include "llvm/MC/MCExpr.h"
Chad Rosierb1f8c132012-10-18 15:49:34 +000022#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCInstrInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000024#include "llvm/MC/MCParser/AsmCond.h"
25#include "llvm/MC/MCParser/AsmLexer.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
27#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Evan Chenge76a33b2011-07-20 05:58:47 +000028#include "llvm/MC/MCRegisterInfo.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000029#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbarecc63f82009-06-23 22:01:43 +000030#include "llvm/MC/MCStreamer.h"
Daniel Dunbardce0f3c2009-06-29 23:43:14 +000031#include "llvm/MC/MCSymbol.h"
Evan Cheng94b95502011-07-26 00:24:13 +000032#include "llvm/MC/MCTargetAsmParser.h"
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000033#include "llvm/Support/CommandLine.h"
Benjamin Kramer518ff562012-01-28 15:28:41 +000034#include "llvm/Support/ErrorHandling.h"
Jim Grosbach254cf032011-06-29 16:05:14 +000035#include "llvm/Support/MathExtras.h"
Kevin Enderbyf187ac52010-06-28 21:45:58 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbaraef87e32010-07-18 18:31:38 +000037#include "llvm/Support/SourceMgr.h"
Chris Lattnerb0789ed2009-06-21 20:54:55 +000038#include "llvm/Support/raw_ostream.h"
Nick Lewycky476b2422010-12-19 20:43:38 +000039#include <cctype>
Chad Rosierb1f8c132012-10-18 15:49:34 +000040#include <set>
41#include <string>
Daniel Dunbaraef87e32010-07-18 18:31:38 +000042#include <vector>
Chris Lattner27aa7d22009-06-21 20:16:42 +000043using namespace llvm;
44
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +000045static cl::opt<bool>
46FatalAssemblerWarnings("fatal-assembler-warnings",
47 cl::desc("Consider warnings as error"));
48
Eric Christopher2318ba12012-12-18 00:30:54 +000049MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewycky0d7d11d2012-10-19 07:00:09 +000050
Daniel Dunbar81ea00f2010-07-12 17:54:38 +000051namespace {
52
Eli Benderskyf9f40bd2013-01-16 18:56:50 +000053/// \brief Helper types for tracking macro definitions.
54typedef std::vector<AsmToken> MCAsmMacroArgument;
55typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
56typedef std::pair<StringRef, MCAsmMacroArgument> MCAsmMacroParameter;
57typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
58
59struct MCAsmMacro {
60 StringRef Name;
61 StringRef Body;
62 MCAsmMacroParameters Parameters;
63
64public:
65 MCAsmMacro(StringRef N, StringRef B, const MCAsmMacroParameters &P) :
66 Name(N), Body(B), Parameters(P) {}
67
68 MCAsmMacro(const MCAsmMacro& Other)
69 : Name(Other.Name), Body(Other.Body), Parameters(Other.Parameters) {}
70};
71
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000072/// \brief Helper class for storing information about an active macro
73/// instantiation.
74struct MacroInstantiation {
75 /// The macro being instantiated.
Eli Benderskyc0c67b02013-01-14 23:22:36 +000076 const MCAsmMacro *TheMacro;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000077
78 /// The macro instantiation with substitutions.
79 MemoryBuffer *Instantiation;
80
81 /// The location of the instantiation.
82 SMLoc InstantiationLoc;
83
Daniel Dunbar4259a1a2012-12-01 01:38:48 +000084 /// The buffer where parsing should resume upon instantiation completion.
85 int ExitBuffer;
86
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000087 /// The location where parsing should resume upon instantiation completion.
88 SMLoc ExitLoc;
89
90public:
Eli Benderskyc0c67b02013-01-14 23:22:36 +000091 MacroInstantiation(const MCAsmMacro *M, SMLoc IL, int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +000092 MemoryBuffer *I);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +000093};
94
Eli Friedman2128aae2012-10-22 23:58:19 +000095struct ParseStatementInfo {
96 /// ParsedOperands - The parsed operands from the last parsed statement.
97 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
98
99 /// Opcode - The opcode from the last parsed instruction.
100 unsigned Opcode;
101
Chad Rosier57498012012-12-12 22:45:52 +0000102 /// Error - Was there an error parsing the inline assembly?
103 bool ParseError;
104
Eli Friedman2128aae2012-10-22 23:58:19 +0000105 SmallVectorImpl<AsmRewrite> *AsmRewrites;
106
Chad Rosier57498012012-12-12 22:45:52 +0000107 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(0) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000108 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier57498012012-12-12 22:45:52 +0000109 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman2128aae2012-10-22 23:58:19 +0000110
111 ~ParseStatementInfo() {
112 // Free any parsed operands.
113 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
114 delete ParsedOperands[i];
115 ParsedOperands.clear();
116 }
117};
118
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000119/// \brief The concrete assembly parser instance.
120class AsmParser : public MCAsmParser {
Craig Topper85aadc02012-09-15 16:23:52 +0000121 AsmParser(const AsmParser &) LLVM_DELETED_FUNCTION;
122 void operator=(const AsmParser &) LLVM_DELETED_FUNCTION;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000123private:
124 AsmLexer Lexer;
125 MCContext &Ctx;
126 MCStreamer &Out;
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000127 const MCAsmInfo &MAI;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000128 SourceMgr &SrcMgr;
Benjamin Kramer04a04262011-10-16 10:48:29 +0000129 SourceMgr::DiagHandlerTy SavedDiagHandler;
130 void *SavedDiagContext;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000131 MCAsmParserExtension *PlatformParser;
Rafael Espindolaa61842b2011-04-11 21:49:50 +0000132
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000133 /// This is the current buffer index we're lexing from as managed by the
134 /// SourceMgr object.
135 int CurBuffer;
136
137 AsmCond TheCondState;
138 std::vector<AsmCond> TheCondStack;
139
Eli Bendersky6ee13082013-01-15 22:59:42 +0000140 /// ExtensionDirectiveMap - maps directive names to handler methods in parser
141 /// extensions. Extensions register themselves in this map by calling
142 /// AddDirectiveHandler.
Eli Bendersky6ee13082013-01-15 22:59:42 +0000143 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000144
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000145 /// MacroMap - Map of currently defined macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000146 StringMap<MCAsmMacro*> MacroMap;
Daniel Dunbar6d8cf082010-07-18 18:47:21 +0000147
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000148 /// ActiveMacros - Stack of active macro instantiations.
149 std::vector<MacroInstantiation*> ActiveMacros;
150
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000151 /// Boolean tracking whether macro substitution is enabled.
Eli Bendersky733c3362013-01-14 18:08:41 +0000152 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar3c802de2010-07-18 18:38:02 +0000153
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000154 /// Flag tracking whether any errors have been encountered.
155 unsigned HadError : 1;
156
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000157 /// The values from the last parsed cpp hash file line comment if any.
158 StringRef CppHashFilename;
159 int64_t CppHashLineNumber;
160 SMLoc CppHashLoc;
Kevin Enderby32c1a822012-11-05 21:55:41 +0000161 int CppHashBuf;
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000162
Devang Patel0db58bf2012-01-31 18:14:05 +0000163 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
164 unsigned AssemblerDialect;
165
Preston Gurd7b6f2032012-09-19 20:36:12 +0000166 /// IsDarwin - is Darwin compatibility enabled?
167 bool IsDarwin;
168
Chad Rosier8f138d12012-10-15 17:19:13 +0000169 /// ParsingInlineAsm - Are we parsing ms-style inline assembly?
Chad Rosier84125ca2012-10-13 00:26:04 +0000170 bool ParsingInlineAsm;
171
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000172public:
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000173 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000174 const MCAsmInfo &MAI);
Craig Topper345d16d2012-08-29 05:48:09 +0000175 virtual ~AsmParser();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000176
177 virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false);
178
Eli Bendersky171192f2013-01-16 00:50:52 +0000179 virtual void AddDirectiveHandler(StringRef Directive,
180 ExtensionDirectiveHandler Handler) {
181 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000182 }
183
184public:
185 /// @name MCAsmParser Interface
186 /// {
187
188 virtual SourceMgr &getSourceManager() { return SrcMgr; }
189 virtual MCAsmLexer &getLexer() { return Lexer; }
190 virtual MCContext &getContext() { return Ctx; }
191 virtual MCStreamer &getStreamer() { return Out; }
Eric Christopher2318ba12012-12-18 00:30:54 +0000192 virtual unsigned getAssemblerDialect() {
Devang Patel0db58bf2012-01-31 18:14:05 +0000193 if (AssemblerDialect == ~0U)
Eric Christopher2318ba12012-12-18 00:30:54 +0000194 return MAI.getAssemblerDialect();
Devang Patel0db58bf2012-01-31 18:14:05 +0000195 else
196 return AssemblerDialect;
197 }
198 virtual void setAssemblerDialect(unsigned i) {
199 AssemblerDialect = i;
200 }
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000201
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000202 virtual bool Warning(SMLoc L, const Twine &Msg,
203 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
204 virtual bool Error(SMLoc L, const Twine &Msg,
205 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>());
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000206
Craig Topper345d16d2012-08-29 05:48:09 +0000207 virtual const AsmToken &Lex();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000208
Chad Rosier84125ca2012-10-13 00:26:04 +0000209 void setParsingInlineAsm(bool V) { ParsingInlineAsm = V; }
Chad Rosierc5ac87d2012-10-16 20:16:20 +0000210 bool isParsingInlineAsm() { return ParsingInlineAsm; }
Chad Rosierb1f8c132012-10-18 15:49:34 +0000211
212 bool ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
213 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +0000214 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000215 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +0000216 SmallVectorImpl<std::string> &Clobbers,
217 const MCInstrInfo *MII,
218 const MCInstPrinter *IP,
219 MCAsmParserSemaCallback &SI);
Chad Rosier84125ca2012-10-13 00:26:04 +0000220
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000221 bool ParseExpression(const MCExpr *&Res);
222 virtual bool ParseExpression(const MCExpr *&Res, SMLoc &EndLoc);
223 virtual bool ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc);
224 virtual bool ParseAbsoluteExpression(int64_t &Res);
225
Eli Benderskybf706b32013-01-12 00:05:00 +0000226 /// ParseIdentifier - Parse an identifier or string (as a quoted identifier)
227 /// and set \p Res to the identifier contents.
228 virtual bool ParseIdentifier(StringRef &Res);
Eli Benderskyb2f0b592013-01-12 00:23:24 +0000229 virtual void EatToEndOfStatement();
Eli Benderskybf706b32013-01-12 00:05:00 +0000230
Eli Bendersky318cad32013-01-14 19:15:01 +0000231 virtual void CheckForValidSection();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000232 /// }
233
234private:
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000235
Eli Friedman2128aae2012-10-22 23:58:19 +0000236 bool ParseStatement(ParseStatementInfo &Info);
Kevin Enderbyf1c21a82011-09-13 23:45:18 +0000237 void EatToEndOfLine();
238 bool ParseCppHashLineFilenameComment(const SMLoc &L);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000239
Rafael Espindola761cb062012-06-03 23:57:14 +0000240 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000241 const MCAsmMacroParameters &Parameters,
242 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +0000243 const SMLoc &L);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000244
Eli Benderskyf9f40bd2013-01-16 18:56:50 +0000245 /// \brief Are macros enabled in the parser?
246 bool MacrosEnabled() {return MacrosEnabledFlag;}
247
248 /// \brief Control a flag in the parser that enables or disables macros.
249 void SetMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
250
251 /// \brief Lookup a previously defined macro.
252 /// \param Name Macro name.
253 /// \returns Pointer to macro. NULL if no such macro was defined.
254 const MCAsmMacro* LookupMacro(StringRef Name);
255
256 /// \brief Define a new macro with the given name and information.
257 void DefineMacro(StringRef Name, const MCAsmMacro& Macro);
258
259 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
260 void UndefineMacro(StringRef Name);
261
262 /// \brief Are we inside a macro instantiation?
263 bool InsideMacroInstantiation() {return !ActiveMacros.empty();}
264
265 /// \brief Handle entry to macro instantiation.
266 ///
267 /// \param M The macro.
268 /// \param NameLoc Instantiation location.
269 bool HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
270
271 /// \brief Handle exit from macro instantiation.
272 void HandleMacroExit();
273
274 /// \brief Extract AsmTokens for a macro argument. If the argument delimiter
275 /// is initially unknown, set it to AsmToken::Eof. It will be set to the
276 /// correct delimiter by the method.
277 bool ParseMacroArgument(MCAsmMacroArgument &MA,
278 AsmToken::TokenKind &ArgumentDelimiter);
279
280 /// \brief Parse all macro arguments for a given macro.
281 bool ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
282
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000283 void PrintMacroInstantiations();
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000284 void PrintMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Chris Lattner462b43c2011-10-16 05:47:55 +0000285 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) const {
286 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000287 }
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000288 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerd1e17032010-09-27 17:42:11 +0000289
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000290 /// EnterIncludeFile - Enter the specified file. This returns true on failure.
291 bool EnterIncludeFile(const std::string &Filename);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000292 /// ProcessIncbinFile - Process the specified file for the .incbin directive.
293 /// This returns true on failure.
294 bool ProcessIncbinFile(const std::string &Filename);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000295
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000296 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000297 /// current token is not set; clients should ensure Lex() is called
298 /// subsequently.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000299 ///
300 /// \param InBuffer If not -1, should be the known buffer id that contains the
301 /// location.
302 void JumpToLoc(SMLoc Loc, int InBuffer=-1);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000303
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000304 /// \brief Parse up to the end of statement and a return the contents from the
305 /// current token until the end of the statement; the current token on exit
306 /// will be either the EndOfStatement or EOF.
Craig Topper345d16d2012-08-29 05:48:09 +0000307 virtual StringRef ParseStringToEndOfStatement();
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000308
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000309 /// \brief Parse until the end of a statement or a comma is encountered,
310 /// return the contents from the current token up to the end or comma.
311 StringRef ParseStringToComma();
312
Jim Grosbach3f90a4c2012-09-13 23:11:31 +0000313 bool ParseAssignment(StringRef Name, bool allow_redef,
314 bool NoDeadStrip = false);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000315
316 bool ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc);
317 bool ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
318 bool ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000319 bool ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000320
Eli Bendersky6ee13082013-01-15 22:59:42 +0000321 bool ParseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola787c3372010-10-28 20:02:27 +0000322
Eli Bendersky6ee13082013-01-15 22:59:42 +0000323 // Generic (target and platform independent) directive parsing.
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000324 enum DirectiveKind {
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000325 DK_NO_DIRECTIVE, // Placeholder
326 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
327 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_SINGLE,
328 DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky9b1bb052013-01-11 22:55:28 +0000329 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky7eef9c12013-01-10 23:40:56 +0000330 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
331 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL, DK_INDIRECT_SYMBOL,
332 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER, DK_PRIVATE_EXTERN,
333 DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
334 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
335 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
336 DK_IF, DK_IFB, DK_IFNB, DK_IFC, DK_IFNC, DK_IFDEF, DK_IFNDEF, DK_IFNOTDEF,
Eli Bendersky6ee13082013-01-15 22:59:42 +0000337 DK_ELSEIF, DK_ELSE, DK_ENDIF,
338 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
339 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
340 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
341 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
342 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
343 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
344 DK_CFI_REGISTER,
345 DK_MACROS_ON, DK_MACROS_OFF, DK_MACRO, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
346 DK_SLEB128, DK_ULEB128
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000347 };
348
Eli Bendersky6ee13082013-01-15 22:59:42 +0000349 /// DirectiveKindMap - Maps directive name --> DirectiveKind enum, for
350 /// directives parsed by this class.
351 StringMap<DirectiveKind> DirectiveKindMap;
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000352
353 // ".ascii", ".asciz", ".string"
Rafael Espindola787c3372010-10-28 20:02:27 +0000354 bool ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000355 bool ParseDirectiveValue(unsigned Size); // ".byte", ".long", ...
Daniel Dunbarb95a0792010-09-24 01:59:56 +0000356 bool ParseDirectiveRealValue(const fltSemantics &); // ".single", ...
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000357 bool ParseDirectiveFill(); // ".fill"
Rafael Espindola2ea2ac72010-09-16 15:03:59 +0000358 bool ParseDirectiveZero(); // ".zero"
Eric Christopher2318ba12012-12-18 00:30:54 +0000359 // ".set", ".equ", ".equiv"
360 bool ParseDirectiveSet(StringRef IDVal, bool allow_redef);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000361 bool ParseDirectiveOrg(); // ".org"
362 // ".align{,32}", ".p2align{,w,l}"
363 bool ParseDirectiveAlign(bool IsPow2, unsigned ValueSize);
364
Eli Bendersky6ee13082013-01-15 22:59:42 +0000365 // ".file", ".line", ".loc", ".stabs"
366 bool ParseDirectiveFile(SMLoc DirectiveLoc);
367 bool ParseDirectiveLine();
368 bool ParseDirectiveLoc();
369 bool ParseDirectiveStabs();
370
371 // .cfi directives
372 bool ParseDirectiveCFIRegister(SMLoc DirectiveLoc);
373 bool ParseDirectiveCFISections();
374 bool ParseDirectiveCFIStartProc();
375 bool ParseDirectiveCFIEndProc();
376 bool ParseDirectiveCFIDefCfaOffset();
377 bool ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
378 bool ParseDirectiveCFIAdjustCfaOffset();
379 bool ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
380 bool ParseDirectiveCFIOffset(SMLoc DirectiveLoc);
381 bool ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
382 bool ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
383 bool ParseDirectiveCFIRememberState();
384 bool ParseDirectiveCFIRestoreState();
385 bool ParseDirectiveCFISameValue(SMLoc DirectiveLoc);
386 bool ParseDirectiveCFIRestore(SMLoc DirectiveLoc);
387 bool ParseDirectiveCFIEscape();
388 bool ParseDirectiveCFISignalFrame();
389 bool ParseDirectiveCFIUndefined(SMLoc DirectiveLoc);
390
391 // macro directives
392 bool ParseDirectivePurgeMacro(SMLoc DirectiveLoc);
393 bool ParseDirectiveEndMacro(StringRef Directive);
394 bool ParseDirectiveMacro(SMLoc DirectiveLoc);
395 bool ParseDirectiveMacrosOnOff(StringRef Directive);
396
Eli Bendersky4766ef42012-12-20 19:05:53 +0000397 // ".bundle_align_mode"
398 bool ParseDirectiveBundleAlignMode();
399 // ".bundle_lock"
400 bool ParseDirectiveBundleLock();
401 // ".bundle_unlock"
402 bool ParseDirectiveBundleUnlock();
403
Eli Bendersky6ee13082013-01-15 22:59:42 +0000404 // ".space", ".skip"
405 bool ParseDirectiveSpace(StringRef IDVal);
406
407 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
408 bool ParseDirectiveLEB128(bool Signed);
409
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000410 /// ParseDirectiveSymbolAttribute - Parse a directive like ".globl" which
411 /// accepts a single symbol (which should be a label or an external).
412 bool ParseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000413
414 bool ParseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
415
416 bool ParseDirectiveAbort(); // ".abort"
417 bool ParseDirectiveInclude(); // ".include"
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000418 bool ParseDirectiveIncbin(); // ".incbin"
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000419
420 bool ParseDirectiveIf(SMLoc DirectiveLoc); // ".if"
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +0000421 // ".ifb" or ".ifnb", depending on ExpectBlank.
422 bool ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000423 // ".ifc" or ".ifnc", depending on ExpectEqual.
424 bool ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +0000425 // ".ifdef" or ".ifndef", depending on expect_defined
426 bool ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000427 bool ParseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
428 bool ParseDirectiveElse(SMLoc DirectiveLoc); // ".else"
429 bool ParseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
430
431 /// ParseEscapedString - Parse the current token as a string which may include
432 /// escaped characters and return the string contents.
433 bool ParseEscapedString(std::string &Data);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000434
435 const MCExpr *ApplyModifierToExpr(const MCExpr *E,
436 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola2ec304c2012-05-12 16:31:10 +0000437
Rafael Espindola761cb062012-06-03 23:57:14 +0000438 // Macro-like directives
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000439 MCAsmMacro *ParseMacroLikeBody(SMLoc DirectiveLoc);
440 void InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +0000441 raw_svector_ostream &OS);
442 bool ParseDirectiveRept(SMLoc DirectiveLoc); // ".rept"
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +0000443 bool ParseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
Rafael Espindolafc9216e2012-06-16 18:03:25 +0000444 bool ParseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
Rafael Espindola761cb062012-06-03 23:57:14 +0000445 bool ParseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosierb1f8c132012-10-18 15:49:34 +0000446
Eli Friedman2128aae2012-10-22 23:58:19 +0000447 // "_emit"
448 bool ParseDirectiveEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000449
Eli Bendersky6ee13082013-01-15 22:59:42 +0000450 void initializeDirectiveKindMap();
Daniel Dunbaraef87e32010-07-18 18:31:38 +0000451};
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000452}
453
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000454namespace llvm {
455
456extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbar5146a092010-07-12 21:23:32 +0000457extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencer7d490042010-10-09 11:01:07 +0000458extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000459
460}
461
Chris Lattneraaec2052010-01-19 19:46:13 +0000462enum { DEFAULT_ADDRSPACE = 0 };
463
Jim Grosbach1b84cce2011-08-16 18:33:49 +0000464AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx,
Daniel Dunbar9186fa62010-07-01 20:41:56 +0000465 MCStreamer &_Out, const MCAsmInfo &_MAI)
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000466 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), MAI(_MAI), SrcMgr(_SM),
Eli Bendersky6ee13082013-01-15 22:59:42 +0000467 PlatformParser(0),
Eli Bendersky733c3362013-01-14 18:08:41 +0000468 CurBuffer(0), MacrosEnabledFlag(true), CppHashLineNumber(0),
Eli Friedman2128aae2012-10-22 23:58:19 +0000469 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer04a04262011-10-16 10:48:29 +0000470 // Save the old handler.
471 SavedDiagHandler = SrcMgr.getDiagHandler();
472 SavedDiagContext = SrcMgr.getDiagContext();
473 // Set our own handler which calls the saved handler.
Kevin Enderbyacbaecd2011-10-12 21:38:39 +0000474 SrcMgr.setDiagHandler(DiagHandler, this);
Sean Callananfd0b0282010-01-21 00:19:58 +0000475 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Daniel Dunbar81ea00f2010-07-12 17:54:38 +0000476
Daniel Dunbare4749702010-07-12 18:12:02 +0000477 // Initialize the platform / file format parser.
478 //
479 // FIXME: This is a hack, we need to (majorly) cleanup how these objects are
480 // created.
Michael J. Spencer7d490042010-10-09 11:01:07 +0000481 if (_MAI.hasMicrosoftFastStdCallMangling()) {
482 PlatformParser = createCOFFAsmParser();
483 PlatformParser->Initialize(*this);
484 } else if (_MAI.hasSubsectionsViaSymbols()) {
Daniel Dunbar9c23d7f2010-07-12 20:51:51 +0000485 PlatformParser = createDarwinAsmParser();
Daniel Dunbare4749702010-07-12 18:12:02 +0000486 PlatformParser->Initialize(*this);
Preston Gurd7b6f2032012-09-19 20:36:12 +0000487 IsDarwin = true;
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000488 } else {
Daniel Dunbar5146a092010-07-12 21:23:32 +0000489 PlatformParser = createELFAsmParser();
Daniel Dunbar7a56fc22010-07-12 20:08:04 +0000490 PlatformParser->Initialize(*this);
Daniel Dunbare4749702010-07-12 18:12:02 +0000491 }
Eli Bendersky5d0f0612013-01-10 22:44:57 +0000492
Eli Bendersky6ee13082013-01-15 22:59:42 +0000493 initializeDirectiveKindMap();
Chris Lattnerebb89b42009-09-27 21:16:52 +0000494}
495
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000496AsmParser::~AsmParser() {
Daniel Dunbar56491302010-07-29 01:51:55 +0000497 assert(ActiveMacros.empty() && "Unexpected active macro instantiation!");
498
499 // Destroy any macros.
Eli Benderskyc0c67b02013-01-14 23:22:36 +0000500 for (StringMap<MCAsmMacro*>::iterator it = MacroMap.begin(),
Daniel Dunbar56491302010-07-29 01:51:55 +0000501 ie = MacroMap.end(); it != ie; ++it)
502 delete it->getValue();
503
Daniel Dunbare4749702010-07-12 18:12:02 +0000504 delete PlatformParser;
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000505}
506
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000507void AsmParser::PrintMacroInstantiations() {
508 // Print the active macro instantiation stack.
509 for (std::vector<MacroInstantiation*>::const_reverse_iterator
510 it = ActiveMacros.rbegin(), ie = ActiveMacros.rend(); it != ie; ++it)
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000511 PrintMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
512 "while in macro instantiation");
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000513}
514
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000515bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000516 if (FatalAssemblerWarnings)
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000517 return Error(L, Msg, Ranges);
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000518 PrintMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000519 PrintMacroInstantiations();
Joerg Sonnenbergerf8cd7082011-05-19 18:00:13 +0000520 return false;
Daniel Dunbar3fb76832009-06-30 00:49:23 +0000521}
522
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000523bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000524 HadError = true;
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000525 PrintMessage(L, SourceMgr::DK_Error, Msg, Ranges);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000526 PrintMacroInstantiations();
Chris Lattner14ee48a2009-06-21 21:22:11 +0000527 return true;
528}
529
Sean Callananfd0b0282010-01-21 00:19:58 +0000530bool AsmParser::EnterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergerdd137902011-06-01 13:10:15 +0000531 std::string IncludedFile;
532 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
Sean Callananfd0b0282010-01-21 00:19:58 +0000533 if (NewBuf == -1)
534 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000535
Sean Callananfd0b0282010-01-21 00:19:58 +0000536 CurBuffer = NewBuf;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000537
Sean Callananfd0b0282010-01-21 00:19:58 +0000538 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000539
Sean Callananfd0b0282010-01-21 00:19:58 +0000540 return false;
541}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000542
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000543/// Process the specified .incbin file by seaching for it in the include paths
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000544/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000545/// returns true on failure.
546bool AsmParser::ProcessIncbinFile(const std::string &Filename) {
547 std::string IncludedFile;
548 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
549 if (NewBuf == -1)
550 return true;
551
Kevin Enderbyc3fc3132011-12-14 22:34:45 +0000552 // Pick up the bytes from the file and emit them.
Kevin Enderbydac29532011-12-15 00:00:27 +0000553 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer(),
554 DEFAULT_ADDRSPACE);
Kevin Enderbyc55acca2011-12-14 21:47:48 +0000555 return false;
556}
557
Daniel Dunbar4259a1a2012-12-01 01:38:48 +0000558void AsmParser::JumpToLoc(SMLoc Loc, int InBuffer) {
559 if (InBuffer != -1) {
560 CurBuffer = InBuffer;
561 } else {
562 CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
563 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000564 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer), Loc.getPointer());
565}
566
Sean Callananfd0b0282010-01-21 00:19:58 +0000567const AsmToken &AsmParser::Lex() {
568 const AsmToken *tok = &Lexer.Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000569
Sean Callananfd0b0282010-01-21 00:19:58 +0000570 if (tok->is(AsmToken::Eof)) {
571 // If this is the end of an included file, pop the parent file off the
572 // include stack.
573 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
574 if (ParentIncludeLoc != SMLoc()) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +0000575 JumpToLoc(ParentIncludeLoc);
Sean Callananfd0b0282010-01-21 00:19:58 +0000576 tok = &Lexer.Lex();
577 }
578 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000579
Sean Callananfd0b0282010-01-21 00:19:58 +0000580 if (tok->is(AsmToken::Error))
Daniel Dunbar275ce392010-07-18 18:31:45 +0000581 Error(Lexer.getErrLoc(), Lexer.getErr());
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000582
Sean Callananfd0b0282010-01-21 00:19:58 +0000583 return *tok;
Sean Callanan79ed1a82010-01-19 20:22:31 +0000584}
585
Chris Lattner79180e22010-04-05 23:15:42 +0000586bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000587 // Create the initial section, if requested.
Daniel Dunbar5e6a7a22010-03-13 02:20:57 +0000588 if (!NoInitialTextSection)
Rafael Espindolad80781b2010-09-15 21:48:40 +0000589 Out.InitSections();
Daniel Dunbar7c0a3342009-08-26 22:49:51 +0000590
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000591 // Prime the lexer.
Sean Callanan79ed1a82010-01-19 20:22:31 +0000592 Lex();
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000593
594 HadError = false;
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000595 AsmCond StartingCondState = TheCondState;
596
Kevin Enderby613b7572011-11-01 22:27:22 +0000597 // If we are generating dwarf for assembly source files save the initial text
598 // section and generate a .file directive.
599 if (getContext().getGenDwarfForAssembly()) {
600 getContext().setGenDwarfSection(getStreamer().getCurrentSection());
Kevin Enderby94c2e852011-12-09 18:09:40 +0000601 MCSymbol *SectionStartSym = getContext().CreateTempSymbol();
602 getStreamer().EmitLabel(SectionStartSym);
603 getContext().setGenDwarfSectionStartSym(SectionStartSym);
Kevin Enderby613b7572011-11-01 22:27:22 +0000604 getStreamer().EmitDwarfFileDirective(getContext().nextGenDwarfFileNumber(),
Eric Christopher6c583142012-12-18 00:31:01 +0000605 StringRef(),
606 getContext().getMainFileName());
Kevin Enderby613b7572011-11-01 22:27:22 +0000607 }
608
Chris Lattnerb717fb02009-07-02 21:53:43 +0000609 // While we have input, parse each statement.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000610 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +0000611 ParseStatementInfo Info;
612 if (!ParseStatement(Info)) continue;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000613
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000614 // We had an error, validate that one was emitted and recover by skipping to
615 // the next line.
616 assert(HadError && "Parse statement returned an error, but none emitted!");
Chris Lattnerb717fb02009-07-02 21:53:43 +0000617 EatToEndOfStatement();
618 }
Kevin Enderbyc114ed72009-08-07 22:46:00 +0000619
620 if (TheCondState.TheCond != StartingCondState.TheCond ||
621 TheCondState.Ignore != StartingCondState.Ignore)
622 return TokError("unmatched .ifs or .elses");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000623
624 // Check to see there are no empty DwarfFile slots.
625 const std::vector<MCDwarfFile *> &MCDwarfFiles =
626 getContext().getMCDwarfFiles();
627 for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
Daniel Dunbar93bd4d12010-09-09 22:42:56 +0000628 if (!MCDwarfFiles[i])
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000629 TokError("unassigned file number: " + Twine(i) + " for .file directives");
Kevin Enderby7cbf73a2010-07-28 20:55:35 +0000630 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000631
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000632 // Check to see that all assembler local symbols were actually defined.
633 // Targets that don't do subsections via symbols may not want this, though,
634 // so conservatively exclude them. Only do this if we're finalizing, though,
635 // as otherwise we won't necessarilly have seen everything yet.
636 if (!NoFinalize && MAI.hasSubsectionsViaSymbols()) {
637 const MCContext::SymbolTable &Symbols = getContext().getSymbols();
638 for (MCContext::SymbolTable::const_iterator i = Symbols.begin(),
639 e = Symbols.end();
640 i != e; ++i) {
641 MCSymbol *Sym = i->getValue();
642 // Variable symbols may not be marked as defined, so check those
643 // explicitly. If we know it's a variable, we have a definition for
644 // the purposes of this check.
645 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
646 // FIXME: We would really like to refer back to where the symbol was
647 // first referenced for a source location. We need to add something
648 // to track that. Currently, we just point to the end of the file.
Chris Lattner3f2d5f62011-10-16 05:43:57 +0000649 PrintMessage(getLexer().getLoc(), SourceMgr::DK_Error,
650 "assembler local symbol '" + Sym->getName() +
651 "' not defined");
Jim Grosbache82b8ee2011-06-15 18:33:28 +0000652 }
653 }
654
655
Chris Lattner79180e22010-04-05 23:15:42 +0000656 // Finalize the output stream if there are no errors and if the client wants
657 // us to.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000658 if (!HadError && !NoFinalize)
Daniel Dunbarb3f3c032009-08-21 08:34:18 +0000659 Out.Finish();
660
Chris Lattnerb717fb02009-07-02 21:53:43 +0000661 return HadError;
Chris Lattnerb0789ed2009-06-21 20:54:55 +0000662}
663
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000664void AsmParser::CheckForValidSection() {
Chad Rosier84125ca2012-10-13 00:26:04 +0000665 if (!ParsingInlineAsm && !getStreamer().getCurrentSection()) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000666 TokError("expected section directive before assembly directive");
Eli Bendersky030f63a2013-01-14 19:04:57 +0000667 Out.InitToTextSection();
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +0000668 }
669}
670
Chris Lattner2cf5f142009-06-22 01:29:09 +0000671/// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
672void AsmParser::EatToEndOfStatement() {
Daniel Dunbar3f872332009-07-28 16:08:33 +0000673 while (Lexer.isNot(AsmToken::EndOfStatement) &&
674 Lexer.isNot(AsmToken::Eof))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000675 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000676
Chris Lattner2cf5f142009-06-22 01:29:09 +0000677 // Eat EOL.
Daniel Dunbar3f872332009-07-28 16:08:33 +0000678 if (Lexer.is(AsmToken::EndOfStatement))
Sean Callanan79ed1a82010-01-19 20:22:31 +0000679 Lex();
Chris Lattner2cf5f142009-06-22 01:29:09 +0000680}
681
Daniel Dunbar6a46d572010-07-18 20:15:59 +0000682StringRef AsmParser::ParseStringToEndOfStatement() {
683 const char *Start = getTok().getLoc().getPointer();
684
685 while (Lexer.isNot(AsmToken::EndOfStatement) &&
686 Lexer.isNot(AsmToken::Eof))
687 Lex();
688
689 const char *End = getTok().getLoc().getPointer();
690 return StringRef(Start, End - Start);
691}
Chris Lattnerc4193832009-06-22 05:51:26 +0000692
Benjamin Kramerdec06ef2012-05-12 11:18:51 +0000693StringRef AsmParser::ParseStringToComma() {
694 const char *Start = getTok().getLoc().getPointer();
695
696 while (Lexer.isNot(AsmToken::EndOfStatement) &&
697 Lexer.isNot(AsmToken::Comma) &&
698 Lexer.isNot(AsmToken::Eof))
699 Lex();
700
701 const char *End = getTok().getLoc().getPointer();
702 return StringRef(Start, End - Start);
703}
704
Chris Lattner74ec1a32009-06-22 06:32:03 +0000705/// ParseParenExpr - Parse a paren expression and return it.
706/// NOTE: This assumes the leading '(' has already been consumed.
707///
708/// parenexpr ::= expr)
709///
Chris Lattnerb4307b32010-01-15 19:28:38 +0000710bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner74ec1a32009-06-22 06:32:03 +0000711 if (ParseExpression(Res)) return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000712 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner74ec1a32009-06-22 06:32:03 +0000713 return TokError("expected ')' in parentheses expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000714 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000715 Lex();
Chris Lattner74ec1a32009-06-22 06:32:03 +0000716 return false;
717}
Chris Lattnerc4193832009-06-22 05:51:26 +0000718
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000719/// ParseBracketExpr - Parse a bracket expression and return it.
720/// NOTE: This assumes the leading '[' has already been consumed.
721///
722/// bracketexpr ::= expr]
723///
724bool AsmParser::ParseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
725 if (ParseExpression(Res)) return true;
726 if (Lexer.isNot(AsmToken::RBrac))
727 return TokError("expected ']' in brackets expression");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000728 EndLoc = Lexer.getTok().getEndLoc();
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000729 Lex();
730 return false;
731}
732
Chris Lattner74ec1a32009-06-22 06:32:03 +0000733/// ParsePrimaryExpr - Parse a primary expression and return it.
734/// primaryexpr ::= (parenexpr
735/// primaryexpr ::= symbol
736/// primaryexpr ::= number
Chris Lattnerd3050352010-04-14 04:40:28 +0000737/// primaryexpr ::= '.'
Chris Lattner74ec1a32009-06-22 06:32:03 +0000738/// primaryexpr ::= ~,+,- primaryexpr
Chris Lattnerb4307b32010-01-15 19:28:38 +0000739bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattnerc4193832009-06-22 05:51:26 +0000740 switch (Lexer.getKind()) {
741 default:
742 return TokError("unknown token in expression");
Eric Christopherf3755b22011-04-12 00:03:13 +0000743 // If we have an error assume that we've already handled it.
744 case AsmToken::Error:
745 return true;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000746 case AsmToken::Exclaim:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000747 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000748 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000749 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000750 Res = MCUnaryExpr::CreateLNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000751 return false;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000752 case AsmToken::Dollar:
Daniel Dunbar76c4d762009-07-31 21:55:09 +0000753 case AsmToken::String:
Daniel Dunbarfffff912009-10-16 01:34:54 +0000754 case AsmToken::Identifier: {
Daniel Dunbare17edff2010-08-24 19:13:42 +0000755 StringRef Identifier;
756 if (ParseIdentifier(Identifier))
Jim Grosbach95ae09a2011-05-23 20:36:04 +0000757 return true;
Daniel Dunbare17edff2010-08-24 19:13:42 +0000758
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000759 EndLoc = SMLoc::getFromPointer(Identifier.end());
760
Daniel Dunbarfffff912009-10-16 01:34:54 +0000761 // This is a symbol reference.
Daniel Dunbare17edff2010-08-24 19:13:42 +0000762 std::pair<StringRef, StringRef> Split = Identifier.split('@');
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +0000763 MCSymbol *Sym = getContext().GetOrCreateSymbol(Split.first);
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000764
765 // Lookup the symbol variant if used.
766 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Daniel Dunbarcceba832010-09-17 02:47:07 +0000767 if (Split.first.size() != Identifier.size()) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000768 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Daniel Dunbarcceba832010-09-17 02:47:07 +0000769 if (Variant == MCSymbolRefExpr::VK_Invalid) {
770 Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach4121e8a2011-01-19 23:06:07 +0000771 return TokError("invalid variant '" + Split.second + "'");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000772 }
773 }
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000774
Daniel Dunbarfffff912009-10-16 01:34:54 +0000775 // If this is an absolute variable reference, substitute it now to preserve
776 // semantics in the face of reassignment.
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000777 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000778 if (Variant)
Daniel Dunbar603abd52010-11-08 17:53:02 +0000779 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000780
Daniel Dunbar08a408a2010-05-05 17:41:00 +0000781 Res = Sym->getVariableValue();
Daniel Dunbarfffff912009-10-16 01:34:54 +0000782 return false;
783 }
784
785 // Otherwise create a symbol ref.
Daniel Dunbar4e815f82010-03-15 23:51:06 +0000786 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
Chris Lattnerc4193832009-06-22 05:51:26 +0000787 return false;
Daniel Dunbarfffff912009-10-16 01:34:54 +0000788 }
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000789 case AsmToken::Integer: {
790 SMLoc Loc = getTok().getLoc();
791 int64_t IntVal = getTok().getIntVal();
792 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000793 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +0000794 Lex(); // Eat token.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000795 // Look for 'b' or 'f' following an Integer as a directional label
796 if (Lexer.getKind() == AsmToken::Identifier) {
797 StringRef IDVal = getTok().getString();
798 if (IDVal == "f" || IDVal == "b"){
799 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
800 IDVal == "f" ? 1 : 0);
801 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
802 getContext());
Benjamin Kramer29739e72012-05-12 16:52:21 +0000803 if (IDVal == "b" && Sym->isUndefined())
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000804 return Error(Loc, "invalid reference to undefined symbol");
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000805 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000806 Lex(); // Eat identifier.
807 }
808 }
Chris Lattnerc4193832009-06-22 05:51:26 +0000809 return false;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +0000810 }
Bill Wendling69c4ef32011-01-25 21:26:41 +0000811 case AsmToken::Real: {
812 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson720b9182011-02-03 23:17:47 +0000813 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000814 Res = MCConstantExpr::Create(IntVal, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000815 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendling69c4ef32011-01-25 21:26:41 +0000816 Lex(); // Eat token.
817 return false;
818 }
Chris Lattnerd3050352010-04-14 04:40:28 +0000819 case AsmToken::Dot: {
820 // This is a '.' reference, which references the current PC. Emit a
821 // temporary label to the streamer and refer to it.
822 MCSymbol *Sym = Ctx.CreateTempSymbol();
823 Out.EmitLabel(Sym);
824 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rose3ebe59c2013-01-07 19:00:49 +0000825 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattnerd3050352010-04-14 04:40:28 +0000826 Lex(); // Eat identifier.
827 return false;
828 }
Daniel Dunbar3f872332009-07-28 16:08:33 +0000829 case AsmToken::LParen:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000830 Lex(); // Eat the '('.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000831 return ParseParenExpr(Res, EndLoc);
Joerg Sonnenberger93c65e62011-02-24 21:59:22 +0000832 case AsmToken::LBrac:
833 if (!PlatformParser->HasBracketExpressions())
834 return TokError("brackets expression not supported on this target");
835 Lex(); // Eat the '['.
836 return ParseBracketExpr(Res, EndLoc);
Daniel Dunbar3f872332009-07-28 16:08:33 +0000837 case AsmToken::Minus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000838 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000839 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000840 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000841 Res = MCUnaryExpr::CreateMinus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000842 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000843 case AsmToken::Plus:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000844 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000845 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000846 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000847 Res = MCUnaryExpr::CreatePlus(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000848 return false;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000849 case AsmToken::Tilde:
Sean Callanan79ed1a82010-01-19 20:22:31 +0000850 Lex(); // Eat the operator.
Chris Lattnerb4307b32010-01-15 19:28:38 +0000851 if (ParsePrimaryExpr(Res, EndLoc))
Daniel Dunbar475839e2009-06-29 20:37:27 +0000852 return true;
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000853 Res = MCUnaryExpr::CreateNot(Res, getContext());
Daniel Dunbar475839e2009-06-29 20:37:27 +0000854 return false;
Chris Lattnerc4193832009-06-22 05:51:26 +0000855 }
856}
Chris Lattner74ec1a32009-06-22 06:32:03 +0000857
Chris Lattnerb4307b32010-01-15 19:28:38 +0000858bool AsmParser::ParseExpression(const MCExpr *&Res) {
Chris Lattner54482b42010-01-15 19:39:23 +0000859 SMLoc EndLoc;
860 return ParseExpression(Res, EndLoc);
Chris Lattnerb4307b32010-01-15 19:28:38 +0000861}
862
Daniel Dunbarcceba832010-09-17 02:47:07 +0000863const MCExpr *
864AsmParser::ApplyModifierToExpr(const MCExpr *E,
865 MCSymbolRefExpr::VariantKind Variant) {
866 // Recurse over the given expression, rebuilding it to apply the given variant
867 // if there is exactly one symbol.
868 switch (E->getKind()) {
869 case MCExpr::Target:
870 case MCExpr::Constant:
871 return 0;
872
873 case MCExpr::SymbolRef: {
874 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
875
876 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
877 TokError("invalid variant on expression '" +
878 getTok().getIdentifier() + "' (already modified)");
879 return E;
880 }
881
882 return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
883 }
884
885 case MCExpr::Unary: {
886 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
887 const MCExpr *Sub = ApplyModifierToExpr(UE->getSubExpr(), Variant);
888 if (!Sub)
889 return 0;
890 return MCUnaryExpr::Create(UE->getOpcode(), Sub, getContext());
891 }
892
893 case MCExpr::Binary: {
894 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
895 const MCExpr *LHS = ApplyModifierToExpr(BE->getLHS(), Variant);
896 const MCExpr *RHS = ApplyModifierToExpr(BE->getRHS(), Variant);
897
898 if (!LHS && !RHS)
899 return 0;
900
901 if (!LHS) LHS = BE->getLHS();
902 if (!RHS) RHS = BE->getRHS();
903
904 return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
905 }
906 }
Daniel Dunbarf3f95c92010-09-17 16:34:24 +0000907
Craig Topper85814382012-02-07 05:05:23 +0000908 llvm_unreachable("Invalid expression kind!");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000909}
910
Chris Lattner74ec1a32009-06-22 06:32:03 +0000911/// ParseExpression - Parse an expression and return it.
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000912///
Jim Grosbachfbe16812011-08-20 16:24:13 +0000913/// expr ::= expr &&,|| expr -> lowest.
914/// expr ::= expr |,^,&,! expr
915/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
916/// expr ::= expr <<,>> expr
917/// expr ::= expr +,- expr
918/// expr ::= expr *,/,% expr -> highest.
Chris Lattner74ec1a32009-06-22 06:32:03 +0000919/// expr ::= primaryexpr
920///
Chris Lattner54482b42010-01-15 19:39:23 +0000921bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000922 // Parse the expression.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000923 Res = 0;
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000924 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
925 return true;
926
Daniel Dunbarcceba832010-09-17 02:47:07 +0000927 // As a special case, we support 'a op b @ modifier' by rewriting the
928 // expression to include the modifier. This is inefficient, but in general we
929 // expect users to use 'a@modifier op b'.
930 if (Lexer.getKind() == AsmToken::At) {
931 Lex();
932
933 if (Lexer.isNot(AsmToken::Identifier))
934 return TokError("unexpected symbol modifier following '@'");
935
936 MCSymbolRefExpr::VariantKind Variant =
937 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
938 if (Variant == MCSymbolRefExpr::VK_Invalid)
939 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
940
941 const MCExpr *ModifiedRes = ApplyModifierToExpr(Res, Variant);
942 if (!ModifiedRes) {
943 return TokError("invalid modifier '" + getTok().getIdentifier() +
944 "' (no symbols present)");
Daniel Dunbarcceba832010-09-17 02:47:07 +0000945 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000946
Daniel Dunbarcceba832010-09-17 02:47:07 +0000947 Res = ModifiedRes;
948 Lex();
949 }
950
Daniel Dunbare9a60eb2010-02-13 01:28:07 +0000951 // Try to constant fold it up front, if possible.
952 int64_t Value;
953 if (Res->EvaluateAsAbsolute(Value))
954 Res = MCConstantExpr::Create(Value, getContext());
955
956 return false;
Chris Lattner74ec1a32009-06-22 06:32:03 +0000957}
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000958
Chris Lattnerb4307b32010-01-15 19:28:38 +0000959bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Chris Lattner75f265f2010-01-24 01:07:33 +0000960 Res = 0;
961 return ParseParenExpr(Res, EndLoc) ||
962 ParseBinOpRHS(1, Res, EndLoc);
Daniel Dunbarc18274b2009-08-31 08:08:17 +0000963}
964
Daniel Dunbar475839e2009-06-29 20:37:27 +0000965bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
Daniel Dunbar9643ac52009-08-31 08:07:22 +0000966 const MCExpr *Expr;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000967
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000968 SMLoc StartLoc = Lexer.getLoc();
Daniel Dunbar475839e2009-06-29 20:37:27 +0000969 if (ParseExpression(Expr))
970 return true;
971
Daniel Dunbare00b0112009-10-16 01:57:52 +0000972 if (!Expr->EvaluateAsAbsolute(Res))
Daniel Dunbarf4b830f2009-06-30 02:10:03 +0000973 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar475839e2009-06-29 20:37:27 +0000974
975 return false;
976}
977
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000978static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000979 MCBinaryExpr::Opcode &Kind) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000980 switch (K) {
Daniel Dunbar6ce004d2009-08-31 08:07:44 +0000981 default:
982 return 0; // not a binop.
Daniel Dunbar475839e2009-06-29 20:37:27 +0000983
Jim Grosbachfbe16812011-08-20 16:24:13 +0000984 // Lowest Precedence: &&, ||
Daniel Dunbar3f872332009-07-28 16:08:33 +0000985 case AsmToken::AmpAmp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000986 Kind = MCBinaryExpr::LAnd;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +0000987 return 1;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000988 case AsmToken::PipePipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000989 Kind = MCBinaryExpr::LOr;
Daniel Dunbar475839e2009-06-29 20:37:27 +0000990 return 1;
991
Michael J. Spencerc0c8df32010-10-09 11:00:50 +0000992
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000993 // Low Precedence: |, &, ^
Daniel Dunbar475839e2009-06-29 20:37:27 +0000994 //
995 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbar3f872332009-07-28 16:08:33 +0000996 case AsmToken::Pipe:
Daniel Dunbar28c251b2009-08-31 08:06:59 +0000997 Kind = MCBinaryExpr::Or;
Chris Lattnerf7d4da02010-09-22 05:05:16 +0000998 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +0000999 case AsmToken::Caret:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001000 Kind = MCBinaryExpr::Xor;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001001 return 2;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001002 case AsmToken::Amp:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001003 Kind = MCBinaryExpr::And;
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001004 return 2;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001005
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001006 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattnerf7d4da02010-09-22 05:05:16 +00001007 case AsmToken::EqualEqual:
1008 Kind = MCBinaryExpr::EQ;
1009 return 3;
1010 case AsmToken::ExclaimEqual:
1011 case AsmToken::LessGreater:
1012 Kind = MCBinaryExpr::NE;
1013 return 3;
1014 case AsmToken::Less:
1015 Kind = MCBinaryExpr::LT;
1016 return 3;
1017 case AsmToken::LessEqual:
1018 Kind = MCBinaryExpr::LTE;
1019 return 3;
1020 case AsmToken::Greater:
1021 Kind = MCBinaryExpr::GT;
1022 return 3;
1023 case AsmToken::GreaterEqual:
1024 Kind = MCBinaryExpr::GTE;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001025 return 3;
1026
Jim Grosbachfbe16812011-08-20 16:24:13 +00001027 // Intermediate Precedence: <<, >>
1028 case AsmToken::LessLess:
1029 Kind = MCBinaryExpr::Shl;
1030 return 4;
1031 case AsmToken::GreaterGreater:
1032 Kind = MCBinaryExpr::Shr;
1033 return 4;
1034
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001035 // High Intermediate Precedence: +, -
1036 case AsmToken::Plus:
1037 Kind = MCBinaryExpr::Add;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001038 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001039 case AsmToken::Minus:
1040 Kind = MCBinaryExpr::Sub;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001041 return 5;
Daniel Dunbarb1e0f762010-10-25 20:18:56 +00001042
Jim Grosbachfbe16812011-08-20 16:24:13 +00001043 // Highest Precedence: *, /, %
Daniel Dunbar3f872332009-07-28 16:08:33 +00001044 case AsmToken::Star:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001045 Kind = MCBinaryExpr::Mul;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001046 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001047 case AsmToken::Slash:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001048 Kind = MCBinaryExpr::Div;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001049 return 6;
Daniel Dunbar3f872332009-07-28 16:08:33 +00001050 case AsmToken::Percent:
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001051 Kind = MCBinaryExpr::Mod;
Jim Grosbachfbe16812011-08-20 16:24:13 +00001052 return 6;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001053 }
1054}
1055
1056
1057/// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
1058/// Res contains the LHS of the expression on input.
Chris Lattnerb4307b32010-01-15 19:28:38 +00001059bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1060 SMLoc &EndLoc) {
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001061 while (1) {
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001062 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001063 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001064
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001065 // If the next token is lower precedence than we are allowed to eat, return
1066 // successfully with what we ate already.
1067 if (TokPrec < Precedence)
1068 return false;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001069
Sean Callanan79ed1a82010-01-19 20:22:31 +00001070 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001071
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001072 // Eat the next primary expression.
Daniel Dunbar9643ac52009-08-31 08:07:22 +00001073 const MCExpr *RHS;
Chris Lattnerb4307b32010-01-15 19:28:38 +00001074 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001075
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001076 // If BinOp binds less tightly with RHS than the operator after RHS, let
1077 // the pending operator take RHS as its LHS.
Daniel Dunbar28c251b2009-08-31 08:06:59 +00001078 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar475839e2009-06-29 20:37:27 +00001079 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001080 if (TokPrec < NextTokPrec) {
Chris Lattnerb4307b32010-01-15 19:28:38 +00001081 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001082 }
1083
Daniel Dunbar475839e2009-06-29 20:37:27 +00001084 // Merge LHS and RHS according to operator.
Daniel Dunbar6ce004d2009-08-31 08:07:44 +00001085 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
Chris Lattner8dfbe6c2009-06-23 05:57:07 +00001086 }
1087}
1088
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001089/// ParseStatement:
1090/// ::= EndOfStatement
Chris Lattner2cf5f142009-06-22 01:29:09 +00001091/// ::= Label* Directive ...Operands... EndOfStatement
1092/// ::= Label* Identifier OperandList* EndOfStatement
Eli Friedman2128aae2012-10-22 23:58:19 +00001093bool AsmParser::ParseStatement(ParseStatementInfo &Info) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001094 if (Lexer.is(AsmToken::EndOfStatement)) {
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001095 Out.AddBlankLine();
Sean Callanan79ed1a82010-01-19 20:22:31 +00001096 Lex();
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001097 return false;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001098 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001099
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001100 // Statements always start with an identifier or are a full line comment.
Sean Callanan18b83232010-01-19 21:44:56 +00001101 AsmToken ID = getTok();
Daniel Dunbar419aded2009-07-28 16:38:40 +00001102 SMLoc IDLoc = ID.getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001103 StringRef IDVal;
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001104 int64_t LocalLabelVal = -1;
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001105 // A full line comment is a '#' as the first token.
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001106 if (Lexer.is(AsmToken::Hash))
1107 return ParseCppHashLineFilenameComment(IDLoc);
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001108
Kevin Enderbyd82ed5b2010-12-24 00:12:02 +00001109 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001110 if (Lexer.is(AsmToken::Integer)) {
1111 LocalLabelVal = getTok().getIntVal();
1112 if (LocalLabelVal < 0) {
1113 if (!TheCondState.Ignore)
1114 return TokError("unexpected token at start of statement");
1115 IDVal = "";
Eli Benderskyed5df012013-01-16 19:32:36 +00001116 } else {
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001117 IDVal = getTok().getString();
1118 Lex(); // Consume the integer token to be used as an identifier token.
1119 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands34727662010-07-12 08:16:59 +00001120 if (!TheCondState.Ignore)
1121 return TokError("unexpected token at start of statement");
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001122 }
1123 }
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001124 } else if (Lexer.is(AsmToken::Dot)) {
1125 // Treat '.' as a valid identifier in this context.
1126 Lex();
1127 IDVal = ".";
Daniel Dunbar0143ac12011-03-25 17:47:14 +00001128 } else if (ParseIdentifier(IDVal)) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001129 if (!TheCondState.Ignore)
1130 return TokError("unexpected token at start of statement");
1131 IDVal = "";
1132 }
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001133
Chris Lattner7834fac2010-04-17 18:14:27 +00001134 // Handle conditional assembly here before checking for skipping. We
1135 // have to do this so that .endif isn't skipped in a ".if 0" block for
1136 // example.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001137 StringMap<DirectiveKind>::const_iterator DirKindIt =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001138 DirectiveKindMap.find(IDVal);
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001139 DirectiveKind DirKind =
Eli Bendersky6ee13082013-01-15 22:59:42 +00001140 (DirKindIt == DirectiveKindMap.end()) ? DK_NO_DIRECTIVE :
1141 DirKindIt->getValue();
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001142 switch (DirKind) {
1143 default:
1144 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001145 case DK_IF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001146 return ParseDirectiveIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001147 case DK_IFB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001148 return ParseDirectiveIfb(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001149 case DK_IFNB:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001150 return ParseDirectiveIfb(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001151 case DK_IFC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001152 return ParseDirectiveIfc(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001153 case DK_IFNC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001154 return ParseDirectiveIfc(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001155 case DK_IFDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001156 return ParseDirectiveIfdef(IDLoc, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001157 case DK_IFNDEF:
1158 case DK_IFNOTDEF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001159 return ParseDirectiveIfdef(IDLoc, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001160 case DK_ELSEIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001161 return ParseDirectiveElseIf(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001162 case DK_ELSE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001163 return ParseDirectiveElse(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001164 case DK_ENDIF:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001165 return ParseDirectiveEndIf(IDLoc);
1166 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001167
Eli Benderskyed5df012013-01-16 19:32:36 +00001168 // Ignore the statement if in the middle of inactive conditional
1169 // (e.g. ".if 0").
Chad Rosier17feeec2012-10-20 00:47:08 +00001170 if (TheCondState.Ignore) {
Chris Lattner7834fac2010-04-17 18:14:27 +00001171 EatToEndOfStatement();
1172 return false;
1173 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001174
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00001175 // FIXME: Recurse on local labels?
1176
1177 // See what kind of statement we have.
1178 switch (Lexer.getKind()) {
Daniel Dunbar3f872332009-07-28 16:08:33 +00001179 case AsmToken::Colon: {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001180 CheckForValidSection();
1181
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001182 // identifier ':' -> Label.
Sean Callanan79ed1a82010-01-19 20:22:31 +00001183 Lex();
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001184
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001185 // Diagnose attempt to use '.' as a label.
1186 if (IDVal == ".")
1187 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1188
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001189 // Diagnose attempt to use a variable as a label.
1190 //
1191 // FIXME: Diagnostics. Note the location of the definition as a label.
1192 // FIXME: This doesn't diagnose assignment to a symbol which has been
1193 // implicitly marked as external.
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001194 MCSymbol *Sym;
1195 if (LocalLabelVal == -1)
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00001196 Sym = getContext().GetOrCreateSymbol(IDVal);
Kevin Enderbyebe7fcd2010-05-17 23:08:19 +00001197 else
1198 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
Daniel Dunbarc3047182010-05-05 19:01:00 +00001199 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001200 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001201
Daniel Dunbar959fd882009-08-26 22:13:22 +00001202 // Emit the label.
Chad Rosierdeb1bab2013-01-07 20:34:12 +00001203 if (!ParsingInlineAsm)
1204 Out.EmitLabel(Sym);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001205
Kevin Enderby94c2e852011-12-09 18:09:40 +00001206 // If we are generating dwarf for assembly source files then gather the
Kevin Enderby11c2def2012-01-10 21:12:34 +00001207 // info to make a dwarf label entry for this label if needed.
Kevin Enderby94c2e852011-12-09 18:09:40 +00001208 if (getContext().getGenDwarfForAssembly())
Kevin Enderby11c2def2012-01-10 21:12:34 +00001209 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1210 IDLoc);
Kevin Enderby94c2e852011-12-09 18:09:40 +00001211
Daniel Dunbar01777ff2010-05-23 18:36:34 +00001212 // Consume any end of statement token, if present, to avoid spurious
1213 // AddBlankLine calls().
1214 if (Lexer.is(AsmToken::EndOfStatement)) {
1215 Lex();
1216 if (Lexer.is(AsmToken::Eof))
1217 return false;
1218 }
1219
Eli Friedman2128aae2012-10-22 23:58:19 +00001220 return false;
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001221 }
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001222
Daniel Dunbar3f872332009-07-28 16:08:33 +00001223 case AsmToken::Equal:
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001224 // identifier '=' ... -> assignment statement
Sean Callanan79ed1a82010-01-19 20:22:31 +00001225 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001226
Nico Weber4c4c7322011-01-28 03:04:41 +00001227 return ParseAssignment(IDVal, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001228
1229 default: // Normal instruction or directive.
1230 break;
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001231 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001232
1233 // If macros are enabled, check to see if this is a macro instantiation.
Eli Bendersky733c3362013-01-14 18:08:41 +00001234 if (MacrosEnabled())
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001235 if (const MCAsmMacro *M = LookupMacro(IDVal)) {
1236 return HandleMacroEntry(M, IDLoc);
1237 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001238
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001239 // Otherwise, we have a normal instruction or directive.
Eli Bendersky6ee13082013-01-15 22:59:42 +00001240
1241 // Directives start with "."
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001242 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky6ee13082013-01-15 22:59:42 +00001243 // There are several entities interested in parsing directives:
1244 //
1245 // 1. The target-specific assembly parser. Some directives are target
1246 // specific or may potentially behave differently on certain targets.
1247 // 2. Asm parser extensions. For example, platform-specific parsers
1248 // (like the ELF parser) register themselves as extensions.
1249 // 3. The generic directive parser implemented by this class. These are
1250 // all the directives that behave in a target and platform independent
1251 // manner, or at least have a default behavior that's shared between
1252 // all targets and platforms.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001253
Eli Bendersky6ee13082013-01-15 22:59:42 +00001254 // First query the target-specific parser. It will return 'true' if it
1255 // isn't interested in this directive.
Akira Hatanaka3b02d952012-07-05 19:09:33 +00001256 if (!getTargetParser().ParseDirective(ID))
1257 return false;
1258
Eli Bendersky6ee13082013-01-15 22:59:42 +00001259 // Next, check the extention directive map to see if any extension has
1260 // registered itself to parse this directive.
1261 std::pair<MCAsmParserExtension*, DirectiveHandler> Handler =
1262 ExtensionDirectiveMap.lookup(IDVal);
1263 if (Handler.first)
1264 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1265
1266 // Finally, if no one else is interested in this directive, it must be
1267 // generic and familiar to this class.
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001268 switch (DirKind) {
1269 default:
1270 break;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001271 case DK_SET:
1272 case DK_EQU:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001273 return ParseDirectiveSet(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001274 case DK_EQUIV:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001275 return ParseDirectiveSet(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001276 case DK_ASCII:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001277 return ParseDirectiveAscii(IDVal, false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001278 case DK_ASCIZ:
1279 case DK_STRING:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001280 return ParseDirectiveAscii(IDVal, true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001281 case DK_BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001282 return ParseDirectiveValue(1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001283 case DK_SHORT:
1284 case DK_VALUE:
1285 case DK_2BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001286 return ParseDirectiveValue(2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001287 case DK_LONG:
1288 case DK_INT:
1289 case DK_4BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001290 return ParseDirectiveValue(4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001291 case DK_QUAD:
1292 case DK_8BYTE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001293 return ParseDirectiveValue(8);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001294 case DK_SINGLE:
1295 case DK_FLOAT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001296 return ParseDirectiveRealValue(APFloat::IEEEsingle);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001297 case DK_DOUBLE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001298 return ParseDirectiveRealValue(APFloat::IEEEdouble);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001299 case DK_ALIGN: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001300 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1301 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1302 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001303 case DK_ALIGN32: {
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001304 bool IsPow2 = !getContext().getAsmInfo().getAlignmentIsInBytes();
1305 return ParseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1306 }
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001307 case DK_BALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001308 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001309 case DK_BALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001310 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001311 case DK_BALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001312 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001313 case DK_P2ALIGN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001314 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001315 case DK_P2ALIGNW:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001316 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001317 case DK_P2ALIGNL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001318 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001319 case DK_ORG:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001320 return ParseDirectiveOrg();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001321 case DK_FILL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001322 return ParseDirectiveFill();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001323 case DK_ZERO:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001324 return ParseDirectiveZero();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001325 case DK_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001326 EatToEndOfStatement(); // .extern is the default, ignore it.
1327 return false;
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001328 case DK_GLOBL:
1329 case DK_GLOBAL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001330 return ParseDirectiveSymbolAttribute(MCSA_Global);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001331 case DK_INDIRECT_SYMBOL:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001332 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001333 case DK_LAZY_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001334 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001335 case DK_NO_DEAD_STRIP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001336 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001337 case DK_SYMBOL_RESOLVER:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001338 return ParseDirectiveSymbolAttribute(MCSA_SymbolResolver);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001339 case DK_PRIVATE_EXTERN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001340 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001341 case DK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001342 return ParseDirectiveSymbolAttribute(MCSA_Reference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001343 case DK_WEAK_DEFINITION:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001344 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001345 case DK_WEAK_REFERENCE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001346 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001347 case DK_WEAK_DEF_CAN_BE_HIDDEN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001348 return ParseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001349 case DK_COMM:
1350 case DK_COMMON:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001351 return ParseDirectiveComm(/*IsLocal=*/false);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001352 case DK_LCOMM:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001353 return ParseDirectiveComm(/*IsLocal=*/true);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001354 case DK_ABORT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001355 return ParseDirectiveAbort();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001356 case DK_INCLUDE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001357 return ParseDirectiveInclude();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001358 case DK_INCBIN:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001359 return ParseDirectiveIncbin();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001360 case DK_CODE16:
1361 case DK_CODE16GCC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001362 return TokError(Twine(IDVal) + " not supported yet");
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001363 case DK_REPT:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001364 return ParseDirectiveRept(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001365 case DK_IRP:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001366 return ParseDirectiveIrp(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001367 case DK_IRPC:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001368 return ParseDirectiveIrpc(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001369 case DK_ENDR:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001370 return ParseDirectiveEndr(IDLoc);
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001371 case DK_BUNDLE_ALIGN_MODE:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001372 return ParseDirectiveBundleAlignMode();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001373 case DK_BUNDLE_LOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001374 return ParseDirectiveBundleLock();
Eli Bendersky7eef9c12013-01-10 23:40:56 +00001375 case DK_BUNDLE_UNLOCK:
Eli Bendersky5d0f0612013-01-10 22:44:57 +00001376 return ParseDirectiveBundleUnlock();
Eli Bendersky6ee13082013-01-15 22:59:42 +00001377 case DK_SLEB128:
1378 return ParseDirectiveLEB128(true);
1379 case DK_ULEB128:
1380 return ParseDirectiveLEB128(false);
1381 case DK_SPACE:
1382 case DK_SKIP:
1383 return ParseDirectiveSpace(IDVal);
1384 case DK_FILE:
1385 return ParseDirectiveFile(IDLoc);
1386 case DK_LINE:
1387 return ParseDirectiveLine();
1388 case DK_LOC:
1389 return ParseDirectiveLoc();
1390 case DK_STABS:
1391 return ParseDirectiveStabs();
1392 case DK_CFI_SECTIONS:
1393 return ParseDirectiveCFISections();
1394 case DK_CFI_STARTPROC:
1395 return ParseDirectiveCFIStartProc();
1396 case DK_CFI_ENDPROC:
1397 return ParseDirectiveCFIEndProc();
1398 case DK_CFI_DEF_CFA:
1399 return ParseDirectiveCFIDefCfa(IDLoc);
1400 case DK_CFI_DEF_CFA_OFFSET:
1401 return ParseDirectiveCFIDefCfaOffset();
1402 case DK_CFI_ADJUST_CFA_OFFSET:
1403 return ParseDirectiveCFIAdjustCfaOffset();
1404 case DK_CFI_DEF_CFA_REGISTER:
1405 return ParseDirectiveCFIDefCfaRegister(IDLoc);
1406 case DK_CFI_OFFSET:
1407 return ParseDirectiveCFIOffset(IDLoc);
1408 case DK_CFI_REL_OFFSET:
1409 return ParseDirectiveCFIRelOffset(IDLoc);
1410 case DK_CFI_PERSONALITY:
1411 return ParseDirectiveCFIPersonalityOrLsda(true);
1412 case DK_CFI_LSDA:
1413 return ParseDirectiveCFIPersonalityOrLsda(false);
1414 case DK_CFI_REMEMBER_STATE:
1415 return ParseDirectiveCFIRememberState();
1416 case DK_CFI_RESTORE_STATE:
1417 return ParseDirectiveCFIRestoreState();
1418 case DK_CFI_SAME_VALUE:
1419 return ParseDirectiveCFISameValue(IDLoc);
1420 case DK_CFI_RESTORE:
1421 return ParseDirectiveCFIRestore(IDLoc);
1422 case DK_CFI_ESCAPE:
1423 return ParseDirectiveCFIEscape();
1424 case DK_CFI_SIGNAL_FRAME:
1425 return ParseDirectiveCFISignalFrame();
1426 case DK_CFI_UNDEFINED:
1427 return ParseDirectiveCFIUndefined(IDLoc);
1428 case DK_CFI_REGISTER:
1429 return ParseDirectiveCFIRegister(IDLoc);
1430 case DK_MACROS_ON:
1431 case DK_MACROS_OFF:
1432 return ParseDirectiveMacrosOnOff(IDVal);
1433 case DK_MACRO:
1434 return ParseDirectiveMacro(IDLoc);
1435 case DK_ENDM:
1436 case DK_ENDMACRO:
1437 return ParseDirectiveEndMacro(IDVal);
1438 case DK_PURGEM:
1439 return ParseDirectivePurgeMacro(IDLoc);
Eli Friedman5d68ec22010-07-19 04:17:25 +00001440 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00001441
Jim Grosbach686c0182012-05-01 18:38:27 +00001442 return Error(IDLoc, "unknown directive");
Chris Lattner2cf5f142009-06-22 01:29:09 +00001443 }
Chris Lattnerb0789ed2009-06-21 20:54:55 +00001444
Eli Friedman2128aae2012-10-22 23:58:19 +00001445 // _emit
1446 if (ParsingInlineAsm && IDVal == "_emit")
1447 return ParseDirectiveEmit(IDLoc, Info);
1448
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00001449 CheckForValidSection();
1450
Chris Lattnera7f13542010-05-19 23:34:33 +00001451 // Canonicalize the opcode to lower case.
Eli Benderskyed5df012013-01-16 19:32:36 +00001452 std::string OpcodeStr = IDVal.lower();
Chad Rosier6a020a72012-10-25 20:41:34 +00001453 ParseInstructionInfo IInfo(Info.AsmRewrites);
Eli Benderskyed5df012013-01-16 19:32:36 +00001454 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr,
1455 IDLoc, Info.ParsedOperands);
Chad Rosier57498012012-12-12 22:45:52 +00001456 Info.ParseError = HadError;
Chris Lattner2cf5f142009-06-22 01:29:09 +00001457
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001458 // Dump the parsed representation, if requested.
1459 if (getShowParsedOperands()) {
1460 SmallString<256> Str;
1461 raw_svector_ostream OS(Str);
1462 OS << "parsed instruction: [";
Eli Friedman2128aae2012-10-22 23:58:19 +00001463 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001464 if (i != 0)
1465 OS << ", ";
Eli Friedman2128aae2012-10-22 23:58:19 +00001466 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001467 }
1468 OS << "]";
1469
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001470 PrintMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar3c14ca42010-08-11 06:37:09 +00001471 }
1472
Kevin Enderby613b7572011-11-01 22:27:22 +00001473 // If we are generating dwarf for assembly source files and the current
1474 // section is the initial text section then generate a .loc directive for
1475 // the instruction.
1476 if (!HadError && getContext().getGenDwarfForAssembly() &&
Eric Christopher2318ba12012-12-18 00:30:54 +00001477 getContext().getGenDwarfSection() == getStreamer().getCurrentSection()) {
Kevin Enderby938482f2012-11-01 17:31:35 +00001478
Eli Benderskyed5df012013-01-16 19:32:36 +00001479 unsigned Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
Kevin Enderby938482f2012-11-01 17:31:35 +00001480
Eli Benderskyed5df012013-01-16 19:32:36 +00001481 // If we previously parsed a cpp hash file line comment then make sure the
1482 // current Dwarf File is for the CppHashFilename if not then emit the
1483 // Dwarf File table for it and adjust the line number for the .loc.
1484 const std::vector<MCDwarfFile *> &MCDwarfFiles =
1485 getContext().getMCDwarfFiles();
1486 if (CppHashFilename.size() != 0) {
1487 if (MCDwarfFiles[getContext().getGenDwarfFileNumber()]->getName() !=
Kevin Enderby938482f2012-11-01 17:31:35 +00001488 CppHashFilename)
Eli Benderskyed5df012013-01-16 19:32:36 +00001489 getStreamer().EmitDwarfFileDirective(
1490 getContext().nextGenDwarfFileNumber(), StringRef(), CppHashFilename);
Kevin Enderby938482f2012-11-01 17:31:35 +00001491
Kevin Enderby32c1a822012-11-05 21:55:41 +00001492 unsigned CppHashLocLineNo = SrcMgr.FindLineNumber(CppHashLoc,CppHashBuf);
Kevin Enderby938482f2012-11-01 17:31:35 +00001493 Line = CppHashLineNumber - 1 + (Line - CppHashLocLineNo);
Eli Benderskyed5df012013-01-16 19:32:36 +00001494 }
Kevin Enderby938482f2012-11-01 17:31:35 +00001495
Kevin Enderby613b7572011-11-01 22:27:22 +00001496 getStreamer().EmitDwarfLocDirective(getContext().getGenDwarfFileNumber(),
Kevin Enderby938482f2012-11-01 17:31:35 +00001497 Line, 0, DWARF2_LINE_DEFAULT_IS_STMT ?
Kevin Enderbydba9a172011-11-02 17:56:38 +00001498 DWARF2_FLAG_IS_STMT : 0, 0, 0,
Kevin Enderby613b7572011-11-01 22:27:22 +00001499 StringRef());
1500 }
1501
Daniel Dunbar31e8e1d2010-05-04 00:33:07 +00001502 // If parsing succeeded, match the instruction.
Chad Rosier84125ca2012-10-13 00:26:04 +00001503 if (!HadError) {
Chad Rosier84125ca2012-10-13 00:26:04 +00001504 unsigned ErrorInfo;
Eli Friedman2128aae2012-10-22 23:58:19 +00001505 HadError = getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
1506 Info.ParsedOperands,
1507 Out, ErrorInfo,
Chad Rosier84125ca2012-10-13 00:26:04 +00001508 ParsingInlineAsm);
1509 }
Chris Lattner98986712010-01-14 22:21:20 +00001510
Chris Lattnercbf8a982010-09-11 16:18:25 +00001511 // Don't skip the rest of the line, the instruction parser is responsible for
1512 // that.
1513 return false;
Chris Lattner27aa7d22009-06-21 20:16:42 +00001514}
Chris Lattner9a023f72009-06-24 04:43:34 +00001515
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001516/// EatToEndOfLine uses the Lexer to eat the characters to the end of the line
1517/// since they may not be able to be tokenized to get to the end of line token.
1518void AsmParser::EatToEndOfLine() {
Rafael Espindola12ae5272011-10-19 18:48:52 +00001519 if (!Lexer.is(AsmToken::EndOfStatement))
1520 Lexer.LexUntilEndOfLine();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001521 // Eat EOL.
1522 Lex();
1523}
1524
1525/// ParseCppHashLineFilenameComment as this:
1526/// ::= # number "filename"
1527/// or just as a full line comment if it doesn't have a number and a string.
1528bool AsmParser::ParseCppHashLineFilenameComment(const SMLoc &L) {
1529 Lex(); // Eat the hash token.
1530
1531 if (getLexer().isNot(AsmToken::Integer)) {
1532 // Consume the line since in cases it is not a well-formed line directive,
1533 // as if were simply a full line comment.
1534 EatToEndOfLine();
1535 return false;
1536 }
1537
1538 int64_t LineNumber = getTok().getIntVal();
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001539 Lex();
1540
1541 if (getLexer().isNot(AsmToken::String)) {
1542 EatToEndOfLine();
1543 return false;
1544 }
1545
1546 StringRef Filename = getTok().getString();
1547 // Get rid of the enclosing quotes.
1548 Filename = Filename.substr(1, Filename.size()-2);
1549
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001550 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
1551 CppHashLoc = L;
1552 CppHashFilename = Filename;
1553 CppHashLineNumber = LineNumber;
Kevin Enderby32c1a822012-11-05 21:55:41 +00001554 CppHashBuf = CurBuffer;
Kevin Enderbyf1c21a82011-09-13 23:45:18 +00001555
1556 // Ignore any trailing characters, they're just comment.
1557 EatToEndOfLine();
1558 return false;
1559}
1560
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +00001561/// DiagHandler - will use the last parsed cpp hash line filename comment
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001562/// for the Filename and LineNo if any in the diagnostic.
1563void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
1564 const AsmParser *Parser = static_cast<const AsmParser*>(Context);
1565 raw_ostream &OS = errs();
1566
1567 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
1568 const SMLoc &DiagLoc = Diag.getLoc();
1569 int DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
1570 int CppHashBuf = Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashLoc);
1571
1572 // Like SourceMgr::PrintMessage() we need to print the include stack if any
1573 // before printing the message.
1574 int DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
Benjamin Kramer04a04262011-10-16 10:48:29 +00001575 if (!Parser->SavedDiagHandler && DiagCurBuffer > 0) {
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001576 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
1577 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
1578 }
1579
Eric Christopher2318ba12012-12-18 00:30:54 +00001580 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001581 // manager changed or buffer changed (like in a nested include) then just
1582 // print the normal diagnostic using its Filename and LineNo.
1583 if (!Parser->CppHashLineNumber ||
1584 &DiagSrcMgr != &Parser->SrcMgr ||
1585 DiagBuf != CppHashBuf) {
Benjamin Kramer04a04262011-10-16 10:48:29 +00001586 if (Parser->SavedDiagHandler)
1587 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
1588 else
1589 Diag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001590 return;
1591 }
1592
Eric Christopher2318ba12012-12-18 00:30:54 +00001593 // Use the CppHashFilename and calculate a line number based on the
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001594 // CppHashLoc and CppHashLineNumber relative to this Diag's SMLoc for
1595 // the diagnostic.
1596 const std::string Filename = Parser->CppHashFilename;
1597
1598 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
1599 int CppHashLocLineNo =
1600 Parser->SrcMgr.FindLineNumber(Parser->CppHashLoc, CppHashBuf);
1601 int LineNo = Parser->CppHashLineNumber - 1 +
1602 (DiagLocLineNo - CppHashLocLineNo);
1603
Chris Lattnerd8b7aa22011-10-16 04:47:35 +00001604 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(),
1605 Filename, LineNo, Diag.getColumnNo(),
Chris Lattner3f2d5f62011-10-16 05:43:57 +00001606 Diag.getKind(), Diag.getMessage(),
Chris Lattner462b43c2011-10-16 05:47:55 +00001607 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001608
Benjamin Kramer04a04262011-10-16 10:48:29 +00001609 if (Parser->SavedDiagHandler)
1610 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
1611 else
1612 NewDiag.print(0, OS);
Kevin Enderbyacbaecd2011-10-12 21:38:39 +00001613}
1614
Rafael Espindola799aacf2012-08-21 18:29:30 +00001615// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
1616// difference being that that function accepts '@' as part of identifiers and
1617// we can't do that. AsmLexer.cpp should probably be changed to handle
1618// '@' as a special case when needed.
1619static bool isIdentifierChar(char c) {
1620 return isalnum(c) || c == '_' || c == '$' || c == '.';
1621}
1622
Rafael Espindola761cb062012-06-03 23:57:14 +00001623bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001624 const MCAsmMacroParameters &Parameters,
1625 const MCAsmMacroArguments &A,
Rafael Espindola65366442011-06-05 02:43:45 +00001626 const SMLoc &L) {
Rafael Espindola65366442011-06-05 02:43:45 +00001627 unsigned NParameters = Parameters.size();
1628 if (NParameters != 0 && NParameters != A.size())
1629 return Error(L, "Wrong number of arguments");
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001630
Preston Gurd7b6f2032012-09-19 20:36:12 +00001631 // A macro without parameters is handled differently on Darwin:
1632 // gas accepts no arguments and does no substitutions
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001633 while (!Body.empty()) {
1634 // Scan for the next substitution.
1635 std::size_t End = Body.size(), Pos = 0;
1636 for (; Pos != End; ++Pos) {
1637 // Check for a substitution or escape.
Rafael Espindola65366442011-06-05 02:43:45 +00001638 if (!NParameters) {
1639 // This macro has no parameters, look for $0, $1, etc.
1640 if (Body[Pos] != '$' || Pos + 1 == End)
1641 continue;
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001642
Rafael Espindola65366442011-06-05 02:43:45 +00001643 char Next = Body[Pos + 1];
1644 if (Next == '$' || Next == 'n' || isdigit(Next))
1645 break;
1646 } else {
1647 // This macro has parameters, look for \foo, \bar, etc.
1648 if (Body[Pos] == '\\' && Pos + 1 != End)
1649 break;
1650 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001651 }
1652
1653 // Add the prefix.
1654 OS << Body.slice(0, Pos);
1655
1656 // Check if we reached the end.
1657 if (Pos == End)
1658 break;
1659
Rafael Espindola65366442011-06-05 02:43:45 +00001660 if (!NParameters) {
1661 switch (Body[Pos+1]) {
1662 // $$ => $
1663 case '$':
1664 OS << '$';
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001665 break;
1666
Rafael Espindola65366442011-06-05 02:43:45 +00001667 // $n => number of arguments
1668 case 'n':
1669 OS << A.size();
1670 break;
1671
1672 // $[0-9] => argument
1673 default: {
1674 // Missing arguments are ignored.
1675 unsigned Index = Body[Pos+1] - '0';
1676 if (Index >= A.size())
1677 break;
1678
1679 // Otherwise substitute with the token values, with spaces eliminated.
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001680 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Rafael Espindola65366442011-06-05 02:43:45 +00001681 ie = A[Index].end(); it != ie; ++it)
1682 OS << it->getString();
1683 break;
1684 }
1685 }
1686 Pos += 2;
1687 } else {
1688 unsigned I = Pos + 1;
Rafael Espindola799aacf2012-08-21 18:29:30 +00001689 while (isIdentifierChar(Body[I]) && I + 1 != End)
Rafael Espindola65366442011-06-05 02:43:45 +00001690 ++I;
1691
1692 const char *Begin = Body.data() + Pos +1;
1693 StringRef Argument(Begin, I - (Pos +1));
1694 unsigned Index = 0;
1695 for (; Index < NParameters; ++Index)
Preston Gurd6c9176a2012-09-19 20:29:04 +00001696 if (Parameters[Index].first == Argument)
Rafael Espindola65366442011-06-05 02:43:45 +00001697 break;
1698
Preston Gurd7b6f2032012-09-19 20:36:12 +00001699 if (Index == NParameters) {
1700 if (Body[Pos+1] == '(' && Body[Pos+2] == ')')
1701 Pos += 3;
1702 else {
1703 OS << '\\' << Argument;
1704 Pos = I;
1705 }
1706 } else {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001707 for (MCAsmMacroArgument::const_iterator it = A[Index].begin(),
Preston Gurd7b6f2032012-09-19 20:36:12 +00001708 ie = A[Index].end(); it != ie; ++it)
1709 if (it->getKind() == AsmToken::String)
1710 OS << it->getStringContents();
1711 else
1712 OS << it->getString();
Rafael Espindola65366442011-06-05 02:43:45 +00001713
Preston Gurd7b6f2032012-09-19 20:36:12 +00001714 Pos += 1 + Argument.size();
1715 }
Rafael Espindola65366442011-06-05 02:43:45 +00001716 }
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001717 // Update the scan point.
Rafael Espindola65366442011-06-05 02:43:45 +00001718 Body = Body.substr(Pos);
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001719 }
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001720
Rafael Espindola65366442011-06-05 02:43:45 +00001721 return false;
1722}
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001723
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001724MacroInstantiation::MacroInstantiation(const MCAsmMacro *M, SMLoc IL,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001725 int EB, SMLoc EL,
Rafael Espindola65366442011-06-05 02:43:45 +00001726 MemoryBuffer *I)
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001727 : TheMacro(M), Instantiation(I), InstantiationLoc(IL), ExitBuffer(EB),
1728 ExitLoc(EL)
Rafael Espindola65366442011-06-05 02:43:45 +00001729{
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001730}
1731
Preston Gurd7b6f2032012-09-19 20:36:12 +00001732static bool IsOperator(AsmToken::TokenKind kind)
1733{
1734 switch (kind)
1735 {
1736 default:
1737 return false;
1738 case AsmToken::Plus:
1739 case AsmToken::Minus:
1740 case AsmToken::Tilde:
1741 case AsmToken::Slash:
1742 case AsmToken::Star:
1743 case AsmToken::Dot:
1744 case AsmToken::Equal:
1745 case AsmToken::EqualEqual:
1746 case AsmToken::Pipe:
1747 case AsmToken::PipePipe:
1748 case AsmToken::Caret:
1749 case AsmToken::Amp:
1750 case AsmToken::AmpAmp:
1751 case AsmToken::Exclaim:
1752 case AsmToken::ExclaimEqual:
1753 case AsmToken::Percent:
1754 case AsmToken::Less:
1755 case AsmToken::LessEqual:
1756 case AsmToken::LessLess:
1757 case AsmToken::LessGreater:
1758 case AsmToken::Greater:
1759 case AsmToken::GreaterEqual:
1760 case AsmToken::GreaterGreater:
1761 return true;
1762 }
1763}
1764
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001765bool AsmParser::ParseMacroArgument(MCAsmMacroArgument &MA,
Preston Gurd7b6f2032012-09-19 20:36:12 +00001766 AsmToken::TokenKind &ArgumentDelimiter) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001767 unsigned ParenLevel = 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001768 unsigned AddTokens = 0;
1769
1770 // gas accepts arguments separated by whitespace, except on Darwin
1771 if (!IsDarwin)
1772 Lexer.setSkipSpace(false);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001773
1774 for (;;) {
Preston Gurd7b6f2032012-09-19 20:36:12 +00001775 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal)) {
1776 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001777 return TokError("unexpected token in macro instantiation");
Preston Gurd7b6f2032012-09-19 20:36:12 +00001778 }
1779
1780 if (ParenLevel == 0 && Lexer.is(AsmToken::Comma)) {
1781 // Spaces and commas cannot be mixed to delimit parameters
1782 if (ArgumentDelimiter == AsmToken::Eof)
1783 ArgumentDelimiter = AsmToken::Comma;
1784 else if (ArgumentDelimiter != AsmToken::Comma) {
1785 Lexer.setSkipSpace(true);
1786 return TokError("expected ' ' for macro argument separator");
1787 }
1788 break;
1789 }
1790
1791 if (Lexer.is(AsmToken::Space)) {
1792 Lex(); // Eat spaces
1793
1794 // Spaces can delimit parameters, but could also be part an expression.
1795 // If the token after a space is an operator, add the token and the next
1796 // one into this argument
1797 if (ArgumentDelimiter == AsmToken::Space ||
1798 ArgumentDelimiter == AsmToken::Eof) {
1799 if (IsOperator(Lexer.getKind())) {
1800 // Check to see whether the token is used as an operator,
1801 // or part of an identifier
Jordan Rose3ebe59c2013-01-07 19:00:49 +00001802 const char *NextChar = getTok().getEndLoc().getPointer();
Preston Gurd7b6f2032012-09-19 20:36:12 +00001803 if (*NextChar == ' ')
1804 AddTokens = 2;
1805 }
1806
1807 if (!AddTokens && ParenLevel == 0) {
1808 if (ArgumentDelimiter == AsmToken::Eof &&
1809 !IsOperator(Lexer.getKind()))
1810 ArgumentDelimiter = AsmToken::Space;
1811 break;
1812 }
1813 }
1814 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001815
1816 // HandleMacroEntry relies on not advancing the lexer here
1817 // to be able to fill in the remaining default parameter values
1818 if (Lexer.is(AsmToken::EndOfStatement))
1819 break;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001820
1821 // Adjust the current parentheses level.
1822 if (Lexer.is(AsmToken::LParen))
1823 ++ParenLevel;
1824 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
1825 --ParenLevel;
1826
1827 // Append the token to the current argument list.
1828 MA.push_back(getTok());
Preston Gurd7b6f2032012-09-19 20:36:12 +00001829 if (AddTokens)
1830 AddTokens--;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001831 Lex();
1832 }
Preston Gurd7b6f2032012-09-19 20:36:12 +00001833
1834 Lexer.setSkipSpace(true);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001835 if (ParenLevel != 0)
Rafael Espindola76ac2002012-08-21 15:55:04 +00001836 return TokError("unbalanced parentheses in macro argument");
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001837 return false;
1838}
1839
1840// Parse the macro instantiation arguments.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001841bool AsmParser::ParseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A) {
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001842 const unsigned NParameters = M ? M->Parameters.size() : 0;
Preston Gurd7b6f2032012-09-19 20:36:12 +00001843 // Argument delimiter is initially unknown. It will be set by
1844 // ParseMacroArgument()
1845 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001846
1847 // Parse two kinds of macro invocations:
1848 // - macros defined without any parameters accept an arbitrary number of them
1849 // - macros defined with parameters accept at most that many of them
1850 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
1851 ++Parameter) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00001852 MCAsmMacroArgument MA;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001853
Preston Gurd7b6f2032012-09-19 20:36:12 +00001854 if (ParseMacroArgument(MA, ArgumentDelimiter))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001855 return true;
1856
Preston Gurd6c9176a2012-09-19 20:29:04 +00001857 if (!MA.empty() || !NParameters)
1858 A.push_back(MA);
1859 else if (NParameters) {
1860 if (!M->Parameters[Parameter].second.empty())
1861 A.push_back(M->Parameters[Parameter].second);
1862 }
Jim Grosbach97146442012-07-30 22:44:17 +00001863
Preston Gurd6c9176a2012-09-19 20:29:04 +00001864 // At the end of the statement, fill in remaining arguments that have
1865 // default values. If there aren't any, then the next argument is
1866 // required but missing
1867 if (Lexer.is(AsmToken::EndOfStatement)) {
1868 if (NParameters && Parameter < NParameters - 1) {
1869 if (M->Parameters[Parameter + 1].second.empty())
1870 return TokError("macro argument '" +
1871 Twine(M->Parameters[Parameter + 1].first) +
1872 "' is missing");
1873 else
1874 continue;
1875 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001876 return false;
Preston Gurd6c9176a2012-09-19 20:29:04 +00001877 }
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001878
1879 if (Lexer.is(AsmToken::Comma))
1880 Lex();
1881 }
1882 return TokError("Too many arguments");
1883}
1884
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001885const MCAsmMacro* AsmParser::LookupMacro(StringRef Name) {
1886 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1887 return (I == MacroMap.end()) ? NULL : I->getValue();
1888}
1889
1890void AsmParser::DefineMacro(StringRef Name, const MCAsmMacro& Macro) {
1891 MacroMap[Name] = new MCAsmMacro(Macro);
1892}
1893
1894void AsmParser::UndefineMacro(StringRef Name) {
1895 StringMap<MCAsmMacro*>::iterator I = MacroMap.find(Name);
1896 if (I != MacroMap.end()) {
1897 delete I->getValue();
1898 MacroMap.erase(I);
1899 }
1900}
1901
1902bool AsmParser::HandleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001903 // Arbitrarily limit macro nesting depth, to match 'as'. We can eliminate
1904 // this, although we should protect against infinite loops.
1905 if (ActiveMacros.size() == 20)
1906 return TokError("macros cannot be nested more than 20 levels deep");
1907
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001908 MCAsmMacroArguments A;
Rafael Espindola8a403d32012-08-08 14:51:03 +00001909 if (ParseMacroArguments(M, A))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00001910 return true;
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001911
Jim Grosbach97146442012-07-30 22:44:17 +00001912 // Remove any trailing empty arguments. Do this after-the-fact as we have
1913 // to keep empty arguments in the middle of the list or positionality
1914 // gets off. e.g., "foo 1, , 2" vs. "foo 1, 2,"
Rafael Espindola8a403d32012-08-08 14:51:03 +00001915 while (!A.empty() && A.back().empty())
1916 A.pop_back();
Jim Grosbach97146442012-07-30 22:44:17 +00001917
Rafael Espindola65366442011-06-05 02:43:45 +00001918 // Macro instantiation is lexical, unfortunately. We construct a new buffer
1919 // to hold the macro body with substitutions.
1920 SmallString<256> Buf;
1921 StringRef Body = M->Body;
Rafael Espindola761cb062012-06-03 23:57:14 +00001922 raw_svector_ostream OS(Buf);
Rafael Espindola65366442011-06-05 02:43:45 +00001923
Rafael Espindola8a403d32012-08-08 14:51:03 +00001924 if (expandMacro(OS, Body, M->Parameters, A, getTok().getLoc()))
Rafael Espindola65366442011-06-05 02:43:45 +00001925 return true;
1926
Eli Benderskyc0c67b02013-01-14 23:22:36 +00001927 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola761cb062012-06-03 23:57:14 +00001928 // instantiation.
1929 OS << ".endmacro\n";
1930
Rafael Espindola65366442011-06-05 02:43:45 +00001931 MemoryBuffer *Instantiation =
Rafael Espindola761cb062012-06-03 23:57:14 +00001932 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola65366442011-06-05 02:43:45 +00001933
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001934 // Create the macro instantiation object and add to the current macro
1935 // instantiation stack.
1936 MacroInstantiation *MI = new MacroInstantiation(M, NameLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001937 CurBuffer,
Daniel Dunbar7a570d02010-07-18 19:00:10 +00001938 getTok().getLoc(),
Rafael Espindola65366442011-06-05 02:43:45 +00001939 Instantiation);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001940 ActiveMacros.push_back(MI);
1941
1942 // Jump to the macro instantiation and prime the lexer.
1943 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
1944 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
1945 Lex();
1946
1947 return false;
1948}
1949
1950void AsmParser::HandleMacroExit() {
1951 // Jump to the EndOfStatement we should return to, and consume it.
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00001952 JumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbarc64a0d72010-07-18 18:54:11 +00001953 Lex();
1954
1955 // Pop the instantiation entry.
1956 delete ActiveMacros.back();
1957 ActiveMacros.pop_back();
1958}
1959
Rafael Espindolae71cc862012-01-28 05:57:00 +00001960static bool IsUsedIn(const MCSymbol *Sym, const MCExpr *Value) {
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001961 switch (Value->getKind()) {
Rafael Espindolae71cc862012-01-28 05:57:00 +00001962 case MCExpr::Binary: {
1963 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr*>(Value);
1964 return IsUsedIn(Sym, BE->getLHS()) || IsUsedIn(Sym, BE->getRHS());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001965 break;
1966 }
Rafael Espindolae71cc862012-01-28 05:57:00 +00001967 case MCExpr::Target:
1968 case MCExpr::Constant:
1969 return false;
1970 case MCExpr::SymbolRef: {
1971 const MCSymbol &S = static_cast<const MCSymbolRefExpr*>(Value)->getSymbol();
Rafael Espindola8b01c822012-01-28 06:22:14 +00001972 if (S.isVariable())
1973 return IsUsedIn(Sym, S.getVariableValue());
1974 return &S == Sym;
Rafael Espindolae71cc862012-01-28 05:57:00 +00001975 }
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001976 case MCExpr::Unary:
Rafael Espindolae71cc862012-01-28 05:57:00 +00001977 return IsUsedIn(Sym, static_cast<const MCUnaryExpr*>(Value)->getSubExpr());
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001978 }
Benjamin Kramer518ff562012-01-28 15:28:41 +00001979
1980 llvm_unreachable("Unknown expr kind!");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001981}
1982
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00001983bool AsmParser::ParseAssignment(StringRef Name, bool allow_redef,
1984 bool NoDeadStrip) {
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00001985 // FIXME: Use better location, we should use proper tokens.
1986 SMLoc EqualLoc = Lexer.getLoc();
1987
Daniel Dunbar821e3332009-08-31 08:09:28 +00001988 const MCExpr *Value;
Daniel Dunbar821e3332009-08-31 08:09:28 +00001989 if (ParseExpression(Value))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001990 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00001991
Rafael Espindolae71cc862012-01-28 05:57:00 +00001992 // Note: we don't count b as used in "a = b". This is to allow
1993 // a = b
1994 // b = c
Rafael Espindoladb9835d2010-11-15 14:40:36 +00001995
Daniel Dunbar3f872332009-07-28 16:08:33 +00001996 if (Lexer.isNot(AsmToken::EndOfStatement))
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00001997 return TokError("unexpected token in assignment");
1998
Daniel Dunbar8b2b43c2011-03-25 17:47:17 +00001999 // Error on assignment to '.'.
2000 if (Name == ".") {
2001 return Error(EqualLoc, ("assignment to pseudo-symbol '.' is unsupported "
2002 "(use '.space' or '.org').)"));
2003 }
2004
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002005 // Eat the end of statement marker.
Sean Callanan79ed1a82010-01-19 20:22:31 +00002006 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002007
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002008 // Validate that the LHS is allowed to be a variable (either it has not been
2009 // used as a symbol, or it is an absolute symbol).
2010 MCSymbol *Sym = getContext().LookupSymbol(Name);
2011 if (Sym) {
2012 // Diagnose assignment to a label.
2013 //
2014 // FIXME: Diagnostics. Note the location of the definition as a label.
2015 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
Rafael Espindolae71cc862012-01-28 05:57:00 +00002016 if (IsUsedIn(Sym, Value))
2017 return Error(EqualLoc, "Recursive use of '" + Name + "'");
2018 else if (Sym->isUndefined() && !Sym->isUsed() && !Sym->isVariable())
Daniel Dunbar525a3a62010-05-17 17:46:23 +00002019 ; // Allow redefinitions of undefined symbols only used in directives.
Jim Grosbach48c95332012-03-20 21:33:21 +00002020 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
2021 ; // Allow redefinitions of variables that haven't yet been used.
Daniel Dunbar6db7fe82011-04-29 17:53:11 +00002022 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002023 return Error(EqualLoc, "redefinition of '" + Name + "'");
2024 else if (!Sym->isVariable())
2025 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
Daniel Dunbar08a408a2010-05-05 17:41:00 +00002026 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002027 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
2028 Name + "'");
Rafael Espindoladb9835d2010-11-15 14:40:36 +00002029
2030 // Don't count these checks as uses.
2031 Sym->setUsed(false);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002032 } else
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00002033 Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbar75773ff2009-10-16 01:57:39 +00002034
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002035 // FIXME: Handle '.'.
Daniel Dunbardce0f3c2009-06-29 23:43:14 +00002036
2037 // Do the assignment.
Daniel Dunbare2ace502009-08-31 08:09:09 +00002038 Out.EmitAssignment(Sym, Value);
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002039 if (NoDeadStrip)
2040 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2041
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002042
2043 return false;
2044}
2045
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002046/// ParseIdentifier:
2047/// ::= identifier
2048/// ::= string
2049bool AsmParser::ParseIdentifier(StringRef &Res) {
Daniel Dunbar1f1b8652010-08-24 18:12:12 +00002050 // The assembler has relaxed rules for accepting identifiers, in particular we
2051 // allow things like '.globl $foo', which would normally be separate
2052 // tokens. At this level, we have already lexed so we cannot (currently)
2053 // handle this as a context dependent token, instead we detect adjacent tokens
2054 // and return the combined identifier.
2055 if (Lexer.is(AsmToken::Dollar)) {
2056 SMLoc DollarLoc = getLexer().getLoc();
2057
2058 // Consume the dollar sign, and check for a following identifier.
2059 Lex();
2060 if (Lexer.isNot(AsmToken::Identifier))
2061 return true;
2062
2063 // We have a '$' followed by an identifier, make sure they are adjacent.
2064 if (DollarLoc.getPointer() + 1 != getTok().getLoc().getPointer())
2065 return true;
2066
2067 // Construct the joined identifier and consume the token.
2068 Res = StringRef(DollarLoc.getPointer(),
2069 getTok().getIdentifier().size() + 1);
2070 Lex();
2071 return false;
2072 }
2073
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002074 if (Lexer.isNot(AsmToken::Identifier) &&
2075 Lexer.isNot(AsmToken::String))
2076 return true;
2077
Sean Callanan18b83232010-01-19 21:44:56 +00002078 Res = getTok().getIdentifier();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002079
Sean Callanan79ed1a82010-01-19 20:22:31 +00002080 Lex(); // Consume the identifier token.
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002081
2082 return false;
2083}
2084
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002085/// ParseDirectiveSet:
Nico Weber4c4c7322011-01-28 03:04:41 +00002086/// ::= .equ identifier ',' expression
2087/// ::= .equiv identifier ',' expression
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002088/// ::= .set identifier ',' expression
Nico Weber4c4c7322011-01-28 03:04:41 +00002089bool AsmParser::ParseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002090 StringRef Name;
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002091
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00002092 if (ParseIdentifier(Name))
Roman Divackyf9d17522010-10-28 16:57:58 +00002093 return TokError("expected identifier after '" + Twine(IDVal) + "'");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002094
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002095 if (getLexer().isNot(AsmToken::Comma))
Roman Divackyf9d17522010-10-28 16:57:58 +00002096 return TokError("unexpected token in '" + Twine(IDVal) + "'");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002097 Lex();
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002098
Jim Grosbach3f90a4c2012-09-13 23:11:31 +00002099 return ParseAssignment(Name, allow_redef, true);
Daniel Dunbar8f780cd2009-06-25 21:56:11 +00002100}
2101
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002102bool AsmParser::ParseEscapedString(std::string &Data) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002103 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002104
2105 Data = "";
Sean Callanan18b83232010-01-19 21:44:56 +00002106 StringRef Str = getTok().getStringContents();
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002107 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2108 if (Str[i] != '\\') {
2109 Data += Str[i];
2110 continue;
2111 }
2112
2113 // Recognize escaped characters. Note that this escape semantics currently
2114 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2115 ++i;
2116 if (i == e)
2117 return TokError("unexpected backslash at end of string");
2118
2119 // Recognize octal sequences.
2120 if ((unsigned) (Str[i] - '0') <= 7) {
2121 // Consume up to three octal characters.
2122 unsigned Value = Str[i] - '0';
2123
2124 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2125 ++i;
2126 Value = Value * 8 + (Str[i] - '0');
2127
2128 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
2129 ++i;
2130 Value = Value * 8 + (Str[i] - '0');
2131 }
2132 }
2133
2134 if (Value > 255)
2135 return TokError("invalid octal escape sequence (out of range)");
2136
2137 Data += (unsigned char) Value;
2138 continue;
2139 }
2140
2141 // Otherwise recognize individual escapes.
2142 switch (Str[i]) {
2143 default:
2144 // Just reject invalid escape sequences for now.
2145 return TokError("invalid escape sequence (unrecognized character)");
2146
2147 case 'b': Data += '\b'; break;
2148 case 'f': Data += '\f'; break;
2149 case 'n': Data += '\n'; break;
2150 case 'r': Data += '\r'; break;
2151 case 't': Data += '\t'; break;
2152 case '"': Data += '"'; break;
2153 case '\\': Data += '\\'; break;
2154 }
2155 }
2156
2157 return false;
2158}
2159
Daniel Dunbara0d14262009-06-24 23:30:00 +00002160/// ParseDirectiveAscii:
Rafael Espindola787c3372010-10-28 20:02:27 +00002161/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2162bool AsmParser::ParseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002163 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002164 CheckForValidSection();
2165
Daniel Dunbara0d14262009-06-24 23:30:00 +00002166 for (;;) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002167 if (getLexer().isNot(AsmToken::String))
Rafael Espindola787c3372010-10-28 20:02:27 +00002168 return TokError("expected string in '" + Twine(IDVal) + "' directive");
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002169
Daniel Dunbar1ab75942009-08-14 18:19:52 +00002170 std::string Data;
2171 if (ParseEscapedString(Data))
2172 return true;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002173
2174 getStreamer().EmitBytes(Data, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002175 if (ZeroTerminated)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002176 getStreamer().EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
2177
Sean Callanan79ed1a82010-01-19 20:22:31 +00002178 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002179
2180 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002181 break;
2182
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002183 if (getLexer().isNot(AsmToken::Comma))
Rafael Espindola787c3372010-10-28 20:02:27 +00002184 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002185 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002186 }
2187 }
2188
Sean Callanan79ed1a82010-01-19 20:22:31 +00002189 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002190 return false;
2191}
2192
2193/// ParseDirectiveValue
2194/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2195bool AsmParser::ParseDirectiveValue(unsigned Size) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002196 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002197 CheckForValidSection();
2198
Daniel Dunbara0d14262009-06-24 23:30:00 +00002199 for (;;) {
Daniel Dunbar821e3332009-08-31 08:09:28 +00002200 const MCExpr *Value;
Jim Grosbach254cf032011-06-29 16:05:14 +00002201 SMLoc ExprLoc = getLexer().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002202 if (ParseExpression(Value))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002203 return true;
2204
Daniel Dunbar414c0c42010-05-23 18:36:38 +00002205 // Special case constant expressions to match code generator.
Jim Grosbach254cf032011-06-29 16:05:14 +00002206 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2207 assert(Size <= 8 && "Invalid size");
2208 uint64_t IntValue = MCE->getValue();
2209 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2210 return Error(ExprLoc, "literal value out of range for directive");
2211 getStreamer().EmitIntValue(IntValue, Size, DEFAULT_ADDRSPACE);
2212 } else
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002213 getStreamer().EmitValue(Value, Size, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002214
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002215 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002216 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002217
Daniel Dunbara0d14262009-06-24 23:30:00 +00002218 // FIXME: Improve diagnostic.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002219 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002220 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002221 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002222 }
2223 }
2224
Sean Callanan79ed1a82010-01-19 20:22:31 +00002225 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002226 return false;
2227}
2228
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002229/// ParseDirectiveRealValue
2230/// ::= (.single | .double) [ expression (, expression)* ]
2231bool AsmParser::ParseDirectiveRealValue(const fltSemantics &Semantics) {
2232 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2233 CheckForValidSection();
2234
2235 for (;;) {
2236 // We don't truly support arithmetic on floating point expressions, so we
2237 // have to manually parse unary prefixes.
2238 bool IsNeg = false;
2239 if (getLexer().is(AsmToken::Minus)) {
2240 Lex();
2241 IsNeg = true;
2242 } else if (getLexer().is(AsmToken::Plus))
2243 Lex();
2244
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002245 if (getLexer().isNot(AsmToken::Integer) &&
Kevin Enderby360d8d72011-03-29 21:11:52 +00002246 getLexer().isNot(AsmToken::Real) &&
2247 getLexer().isNot(AsmToken::Identifier))
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002248 return TokError("unexpected token in directive");
2249
2250 // Convert to an APFloat.
2251 APFloat Value(Semantics);
Kevin Enderby360d8d72011-03-29 21:11:52 +00002252 StringRef IDVal = getTok().getString();
2253 if (getLexer().is(AsmToken::Identifier)) {
2254 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2255 Value = APFloat::getInf(Semantics);
2256 else if (!IDVal.compare_lower("nan"))
2257 Value = APFloat::getNaN(Semantics, false, ~0);
2258 else
2259 return TokError("invalid floating point literal");
2260 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002261 APFloat::opInvalidOp)
2262 return TokError("invalid floating point literal");
2263 if (IsNeg)
2264 Value.changeSign();
2265
2266 // Consume the numeric token.
2267 Lex();
2268
2269 // Emit the value as an integer.
2270 APInt AsInt = Value.bitcastToAPInt();
2271 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2272 AsInt.getBitWidth() / 8, DEFAULT_ADDRSPACE);
2273
2274 if (getLexer().is(AsmToken::EndOfStatement))
2275 break;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002276
Daniel Dunbarb95a0792010-09-24 01:59:56 +00002277 if (getLexer().isNot(AsmToken::Comma))
2278 return TokError("unexpected token in directive");
2279 Lex();
2280 }
2281 }
2282
2283 Lex();
2284 return false;
2285}
2286
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002287/// ParseDirectiveZero
2288/// ::= .zero expression
2289bool AsmParser::ParseDirectiveZero() {
2290 CheckForValidSection();
2291
2292 int64_t NumBytes;
2293 if (ParseAbsoluteExpression(NumBytes))
2294 return true;
2295
Rafael Espindolae452b172010-10-05 19:42:57 +00002296 int64_t Val = 0;
2297 if (getLexer().is(AsmToken::Comma)) {
2298 Lex();
2299 if (ParseAbsoluteExpression(Val))
2300 return true;
2301 }
2302
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002303 if (getLexer().isNot(AsmToken::EndOfStatement))
2304 return TokError("unexpected token in '.zero' directive");
2305
2306 Lex();
2307
Rafael Espindolae452b172010-10-05 19:42:57 +00002308 getStreamer().EmitFill(NumBytes, Val, DEFAULT_ADDRSPACE);
Rafael Espindola2ea2ac72010-09-16 15:03:59 +00002309
2310 return false;
2311}
2312
Daniel Dunbara0d14262009-06-24 23:30:00 +00002313/// ParseDirectiveFill
2314/// ::= .fill expression , expression , expression
2315bool AsmParser::ParseDirectiveFill() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002316 CheckForValidSection();
2317
Daniel Dunbara0d14262009-06-24 23:30:00 +00002318 int64_t NumValues;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002319 if (ParseAbsoluteExpression(NumValues))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002320 return true;
2321
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002322 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002323 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002324 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002325
Daniel Dunbara0d14262009-06-24 23:30:00 +00002326 int64_t FillSize;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002327 if (ParseAbsoluteExpression(FillSize))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002328 return true;
2329
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002330 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002331 return TokError("unexpected token in '.fill' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002332 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002333
Daniel Dunbara0d14262009-06-24 23:30:00 +00002334 int64_t FillExpr;
Daniel Dunbar475839e2009-06-29 20:37:27 +00002335 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002336 return true;
2337
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002338 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbara0d14262009-06-24 23:30:00 +00002339 return TokError("unexpected token in '.fill' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002340
Sean Callanan79ed1a82010-01-19 20:22:31 +00002341 Lex();
Daniel Dunbara0d14262009-06-24 23:30:00 +00002342
Daniel Dunbarbc38ca72009-08-21 15:43:35 +00002343 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
2344 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
Daniel Dunbara0d14262009-06-24 23:30:00 +00002345
2346 for (uint64_t i = 0, e = NumValues; i != e; ++i)
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002347 getStreamer().EmitIntValue(FillExpr, FillSize, DEFAULT_ADDRSPACE);
Daniel Dunbara0d14262009-06-24 23:30:00 +00002348
2349 return false;
2350}
Daniel Dunbarc238b582009-06-25 22:44:51 +00002351
2352/// ParseDirectiveOrg
2353/// ::= .org expression [ , expression ]
2354bool AsmParser::ParseDirectiveOrg() {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002355 CheckForValidSection();
2356
Daniel Dunbar821e3332009-08-31 08:09:28 +00002357 const MCExpr *Offset;
Jim Grosbachebd4c052012-01-27 00:37:08 +00002358 SMLoc Loc = getTok().getLoc();
Daniel Dunbar821e3332009-08-31 08:09:28 +00002359 if (ParseExpression(Offset))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002360 return true;
2361
2362 // Parse optional fill expression.
2363 int64_t FillExpr = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002364 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2365 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002366 return TokError("unexpected token in '.org' directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002367 Lex();
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002368
Daniel Dunbar475839e2009-06-29 20:37:27 +00002369 if (ParseAbsoluteExpression(FillExpr))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002370 return true;
2371
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002372 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc238b582009-06-25 22:44:51 +00002373 return TokError("unexpected token in '.org' directive");
2374 }
2375
Sean Callanan79ed1a82010-01-19 20:22:31 +00002376 Lex();
Daniel Dunbarf4b830f2009-06-30 02:10:03 +00002377
Jim Grosbachebd4c052012-01-27 00:37:08 +00002378 // Only limited forms of relocatable expressions are accepted here, it
2379 // has to be relative to the current section. The streamer will return
2380 // 'true' if the expression wasn't evaluatable.
2381 if (getStreamer().EmitValueToOffset(Offset, FillExpr))
2382 return Error(Loc, "expected assembly-time absolute expression");
Daniel Dunbarc238b582009-06-25 22:44:51 +00002383
2384 return false;
2385}
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002386
2387/// ParseDirectiveAlign
2388/// ::= {.align, ...} expression [ , expression [ , expression ]]
2389bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00002390 CheckForValidSection();
2391
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002392 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002393 int64_t Alignment;
2394 if (ParseAbsoluteExpression(Alignment))
2395 return true;
2396
2397 SMLoc MaxBytesLoc;
2398 bool HasFillExpr = false;
2399 int64_t FillExpr = 0;
2400 int64_t MaxBytesToFill = 0;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002401 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2402 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002403 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002404 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002405
2406 // The fill expression can be omitted while specifying a maximum number of
2407 // alignment bytes, e.g:
2408 // .align 3,,4
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002409 if (getLexer().isNot(AsmToken::Comma)) {
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002410 HasFillExpr = true;
2411 if (ParseAbsoluteExpression(FillExpr))
2412 return true;
2413 }
2414
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002415 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2416 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002417 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00002418 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002419
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002420 MaxBytesLoc = getLexer().getLoc();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002421 if (ParseAbsoluteExpression(MaxBytesToFill))
2422 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00002423
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002424 if (getLexer().isNot(AsmToken::EndOfStatement))
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002425 return TokError("unexpected token in directive");
2426 }
2427 }
2428
Sean Callanan79ed1a82010-01-19 20:22:31 +00002429 Lex();
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002430
Daniel Dunbar648ac512010-05-17 21:54:30 +00002431 if (!HasFillExpr)
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002432 FillExpr = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002433
2434 // Compute alignment in bytes.
2435 if (IsPow2) {
2436 // FIXME: Diagnose overflow.
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002437 if (Alignment >= 32) {
2438 Error(AlignmentLoc, "invalid alignment value");
2439 Alignment = 31;
2440 }
2441
Benjamin Kramer12fd7672009-09-06 09:35:10 +00002442 Alignment = 1ULL << Alignment;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002443 }
2444
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002445 // Diagnose non-sensical max bytes to align.
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002446 if (MaxBytesLoc.isValid()) {
2447 if (MaxBytesToFill < 1) {
Daniel Dunbarb58a8042009-08-26 09:16:34 +00002448 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
2449 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar0afb9f52009-08-21 23:01:53 +00002450 MaxBytesToFill = 0;
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002451 }
2452
2453 if (MaxBytesToFill >= Alignment) {
Daniel Dunbar3fb76832009-06-30 00:49:23 +00002454 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
2455 "has no effect");
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002456 MaxBytesToFill = 0;
2457 }
2458 }
2459
Daniel Dunbar648ac512010-05-17 21:54:30 +00002460 // Check whether we should use optimal code alignment for this .align
2461 // directive.
Jan Wen Voung083cf152010-10-04 17:32:41 +00002462 bool UseCodeAlign = getStreamer().getCurrentSection()->UseCodeAlign();
Daniel Dunbar648ac512010-05-17 21:54:30 +00002463 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
2464 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00002465 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002466 } else {
Kevin Enderbyd74acb02010-02-25 18:46:04 +00002467 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnera9558532010-07-15 21:19:31 +00002468 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
2469 MaxBytesToFill);
Daniel Dunbar648ac512010-05-17 21:54:30 +00002470 }
Daniel Dunbarc29dfa72009-06-29 23:46:59 +00002471
2472 return false;
2473}
2474
Eli Bendersky6ee13082013-01-15 22:59:42 +00002475/// ParseDirectiveFile
2476/// ::= .file [number] filename
2477/// ::= .file number directory filename
2478bool AsmParser::ParseDirectiveFile(SMLoc DirectiveLoc) {
2479 // FIXME: I'm not sure what this is.
2480 int64_t FileNumber = -1;
2481 SMLoc FileNumberLoc = getLexer().getLoc();
2482 if (getLexer().is(AsmToken::Integer)) {
2483 FileNumber = getTok().getIntVal();
2484 Lex();
2485
2486 if (FileNumber < 1)
2487 return TokError("file number less than one");
2488 }
2489
2490 if (getLexer().isNot(AsmToken::String))
2491 return TokError("unexpected token in '.file' directive");
2492
2493 // Usually the directory and filename together, otherwise just the directory.
2494 StringRef Path = getTok().getString();
2495 Path = Path.substr(1, Path.size()-2);
2496 Lex();
2497
2498 StringRef Directory;
2499 StringRef Filename;
2500 if (getLexer().is(AsmToken::String)) {
2501 if (FileNumber == -1)
2502 return TokError("explicit path specified, but no file number");
2503 Filename = getTok().getString();
2504 Filename = Filename.substr(1, Filename.size()-2);
2505 Directory = Path;
2506 Lex();
2507 } else {
2508 Filename = Path;
2509 }
2510
2511 if (getLexer().isNot(AsmToken::EndOfStatement))
2512 return TokError("unexpected token in '.file' directive");
2513
2514 if (FileNumber == -1)
2515 getStreamer().EmitFileDirective(Filename);
2516 else {
2517 if (getContext().getGenDwarfForAssembly() == true)
2518 Error(DirectiveLoc, "input can't have .file dwarf directives when -g is "
2519 "used to generate dwarf debug info for assembly code");
2520
2521 if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename))
2522 Error(FileNumberLoc, "file number already allocated");
2523 }
2524
2525 return false;
2526}
2527
2528/// ParseDirectiveLine
2529/// ::= .line [number]
2530bool AsmParser::ParseDirectiveLine() {
2531 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2532 if (getLexer().isNot(AsmToken::Integer))
2533 return TokError("unexpected token in '.line' directive");
2534
2535 int64_t LineNumber = getTok().getIntVal();
2536 (void) LineNumber;
2537 Lex();
2538
2539 // FIXME: Do something with the .line.
2540 }
2541
2542 if (getLexer().isNot(AsmToken::EndOfStatement))
2543 return TokError("unexpected token in '.line' directive");
2544
2545 return false;
2546}
2547
2548/// ParseDirectiveLoc
2549/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
2550/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
2551/// The first number is a file number, must have been previously assigned with
2552/// a .file directive, the second number is the line number and optionally the
2553/// third number is a column position (zero if not specified). The remaining
2554/// optional items are .loc sub-directives.
2555bool AsmParser::ParseDirectiveLoc() {
2556 if (getLexer().isNot(AsmToken::Integer))
2557 return TokError("unexpected token in '.loc' directive");
2558 int64_t FileNumber = getTok().getIntVal();
2559 if (FileNumber < 1)
2560 return TokError("file number less than one in '.loc' directive");
2561 if (!getContext().isValidDwarfFileNumber(FileNumber))
2562 return TokError("unassigned file number in '.loc' directive");
2563 Lex();
2564
2565 int64_t LineNumber = 0;
2566 if (getLexer().is(AsmToken::Integer)) {
2567 LineNumber = getTok().getIntVal();
2568 if (LineNumber < 1)
2569 return TokError("line number less than one in '.loc' directive");
2570 Lex();
2571 }
2572
2573 int64_t ColumnPos = 0;
2574 if (getLexer().is(AsmToken::Integer)) {
2575 ColumnPos = getTok().getIntVal();
2576 if (ColumnPos < 0)
2577 return TokError("column position less than zero in '.loc' directive");
2578 Lex();
2579 }
2580
2581 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
2582 unsigned Isa = 0;
2583 int64_t Discriminator = 0;
2584 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2585 for (;;) {
2586 if (getLexer().is(AsmToken::EndOfStatement))
2587 break;
2588
2589 StringRef Name;
2590 SMLoc Loc = getTok().getLoc();
2591 if (ParseIdentifier(Name))
2592 return TokError("unexpected token in '.loc' directive");
2593
2594 if (Name == "basic_block")
2595 Flags |= DWARF2_FLAG_BASIC_BLOCK;
2596 else if (Name == "prologue_end")
2597 Flags |= DWARF2_FLAG_PROLOGUE_END;
2598 else if (Name == "epilogue_begin")
2599 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
2600 else if (Name == "is_stmt") {
2601 Loc = getTok().getLoc();
2602 const MCExpr *Value;
2603 if (ParseExpression(Value))
2604 return true;
2605 // The expression must be the constant 0 or 1.
2606 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2607 int Value = MCE->getValue();
2608 if (Value == 0)
2609 Flags &= ~DWARF2_FLAG_IS_STMT;
2610 else if (Value == 1)
2611 Flags |= DWARF2_FLAG_IS_STMT;
2612 else
2613 return Error(Loc, "is_stmt value not 0 or 1");
2614 }
2615 else {
2616 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
2617 }
2618 }
2619 else if (Name == "isa") {
2620 Loc = getTok().getLoc();
2621 const MCExpr *Value;
2622 if (ParseExpression(Value))
2623 return true;
2624 // The expression must be a constant greater or equal to 0.
2625 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2626 int Value = MCE->getValue();
2627 if (Value < 0)
2628 return Error(Loc, "isa number less than zero");
2629 Isa = Value;
2630 }
2631 else {
2632 return Error(Loc, "isa number not a constant value");
2633 }
2634 }
2635 else if (Name == "discriminator") {
2636 if (ParseAbsoluteExpression(Discriminator))
2637 return true;
2638 }
2639 else {
2640 return Error(Loc, "unknown sub-directive in '.loc' directive");
2641 }
2642
2643 if (getLexer().is(AsmToken::EndOfStatement))
2644 break;
2645 }
2646 }
2647
2648 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
2649 Isa, Discriminator, StringRef());
2650
2651 return false;
2652}
2653
2654/// ParseDirectiveStabs
2655/// ::= .stabs string, number, number, number
2656bool AsmParser::ParseDirectiveStabs() {
2657 return TokError("unsupported directive '.stabs'");
2658}
2659
2660/// ParseDirectiveCFISections
2661/// ::= .cfi_sections section [, section]
2662bool AsmParser::ParseDirectiveCFISections() {
2663 StringRef Name;
2664 bool EH = false;
2665 bool Debug = false;
2666
2667 if (ParseIdentifier(Name))
2668 return TokError("Expected an identifier");
2669
2670 if (Name == ".eh_frame")
2671 EH = true;
2672 else if (Name == ".debug_frame")
2673 Debug = true;
2674
2675 if (getLexer().is(AsmToken::Comma)) {
2676 Lex();
2677
2678 if (ParseIdentifier(Name))
2679 return TokError("Expected an identifier");
2680
2681 if (Name == ".eh_frame")
2682 EH = true;
2683 else if (Name == ".debug_frame")
2684 Debug = true;
2685 }
2686
2687 getStreamer().EmitCFISections(EH, Debug);
2688 return false;
2689}
2690
2691/// ParseDirectiveCFIStartProc
2692/// ::= .cfi_startproc
2693bool AsmParser::ParseDirectiveCFIStartProc() {
2694 getStreamer().EmitCFIStartProc();
2695 return false;
2696}
2697
2698/// ParseDirectiveCFIEndProc
2699/// ::= .cfi_endproc
2700bool AsmParser::ParseDirectiveCFIEndProc() {
2701 getStreamer().EmitCFIEndProc();
2702 return false;
2703}
2704
2705/// ParseRegisterOrRegisterNumber - parse register name or number.
2706bool AsmParser::ParseRegisterOrRegisterNumber(int64_t &Register,
2707 SMLoc DirectiveLoc) {
2708 unsigned RegNo;
2709
2710 if (getLexer().isNot(AsmToken::Integer)) {
2711 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
2712 return true;
2713 Register = getContext().getRegisterInfo().getDwarfRegNum(RegNo, true);
2714 } else
2715 return ParseAbsoluteExpression(Register);
2716
2717 return false;
2718}
2719
2720/// ParseDirectiveCFIDefCfa
2721/// ::= .cfi_def_cfa register, offset
2722bool AsmParser::ParseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
2723 int64_t Register = 0;
2724 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2725 return true;
2726
2727 if (getLexer().isNot(AsmToken::Comma))
2728 return TokError("unexpected token in directive");
2729 Lex();
2730
2731 int64_t Offset = 0;
2732 if (ParseAbsoluteExpression(Offset))
2733 return true;
2734
2735 getStreamer().EmitCFIDefCfa(Register, Offset);
2736 return false;
2737}
2738
2739/// ParseDirectiveCFIDefCfaOffset
2740/// ::= .cfi_def_cfa_offset offset
2741bool AsmParser::ParseDirectiveCFIDefCfaOffset() {
2742 int64_t Offset = 0;
2743 if (ParseAbsoluteExpression(Offset))
2744 return true;
2745
2746 getStreamer().EmitCFIDefCfaOffset(Offset);
2747 return false;
2748}
2749
2750/// ParseDirectiveCFIRegister
2751/// ::= .cfi_register register, register
2752bool AsmParser::ParseDirectiveCFIRegister(SMLoc DirectiveLoc) {
2753 int64_t Register1 = 0;
2754 if (ParseRegisterOrRegisterNumber(Register1, DirectiveLoc))
2755 return true;
2756
2757 if (getLexer().isNot(AsmToken::Comma))
2758 return TokError("unexpected token in directive");
2759 Lex();
2760
2761 int64_t Register2 = 0;
2762 if (ParseRegisterOrRegisterNumber(Register2, DirectiveLoc))
2763 return true;
2764
2765 getStreamer().EmitCFIRegister(Register1, Register2);
2766 return false;
2767}
2768
2769/// ParseDirectiveCFIAdjustCfaOffset
2770/// ::= .cfi_adjust_cfa_offset adjustment
2771bool AsmParser::ParseDirectiveCFIAdjustCfaOffset() {
2772 int64_t Adjustment = 0;
2773 if (ParseAbsoluteExpression(Adjustment))
2774 return true;
2775
2776 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
2777 return false;
2778}
2779
2780/// ParseDirectiveCFIDefCfaRegister
2781/// ::= .cfi_def_cfa_register register
2782bool AsmParser::ParseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
2783 int64_t Register = 0;
2784 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2785 return true;
2786
2787 getStreamer().EmitCFIDefCfaRegister(Register);
2788 return false;
2789}
2790
2791/// ParseDirectiveCFIOffset
2792/// ::= .cfi_offset register, offset
2793bool AsmParser::ParseDirectiveCFIOffset(SMLoc DirectiveLoc) {
2794 int64_t Register = 0;
2795 int64_t Offset = 0;
2796
2797 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2798 return true;
2799
2800 if (getLexer().isNot(AsmToken::Comma))
2801 return TokError("unexpected token in directive");
2802 Lex();
2803
2804 if (ParseAbsoluteExpression(Offset))
2805 return true;
2806
2807 getStreamer().EmitCFIOffset(Register, Offset);
2808 return false;
2809}
2810
2811/// ParseDirectiveCFIRelOffset
2812/// ::= .cfi_rel_offset register, offset
2813bool AsmParser::ParseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
2814 int64_t Register = 0;
2815
2816 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2817 return true;
2818
2819 if (getLexer().isNot(AsmToken::Comma))
2820 return TokError("unexpected token in directive");
2821 Lex();
2822
2823 int64_t Offset = 0;
2824 if (ParseAbsoluteExpression(Offset))
2825 return true;
2826
2827 getStreamer().EmitCFIRelOffset(Register, Offset);
2828 return false;
2829}
2830
2831static bool isValidEncoding(int64_t Encoding) {
2832 if (Encoding & ~0xff)
2833 return false;
2834
2835 if (Encoding == dwarf::DW_EH_PE_omit)
2836 return true;
2837
2838 const unsigned Format = Encoding & 0xf;
2839 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
2840 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
2841 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
2842 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
2843 return false;
2844
2845 const unsigned Application = Encoding & 0x70;
2846 if (Application != dwarf::DW_EH_PE_absptr &&
2847 Application != dwarf::DW_EH_PE_pcrel)
2848 return false;
2849
2850 return true;
2851}
2852
2853/// ParseDirectiveCFIPersonalityOrLsda
2854/// IsPersonality true for cfi_personality, false for cfi_lsda
2855/// ::= .cfi_personality encoding, [symbol_name]
2856/// ::= .cfi_lsda encoding, [symbol_name]
2857bool AsmParser::ParseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
2858 int64_t Encoding = 0;
2859 if (ParseAbsoluteExpression(Encoding))
2860 return true;
2861 if (Encoding == dwarf::DW_EH_PE_omit)
2862 return false;
2863
2864 if (!isValidEncoding(Encoding))
2865 return TokError("unsupported encoding.");
2866
2867 if (getLexer().isNot(AsmToken::Comma))
2868 return TokError("unexpected token in directive");
2869 Lex();
2870
2871 StringRef Name;
2872 if (ParseIdentifier(Name))
2873 return TokError("expected identifier in directive");
2874
2875 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
2876
2877 if (IsPersonality)
2878 getStreamer().EmitCFIPersonality(Sym, Encoding);
2879 else
2880 getStreamer().EmitCFILsda(Sym, Encoding);
2881 return false;
2882}
2883
2884/// ParseDirectiveCFIRememberState
2885/// ::= .cfi_remember_state
2886bool AsmParser::ParseDirectiveCFIRememberState() {
2887 getStreamer().EmitCFIRememberState();
2888 return false;
2889}
2890
2891/// ParseDirectiveCFIRestoreState
2892/// ::= .cfi_remember_state
2893bool AsmParser::ParseDirectiveCFIRestoreState() {
2894 getStreamer().EmitCFIRestoreState();
2895 return false;
2896}
2897
2898/// ParseDirectiveCFISameValue
2899/// ::= .cfi_same_value register
2900bool AsmParser::ParseDirectiveCFISameValue(SMLoc DirectiveLoc) {
2901 int64_t Register = 0;
2902
2903 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2904 return true;
2905
2906 getStreamer().EmitCFISameValue(Register);
2907 return false;
2908}
2909
2910/// ParseDirectiveCFIRestore
2911/// ::= .cfi_restore register
2912bool AsmParser::ParseDirectiveCFIRestore(SMLoc DirectiveLoc) {
2913 int64_t Register = 0;
2914 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2915 return true;
2916
2917 getStreamer().EmitCFIRestore(Register);
2918 return false;
2919}
2920
2921/// ParseDirectiveCFIEscape
2922/// ::= .cfi_escape expression[,...]
2923bool AsmParser::ParseDirectiveCFIEscape() {
2924 std::string Values;
2925 int64_t CurrValue;
2926 if (ParseAbsoluteExpression(CurrValue))
2927 return true;
2928
2929 Values.push_back((uint8_t)CurrValue);
2930
2931 while (getLexer().is(AsmToken::Comma)) {
2932 Lex();
2933
2934 if (ParseAbsoluteExpression(CurrValue))
2935 return true;
2936
2937 Values.push_back((uint8_t)CurrValue);
2938 }
2939
2940 getStreamer().EmitCFIEscape(Values);
2941 return false;
2942}
2943
2944/// ParseDirectiveCFISignalFrame
2945/// ::= .cfi_signal_frame
2946bool AsmParser::ParseDirectiveCFISignalFrame() {
2947 if (getLexer().isNot(AsmToken::EndOfStatement))
2948 return Error(getLexer().getLoc(),
2949 "unexpected token in '.cfi_signal_frame'");
2950
2951 getStreamer().EmitCFISignalFrame();
2952 return false;
2953}
2954
2955/// ParseDirectiveCFIUndefined
2956/// ::= .cfi_undefined register
2957bool AsmParser::ParseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
2958 int64_t Register = 0;
2959
2960 if (ParseRegisterOrRegisterNumber(Register, DirectiveLoc))
2961 return true;
2962
2963 getStreamer().EmitCFIUndefined(Register);
2964 return false;
2965}
2966
2967/// ParseDirectiveMacrosOnOff
2968/// ::= .macros_on
2969/// ::= .macros_off
2970bool AsmParser::ParseDirectiveMacrosOnOff(StringRef Directive) {
2971 if (getLexer().isNot(AsmToken::EndOfStatement))
2972 return Error(getLexer().getLoc(),
2973 "unexpected token in '" + Directive + "' directive");
2974
2975 SetMacrosEnabled(Directive == ".macros_on");
2976 return false;
2977}
2978
2979/// ParseDirectiveMacro
2980/// ::= .macro name [parameters]
2981bool AsmParser::ParseDirectiveMacro(SMLoc DirectiveLoc) {
2982 StringRef Name;
2983 if (ParseIdentifier(Name))
2984 return TokError("expected identifier in '.macro' directive");
2985
2986 MCAsmMacroParameters Parameters;
2987 // Argument delimiter is initially unknown. It will be set by
2988 // ParseMacroArgument()
2989 AsmToken::TokenKind ArgumentDelimiter = AsmToken::Eof;
2990 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2991 for (;;) {
2992 MCAsmMacroParameter Parameter;
2993 if (ParseIdentifier(Parameter.first))
2994 return TokError("expected identifier in '.macro' directive");
2995
2996 if (getLexer().is(AsmToken::Equal)) {
2997 Lex();
2998 if (ParseMacroArgument(Parameter.second, ArgumentDelimiter))
2999 return true;
3000 }
3001
3002 Parameters.push_back(Parameter);
3003
3004 if (getLexer().is(AsmToken::Comma))
3005 Lex();
3006 else if (getLexer().is(AsmToken::EndOfStatement))
3007 break;
3008 }
3009 }
3010
3011 // Eat the end of statement.
3012 Lex();
3013
3014 AsmToken EndToken, StartToken = getTok();
3015
3016 // Lex the macro definition.
3017 for (;;) {
3018 // Check whether we have reached the end of the file.
3019 if (getLexer().is(AsmToken::Eof))
3020 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3021
3022 // Otherwise, check whether we have reach the .endmacro.
3023 if (getLexer().is(AsmToken::Identifier) &&
3024 (getTok().getIdentifier() == ".endm" ||
3025 getTok().getIdentifier() == ".endmacro")) {
3026 EndToken = getTok();
3027 Lex();
3028 if (getLexer().isNot(AsmToken::EndOfStatement))
3029 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3030 "' directive");
3031 break;
3032 }
3033
3034 // Otherwise, scan til the end of the statement.
3035 EatToEndOfStatement();
3036 }
3037
3038 if (LookupMacro(Name)) {
3039 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3040 }
3041
3042 const char *BodyStart = StartToken.getLoc().getPointer();
3043 const char *BodyEnd = EndToken.getLoc().getPointer();
3044 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3045 DefineMacro(Name, MCAsmMacro(Name, Body, Parameters));
3046 return false;
3047}
3048
3049/// ParseDirectiveEndMacro
3050/// ::= .endm
3051/// ::= .endmacro
3052bool AsmParser::ParseDirectiveEndMacro(StringRef Directive) {
3053 if (getLexer().isNot(AsmToken::EndOfStatement))
3054 return TokError("unexpected token in '" + Directive + "' directive");
3055
3056 // If we are inside a macro instantiation, terminate the current
3057 // instantiation.
3058 if (InsideMacroInstantiation()) {
3059 HandleMacroExit();
3060 return false;
3061 }
3062
3063 // Otherwise, this .endmacro is a stray entry in the file; well formed
3064 // .endmacro directives are handled during the macro definition parsing.
3065 return TokError("unexpected '" + Directive + "' in file, "
3066 "no current macro definition");
3067}
3068
3069/// ParseDirectivePurgeMacro
3070/// ::= .purgem
3071bool AsmParser::ParseDirectivePurgeMacro(SMLoc DirectiveLoc) {
3072 StringRef Name;
3073 if (ParseIdentifier(Name))
3074 return TokError("expected identifier in '.purgem' directive");
3075
3076 if (getLexer().isNot(AsmToken::EndOfStatement))
3077 return TokError("unexpected token in '.purgem' directive");
3078
3079 if (!LookupMacro(Name))
3080 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
3081
3082 UndefineMacro(Name);
3083 return false;
3084}
Eli Bendersky4766ef42012-12-20 19:05:53 +00003085
3086/// ParseDirectiveBundleAlignMode
3087/// ::= {.bundle_align_mode} expression
3088bool AsmParser::ParseDirectiveBundleAlignMode() {
3089 CheckForValidSection();
3090
3091 // Expect a single argument: an expression that evaluates to a constant
3092 // in the inclusive range 0-30.
3093 SMLoc ExprLoc = getLexer().getLoc();
3094 int64_t AlignSizePow2;
3095 if (ParseAbsoluteExpression(AlignSizePow2))
3096 return true;
3097 else if (getLexer().isNot(AsmToken::EndOfStatement))
3098 return TokError("unexpected token after expression in"
3099 " '.bundle_align_mode' directive");
3100 else if (AlignSizePow2 < 0 || AlignSizePow2 > 30)
3101 return Error(ExprLoc,
3102 "invalid bundle alignment size (expected between 0 and 30)");
3103
3104 Lex();
3105
3106 // Because of AlignSizePow2's verified range we can safely truncate it to
3107 // unsigned.
3108 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
3109 return false;
3110}
3111
3112/// ParseDirectiveBundleLock
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003113/// ::= {.bundle_lock} [align_to_end]
Eli Bendersky4766ef42012-12-20 19:05:53 +00003114bool AsmParser::ParseDirectiveBundleLock() {
3115 CheckForValidSection();
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003116 bool AlignToEnd = false;
Eli Bendersky4766ef42012-12-20 19:05:53 +00003117
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003118 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3119 StringRef Option;
3120 SMLoc Loc = getTok().getLoc();
3121 const char *kInvalidOptionError =
3122 "invalid option for '.bundle_lock' directive";
3123
3124 if (ParseIdentifier(Option))
3125 return Error(Loc, kInvalidOptionError);
3126
3127 if (Option != "align_to_end")
3128 return Error(Loc, kInvalidOptionError);
3129 else if (getLexer().isNot(AsmToken::EndOfStatement))
3130 return Error(Loc,
3131 "unexpected token after '.bundle_lock' directive option");
3132 AlignToEnd = true;
3133 }
3134
Eli Bendersky4766ef42012-12-20 19:05:53 +00003135 Lex();
3136
Eli Bendersky6c1d4972013-01-07 21:51:08 +00003137 getStreamer().EmitBundleLock(AlignToEnd);
Eli Bendersky4766ef42012-12-20 19:05:53 +00003138 return false;
3139}
3140
3141/// ParseDirectiveBundleLock
3142/// ::= {.bundle_lock}
3143bool AsmParser::ParseDirectiveBundleUnlock() {
3144 CheckForValidSection();
3145
3146 if (getLexer().isNot(AsmToken::EndOfStatement))
3147 return TokError("unexpected token in '.bundle_unlock' directive");
3148 Lex();
3149
3150 getStreamer().EmitBundleUnlock();
3151 return false;
3152}
3153
Eli Bendersky6ee13082013-01-15 22:59:42 +00003154/// ParseDirectiveSpace
3155/// ::= (.skip | .space) expression [ , expression ]
3156bool AsmParser::ParseDirectiveSpace(StringRef IDVal) {
3157 CheckForValidSection();
3158
3159 int64_t NumBytes;
3160 if (ParseAbsoluteExpression(NumBytes))
3161 return true;
3162
3163 int64_t FillExpr = 0;
3164 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3165 if (getLexer().isNot(AsmToken::Comma))
3166 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3167 Lex();
3168
3169 if (ParseAbsoluteExpression(FillExpr))
3170 return true;
3171
3172 if (getLexer().isNot(AsmToken::EndOfStatement))
3173 return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
3174 }
3175
3176 Lex();
3177
3178 if (NumBytes <= 0)
3179 return TokError("invalid number of bytes in '" +
3180 Twine(IDVal) + "' directive");
3181
3182 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
3183 getStreamer().EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
3184
3185 return false;
3186}
3187
3188/// ParseDirectiveLEB128
3189/// ::= (.sleb128 | .uleb128) expression
3190bool AsmParser::ParseDirectiveLEB128(bool Signed) {
3191 CheckForValidSection();
3192 const MCExpr *Value;
3193
3194 if (ParseExpression(Value))
3195 return true;
3196
3197 if (getLexer().isNot(AsmToken::EndOfStatement))
3198 return TokError("unexpected token in directive");
3199
3200 if (Signed)
3201 getStreamer().EmitSLEB128Value(Value);
3202 else
3203 getStreamer().EmitULEB128Value(Value);
3204
3205 return false;
3206}
3207
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003208/// ParseDirectiveSymbolAttribute
3209/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Chris Lattnera5ad93a2010-01-23 06:39:22 +00003210bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003211 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003212 for (;;) {
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003213 StringRef Name;
Jim Grosbach10ec6502011-09-15 17:56:49 +00003214 SMLoc Loc = getTok().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003215
3216 if (ParseIdentifier(Name))
Jim Grosbach10ec6502011-09-15 17:56:49 +00003217 return Error(Loc, "expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003218
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003219 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003220
Jim Grosbach10ec6502011-09-15 17:56:49 +00003221 // Assembler local symbols don't make any sense here. Complain loudly.
3222 if (Sym->isTemporary())
3223 return Error(Loc, "non-local symbol required in directive");
3224
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003225 getStreamer().EmitSymbolAttribute(Sym, Attr);
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003226
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003227 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003228 break;
3229
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003230 if (getLexer().isNot(AsmToken::Comma))
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003231 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003232 Lex();
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003233 }
3234 }
3235
Sean Callanan79ed1a82010-01-19 20:22:31 +00003236 Lex();
Jan Wen Vounga854a4b2010-09-30 01:09:20 +00003237 return false;
Daniel Dunbard7b267b2009-06-30 00:33:19 +00003238}
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003239
3240/// ParseDirectiveComm
Chris Lattner1fc3d752009-07-09 17:25:12 +00003241/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
3242bool AsmParser::ParseDirectiveComm(bool IsLocal) {
Daniel Dunbar1ab6f2f2010-09-09 22:42:59 +00003243 CheckForValidSection();
3244
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003245 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbara6b3c5d2009-08-01 00:48:30 +00003246 StringRef Name;
3247 if (ParseIdentifier(Name))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003248 return TokError("expected identifier in directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003249
Daniel Dunbar76c4d762009-07-31 21:55:09 +00003250 // Handle the identifier as the key symbol.
Daniel Dunbar4c7c08b2010-07-12 19:52:10 +00003251 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003252
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003253 if (getLexer().isNot(AsmToken::Comma))
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003254 return TokError("unexpected token in directive");
Sean Callanan79ed1a82010-01-19 20:22:31 +00003255 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003256
3257 int64_t Size;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003258 SMLoc SizeLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003259 if (ParseAbsoluteExpression(Size))
3260 return true;
3261
3262 int64_t Pow2Alignment = 0;
3263 SMLoc Pow2AlignmentLoc;
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003264 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan79ed1a82010-01-19 20:22:31 +00003265 Lex();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003266 Pow2AlignmentLoc = getLexer().getLoc();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003267 if (ParseAbsoluteExpression(Pow2Alignment))
3268 return true;
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003269
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003270 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
3271 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer39646d92012-09-07 17:25:13 +00003272 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
3273
Chris Lattner258281d2010-01-19 06:22:22 +00003274 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramera9e37c52012-09-07 21:08:01 +00003275 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
3276 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattner258281d2010-01-19 06:22:22 +00003277 if (!isPowerOf2_64(Pow2Alignment))
3278 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
3279 Pow2Alignment = Log2_64(Pow2Alignment);
3280 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003281 }
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003282
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003283 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner1fc3d752009-07-09 17:25:12 +00003284 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003285
Sean Callanan79ed1a82010-01-19 20:22:31 +00003286 Lex();
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003287
Chris Lattner1fc3d752009-07-09 17:25:12 +00003288 // NOTE: a size of zero for a .comm should create a undefined symbol
3289 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003290 if (Size < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003291 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
3292 "be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003293
Eric Christopherc260a3e2010-05-14 01:38:54 +00003294 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003295 // may internally end up wanting an alignment in bytes.
3296 // FIXME: Diagnose overflow.
3297 if (Pow2Alignment < 0)
Chris Lattner1fc3d752009-07-09 17:25:12 +00003298 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
3299 "alignment, can't be less than zero");
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003300
Daniel Dunbar8906ff12009-08-22 07:22:36 +00003301 if (!Sym->isUndefined())
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003302 return Error(IDLoc, "invalid symbol redefinition");
3303
Chris Lattner1fc3d752009-07-09 17:25:12 +00003304 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003305 if (IsLocal) {
Benjamin Kramer39646d92012-09-07 17:25:13 +00003306 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar7092c7e2009-08-30 06:17:16 +00003307 return false;
3308 }
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003309
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003310 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattner4e4db7a2009-07-07 20:30:46 +00003311 return false;
3312}
Chris Lattner9be3fee2009-07-10 22:20:30 +00003313
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003314/// ParseDirectiveAbort
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003315/// ::= .abort [... message ...]
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003316bool AsmParser::ParseDirectiveAbort() {
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003317 // FIXME: Use loc from directive.
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003318 SMLoc Loc = getLexer().getLoc();
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003319
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003320 StringRef Str = ParseStringToEndOfStatement();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003321 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003322 return TokError("unexpected token in '.abort' directive");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003323
Sean Callanan79ed1a82010-01-19 20:22:31 +00003324 Lex();
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003325
Daniel Dunbarf9507ff2009-07-27 23:20:52 +00003326 if (Str.empty())
3327 Error(Loc, ".abort detected. Assembly stopping.");
3328 else
3329 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar6a46d572010-07-18 20:15:59 +00003330 // FIXME: Actually abort assembly here.
Kevin Enderby5f1f0b82009-07-13 23:15:14 +00003331
3332 return false;
3333}
Kevin Enderby71148242009-07-14 21:35:03 +00003334
Kevin Enderby1f049b22009-07-14 23:21:55 +00003335/// ParseDirectiveInclude
3336/// ::= .include "filename"
3337bool AsmParser::ParseDirectiveInclude() {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003338 if (getLexer().isNot(AsmToken::String))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003339 return TokError("expected string in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003340
Sean Callanan18b83232010-01-19 21:44:56 +00003341 std::string Filename = getTok().getString();
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003342 SMLoc IncludeLoc = getLexer().getLoc();
Sean Callanan79ed1a82010-01-19 20:22:31 +00003343 Lex();
Kevin Enderby1f049b22009-07-14 23:21:55 +00003344
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003345 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderby1f049b22009-07-14 23:21:55 +00003346 return TokError("unexpected token in '.include' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003347
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003348 // Strip the quotes.
3349 Filename = Filename.substr(1, Filename.size()-2);
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003350
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003351 // Attempt to switch the lexer to the included file before consuming the end
3352 // of statement to avoid losing it when we switch.
Sean Callananfd0b0282010-01-21 00:19:58 +00003353 if (EnterIncludeFile(Filename)) {
Daniel Dunbar275ce392010-07-18 18:31:45 +00003354 Error(IncludeLoc, "Could not find include file '" + Filename + "'");
Chris Lattner8e25e2d2009-07-16 06:14:39 +00003355 return true;
3356 }
Kevin Enderby1f049b22009-07-14 23:21:55 +00003357
3358 return false;
3359}
Kevin Enderby6e68cd92009-07-15 15:30:11 +00003360
Kevin Enderbyc55acca2011-12-14 21:47:48 +00003361/// ParseDirectiveIncbin
3362/// ::= .incbin "filename"
3363bool AsmParser::ParseDirectiveIncbin() {
3364 if (getLexer().isNot(AsmToken::String))
3365 return TokError("expected string in '.incbin' directive");
3366
3367 std::string Filename = getTok().getString();
3368 SMLoc IncbinLoc = getLexer().getLoc();
3369 Lex();
3370
3371 if (getLexer().isNot(AsmToken::EndOfStatement))
3372 return TokError("unexpected token in '.incbin' directive");
3373
3374 // Strip the quotes.
3375 Filename = Filename.substr(1, Filename.size()-2);
3376
3377 // Attempt to process the included file.
3378 if (ProcessIncbinFile(Filename)) {
3379 Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
3380 return true;
3381 }
3382
3383 return false;
3384}
3385
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003386/// ParseDirectiveIf
3387/// ::= .if expression
3388bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003389 TheCondStack.push_back(TheCondState);
3390 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramer29739e72012-05-12 16:52:21 +00003391 if (TheCondState.Ignore) {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003392 EatToEndOfStatement();
Benjamin Kramer29739e72012-05-12 16:52:21 +00003393 } else {
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003394 int64_t ExprValue;
3395 if (ParseAbsoluteExpression(ExprValue))
3396 return true;
3397
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003398 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003399 return TokError("unexpected token in '.if' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003400
Sean Callanan79ed1a82010-01-19 20:22:31 +00003401 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003402
3403 TheCondState.CondMet = ExprValue;
3404 TheCondState.Ignore = !TheCondState.CondMet;
3405 }
3406
3407 return false;
3408}
3409
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003410/// ParseDirectiveIfb
3411/// ::= .ifb string
3412bool AsmParser::ParseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
3413 TheCondStack.push_back(TheCondState);
3414 TheCondState.TheCond = AsmCond::IfCond;
3415
Benjamin Kramer29739e72012-05-12 16:52:21 +00003416 if (TheCondState.Ignore) {
Benjamin Kramera3dd0eb2012-05-12 11:18:42 +00003417 EatToEndOfStatement();
3418 } else {
3419 StringRef Str = ParseStringToEndOfStatement();
3420
3421 if (getLexer().isNot(AsmToken::EndOfStatement))
3422 return TokError("unexpected token in '.ifb' directive");
3423
3424 Lex();
3425
3426 TheCondState.CondMet = ExpectBlank == Str.empty();
3427 TheCondState.Ignore = !TheCondState.CondMet;
3428 }
3429
3430 return false;
3431}
3432
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003433/// ParseDirectiveIfc
3434/// ::= .ifc string1, string2
3435bool AsmParser::ParseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
3436 TheCondStack.push_back(TheCondState);
3437 TheCondState.TheCond = AsmCond::IfCond;
3438
Benjamin Kramer29739e72012-05-12 16:52:21 +00003439 if (TheCondState.Ignore) {
Benjamin Kramerdec06ef2012-05-12 11:18:51 +00003440 EatToEndOfStatement();
3441 } else {
3442 StringRef Str1 = ParseStringToComma();
3443
3444 if (getLexer().isNot(AsmToken::Comma))
3445 return TokError("unexpected token in '.ifc' directive");
3446
3447 Lex();
3448
3449 StringRef Str2 = ParseStringToEndOfStatement();
3450
3451 if (getLexer().isNot(AsmToken::EndOfStatement))
3452 return TokError("unexpected token in '.ifc' directive");
3453
3454 Lex();
3455
3456 TheCondState.CondMet = ExpectEqual == (Str1 == Str2);
3457 TheCondState.Ignore = !TheCondState.CondMet;
3458 }
3459
3460 return false;
3461}
3462
3463/// ParseDirectiveIfdef
3464/// ::= .ifdef symbol
Benjamin Kramer0fd90bc2011-02-08 22:29:56 +00003465bool AsmParser::ParseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
3466 StringRef Name;
3467 TheCondStack.push_back(TheCondState);
3468 TheCondState.TheCond = AsmCond::IfCond;
3469
3470 if (TheCondState.Ignore) {
3471 EatToEndOfStatement();
3472 } else {
3473 if (ParseIdentifier(Name))
3474 return TokError("expected identifier after '.ifdef'");
3475
3476 Lex();
3477
3478 MCSymbol *Sym = getContext().LookupSymbol(Name);
3479
3480 if (expect_defined)
3481 TheCondState.CondMet = (Sym != NULL && !Sym->isUndefined());
3482 else
3483 TheCondState.CondMet = (Sym == NULL || Sym->isUndefined());
3484 TheCondState.Ignore = !TheCondState.CondMet;
3485 }
3486
3487 return false;
3488}
3489
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003490/// ParseDirectiveElseIf
3491/// ::= .elseif expression
3492bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
3493 if (TheCondState.TheCond != AsmCond::IfCond &&
3494 TheCondState.TheCond != AsmCond::ElseIfCond)
3495 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
3496 " an .elseif");
3497 TheCondState.TheCond = AsmCond::ElseIfCond;
3498
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003499 bool LastIgnoreState = false;
3500 if (!TheCondStack.empty())
3501 LastIgnoreState = TheCondStack.back().Ignore;
3502 if (LastIgnoreState || TheCondState.CondMet) {
3503 TheCondState.Ignore = true;
3504 EatToEndOfStatement();
3505 }
3506 else {
3507 int64_t ExprValue;
3508 if (ParseAbsoluteExpression(ExprValue))
3509 return true;
3510
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003511 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003512 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003513
Sean Callanan79ed1a82010-01-19 20:22:31 +00003514 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003515 TheCondState.CondMet = ExprValue;
3516 TheCondState.Ignore = !TheCondState.CondMet;
3517 }
3518
3519 return false;
3520}
3521
3522/// ParseDirectiveElse
3523/// ::= .else
3524bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003525 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003526 return TokError("unexpected token in '.else' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003527
Sean Callanan79ed1a82010-01-19 20:22:31 +00003528 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003529
3530 if (TheCondState.TheCond != AsmCond::IfCond &&
3531 TheCondState.TheCond != AsmCond::ElseIfCond)
3532 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
3533 ".elseif");
3534 TheCondState.TheCond = AsmCond::ElseCond;
3535 bool LastIgnoreState = false;
3536 if (!TheCondStack.empty())
3537 LastIgnoreState = TheCondStack.back().Ignore;
3538 if (LastIgnoreState || TheCondState.CondMet)
3539 TheCondState.Ignore = true;
3540 else
3541 TheCondState.Ignore = false;
3542
3543 return false;
3544}
3545
3546/// ParseDirectiveEndIf
3547/// ::= .endif
3548bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
Daniel Dunbar8f34bea2010-07-12 18:03:11 +00003549 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003550 return TokError("unexpected token in '.endif' directive");
Michael J. Spencerc0c8df32010-10-09 11:00:50 +00003551
Sean Callanan79ed1a82010-01-19 20:22:31 +00003552 Lex();
Kevin Enderbyc114ed72009-08-07 22:46:00 +00003553
3554 if ((TheCondState.TheCond == AsmCond::NoCond) ||
3555 TheCondStack.empty())
3556 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
3557 ".else");
3558 if (!TheCondStack.empty()) {
3559 TheCondState = TheCondStack.back();
3560 TheCondStack.pop_back();
3561 }
3562
3563 return false;
3564}
Daniel Dunbard0c14d62009-08-11 04:24:50 +00003565
Eli Bendersky6ee13082013-01-15 22:59:42 +00003566void AsmParser::initializeDirectiveKindMap() {
3567 DirectiveKindMap[".set"] = DK_SET;
3568 DirectiveKindMap[".equ"] = DK_EQU;
3569 DirectiveKindMap[".equiv"] = DK_EQUIV;
3570 DirectiveKindMap[".ascii"] = DK_ASCII;
3571 DirectiveKindMap[".asciz"] = DK_ASCIZ;
3572 DirectiveKindMap[".string"] = DK_STRING;
3573 DirectiveKindMap[".byte"] = DK_BYTE;
3574 DirectiveKindMap[".short"] = DK_SHORT;
3575 DirectiveKindMap[".value"] = DK_VALUE;
3576 DirectiveKindMap[".2byte"] = DK_2BYTE;
3577 DirectiveKindMap[".long"] = DK_LONG;
3578 DirectiveKindMap[".int"] = DK_INT;
3579 DirectiveKindMap[".4byte"] = DK_4BYTE;
3580 DirectiveKindMap[".quad"] = DK_QUAD;
3581 DirectiveKindMap[".8byte"] = DK_8BYTE;
3582 DirectiveKindMap[".single"] = DK_SINGLE;
3583 DirectiveKindMap[".float"] = DK_FLOAT;
3584 DirectiveKindMap[".double"] = DK_DOUBLE;
3585 DirectiveKindMap[".align"] = DK_ALIGN;
3586 DirectiveKindMap[".align32"] = DK_ALIGN32;
3587 DirectiveKindMap[".balign"] = DK_BALIGN;
3588 DirectiveKindMap[".balignw"] = DK_BALIGNW;
3589 DirectiveKindMap[".balignl"] = DK_BALIGNL;
3590 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
3591 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
3592 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
3593 DirectiveKindMap[".org"] = DK_ORG;
3594 DirectiveKindMap[".fill"] = DK_FILL;
3595 DirectiveKindMap[".zero"] = DK_ZERO;
3596 DirectiveKindMap[".extern"] = DK_EXTERN;
3597 DirectiveKindMap[".globl"] = DK_GLOBL;
3598 DirectiveKindMap[".global"] = DK_GLOBAL;
3599 DirectiveKindMap[".indirect_symbol"] = DK_INDIRECT_SYMBOL;
3600 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
3601 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
3602 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
3603 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
3604 DirectiveKindMap[".reference"] = DK_REFERENCE;
3605 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
3606 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
3607 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
3608 DirectiveKindMap[".comm"] = DK_COMM;
3609 DirectiveKindMap[".common"] = DK_COMMON;
3610 DirectiveKindMap[".lcomm"] = DK_LCOMM;
3611 DirectiveKindMap[".abort"] = DK_ABORT;
3612 DirectiveKindMap[".include"] = DK_INCLUDE;
3613 DirectiveKindMap[".incbin"] = DK_INCBIN;
3614 DirectiveKindMap[".code16"] = DK_CODE16;
3615 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
3616 DirectiveKindMap[".rept"] = DK_REPT;
3617 DirectiveKindMap[".irp"] = DK_IRP;
3618 DirectiveKindMap[".irpc"] = DK_IRPC;
3619 DirectiveKindMap[".endr"] = DK_ENDR;
3620 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
3621 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
3622 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
3623 DirectiveKindMap[".if"] = DK_IF;
3624 DirectiveKindMap[".ifb"] = DK_IFB;
3625 DirectiveKindMap[".ifnb"] = DK_IFNB;
3626 DirectiveKindMap[".ifc"] = DK_IFC;
3627 DirectiveKindMap[".ifnc"] = DK_IFNC;
3628 DirectiveKindMap[".ifdef"] = DK_IFDEF;
3629 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
3630 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
3631 DirectiveKindMap[".elseif"] = DK_ELSEIF;
3632 DirectiveKindMap[".else"] = DK_ELSE;
3633 DirectiveKindMap[".endif"] = DK_ENDIF;
3634 DirectiveKindMap[".skip"] = DK_SKIP;
3635 DirectiveKindMap[".space"] = DK_SPACE;
3636 DirectiveKindMap[".file"] = DK_FILE;
3637 DirectiveKindMap[".line"] = DK_LINE;
3638 DirectiveKindMap[".loc"] = DK_LOC;
3639 DirectiveKindMap[".stabs"] = DK_STABS;
3640 DirectiveKindMap[".sleb128"] = DK_SLEB128;
3641 DirectiveKindMap[".uleb128"] = DK_ULEB128;
3642 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
3643 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
3644 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
3645 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
3646 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
3647 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
3648 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
3649 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
3650 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
3651 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
3652 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
3653 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
3654 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
3655 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
3656 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
3657 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
3658 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
3659 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
3660 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
3661 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
3662 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
3663 DirectiveKindMap[".macro"] = DK_MACRO;
3664 DirectiveKindMap[".endm"] = DK_ENDM;
3665 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
3666 DirectiveKindMap[".purgem"] = DK_PURGEM;
Eli Bendersky5d0f0612013-01-10 22:44:57 +00003667}
3668
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003669
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003670MCAsmMacro *AsmParser::ParseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003671 AsmToken EndToken, StartToken = getTok();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003672
Rafael Espindola761cb062012-06-03 23:57:14 +00003673 unsigned NestLevel = 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003674 for (;;) {
3675 // Check whether we have reached the end of the file.
Rafael Espindola761cb062012-06-03 23:57:14 +00003676 if (getLexer().is(AsmToken::Eof)) {
3677 Error(DirectiveLoc, "no matching '.endr' in definition");
3678 return 0;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003679 }
3680
Rafael Espindola761cb062012-06-03 23:57:14 +00003681 if (Lexer.is(AsmToken::Identifier) &&
3682 (getTok().getIdentifier() == ".rept")) {
3683 ++NestLevel;
3684 }
3685
3686 // Otherwise, check whether we have reached the .endr.
3687 if (Lexer.is(AsmToken::Identifier) &&
3688 getTok().getIdentifier() == ".endr") {
3689 if (NestLevel == 0) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003690 EndToken = getTok();
3691 Lex();
Rafael Espindola761cb062012-06-03 23:57:14 +00003692 if (Lexer.isNot(AsmToken::EndOfStatement)) {
3693 TokError("unexpected token in '.endr' directive");
3694 return 0;
3695 }
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003696 break;
3697 }
Rafael Espindola761cb062012-06-03 23:57:14 +00003698 --NestLevel;
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003699 }
3700
Rafael Espindola761cb062012-06-03 23:57:14 +00003701 // Otherwise, scan till the end of the statement.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003702 EatToEndOfStatement();
3703 }
3704
3705 const char *BodyStart = StartToken.getLoc().getPointer();
3706 const char *BodyEnd = EndToken.getLoc().getPointer();
3707 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
3708
Rafael Espindola761cb062012-06-03 23:57:14 +00003709 // We Are Anonymous.
3710 StringRef Name;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003711 MCAsmMacroParameters Parameters;
3712 return new MCAsmMacro(Name, Body, Parameters);
Rafael Espindola761cb062012-06-03 23:57:14 +00003713}
3714
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003715void AsmParser::InstantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola761cb062012-06-03 23:57:14 +00003716 raw_svector_ostream &OS) {
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003717 OS << ".endr\n";
3718
3719 MemoryBuffer *Instantiation =
3720 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
3721
Rafael Espindola761cb062012-06-03 23:57:14 +00003722 // Create the macro instantiation object and add to the current macro
3723 // instantiation stack.
3724 MacroInstantiation *MI = new MacroInstantiation(M, DirectiveLoc,
Daniel Dunbar4259a1a2012-12-01 01:38:48 +00003725 CurBuffer,
Rafael Espindola761cb062012-06-03 23:57:14 +00003726 getTok().getLoc(),
3727 Instantiation);
3728 ActiveMacros.push_back(MI);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003729
Rafael Espindola761cb062012-06-03 23:57:14 +00003730 // Jump to the macro instantiation and prime the lexer.
3731 CurBuffer = SrcMgr.AddNewSourceBuffer(MI->Instantiation, SMLoc());
3732 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
3733 Lex();
3734}
3735
3736bool AsmParser::ParseDirectiveRept(SMLoc DirectiveLoc) {
3737 int64_t Count;
3738 if (ParseAbsoluteExpression(Count))
3739 return TokError("unexpected token in '.rept' directive");
3740
3741 if (Count < 0)
3742 return TokError("Count is negative");
3743
3744 if (Lexer.isNot(AsmToken::EndOfStatement))
3745 return TokError("unexpected token in '.rept' directive");
3746
3747 // Eat the end of statement.
3748 Lex();
3749
3750 // Lex the rept definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003751 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindola761cb062012-06-03 23:57:14 +00003752 if (!M)
3753 return true;
3754
3755 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3756 // to hold the macro body with substitutions.
3757 SmallString<256> Buf;
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003758 MCAsmMacroParameters Parameters;
3759 MCAsmMacroArguments A;
Rafael Espindola761cb062012-06-03 23:57:14 +00003760 raw_svector_ostream OS(Buf);
3761 while (Count--) {
3762 if (expandMacro(OS, M->Body, Parameters, A, getTok().getLoc()))
3763 return true;
3764 }
3765 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003766
3767 return false;
3768}
3769
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003770/// ParseDirectiveIrp
3771/// ::= .irp symbol,values
3772bool AsmParser::ParseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003773 MCAsmMacroParameters Parameters;
3774 MCAsmMacroParameter Parameter;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003775
Preston Gurd6c9176a2012-09-19 20:29:04 +00003776 if (ParseIdentifier(Parameter.first))
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003777 return TokError("expected identifier in '.irp' directive");
3778
3779 Parameters.push_back(Parameter);
3780
3781 if (Lexer.isNot(AsmToken::Comma))
3782 return TokError("expected comma in '.irp' directive");
3783
3784 Lex();
3785
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003786 MCAsmMacroArguments A;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003787 if (ParseMacroArguments(0, A))
3788 return true;
3789
3790 // Eat the end of statement.
3791 Lex();
3792
3793 // Lex the irp definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003794 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003795 if (!M)
3796 return true;
3797
3798 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3799 // to hold the macro body with substitutions.
3800 SmallString<256> Buf;
3801 raw_svector_ostream OS(Buf);
3802
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003803 for (MCAsmMacroArguments::iterator i = A.begin(), e = A.end(); i != e; ++i) {
3804 MCAsmMacroArguments Args;
Rafael Espindolaaa7a2f22012-06-15 14:02:34 +00003805 Args.push_back(*i);
3806
3807 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3808 return true;
3809 }
3810
3811 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3812
3813 return false;
3814}
3815
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003816/// ParseDirectiveIrpc
3817/// ::= .irpc symbol,values
3818bool AsmParser::ParseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003819 MCAsmMacroParameters Parameters;
3820 MCAsmMacroParameter Parameter;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003821
Preston Gurd6c9176a2012-09-19 20:29:04 +00003822 if (ParseIdentifier(Parameter.first))
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003823 return TokError("expected identifier in '.irpc' directive");
3824
3825 Parameters.push_back(Parameter);
3826
3827 if (Lexer.isNot(AsmToken::Comma))
3828 return TokError("expected comma in '.irpc' directive");
3829
3830 Lex();
3831
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003832 MCAsmMacroArguments A;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003833 if (ParseMacroArguments(0, A))
3834 return true;
3835
3836 if (A.size() != 1 || A.front().size() != 1)
3837 return TokError("unexpected token in '.irpc' directive");
3838
3839 // Eat the end of statement.
3840 Lex();
3841
3842 // Lex the irpc definition.
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003843 MCAsmMacro *M = ParseMacroLikeBody(DirectiveLoc);
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003844 if (!M)
3845 return true;
3846
3847 // Macro instantiation is lexical, unfortunately. We construct a new buffer
3848 // to hold the macro body with substitutions.
3849 SmallString<256> Buf;
3850 raw_svector_ostream OS(Buf);
3851
3852 StringRef Values = A.front().front().getString();
3853 std::size_t I, End = Values.size();
3854 for (I = 0; I < End; ++I) {
Eli Bendersky9bac6b22013-01-14 19:00:26 +00003855 MCAsmMacroArgument Arg;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003856 Arg.push_back(AsmToken(AsmToken::Identifier, Values.slice(I, I+1)));
3857
Eli Benderskyc0c67b02013-01-14 23:22:36 +00003858 MCAsmMacroArguments Args;
Rafael Espindolafc9216e2012-06-16 18:03:25 +00003859 Args.push_back(Arg);
3860
3861 if (expandMacro(OS, M->Body, Parameters, Args, getTok().getLoc()))
3862 return true;
3863 }
3864
3865 InstantiateMacroLikeBody(M, DirectiveLoc, OS);
3866
3867 return false;
3868}
3869
Rafael Espindola761cb062012-06-03 23:57:14 +00003870bool AsmParser::ParseDirectiveEndr(SMLoc DirectiveLoc) {
3871 if (ActiveMacros.empty())
Preston Gurd6579eea2012-09-19 20:23:43 +00003872 return TokError("unmatched '.endr' directive");
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003873
3874 // The only .repl that should get here are the ones created by
Rafael Espindola761cb062012-06-03 23:57:14 +00003875 // InstantiateMacroLikeBody.
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003876 assert(getLexer().is(AsmToken::EndOfStatement));
3877
Rafael Espindola761cb062012-06-03 23:57:14 +00003878 HandleMacroExit();
Rafael Espindola2ec304c2012-05-12 16:31:10 +00003879 return false;
3880}
Rafael Espindolab98ac2a2010-09-11 16:45:15 +00003881
Eli Friedman2128aae2012-10-22 23:58:19 +00003882bool AsmParser::ParseDirectiveEmit(SMLoc IDLoc, ParseStatementInfo &Info) {
3883 const MCExpr *Value;
3884 SMLoc ExprLoc = getLexer().getLoc();
3885 if (ParseExpression(Value))
3886 return true;
3887 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
3888 if (!MCE)
3889 return Error(ExprLoc, "unexpected expression in _emit");
3890 uint64_t IntValue = MCE->getValue();
3891 if (!isUIntN(8, IntValue) && !isIntN(8, IntValue))
3892 return Error(ExprLoc, "literal value out of range for directive");
3893
3894 Info.AsmRewrites->push_back(AsmRewrite(AOK_Emit, IDLoc, 5));
3895 return false;
3896}
3897
Chad Rosierb1f8c132012-10-18 15:49:34 +00003898bool AsmParser::ParseMSInlineAsm(void *AsmLoc, std::string &AsmString,
3899 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003900 SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003901 SmallVectorImpl<std::string> &Constraints,
Chad Rosierb1f8c132012-10-18 15:49:34 +00003902 SmallVectorImpl<std::string> &Clobbers,
3903 const MCInstrInfo *MII,
3904 const MCInstPrinter *IP,
3905 MCAsmParserSemaCallback &SI) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00003906 SmallVector<void *, 4> InputDecls;
3907 SmallVector<void *, 4> OutputDecls;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003908 SmallVector<bool, 4> InputDeclsAddressOf;
3909 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003910 SmallVector<std::string, 4> InputConstraints;
3911 SmallVector<std::string, 4> OutputConstraints;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003912 std::set<std::string> ClobberRegs;
3913
Chad Rosier4e472d22012-10-20 01:02:45 +00003914 SmallVector<struct AsmRewrite, 4> AsmStrRewrites;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003915
3916 // Prime the lexer.
3917 Lex();
3918
3919 // While we have input, parse each statement.
3920 unsigned InputIdx = 0;
3921 unsigned OutputIdx = 0;
3922 while (getLexer().isNot(AsmToken::Eof)) {
Eli Friedman2128aae2012-10-22 23:58:19 +00003923 ParseStatementInfo Info(&AsmStrRewrites);
3924 if (ParseStatement(Info))
Chad Rosierab450e42012-10-19 22:57:33 +00003925 return true;
Chad Rosierb1f8c132012-10-18 15:49:34 +00003926
Chad Rosier57498012012-12-12 22:45:52 +00003927 if (Info.ParseError)
3928 return true;
3929
Eli Friedman2128aae2012-10-22 23:58:19 +00003930 if (Info.Opcode != ~0U) {
3931 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosierb1f8c132012-10-18 15:49:34 +00003932
3933 // Build the list of clobbers, outputs and inputs.
Eli Friedman2128aae2012-10-22 23:58:19 +00003934 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
3935 MCParsedAsmOperand *Operand = Info.ParsedOperands[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00003936
3937 // Immediate.
3938 if (Operand->isImm()) {
Chad Rosierefcb3d92012-10-26 18:04:20 +00003939 if (Operand->needAsmRewrite())
3940 AsmStrRewrites.push_back(AsmRewrite(AOK_ImmPrefix,
3941 Operand->getStartLoc()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003942 continue;
3943 }
3944
3945 // Register operand.
Chad Rosierc1ec2072013-01-10 22:10:27 +00003946 if (Operand->isReg() && !Operand->needAddressOf()) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003947 unsigned NumDefs = Desc.getNumDefs();
3948 // Clobber.
3949 if (NumDefs && Operand->getMCOperandNum() < NumDefs) {
3950 std::string Reg;
3951 raw_string_ostream OS(Reg);
3952 IP->printRegName(OS, Operand->getReg());
3953 ClobberRegs.insert(StringRef(OS.str()));
3954 }
3955 continue;
3956 }
3957
3958 // Expr/Input or Output.
Chad Rosier32989592012-10-18 20:27:15 +00003959 unsigned Size;
Chad Rosierc1ec2072013-01-10 22:10:27 +00003960 bool IsVarDecl;
Chad Rosier32989592012-10-18 20:27:15 +00003961 void *OpDecl = SI.LookupInlineAsmIdentifier(Operand->getName(), AsmLoc,
Chad Rosierc1ec2072013-01-10 22:10:27 +00003962 Size, IsVarDecl);
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003963 if (OpDecl) {
Chad Rosierb1f8c132012-10-18 15:49:34 +00003964 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosierc1ec2072013-01-10 22:10:27 +00003965 if (Operand->isMem() && Operand->needSizeDirective())
Chad Rosier4e472d22012-10-20 01:02:45 +00003966 AsmStrRewrites.push_back(AsmRewrite(AOK_SizeDirective,
Chad Rosierefcb3d92012-10-26 18:04:20 +00003967 Operand->getStartLoc(),
3968 /*Len*/0,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003969 Operand->getMemSize()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003970 if (isOutput) {
3971 std::string Constraint = "=";
3972 ++InputIdx;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003973 OutputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003974 OutputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003975 Constraint += Operand->getConstraint().str();
3976 OutputConstraints.push_back(Constraint);
Chad Rosier4e472d22012-10-20 01:02:45 +00003977 AsmStrRewrites.push_back(AsmRewrite(AOK_Output,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003978 Operand->getStartLoc(),
3979 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003980 } else {
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003981 InputDecls.push_back(OpDecl);
NAKAMURA Takumib956ec12013-01-11 02:50:09 +00003982 InputDeclsAddressOf.push_back(Operand->needAddressOf());
Chad Rosierb1f8c132012-10-18 15:49:34 +00003983 InputConstraints.push_back(Operand->getConstraint().str());
Chad Rosier4e472d22012-10-20 01:02:45 +00003984 AsmStrRewrites.push_back(AsmRewrite(AOK_Input,
Chad Rosier5a719fc2012-10-23 17:43:43 +00003985 Operand->getStartLoc(),
3986 Operand->getNameLen()));
Chad Rosierb1f8c132012-10-18 15:49:34 +00003987 }
3988 }
3989 }
Chad Rosierb1f8c132012-10-18 15:49:34 +00003990 }
3991 }
3992
3993 // Set the number of Outputs and Inputs.
Chad Rosierc8dd27e2012-10-18 19:39:30 +00003994 NumOutputs = OutputDecls.size();
3995 NumInputs = InputDecls.size();
Chad Rosierb1f8c132012-10-18 15:49:34 +00003996
3997 // Set the unique clobbers.
3998 for (std::set<std::string>::iterator I = ClobberRegs.begin(),
3999 E = ClobberRegs.end(); I != E; ++I)
4000 Clobbers.push_back(*I);
4001
4002 // Merge the various outputs and inputs. Output are expected first.
4003 if (NumOutputs || NumInputs) {
4004 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierc8dd27e2012-10-18 19:39:30 +00004005 OpDecls.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004006 Constraints.resize(NumExprs);
Chad Rosierb1f8c132012-10-18 15:49:34 +00004007 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004008 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004009 Constraints[i] = OutputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004010 }
4011 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosierc1ec2072013-01-10 22:10:27 +00004012 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier1c99a7f2013-01-15 23:07:53 +00004013 Constraints[j] = InputConstraints[i];
Chad Rosierb1f8c132012-10-18 15:49:34 +00004014 }
4015 }
4016
4017 // Build the IR assembly string.
4018 std::string AsmStringIR;
Chad Rosier4e472d22012-10-20 01:02:45 +00004019 AsmRewriteKind PrevKind = AOK_Imm;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004020 raw_string_ostream OS(AsmStringIR);
4021 const char *Start = SrcMgr.getMemoryBuffer(0)->getBufferStart();
Chad Rosier4e472d22012-10-20 01:02:45 +00004022 for (SmallVectorImpl<struct AsmRewrite>::iterator
Chad Rosierb1f8c132012-10-18 15:49:34 +00004023 I = AsmStrRewrites.begin(), E = AsmStrRewrites.end(); I != E; ++I) {
4024 const char *Loc = (*I).Loc.getPointer();
Chad Rosier96d58e62012-10-19 20:57:14 +00004025
Chad Rosier4e472d22012-10-20 01:02:45 +00004026 AsmRewriteKind Kind = (*I).Kind;
Chad Rosier96d58e62012-10-19 20:57:14 +00004027
4028 // Emit everything up to the immediate/expression. If the previous rewrite
4029 // was a size directive, then this has already been done.
4030 if (PrevKind != AOK_SizeDirective)
4031 OS << StringRef(Start, Loc - Start);
4032 PrevKind = Kind;
4033
Chad Rosier5a719fc2012-10-23 17:43:43 +00004034 // Skip the original expression.
4035 if (Kind == AOK_Skip) {
4036 Start = Loc + (*I).Len;
4037 continue;
4038 }
4039
Chad Rosierb1f8c132012-10-18 15:49:34 +00004040 // Rewrite expressions in $N notation.
Chad Rosier96d58e62012-10-19 20:57:14 +00004041 switch (Kind) {
Chad Rosier5a719fc2012-10-23 17:43:43 +00004042 default: break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004043 case AOK_Imm:
Chad Rosierefcb3d92012-10-26 18:04:20 +00004044 OS << Twine("$$");
4045 OS << (*I).Val;
4046 break;
4047 case AOK_ImmPrefix:
4048 OS << Twine("$$");
Chad Rosierb1f8c132012-10-18 15:49:34 +00004049 break;
4050 case AOK_Input:
4051 OS << '$';
4052 OS << InputIdx++;
4053 break;
4054 case AOK_Output:
4055 OS << '$';
4056 OS << OutputIdx++;
4057 break;
Chad Rosier96d58e62012-10-19 20:57:14 +00004058 case AOK_SizeDirective:
Chad Rosier6a020a72012-10-25 20:41:34 +00004059 switch((*I).Val) {
Chad Rosier96d58e62012-10-19 20:57:14 +00004060 default: break;
4061 case 8: OS << "byte ptr "; break;
4062 case 16: OS << "word ptr "; break;
4063 case 32: OS << "dword ptr "; break;
4064 case 64: OS << "qword ptr "; break;
4065 case 80: OS << "xword ptr "; break;
4066 case 128: OS << "xmmword ptr "; break;
4067 case 256: OS << "ymmword ptr "; break;
4068 }
Eli Friedman2128aae2012-10-22 23:58:19 +00004069 break;
4070 case AOK_Emit:
4071 OS << ".byte";
4072 break;
Chad Rosier6a020a72012-10-25 20:41:34 +00004073 case AOK_DotOperator:
4074 OS << (*I).Val;
4075 break;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004076 }
Chad Rosier96d58e62012-10-19 20:57:14 +00004077
Chad Rosierb1f8c132012-10-18 15:49:34 +00004078 // Skip the original expression.
Chad Rosier96d58e62012-10-19 20:57:14 +00004079 if (Kind != AOK_SizeDirective)
4080 Start = Loc + (*I).Len;
Chad Rosierb1f8c132012-10-18 15:49:34 +00004081 }
4082
4083 // Emit the remainder of the asm string.
4084 const char *AsmEnd = SrcMgr.getMemoryBuffer(0)->getBufferEnd();
4085 if (Start != AsmEnd)
4086 OS << StringRef(Start, AsmEnd - Start);
4087
4088 AsmString = OS.str();
4089 return false;
4090}
4091
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004092/// \brief Create an MCAsmParser instance.
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004093MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM,
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004094 MCContext &C, MCStreamer &Out,
4095 const MCAsmInfo &MAI) {
Jim Grosbach1b84cce2011-08-16 18:33:49 +00004096 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbard1e3b442010-07-17 02:26:10 +00004097}